Blocking brute-force attacks on SSH and web services with Fail2ban
Fail2ban watches your server logs and temporarily blocks, at the firewall, IP addresses that make many failed login attempts in a short time. In this guide you will install Fail2ban on Ubuntu, Debian and AlmaLinux, define the right jails for SSH and Nginx, avoid the logging trap on Debian 12 and later, and manage bans safely.
How does Fail2ban work, and what doesn't it protect?
Fail2ban has three parts. A filter recognizes failed-attempt lines in a log using regular expressions. A jail ties a filter to a specific service, port and log source. An action adds a blocking rule to the firewall once the threshold is reached. If an IP address reaches maxretry failures within findtime, it is blocked for bantime; when that time is up, the rule is removed automatically.
Fail2ban is not a complete security solution on its own; it is a complementary layer. In distributed attacks, where thousands of different addresses each make only a few attempts, every IP stays below the threshold and is never banned. The real protection is to turn off password login for SSH and use keys only, and to close unneeded ports with a firewall. On top of that, Fail2ban reduces log noise and the resources wasted on attack traffic.
On Linux templates, password login over SSH is enabled for root when the server is delivered. Fail2ban reduces that risk but does not remove it; make enabling key login and turning off password login a priority.
Installation on Ubuntu, Debian and AlmaLinux
On Ubuntu and Debian, Fail2ban is in the official repositories. The package on these distributions enables the sshd jail at install time through the /etc/fail2ban/jail.d/defaults-debian.conf file.
# Ubuntu / Debian
sudo apt update
sudo apt install fail2ban
sudo systemctl enable --now fail2ban
sudo systemctl status fail2ban --no-pagerOn AlmaLinux 9, Fail2ban is not in the base repositories; it is installed from EPEL (Extra Packages for Enterprise Linux). The EPEL package also pulls in the fail2ban-firewalld component, which writes bans to firewalld, and makes it the default through /etc/fail2ban/jail.d/00-firewalld.conf. On AlmaLinux, jails ship disabled; you will enable the sshd jail yourself in the next step.
# AlmaLinux 9: Fail2ban comes from the EPEL repository
sudo dnf install epel-release
sudo dnf install fail2ban
sudo systemctl enable --now fail2banAfter installation, check that the service is active (running). If it fails right away, you have most likely hit the log source problem described below.
Basic configuration with jail.local
Do not edit /etc/fail2ban/jail.conf; it can change with package updates, and it becomes hard to track where your settings come from. Fail2ban reads its configuration in this order: jail.conf, jail.d/*.conf, jail.local and jail.d/*.local. A value read later replaces an earlier one, so the settings in jail.local take precedence over the distribution's default files. The following example is for an Ubuntu or Debian server that uses UFW:
# /etc/fail2ban/jail.local
[DEFAULT]
# Ban duration, counting window and allowed failures
bantime = 1h
findtime = 10m
maxretry = 5
# Repeat offenders get longer bans each time (up to 1 week)
bantime.increment = true
bantime.maxtime = 1w
# Addresses that are never banned: local addresses and your static office IP
ignoreip = 127.0.0.1/8 ::1 198.51.100.25
# Only for Ubuntu/Debian with UFW; leave these two lines out on AlmaLinux
banaction = ufw
banaction_allports = ufw
[sshd]
enabled = true
# If you moved SSH to another port: port = 2222
port = ssh
backend = systemdThese values are a sensible start; on a key-only server you can lower maxretry to 3. Only put an IP address in ignoreip that belongs to you and does not change (a static address). If your home or mobile connection changes address, do not add it; use the recovery steps below if you ever ban yourself by mistake. Exempting an entire carrier block means exempting every attacker in that block too.
On AlmaLinux, leave out the banaction lines; the firewalld action in 00-firewalld.conf is already the right choice. If you changed the SSH port, update the port value to the new port; otherwise port-based actions only block port 22. After the change, test the configuration and restart the service:
# Test the configuration, then restart the service
sudo fail2ban-client -t
sudo systemctl restart fail2ban
sudo fail2ban-client status
sudo fail2ban-client status sshdDebian 12 and later: backend = systemd when there is no auth.log
Starting with Debian 12, rsyslog is no longer part of the default installation; system messages are kept only in the systemd journal, and /var/log/auth.log is never created. Debian 13 does not have this file by default either. On Debian 12, the sshd jail looks for this file with the file-based backend, so the service fails to start with Have not found any log file for sshd jail. The fix is to use backend = systemd in the sshd jail; Fail2ban then reads SSH messages straight from the journal. Rather than relying on the package default, set this line explicitly in jail.local.
Ubuntu servers usually have rsyslog installed and do have auth.log; on AlmaLinux the same messages go to /var/log/secure. The systemd backend works fine on these systems too, so you can keep the setting identical on every distribution. It requires the Python systemd module; on Ubuntu and Debian it usually comes with Fail2ban, and if it does not, install it:
# Which authentication log exists? (usually neither on Debian 12 and later)
ls -l /var/log/auth.log /var/log/secure
# Is the Python module for backend = systemd installed?
python3 -c "import systemd.journal" && echo OK
sudo apt install python3-systemd # Ubuntu / Debian
sudo dnf install python3-systemd # AlmaLinux
# Does the filter match the SSH messages in the journal?
sudo fail2ban-regex systemd-journal sshdDo not put backend = systemd in the [DEFAULT] section. That setting is inherited by every jail; jails that read files, such as Nginx and recidive, then ignore logpath, look at the journal instead and catch nothing. If you still want it in DEFAULT, add backend = auto to every jail that reads a file.
On newer distribution releases that ship OpenSSH 9.8 or later, authentication messages come from a process named sshd-session. If the Total failed counter in fail2ban-client status sshd does not increase despite failed logins, update the Fail2ban package and confirm with the fail2ban-regex command above that the filter matches the messages.
Which firewall do the bans go to?
The ban action (banaction) must match the firewall you actually use on the server. With a mismatched action, the ban shows up in the log but the traffic is not blocked; this is the sneakiest Fail2ban problem.
- Ubuntu or Debian with UFW: use
banaction = ufw. The UFW action cuts the banned IP off from every port. Confirm that UFW is active withufw status; a rule added to a disabled UFW does nothing. - AlmaLinux with firewalld: you can keep the
firewallcmd-rich-rulesaction chosen by the EPEL package. If you expect many banned IPs, the ipset-basedfirewallcmd-ipsetis more efficient. If firewalld is stopped, the actions fail; keep it running withsystemctl enable --now firewalld. - Debian without UFW (nftables only):
banaction = nftables-multiportandbanaction_allports = nftables-allportsare a good fit.
Do not guess which action is active; verify it. Ban an address reserved for documentation (192.0.2.50) by hand, check that the rule appears in the firewall, then lift the ban:
# Action currently used by the sshd jail
sudo fail2ban-client get sshd actions
# Ban a documentation address by hand and look for the rule
sudo fail2ban-client set sshd banip 192.0.2.50
sudo ufw status numbered | grep 192.0.2.50 # UFW
sudo firewall-cmd --list-rich-rules | grep 192.0.2.50 # firewalld
sudo nft list ruleset | grep 192.0.2.50 # nftables
# End the test
sudo fail2ban-client set sshd unbanip 192.0.2.50Nginx jails and recidive for repeat offenders
The ready-made web filters catch specific events in the Nginx error log. nginx-http-auth catches failed password attempts on a directory protected with auth_basic (for example, an admin interface), and nginx-botsearch catches bots that probe for admin and script paths that do not exist. The recidive jail reads Fail2ban's own log and blocks an IP that has been banned repeatedly within a day on all ports for a week.
# Append to the end of /etc/fail2ban/jail.local
[nginx-http-auth]
enabled = true
port = http,https
logpath = /var/log/nginx/error.log
[nginx-botsearch]
enabled = true
port = http,https
[recidive]
enabled = true
logpath = /var/log/fail2ban.log
banaction = %(banaction_allports)s
bantime = 1w
findtime = 1dDefault log paths come from the distribution's paths-*.conf files; for Nginx this is usually the /var/log/nginx/*error.log pattern. If your sites write to their own log files, adjust the logpath line accordingly. Before enabling a jail, use fail2ban-regex to test that the filter finds matches in your real log:
# Do the filters find matches in your real log?
sudo fail2ban-regex /var/log/nginx/error.log nginx-http-auth
sudo fail2ban-regex /var/log/nginx/error.log nginx-botsearch
# The log target that recidive reads
sudo fail2ban-client get logtargetIf you enable the Nginx jails while Nginx is not installed or the log file does not exist, Fail2ban cannot start that jail and the service may fail. In applications such as WordPress, a failed login often returns an HTTP 200 response, so the ready-made Nginx filters do not catch those attempts. For application-level measures, see our WordPress security guide; to set up Nginx itself, follow the LEMP installation guide.
Management, verification and common errors
For day-to-day work, fail2ban-client is all you need. After changing the configuration you can use the reload command instead of restarting the service. Fail2ban writes its own activity to /var/log/fail2ban.log.
# All jails, then sshd details (including the banned IP list)
sudo fail2ban-client status
sudo fail2ban-client status sshd
# Remove an IP from one jail or from all jails
sudo fail2ban-client set sshd unbanip 198.51.100.25
sudo fail2ban-client unban 198.51.100.25
# Reload the configuration without stopping the service
sudo fail2ban-client reload
# Latest ban and unban entries
sudo grep -E " (Ban|Unban) " /var/log/fail2ban.log | tail -n 20If you have banned yourself
If your SSH connection suddenly times out or is refused, first try connecting from a different network (for example, your phone's mobile data). If that is not possible, use the VNC Console tool in the client area to reach the server's screen from your browser; the console works independently of the server's network connection. Log in as root, remove your own IP with fail2ban-client unban, and if your address is static, add it to ignoreip. For how to use the console, see the VNC Console guide.
Keep your current SSH session open while you change the configuration. Close it only after you have confirmed that you can connect from a new terminal and that fail2ban-client status sshd looks the way you expect.
The most common errors and how to fix them:
| Symptom | Likely cause | Fix |
|---|---|---|
Have not found any log file for sshd jail | No auth.log (Debian 12 and later) | Add backend = systemd to the sshd section; make sure python3-systemd is installed |
No module named 'asynchat' (Ubuntu 24.04) | An old package version that is incompatible with Python 3.12 | sudo apt update && sudo apt install --only-upgrade fail2ban |
| The ban is in the log, but the attacker keeps connecting | The action writes to a firewall you do not use, UFW is disabled, or the target is a Docker port | Check the action with fail2ban-client get sshd actions, then the firewall status and Docker's published ports |
The Total failed counter never increases | The filter does not match the messages (wrong backend, log path or process name) | Test with fail2ban-regex; check the backend setting and the package version |
| The service does not start after enabling an Nginx jail | The log file is missing or the path is wrong | Disable the jail or fix logpath; test with fail2ban-client -t |
Frequently asked questions
I turned off password login; do I still need Fail2ban?
It is not required, but it is useful. With key login, password attempts cannot succeed; bots still keep connecting, fill up the logs and use some CPU. Fail2ban reduces this noise and also protects web services on the same server. On key-only servers, adding mode = aggressive to the sshd section also counts connections that drop before authentication, so bots are caught earlier.
Are bans lost when the server restarts?
No. Fail2ban stores bans in the /var/lib/fail2ban/fail2ban.sqlite3 database and, when the service starts again, writes the bans that have not yet expired back to the firewall. In the log, this appears as Restore Ban lines.
Should I use permanent bans (bantime = -1)?
We do not recommend it. A large share of attack traffic comes from networks where addresses change often; permanent bans grow into thousands of rules over time and also block legitimate users who later receive the same address. Incremental bans together with the recidive jail keep repeat attackers out for a long time without permanent bans.
Does Fail2ban protect my Docker containers too?
Not with the default configuration. The logs stay inside the container, and because traffic to ports published by Docker passes through the FORWARD chain rather than the host's INPUT chain, it bypasses bans written for the host. If you publish the service only on 127.0.0.1 and put Nginx on the host in front of it as a reverse proxy, Fail2ban can work from the Nginx logs. Details are in the Docker installation guide.
Related articles
Thanks for your feedback!