How to definitely ban an IP with Fail2Ban

Setup Fail2Ban, if it’s not already done :

sudo apt-get install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Configure Fail2Ban :

sudo nano /etc/fail2ban/jail.local
ignoreip = 127.0.0.1/8 192.168.1.0/24
bantime = -1
findtime = 31536000
maxretry = 3

Add your IP in the ignoreip list, you can add a mask of IPs.

Bantime = -1 means indefinitely. Findtime = 31536000 (one year).

Create the ip blacklist file :

sudo touch /etc/fail2ban/ip.blacklist

Make a backup version of iptables-multiport.conf :

sudo cp /etc/fail2ban/action.d/iptables-multiport.conf /etc/fail2ban/action.d/iptables-multiport.conf.bak

Open iptables-multiport.conf :

sudo nano /etc/fail2ban/action.d/iptables-multiport.conf

Edit this part (actionban, actionstart) :

actionstart = iptables -N fail2ban-
              iptables -A fail2ban- -j RETURN
              iptables -I  -p  -m multiport --dports  -j fail2ban-
              # This configuration loads the ip.blacklist file every time Fail2ban service is started.
              if [ -f /etc/fail2ban/ip.blacklist ]; then cat /etc/fail2ban/ip.blacklist | grep -e $ | cut -d "," -s -f 1 | while read IP; do iptables -I fail2ban- 1 -s $IP -j DROP; done; fi
 
actionban = if ! iptables -C fail2ban- -s  -j DROP; then iptables -I fail2ban- 1 -s  -j DROP; fi
            # Add offenders to ip.blacklist file, if it is not already there yet.
            if ! grep -Fxq ',' /etc/fail2ban/ip.blacklist; then echo ',' >> /etc/fail2ban/ip.blacklist; fi

Restart Fail2Ban :

sudo /etc/init.d/fail2ban restart

Check it :

sudo iptables -L -n

You should get some IP added to iptables chain fail2ban-ssh rule.

To unban certain IP, you can use this command :

sudo fail2ban-client set  unbanip 

And

sudo sed --in-place '/,/d' /etc/fail2ban/ip.blacklist

Or if it fails :

sudo fail2ban-client reload
sudo iptables -L -n | grep 

You can use line numbers :

sudo iptables -L -n --line-numbers | grep 

You will get the line number of the IP. And will be able to delete it :

sudo iptables -D fail2ban-ssh 
fail2ban-client reload