Securing SSH With fail2ban

The Problem

Shortly after setting up my server I noticed increasing amounts of authentication log data. The files contained many thousand lines of failed password attempts for the root user account. The attempts not only put my system at risk but also clogged up the log files and introduced stress on the small server instance.

Nov 13 20:20:06 v36436 sshd[7001]: Failed password for root from 116.31.116.36 port 12984 ssh2
Nov 13 20:20:10 v36436 sshd[7001]: message repeated 2 times: [ Failed password for root from 116.31.116.36 port 12984 ssh2]
Nov 13 20:20:11 v36436 sshd[7001]: Received disconnect from 116.31.116.36 port 12984:11:  [preauth]
Nov 13 20:20:11 v36436 sshd[7001]: Disconnected from 116.31.116.36 port 12984 [preauth]
Nov 13 20:20:11 v36436 sshd[7001]: PAM 2 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=116.31.116.36  user=root

Installing fail2ban

On Ubuntu 16.04 installation is as simple as apt-get install fail2ban.

Configuring fail2ban

To setup fail2ban for protecting your SSH server, just edit /etc/fail2ban/jail.conf. Find the [sshd] jail and enable it (you may have to add the enabled = true line yourself).

[sshd]
enabled = true
port    = ssh
logpath = %(sshd_log)s

The sshd_logs variable is set in one of the included configuration files. The Ubuntu packages include a good set of defaults to minimize the configuration effort required.

You may increase the bantime to slow down brute-force attacks even more. fail2bans default is 10 minutes (600 seconds). 10 minutes is a good starting point, I increased it to 30 minutes to keep my logs from clogging up with failed attempts. I set bantime = 1800 inside the [DEFAULT] section to play it safe.

Do not forget to restart or reload fail2ban to apply configuration changes using systemctl reload fail2ban.

The Result

After installing and configuring fail2ban, I immediately checked my log files at /var/log/fail2ban.log.

2016-11-13 20:56:56,064 fail2ban.actions        [7176]: NOTICE  [sshd] Ban 116.31.116.36

fail2ban detected the failed login attempts and banned the attacker. A quick check of my /var/log/auth.log assured me that the IP-Adress is now blocked by the firewall, as no new attempts can be seen for at least half an hour after fail2ban banned the client.