Fail2Ban on CentOS 7
Fail2ban is an intrusion prevention software for servers that tries to detect and prevent brute-force attacks by banning clients from all access after a certain event like a specific number of failed login attempts. It is not limited to a specific network daemon, but commonly used for services like SSH or mail servers.
This is a short guide on how to install and configure fail2ban on CentOS 7. It should also apply to RHEL and Scientific Linux 7.
Install fail2ban from EPEL repo
Fail2ban is packaged in the Extra Packages for Enterprise Linux (EPEL) Repository provided by the Fedora community. EPEL is one of the few (possibly the only) repository I would recommend to use as extrra repository for CentOS 7 and we do not want to install fail2ban manually. Hence we install/activate the repository and install the fail2ban package:
yum install epel-release yum install fail2ban
All options are in the file
/etc/fail2ban/jail.conf. However, it is not
recommended to modify this file–it may be overwritten by system updates–but to
create either a
jail.local in the same directory or separate files under
For now, let us use
vim -p /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
Go through the options in
jail.conf and copy over to
jail.local what you
want to modify. For example, a
jail.local could look like this:
[DEFAULT] # Ignore localhost as well as my own ip ignoreip = 127.0.0.1/8 18.104.22.168 # Increase bantime to 20min bantime = 1200 # Decrease retries to 3 maxretry = 3 # Enable sshd protection [sshd] enabled = true
Then start fail2ban and make sure it is started automatically:
systemctl enable fail2ban systemctl start fail2ban
Now test it using a PC you did not exclude before. Try logging in, use an incorrect password multiple times, … You should be banned for 20min now.
You can check banned IPs with
An up-to-date CentOS 7 should include the necessary SELinux rules for the fail2ban configuration used the this article by default. Nevertheless, it might be necessary to create your own rules based on the configuration or your operating system. Here is, how to generate a set of rules:
First, temporariy set SELinux to permissive mode to get some data we will later use to generate a policy rule.
This should ensure SELinux is not blocking fail2ban at all. What it will do, however, is log everything it would block. From these logs we can then create the policy. To get a comprehensive list of everything that fail2ban need to be doing, make sure to use it: Start it up, test it so an IP gets blocked, …
Now that we have done this, we need to get the rules from the
generate a policy:
grep fail2ban /var/log/audit/audit.log | \ audit2allow -M fail2ban-syslog
Enable this pilicy:
semodule -i fail2ban-syslog.pp
Finally, change SELinux back to be enforcing: