If you are looking for ways to secure your Ubuntu server, fail2ban is one of them. The way fail2ban works is by detecting unusual login activity such as brute force, then banning the suspicious IP. Fail2ban is a daemon that can be used to monitor the logs of services and ban clients that repeatedly fail authentication checks.
First, we update the package in the repository first, then we install the fail2ban package.
sudo apt-get update
sudo apt-get install fail2ban -y
Once installed, run fail2ban with the command
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
Configure fail2ban
There are two fail2ban configuration files, jail.conf
and jail.local
. jail.conf
is fail2ban's default file, we can directly edit it there. But the risk is that when fail2ban is upgraded (for example, there is a new package in the repository), the configuration will be lost and replaced with a new one.
The solution is to use jail.local
. The file will not be lost even if you upgrade fail2ban.
sudo nano /etc/fail2ban/jail.local
Then fill in it
[DEFAULT]
ignoreip = 127.0.0.1/8 XX.XX.XX.XX # Your IP address
ignorecommand =
bantime = 604800
findtime = 100
maxretry = 2
enabled = false
Note
bantime shows how long the attacker will be banned. The unit is seconds. If you want to do a permanent ban, fill in the value to "-1". 604800 is for 7 days.
maxretry specifies the number of failed attempts allowed. here I make a rule if you fail to log in twice then the IP will be blocked.
enabled false means that this default profile should be disabled, kindly check jail.conf
to see why!
findtime here shows the time limit of failed attempts allowed before being banned. From my example above, it means that if there is a failed attempt twice within 100 seconds, then the IP will be banned for 604800 seconds.
Still in jail.local
file, enter rules to secure the ssh service.
[sshd]
enabled = true
port = ssh
action = iptables-multiport[name="bannedssh", port="80,443,22"]
logpath = %(sshd_log)s
maxretry = 3
The rule above is to secure the ssh service so that if someone tries to brute force, the attacker's IP will be banned after 3 failed logins for 7 days.
For the port section, if you use a custom port, just change it. For example, if you use port 2537 for ssh then the rule will be port = 2537
Next, let's restart fail2ban.
sudo systemctl restart fail2ban
List Blocked IP
To get a list of blocked IPs in your server, run the following command:
fail2ban-client status sshd
Unblock IP
To unblock banned IPs, run the following command
fail2ban-client set sshd unbanip 111.222.333.444
For other services, such as blocking brute force on the mysql port, brute-force in-app login, etc, you can start to add in your jail.local
Thanks for reading!