Tools · Linux command line for security · 23 / 28
How to set up Fail2ban for SSH and check that it is banning
Install Fail2ban, configure an sshd jail in jail.local, test a ban from a lab machine, and unban safely.
What Fail2ban does
Fail2ban watches log files or the journal for patterns such as failed SSH logins. When one source exceeds maxretry failures within findtime, it adds a firewall rule that blocks that source for bantime. It reduces log noise and slows guessing.
It is a supporting control. Key-only SSH is the real defense against password guessing; Fail2ban helps with the remaining noise and other services.
Configure a jail
Never edit jail.conf; it is overwritten on upgrade. Create /etc/fail2ban/jail.local with your settings. On systemd hosts set backend = systemd so it reads the journal. Add your management network to ignoreip so you cannot ban yourself.
bantime.increment = true makes repeat offenders get longer bans.
# /etc/fail2ban/jail.local [DEFAULT] ignoreip = 127.0.0.1/8 192.168.56.20 bantime = 1h findtime = 10m maxretry = 5 bantime.increment = true [sshd] enabled = true backend = systemd
Lab: trigger and clear a ban
Install fail2ban, add the jail, and restart. From a lab VM that is not in ignoreip, fail SSH login six times. On the server, fail2ban-client status sshd should list the address under banned IPs, and new connections from it should time out.
Unban with fail2ban-client set sshd unbanip ADDRESS. Check /var/log/fail2ban.log for the ban and unban lines.
sudo apt install fail2ban sudo systemctl restart fail2ban sudo fail2ban-client status sshd sudo fail2ban-client set sshd unbanip 192.168.56.40 sudo tail /var/log/fail2ban.log
Limits
Distributed guessing from thousands of addresses at a low rate stays under per-source thresholds. Cloud load balancers and NAT can make many users share one address, so a ban may block legitimate users.
Watch for the opposite failure too: Fail2ban not banning anything because its filter does not match the current log format. The status command and a test ban prove it works.
Diagram
How a ban happens
- Watch
Fail2ban reads the sshd journal.
- Count
Failures per source within findtime.
- Ban
Firewall rule blocks the source for bantime.
sudo fail2ban-client status sshd
- Expire
Ban lifts automatically or with unbanip.
Check yourself
1. Which file should hold your Fail2ban settings?
2. Which setting prevents banning your admin workstation?
3. Why is Fail2ban weak against distributed guessing?