SSH Brute Force Protection with Fail2Ban

2 minutes read

Fail2Ban is an Intrusion Prevention framework written in python which protects any protcol that has an “username” and “password” field. Like SSH, FTP, Telnet an so on.

Some pre-checks (Optional)

First check SSH config

sudo vim /etc/ssh/sshd_config

In the SSH config file the line MaxAuthTries is also respected by fail2ban. So, we should also provide the maximum number of failed atemts we want to have. We are going to set the same value in fail2ban config. In this case we are giving it a value of “3”.

MaxAuthTries 3

Check the auth.log file. Check for which filter to use.

fail2ban looks at the /var/log/auth.log file to monitor failed login attempts.

cat /var/log/auth.log | grep "sshd

In this case we can see grepping for “sshd” gives us the logs for ssh. So, “sshd” will be our filter

Setup fail2ban

Install fail2ban

sudo apt install -y fail2ban

Configure fail2ban

Create fail2ban jail

sudo vim /etc/fail2ban/jail.local

Put the followin config in the jail.local file.

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
findtime = 300
bantime = 3600

Legend:

Restart the service

sudo systemctl restart fail2ban.service

Note

Fail2ban will respect the MaxAuthTries entry in sshd_config file. That’s why it will priorities the sshd_config file before its own jail config. For example,

Unban banned IPs

You can check fail2ban status with:

fail2ban-client status sshd

# It will show banned IPs and stuff.

You can unban an IP with:

fail2ban-client set sshd unbanip 192.168.122.1

Done!