Introduction
Any Linux server connected to the internet with SSH port 22 exposed will inevitably face automated brute-force attacks. Bots constantly scan for open SSH ports and attempt to guess usernames and passwords thousands of times per minute. While disabling password authentication in favor of SSH keys is the best defense, another critical layer of security is Fail2Ban. Fail2Ban is a log-parsing application that monitors system logs for malicious activity and dynamically alters firewall rules to ban offending IP addresses. This guide demonstrates how to configure Fail2Ban on Ubuntu.
Prerequisites
You need an Ubuntu server with root or sudo privileges. Ensure that a firewall (such as UFW) is installed and active, as Fail2Ban relies on it to block traffic.
Step 1: Install Fail2Ban
Install the software from the default Ubuntu repositories:
sudo apt update
sudo apt install fail2ban
The service will start automatically after installation. You can verify its status using sudo systemctl status fail2ban.
Step 2: Configure the Local Configuration File
Fail2Ban’s default configuration file is located at /etc/fail2ban/jail.conf. However, you should never edit this file directly, as package updates will overwrite it. Instead, copy it to jail.local, which Fail2Ban reads after jail.conf to apply overrides.
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Open the new file with your preferred text editor (e.g., nano):
sudo nano /etc/fail2ban/jail.local
Step 3: Adjust Global Settings
In the [DEFAULT] section of jail.local, configure the core parameters:
ignoreip: Uncomment this line and add your own IP address or office subnet (e.g.,127.0.0.1/8 ::1 192.168.1.0/24 203.0.113.50). This ensures you do not accidentally ban yourself if you mistype your password.bantime: The duration an IP is banned. The default is usually 10m (10 minutes). Change it to something more substantial, like1hor1d.findtimeandmaxretry: These define the trigger condition. Ifmaxretry(e.g., 5) failures occur within thefindtimewindow (e.g., 10m), the IP is banned.
Step 4: Enable the SSH Jail
Scroll down to the [sshd] section in the file. This is the specific “jail” for the SSH daemon.
Ensure it is enabled by adding the following line beneath the [sshd] header:
enabled = true
If you run SSH on a custom port (e.g., 2222), you must specify it here:
port = 2222
Save and close the file (Ctrl+O, Enter, Ctrl+X in nano).
Step 5: Restart and Monitor
Restart the Fail2Ban service to apply your new configuration:
sudo systemctl restart fail2ban
To check the status of your jails and see if any IP addresses have been blocked, use the fail2ban-client command:
sudo fail2ban-client status
To view the specifics of the SSH jail, including the list of currently banned IPs:
sudo fail2ban-client status sshd
If you ever need to manually unban an IP address that was caught accidentally, you can do so easily:
sudo fail2ban-client set sshd unbanip 198.51.100.12