Configure Fail2ban to Protect SSH on Ubuntu

This guide provides a straightforward walkthrough on how to install and configure Fail2ban on an Ubuntu Linux server to protect the SSH service from brute-force attacks. You will learn how to install the package, set up a local configuration file, define specific banning rules for SSH, and use the Fail2ban client to monitor and manage banned IP addresses.

Step 1: Install Fail2ban

First, update your local package index and install Fail2ban using the APT package manager.

sudo apt update
sudo apt install fail2ban -y

Once installed, the Fail2ban service will start automatically. You can verify its status with:

sudo systemctl status fail2ban

Step 2: Create a Local Configuration File

Fail2ban keeps its default configuration in /etc/fail2ban/jail.conf. Instead of editing this file directly—as it can be overwritten during package updates—you should create a copy named jail.local for your custom rules.

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

Step 3: Configure SSH Protection Rules

Open the newly created jail.local file in a text editor:

sudo nano /etc/fail2ban/jail.local

Scroll down to the [DEFAULT] section to configure global settings, or locate the [sshd] section to apply rules specifically to the SSH service.

To secure SSH, ensure the [sshd] block looks like this:

[sshd]
enabled = true
port    = ssh
filter  = sshd
logpath = /var/log/auth.log
maxretry = 5
findtime = 10m
bantime  = 1h

Here is what these parameters mean: * enabled: Set to true to activate protection for the SSH daemon. * port: The port SSH is running on (default is ssh / 22). If you use a custom port, change this to your custom port number. * logpath: The log file that Fail2ban monitors for failed login attempts. On Ubuntu, this is /var/log/auth.log. * maxretry: The number of failed login attempts allowed before an IP address is banned. * findtime: The window of time during which the failed attempts must occur to trigger a ban. * bantime: The duration for which an offending IP address is blocked (e.g., 10m for 10 minutes, 1h for 1 hour, or 1d for 1 day).

Save and close the file (in nano, press Ctrl+O, Enter, then Ctrl+X).

Step 4: Restart Fail2ban

Apply the configuration changes by restarting the Fail2ban service:

sudo systemctl restart fail2ban

To ensure Fail2ban starts automatically when the server boots, run:

sudo systemctl enable fail2ban

Step 5: Monitor and Manage Fail2ban

You can check the status of the Fail2ban service and see which jails are active using the command-line tool fail2ban-client:

sudo fail2ban-client status

To view detailed statistics for the SSH jail, including currently banned IP addresses, run:

sudo fail2ban-client status sshd

If you ever need to manually unban an IP address, use the following command:

sudo fail2ban-client set sshd unbanip <IP_ADDRESS>