Linux Server setup

Protect SSH with Fail2ban

The software Fail2ban monitors log files and can temporarily block an IP address if too many failed login attempts occur within a defined time window. Here we use it for SSH.

Fail2ban is particularly useful when password-based SSH login is allowed, because it limits repeated attempts to guess a password. If you have already disabled password login and only allow key-based authentication, Fail2ban is not required to secure the SSH login. It can still be useful as an additional measure to reduce repeated requests and keep the log files clearer.

We configure Fail2ban to react to too many failed SSH login attempts within a defined time window.

First, we install Fail2ban.

We'll look at Linux's package management system (apt) in more detail in the chapter, so we'll perform the installation here without further explanation.

Install Fail2ban with apt:


__$ sudo apt install fail2ban -y
 

We first create a jail.local file with touch:


__$ sudo touch /etc/fail2ban/jail.local
 

We can make our modifications to this jail.local file. This remains with us with updates and is not overwritten like the jail.conf.

Let's open it for editing with nano:


__$ sudo nano /etc/fail2ban/jail.local
 

In the file we write the following configuration

/etc/fail2ban/jail.local


[sshd]

enabled   = true
port      = ssh,22123
filter    = sshd
logpath   = /var/log/auth.log
ignoreip  = 127.0.0.1/8
bantime   = 3600
findtime  = 600
maxretry  = 6

There is actually not much leeway in the parameters, except for maxretry, which is the number of failed attempts within a time window. In this case 6 login attempts are allowed before the IP is temporarily banned.

Brief explanation of the most important parameters:

  • ignoreip = 127.0.0.1/8: ignores internal services
  • port = ssh,22123: covers both the standard SSH port and the port used later in this tutorial
  • bantime = 3600: seconds that an IP is blocked (3600 = 60 minutes).
  • findtime = 600: time limit for failed attempts
  • maxretry = 6: number of failed attempts until an IP is blocked.

Let's restart Fail2ban for the changes to take effect:


__$ sudo systemctl restart fail2ban
 

And also check the status:


__$ sudo systemctl status fail2ban
 

There should be a active (running) feedback.

Testing is simple. Just exhaust the set failures (maxretry). But note: If you are locked you need either a new IP from the provider (if possible) or you lower the seconds of the bantime before (restart fail2ban.service if you change).

Unlock IP addresses in Fail2ban again

Unlock an IP in Fail2ban (separate multiple IPs with spaces):


__$ sudo fail2ban-client unban 116.203.69.89 123.456.789.013
 

Clear Fail2ban IP table:


__$ sudo fail2ban-client unban --all