How to install Fail2Ban on CentOS 7 Linux
In our new tutorial, we want to demonstrate how to install Fail2Ban on CentOS 7 Linux.
Most linux servers by default listen on port 22 for ssh protocol connection. so this port heavily being targeted by attackers.
Fail2Ban recognizes these unwanted login attempts and block attackers IP address by using firewalld or iptables
Here is our environment:
OS: CentOS 7 on VMware
IP address: 192.168.147.128
1- Install prerequisites
fail2ban is available in epel repository. so first, we install it:
# yum install epel-release
2- Install fail2ban
Now we install fail2ban and also update SElinux policy, because here we have decided to keep SElinux in enforcing mode.
# yum install fail2ban fail2ban-systemd # yum update -y selinux-policy*
3- Configure fail2ban
Now we tune some setting for fail2ban. main fail2ban configuration file is jail.conf.
but here we work on jail.local file, because this file overrides jail.conf and make your configurations safe after fail2ban upgrade in future:
# cp -pf /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
many options in jail.local file are self explanatory and clear and do not need to explain it.
now we create a file to protect sshd and put the following content in it:
# vim /etc/fail2ban/jail.d/sshd.local
[sshd] enabled = true port = ssh action = firewallcmd-ipset logpath = %(sshd_log)s maxretry = 5 bantime = 86400
enabled parameter allow ssh protection. if you want to disable protection, simply set it to false.
port is set to default ssh port (port 22). if you have changed default ssh port, replace ssh with it.
action is an action that must be taken upon detecting an IP address.
logpath is the path that fail2ban scan it and tries to find unwanted logins.
maxretry is used to set the maximum limit for failed login entries.
bantime is the duration that an IP will be banned.
4- Start fail2ban
before start fail2ban service, make sure firewalld service has been started:
# systemctl enable firewalld # systemctl start firewalld
now enable and start fail2ban:
# systemctl enable fail2ban # systemctl start fail2ban
5- Useful fail2ban commands
to find list of IP addresses that have been banned issue:
# iptables -L -n
to remove an IP address from the banned list, run below command. The name “sshd” is the name of the jail, in this case the “sshd” jail that we configured above:
# fail2ban-client set sshd unbanip IPADDRESS