How to install fail2ban on Ubuntu 20.04 LTS

Endrit Qerreti

Endrit Qerreti

fail2ban is a great tool when it comes to protecting your server from different attacks.

If you see a lot of authentication fail entries on the log file, this means someone is trying to brute force your server's password, and one of many ways of stopping these kind of attacks is by using fail2ban, so you can easily detect and ban them.

In this tutorial, you will learn how to install and configure fail2ban on Ubuntu 20.04 LTS to protect SSH server.

Step 1 - SSH to your Server

First, you must login to your server through ssh

ssh root@server

Step 2 - Install Fail2ban

To install fail2ban on Ubuntu 20.04 LTS, you can use the default package manager apt, as fail2ban is available on Ubuntu repositories.

sudo apt install fail2ban

Step 3 - Configure fail2ban

Next, you need to make a copy of the jail configuration file jail.conf

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

The command above will make a copy of the config file jail.conf to a new file called jail.local , this is done to avoid making changes to the main config file, we create a new file where we can make the necessary changes, just in case if something breaks, we still have the main config file.

Now, you can setup your own configurations, first you need to open the jail.local with a text editor

sudo nano /etc/fail2ban/jail.local

And add the following config into your config file

enabled - Allows you to enable or disable the rule

port - port of the SSH server

backend - the sshd backend

filter - filters sshd

logpath - The location of the log file

maxretry - Maximum retries you want to allow an IP before it gets banned

findtime - This is the time that fail2ban checks which IP(s) are bruteforcing, for example we have set findtime to 300, which means it will check every 5 minutes

bantime - How long the IPs are banned, on the config below we set 4w which means 4 weeks

The config below means, if an IP fails to connect to your server 3 times(maxretry = 3) within 5 minutes (findtime = 300), it will get banned for 4 weeks (bantime = 4w).

You can customize this config as you need.

[sshd]
enabled = true
port    = 22
backend = %(sshd_backend)s
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
findtime = 300
bantime = 4w
ignoreip = 127.0.0.1

Step 4 - Enable Fail2ban

Once you have configured fail2ban, now you need to make sure that fail2ban's process will start once your server boots up.

To do this, run the command below

systemctl enable fail2ban

Step 5 - Check Fail2ban logs

fail2ban.log is the file where fail2ban stores its logs. To read fail2ban logs in real time, you can use the tail command

tail -f /var/log/fail2ban.log

And you should see fail2ban actions, as shown in the image below

Conclusion

In this tutorial, you learned how to install and configure fail2ban to protect your SSH server on Ubuntu 20.04 LTS.