How to setup Fail2Ban

First update your packages list and versions :

sudo apt-get update

Setup Fail2Ban :

sudo apt-get install fail2ban

Create jail.local, by copying jail.conf :

cp sudo nano /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Open jail.local, add your ip in the ignoreip list :

sudo nano /etc/fail2ban/jail.conf
ignoreip = 127.0.0.1/8

It should look like this :

ignoreip = 127.0.0.1/8 111.222.333.444

Set bantime :

bantime = 600

It is expressed in seconds. You can add one year if you want : 31536000. For an unlimited time, set -1.

Then, findtime and maxretry :

findtime = 600
maxretry = 3

You can configure your email address here :

destemail = root@localhost
sendername = Fail2Ban
mta = sendmail

Except if root@localhost is already redirecting to your email address. You can check that by editing the aliases file :

sudo nano /etc/aliases
# See man 5 aliases for format
postmaster:    root
root: your@email.com

In jail.local, replace :

action = $(action_)s

By :

action = $(action_mwl)s

In the jail part, enable [ssh] and [apache] if you have Apache, [nginx-http-auth] if you have Nginx.

[ssh]
enabled = true
...

For information, the filters are available in the filter.d folder :

ls /etc/fail2ban/filter.d

Setup iptables persistent :

sudo apt-get install iptables-persistent
sudo dpkg-reconfigure iptables-persistent

Finally :

sudo service fail2ban start

You can check the iptables rules :

sudo iptables -S

You should get this as a result :

-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-N fail2ban-apache
-N fail2ban-ssh
-A INPUT -p tcp -m multiport --dports 80,443 -j fail2ban-apache
-A INPUT -p tcp -m multiport --dports 22 -j fail2ban-ssh
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -j DROP
-A fail2ban-nginx-http-auth -j RETURN
-A fail2ban-ssh -j RETURN