Install Fail2ban on Ubuntu 20.04

Fail2ban is a tool that allows to protect machine from brute-force attacks. This tool monitors log files and counts failed connection attempts. If the number of failed connection attempts reaches a certain predefined threshold then corresponding IP address can be blocked for specific period.

This tutorial shows how to install Fail2ban on Ubuntu 20.04.

Install Fail2ban

Run the following command to update the package lists:

sudo apt update

Install Fail2ban

sudo apt install -y fail2ban

After the installation is finished, we can check Fail2ban version:

fail2ban-server --version

Fail2ban service was started automatically. We can verify status of the service with command:

sudo service fail2ban status

Also you can stop, start and restart the Fail2ban service:

sudo service fail2ban stop
sudo service fail2ban start
sudo service fail2ban restart

Fail2ban has /etc/fail2ban/jail.conf configuration file. However, it is not recommended to modify this file directly. Instead we can copy the jail.conf to jail.local and modify the .local file.

sudo cp /etc/fail2ban/jail.{conf,local}

Now you can open jail.local file and change various settings such as bantime, maxretry, etc.

sudo nano /etc/fail2ban/jail.local

The bantime is the duration that IP address is banned. By default, the bantime is equal to 10 minutes. The maxretry is the number of failed connection attempts before IP address is banned. By default, the maxretry is set to 5.

/etc/fail2ban/jail.local

bantime  = 10m
maxretry = 5

Don’t forget to restart the service after doing changes.

Testing Fail2ban

You can try to connect to your machine via SSH from different machine by entering invalid password 5 times.

The fail2ban-client command can be used to check the jail status:

sudo fail2ban-client status sshd

Example of the output:

Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     5
|  `- File list:        /var/log/auth.log
`- Actions
   |- Currently banned: 1
   |- Total banned:     1
   `- Banned IP list:   192.168.0.149

Uninstall Fail2ban

If you want to completely remove Fail2ban, execute the following command:

sudo apt purge --autoremove -y fail2ban

During Fail2ban installation, additional package whois has been installed. It can be removed with command:

sudo apt purge --autoremove -y whois

You can also remove Fail2ban related directories:

sudo rm -rf /etc/fail2ban
sudo rm -rf /run/fail2ban

Leave a Comment

Your email address will not be published. Required fields are marked *