Fail2ban is an intrusion detection system that scans the log files to find malicious attacks on your servers. Fail2ban updates firewall rules on its own to block the IP addresses which are trying to exploit the server. Below are the steps to install and configure fail2ban on Ubuntu 18.04 server.
Get the newest versions of the packages and their dependencies, run the command below:
sudo apt-get update
Now install Fail2ban using the below command
sudo apt-get install fail2ban
To configure fail2ban use your custom configuration file 'jail.local' from 'jail.conf'
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Now edit the custom configuration file as below
You can edit the default section as below in which the settings will be applied for every service that does not have the entries overridden in the service's own section.
[DEFAULT] ... bantime = 10m findtime = 10m maxretry = 5 ...
The 'bantime’ represents the time that an IP address is banned before it can be allowed to access the service again. The 'findtime' is the maximum amount of time fail2ban should wait before banning an IP address if it has generated the maximum retries allowed for a particular service. The 'maxretry' indicates the number of failures that an IP should generate before it is banned.
To filter based on the sshd service, you could edit the '/etc/fail2ban/jail.local' file and add the options as below.
[sshd] enabled = true port = 22 filter = sshd logpath = /var/log/auth.log bantime = 10m findtime = 10m maxretry = 5
You could tweak the above values based on your requirement and also the port the service is running.Once configured you could check whether fail2ban is blocking the IP address using the below command.
fail2ban-client status sshd
If the configuration is correct, Then the output should be as below.
Status for the jail: sshd |- Filter | |- Currently failed: 11 | |- Total failed: 93 | `- File list: /var/log/auth.log `- Actions |- Currently banned: 11 |- Total banned: 22 `- Banned IP list: *.*.*.*
You will get the list of IP addresses banned in the 'Banned IP list'.