How To Protect SSH With Fail2Ban on CentOS 7

To install Fail2ban, The EPEL repository needs to be installed first.

sudo yum install epel-release

Note: It will prompt for several permission Press "y" and "Enter" to continue.

Next, install fail2ban package.

sudo yum install fail2ban

Note: This will prompt for several permissions, Press "y" and "Enter" to continue.

To enable fail2ban.

sudo systemctl enable fail2ban

Configuring local file settings.

Jail.conf contains a section which Configuration settings can be done for the fail2ban, we are not going edit this file because package upgrade can overwrite this file.

Jail.local contains same section where jail.conf file contains and it can override this values.

/etc/fail2ban/jail.d/ can override both jails.local and jails.conf files

First we begin with the jail.local file.

Open the file for editing,

sudo vi /etc/fail2ban/jail.local

Add the following content,

[DEFAULT]
# Ban hosts for one hour:
bantime = 3600

# Override /etc/fail2ban/jail.d/00-firewalld.conf:
banaction = iptables-multiport

[sshd]
enabled = true

If server uses firewalld instead of iptables, simply comment the banaction line

Restarting the Fail2Ban service to load new settings.

sudo systemctl restart fail2ban

To check status

sudo fail2ban-client status

sample output:

Status
|- Number of jail:      1
`- Jail list:   sshd

To view detailed information of sshd

sudo fail2ban-client status sshd

Modify the content of the file /etc/fail2ban/jail.local

sudo vi /etc/fail2ban/jail.local

Setting ban time

#ban time setting to 600sec
bantime = 600 

Setting conditions to ban a client

findtime = 600 
maxretry = 3

In this example, the client is blocked if he makes 3 unsuccessful login attempts with in 10 mins.

Set-up email notification

# repace your mail id to get alert
destemail = root@localhost 
sendername = Fail2Ban@servername
mta = sendmail

To configure mail alerts, set the following parameters such as,

  • destemail is the email receiver
  • sendername is the sender of the email
  • mta will be the mail service used to send the email

To check the details of banned IPs and number of login attempts,

sudo fail2ban-client status sshd

Sample Output:

[root@my ~]# fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 4
|  |- Total failed:     31
|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned: 2
   |- Total banned:     2
   `- Banned IP list:   218.92.0.148 117.196.250.234