Persistent Banning of IP Addresses with Fail2Ban
Fail2Ban, Security
If you’re using Fail2Ban you can easily set up a list of banned IP addresses that Fail2Ban will use to set up DROP
rules in iptables whenever Fail2Ban starts. This is very useful since it is easy to persist IP bans across reboots.
You need to modify the relevant action config file, and reference a “blocklist” file. When you add IP addresses to the blocklist and reload Fail2Ban, the relevant drop rules will be added.
Action files specify which commands are executed to ban and unban an IP address. Like with jail.conf files, if you desire local changes create an
[actionname].local
file in the/etc/fail2ban/action.d
directory and override the required settings.
Action files have two sections, [Definition] and [Init]. The [Init] section enables action-specific settings. These can be overridden for a particular jail (in jail.local
) as options of the action’s specification in that jail.
IP Blocklist and Associated Action
For our purposes, we will amend the actionstart
command in the [Definition]
section. This command (or commands) executes when the jail starts. To override the default action, create a corresponding .local
file and add the amended actionstart
command:
After creating and editing the file, save and exit (ctrl-o followed by ctrl-x).
Create a file /etc/fail2ban/ip.blocklist
and enter IP addresses to ban - one per line.
Restart Fail2Ban for the changes to be applied. If you run sudo iptables -S
now, you should see rules like -A f2b-ssh -s 11.22.333.444/32 -j DROP
associated with your different jails.
Auto Add IP Addresses to the Blocklist
If you want to automatically add IPs to your list as they are banned, you need to amend the actionban
command such that the IP is appended to your list when the IP is banned:
Commands specified in the [Definition] section of are executed through a system shell so shell redirection and process control is allowed. Note that commands should return 0, or an error will be logged (ref: man jail.conf
).
References
comments powered by Disqus