To secure your VPS server under Linux, a good practice is to install fail2ban to secure it. With fail2ban, your server will automatically block IP addresses that try to force a connection to the server. It is also able to monitor other services and will make decisions to ban an IP address based on the rules you have configured.

To operate, fail2ban will use the iptables firewall.

Install fail2ban

Let's go for the installation of fail2ban. We will use the package manager of our OS, you must have administrator rights on your server.

Installing fail2ban on Ubuntu

To install fail2ban the Ubuntu operating system:

sudo apt update && sudo apt upgrade

Installing fail2ban on Debian

To install fail2ban on the Debian operating system:

apt update && apt upgrade

Installing fail2ban on CentOS

To install fail2ban on CentOS operating system:

sudo yum -y install fail2ban 
sudo systemctl enable fail2ban
sudo systemctl start fail2ban

Fail2ban configuration

The fail2ban installation adds a default configuration file /etc/fail2ban/jail.conf. This file is overwritten when fail2ban is updated, so we will lose our changes if we customize this file.

Instead, we will copy the jail.conf file to a file called jail.local. By putting our configuration changes in this file, they will persist after any update. Both files are automatically read by fail2ban.

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

All you have to do is edit this last file to add the desired configuration. In this first step, you can leave the default configuration which is still effective to protect your server.

Check the list of banned IPs

Fail2ban relies on iptables, so you can use its commands to display the list of IPs that have been automatically banned:

sudo iptables -L

You can also use the fail2ban client:

sudo fail2ban-client status

To see the list of addresses that have been banned for attempting to connect to the server:

sudo fail2ban-client status sshd

Debug all IP addresses

To unban all IP addresses that have been automatically banned by fail2ban, use the command

sudo fail2ban-client status unban --all

Untagging an IP address

To deban a specific IP address from fail2ban, use the command. Don't forget to replace the IP address with the one you want to deban :)

sudo fail2ban-client unban 127.0.0.1