How to install Fail2Ban on CentOS 7


Fail2ban scans log files and bans IPs that show the malicious signs — too many password failures, seeking for exploits, etc.

The commands are executed with root privilege.

Update the software packages in the system using the command

#yum update -y

Now install fail2ban in the server running the below command,

#yum install fail2ban fail2ban-systemd

Update the selinux policy by

#yum update -y selinux-policy*

After the installation,we have to configure and customize the software with a jail.local configuration file,so even though the default jail.conf modified by package upgrades our changes will be safe.All default options will be taken from the jail.conf file and all the thing which you wish to override will be taken from jail.local file.

#cp -pf /etc/fail2ban/jail.conf  /etc/fail2ban/jail.local

Open the jail.local using vim editorand you can set limit to prevent a ban on one or many IP addresses, set bantime duration, etc. Example is given below.

#vim /etc/fail2ban/jail.local
# "ignoreip" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not
# ban a host which matches an address in this list. Several addresses can be
# defined using space (and/or comma) separator.
ignoreip =

# External command that will take an tagged arguments to ignore, e.g. <ip>,
# and return true if the IP is to be ignored. False otherwise.
# ignorecommand = /path/to/command <ip>
ignorecommand =

# "bantime" is the number of seconds that a host is banned.
bantime  = 600

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime  = 600

# "maxretry" is the number of failures before a host get banned.
Maxretry = 5

We are gonna add a jail file to protect SSH.

Create a file /etc/fail2ban/jail.d/sshd.local using vim and addthe following lines to the file.

#vim /etc/fail2ban/jail.d/sshd.local
enabled = true
port = ssh
#action = firewallcmd-ipset
logpath = %(sshd_log)s
maxretry = 5
bantime = 7200

Now enable and start the fail2ban by executing below commands,

#systemctl enable fail2ban
#systemctl start fail2ban 

To track the failed login attempts,use the given command,

#cat /var/log/secure | grep 'Failed password'

And we will get an output like this:

Apr 19 13:08:48 server sshd[21017]: Failed password for root from port 53188 ssh2
Apr 19 13:08:55 server sshd[21017]: Failed password for root from port 53188 ssh2
Apr 19 13:08:59 server sshd[21017]: Failed password for root from port 53188 ssh2

Command to check the status of the Fail2Ban jails and th output iwill be similar as,

# fail2ban-client status
|- Number of jail:	1
`- Jail list:	sshd

We can remove the ban of the ip address using the command

#fail2ban-client set sshd unbanip ‘IPADDRESS’