How to protect SSH using fail2ban on Ubuntu 16.04

If your SSH server is vulnerable to password-cracking attacks, this guide shows how to protect SSH from malicious login attempts using the fail2ban package on Ubuntu 16.04.

What is fail2ban?

fail2ban monitors log files for repeated failed login attempts and temporarily bans the offending IP addresses using firewall rules.

Installation

Update your package list and install fail2ban:

sudo apt-get update
sudo apt-get install fail2ban

Configuration

The main configuration file is /etc/fail2ban/jail.conf. It is recommended to create a local override file rather than editing the original:

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

Find the [sshd] section and verify or adjust:

[sshd]
enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 5
bantime  = 600
findtime = 600
  • maxretry: Number of failures before a ban is triggered.
  • bantime: Duration of the ban in seconds (600 = 10 minutes).
  • findtime: Time window in which maxretry failures must occur.

Starting and enabling fail2ban

sudo systemctl start fail2ban
sudo systemctl enable fail2ban

Checking status

View active bans and jail status:

sudo fail2ban-client status sshd

Unbanning an IP address

sudo fail2ban-client set sshd unbanip 203.0.113.5

On this page