September 20, 2020

How to secure SSH service with Fail2Ban

2 min read

Fail2Ban scans log files like /var/log/auth.log and bans IP addresses conducting too many failed login attempts. It does this by updating system firewall rules to reject new connections from those IP addresses, for a configurable amount of time. Fail2Ban comes out-of-the-box ready to read many standard log files, such as those for sshd and Apache, and is easily configured to read any log file of your choosing, for any error you wish.

On this post, I’m going guide you on how to secure SSH service with Fail2Ban.

First, you need to install Fail2ban:
aptget install fail2ban
After installation Fail2ban starts working immediately, but only for SSH and with default settings. Now add the settings we need. The whole configuration is in the file /etc/fail2ban/jail.conf. We will need to change the SSH section:
[ssh]
enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 5
findtime = 3600
bantime  = 86400
Parameter
maxretry: the maximum number of incorrect connections during the time specified in the findtime parameter
findtime: the time in the log file for which the number of incorrect connections is analyzed. Calculated in seconds
bantime: blocking time in seconds

Save and restart Fail2ban:

service fail2ban restart
Now after 5 incorrect password entries within an hour, the address will be blocked for a day. You can find out the list of included protections with the command:
fail2banclient status
You can find out statistics on blocked clients for each service using the command:
fail2banclient status service_name