Set up Fail2ban: fend off brute-force attacks on SSH and web servers
Install Fail2ban, protect SSH and Nginx, choose sensible ban times, view banned IPs and never lock yourself out.
Every server on the internet is under constant attack: bots try passwords for SSH, WordPress logins or mail accounts around the clock. Fail2ban reads the logs of your services and bans addresses that fail too often in the firewall for a while.
Fail2ban is no substitute for good credentials. The most effective step is SSH with keys only, see Create SSH keys. Fail2ban additionally keeps the logs clean and slows attackers down on other services.
Install
sudo apt update
sudo apt install fail2ban
On Debian 12, SSH no longer writes to /var/log/auth.log, only to the journal. So that Fail2ban finds it, you switch the backend to systemd; that goes into the configuration in a moment.
Create your own configuration
Never edit jail.conf; it is overwritten on updates. Create a jail.local instead:
sudo nano /etc/fail2ban/jail.local
[DEFAULT]
# Ban for 1 hour after 5 failures within 10 minutes
bantime = 1h
findtime = 10m
maxretry = 5
# Repeat offenders are banned longer
bantime.increment = true
bantime.maxtime = 1w
# Never ban your own addresses (your static IP, your VPN network)
ignoreip = 127.0.0.1/8 ::1 10.8.0.0/24
backend = systemd
[sshd]
enabled = true
port = ssh
If you moved SSH to another port, enter it under port, for example port = 2222.
sudo systemctl restart fail2ban
sudo fail2ban-client status
sudo fail2ban-client status sshd
Protect Nginx
Fail2ban ships filters for many services. For Nginx, nginx-http-auth (wrong passwords with Basic Auth) is useful, and nginx-botsearch for bots looking for weaknesses such as /wp-login.php or /phpmyadmin. Add to jail.local:
[nginx-http-auth]
enabled = true
backend = auto
logpath = /var/log/nginx/error.log
[nginx-botsearch]
enabled = true
backend = auto
logpath = /var/log/nginx/access.log
maxretry = 2
Nginx writes to files, hence backend = auto instead of systemd here.
Manage banned addresses
| Command | Effect |
|---|---|
sudo fail2ban-client status sshd |
show banned IPs of a jail |
sudo fail2ban-client set sshd unbanip 203.0.113.5 |
lift a ban |
sudo fail2ban-client set sshd banip 203.0.113.5 |
ban by hand |
sudo tail -f /var/log/fail2ban.log |
follow bans live |
Locked yourself out?
If you cannot get in via SSH after a few typos, open the console in the TryNxt panel. It works independently of the network. Lift the ban there and add your address to ignoreip.
Test filters
fail2ban-regex shows whether a filter finds matches in the log:
sudo fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-botsearch.conf
For SSH with the journal: sudo fail2ban-regex systemd-journal /etc/fail2ban/filter.d/sshd.conf.
For the community
Know your stuff? Write a guide.
Share what you know: we review every submitted guide, publish it under your name and say thank you with credit for your services.