How to Install and Configure Fail2Ban on Ubuntu

Fail2Ban is a vital security tool that protects Linux servers from brute-force attacks by monitoring logs and banning malicious IPs. This guide simplifies installing and configuring Fail2Ban on Ubuntu, with practical examples and tips to secure your VPS or dedicated server effectively.

Why Use Fail2Ban?

Fail2Ban enhances server security by:

  • Blocking IPs after repeated failed login attempts.

  • Protecting services like SSH, web servers, or email.

  • Reducing the risk of unauthorized access.

  • Automating firewall rules for efficiency.

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 a straightforward yet powerful tool to secure your Ubuntu server against brute-force attacks. By installing, configuring, and testing it with the examples above, you can protect services like SSH and reduce risks. Paired with AvaHost’s reliable VPS or dedicated servers, Fail2Ban ensures your hosting environment stays secure and resilient with minimal effort.