Site icon David Ramsden

Banning Repeat Offenders With fail2ban

More and more I see fail2ban banning the same hosts repeatedly. One way to tackle this could be to increase the ban time but you could also have fail2ban monitor itself to find “repeat offenders” and then ban them for an extended period of time.

Firstly, create a filter definition:

[Definition]
failregex = fail2ban\.actions\[\d+\]: WARNING \[.*\] Unban <HOST>$
ignoreregex = fail2ban\.actions\[\d+\]: WARNING \[repeat-offender\].*$

This will be used against the fail2ban log and will find any hosts that have been unbanned. We don’t want to monitor hosts that have been banned because, er, they’re already banned. We also want to ignore any log entries that are generated by the jail itself.

Next edit jail.local to add a new jail:

[repeat-offender]
enabled = true
filter = repeat-offender
port = all
banaction = iptables-allports
logpath = /var/log/fail2ban.log
# Repeat offender if previously banned 3 times within 5 hours.
maxretry = 3
findtime = 18000
# Ban for 48 hours.
bantime = 172800

This jail will monitor the /var/log/fail2ban.log file and use the repeat-offender filter that was defined earlier. If 3 unban’s are seen within 5 hours, the host will be banned for 48 hours. You could adjust the banaction to use the route action which may give some performance benefits on a very busy server.