fail2ban сохранение настроек IP после перезапуска

In order for bans to persist across a service restart, they obviously have to be saved somewhere. No fancy database required, a simple text file will do the trick.

The principle is simple: every time Fail2Ban sets a new ban on an IP, we’ll save the information « jail name and IP address » in a file along the way. Next, upon each Fail2Ban service start, we’ll load this file a re-create the corresponding bans. All it takes is two lines in the right configuration file.

Each ban action is defined in a corresponding configuration file. Within this file, there’s two parameters we’re interested in:

  1. actionstart : here we can define a list of commands that will be executed only once at the start of Fail2Ban. So we’ll add a custom command loading the file /etc/fail2ban/persistent.bans and re-create the corresponding iptables entries.
  2. actionban : here we can defined a list of commands that will be executed when banning an IP. So we’ll add a custom command to save the useful information to the file /etc/fail2ban/persistent.bans.

The default action in Fail2Ban is iptables-multiport (as defined in the file jail.conf), so we have to edit the action.d/iptables-multiport.conffile and add the following highlighted lines:

[Definition]
 
# Option:  actionstart
# Notes.:  command executed once at the start of Fail2Ban.
# Values:  CMD
#
actionstart = iptables -N fail2ban-
              iptables -A fail2ban- -j RETURN
              iptables -I  -p  -m multiport --dports  -j fail2ban-
          cat /etc/fail2ban/persistent.bans | awk '/^fail2ban-/ {print $2}' \
          | while read IP; do iptables -I fail2ban- 1 -s $IP -j ; done
 
# Option:  actionstop
# Notes.:  command executed once at the end of Fail2Ban
# Values:  CMD
#
actionstop = iptables -D  -p  -m multiport --dports  -j fail2ban-
             iptables -F fail2ban-
             iptables -X fail2ban-
 
# Option:  actioncheck
# Notes.:  command executed once before each actionban command
# Values:  CMD
#
actioncheck = iptables -n -L  | grep -q 'fail2ban-[ \t]'
 
# Option:  actionban
# Notes.:  command executed when banning an IP. Take care that the
#          command is executed with Fail2Ban user rights.
# Tags:    See jail.conf(5) man page
# Values:  CMD
#
actionban = iptables -I fail2ban- 1 -s  -j 
        echo "fail2ban- " >> /etc/fail2ban/persistent.bans

Once done, it is required to restart Fail2Ban in order for those change to be applied.

arno@myserver:/etc/fail2ban/action.d $ sudo service fail2ban restart

And that’s it !

Print Friendly, PDF & Email

Добавить комментарий