Fail2Ban: protect your server
Fail2ban is for me one of my favorite security prevention tool for a linux server. In general, it's scanning your log files. If the defined regular expression and additional rules matches, the IP will be banned.
For example, if a bot trying to login via ssh into your server for a few times, fail2ban will ban this IP. The bot gets a timeout for the next attempts. You can specify, among other things, the bantime, findtime and maxretry. In this post, I want to show you how to install and configure this powerful tool.
How can I install and configure fail2ban?
First of all, fail2ban can be installed with the native package manager. In this example, I will use yum on an CentOS system:
yum install fail2ban
Start the service with the following command:
systemctl start fail2ban
To start fail2ban on every boot, you also need to enable the service:
systemctl enable fail2ban
Common filters are already integrated. These filters can be modified in /etc/fail2ban/filter.d/
It's probably a good idea to modify the default settings. The default values can be viewed in /etc/fail2ban/jail.conf
. If you don't set a specific configuration for your jail, these parameters will be used. To change the settings, you have to edit /etc/fail2ban/jail.local
.
bantime = 3600 # Ban hosts for one hour:
findtime = 600 # time period to find host (10 min)
banaction = iptables-multiport
...
We now want to create a new jail for our nginx web server. We want to timeout IPs, which have a high amount of forbidden responses. This can also be done in the file. Copy&Paste the following code to enable an nginx forbidden filter:
...
[nginx-forbidden]
enabled = true
port = http,https
filter = nginx-forbidden
logpath = /var/log/nginx/*error*.log
Check the configuration with:
fail2ban-client -d
To activate these modifications, the service needs to be restarted:
systemctl restart fail2ban
A few minutes/hours later, you can check if the ban of a jail took action:
fail2ban-client status
What do to, if I banned myself?
If you banned yourself, you can connect with another IP (Smartphone Hotspot or reconnect to your internet provider) and unban your previous IP:
fail2ban-client set JAILNAME unbanip YOUR_IP
Furthermore, you can exclude your IP in the configuration file /etc/fail2ban/jail.local
: in the [DEFAULT]
section add
[DEFAULT]
ignoreip = 127.0.0.1/8 YOUR_IP
...
In this tutorial you installed and started fail2ban. You also added a new filter and activated it.
I recommend to set up more jails to protect from server attacks. I will publish a few more guides.
Tested on:
- OS: CentOS 7
- fail2ban: 0.9.6
Credits:
- Post photo by Jose Fontano on Unsplash