11.12.2024

How to Install and Configure Fail2ban on Ubuntu 20.04

Fail2ban is designed to protect open ports and running services on the server. It monitors unsuccessful authorization attempts and blocks the source IP address for a certain time. This significantly reduces the likelihood of server hacking due to automatic means, for example, brute force login and password.
In this tutorial we will install and configure Fail2ban on Ubuntu 20.04.

Fail2ban installation

To install Fail2ban use this command:

apt install fail2ban

It starts automatically after installation. To check the service status use this command:

systemctl status fail2ban

Fail2ban configuration

To change the default ban settings for all services, make a copy of the jail.conf file.

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

Open the jail.local file and go to the [DEFAULT] section. For example, let's set the ban time to 3600 minutes.

bantime = 3600m

To see all the available rules, go to the JAILS section. For example:

[nginx-http-auth]

After changing the file, restart the service.

systemctl restart fail2ban

Adding and configuring rules

There is a /etc/fail2ban/jail.d/ folder for managing active rules. You can create a separate file for each of them. For example, nginx-http-auth.conf. The second way is to insert configuration into the existing defaults-debian.conf file. Simply add these lines there:

[nginx-http-auth]
enabled = true

You can add individual parameters for each rule here.
Let's set the IP address to ignore in the ignoreip parameter, the time for the ban is 2400 minutes, and the number of failed authorization attempts is 10.

ignoreip = 10.10.10.5
bantime = 2400m
maxretry = 10

Save and close the file and restart the service.

systemctl restart fail2ban

Using fail2ban-client

There is a Fail2ban client for managing its rules. Keep in mind that all changes made here will be reset after the system reboot or service restart. To view active rules use this command:

fail2ban-client status

To see jail statistics use this command with the name you need instead of sshd:

fail2ban-client status sshd

To activate a rule, use its name from the configuration file and the command:

fail2ban-client add nginx-http-auth

Then start it.

fail2ban-client start nginx-http-auth

To view all available commands:

fail2ban-client -h