Introduction

Fail2Ban is a powerful security tool designed to protect Linux-based servers from brute-force attacks. It monitors log files for suspicious activity and bans malicious IP addresses using firewall rules. This guide will walk you through the process of installing, configuring, and using Fail2Ban on an Ubuntu system.

Installing Fail2Ban

First, update your package list and install Fail2Ban using the following commands:

sudo apt update
sudo apt install fail2ban -y

Once installed, start and enable the Fail2Ban service:

sudo systemctl start fail2ban
sudo systemctl enable fail2ban

Сonfiguring Fail2Ban

The default configuration file for Fail2Ban is located at /etc/fail2ban/jail.conf. However, it is recommended to create a custom configuration file to prevent changes from being overwritten during updates.

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

Edit the configuration file using a text editor:

sudo nano /etc/fail2ban/jail.local

Key Configuration Settings

  • bantime: Defines the duration (in seconds) for which an IP address will be banned.
  • findtime: Specifies the time window for detecting multiple failed attempts.
  • maxretry: Number of failed login attempts before an IP gets banned.
  • ignoreip: List of trusted IP addresses that should not be banned.

Example settings:

[DEFAULT]
bantime = 600
findtime = 600
maxretry = 5
ignoreip = 127.0.0.1/8

Enabling Fail2Ban for SSH

To enable Fail2Ban for SSH protection, ensure the following section is present in jail.local:

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

Save the file and restart Fail2Ban:

sudo systemctl restart fail2ban

Checking Fail2Ban Status

To verify that Fail2Ban is working correctly, use the following command:

sudo fail2ban-client status

To check the status of a specific jail (e.g., SSH):

sudo fail2ban-client status sshd

Unbanning an IP Address

If a legitimate IP address gets banned, you can unban it using:

sudo fail2ban-client set sshd unbanip <IP_ADDRESS>

Conclusion

Fail2Ban is an essential tool for enhancing server security by preventing brute-force attacks. By configuring it properly, you can significantly reduce unauthorized access attempts and protect your Ubuntu server from potential threats.