Server hardening using “fail2ban” tool
Fail2ban is an open-source tool to prevent servers from brute force attacks. This tool will scan server log files and if found any suspicious attempts the fail2ban will block the particular IP for a specific time.
Fail2ban also works to prevent dos or DDoS attacks, malicious traffic attacks on websites etc. Depending on the configuration of jails it will block the specific IP addresses through a firewall or iptables. You can also configure for mail notification when any IP is blocked by fail2ban it will send you notifications. You can also ignore(whitelist) any specific IP(s) or blacklist manually.
Let’s see how to configure fail2ban in CentOS.
Step 1: Login to your server and install fail2ban using yum.# yum install epel-release -y
# yum install fail2ban
Step 2: Start and enable the service.
# systemctl start fail2ban
# systemctl enable fail2ban
Step 3: Copy the default configuration file to create a new jail local config file.
# cd /etc/fail2ban/
# cp jail.conf jail.local
# vim jail.local
Step 4: Configure jail file to prevent brute force attacks.
# vim jail.local
[SSH]
port = ssh
logpath = %(sshd_log)s
banaction = iptables-multiport
maxretry = 3
findtime = 300
bantime = 600
enabled = true
filter = sshd
Save the file and restart the service.
# systemctl restart fail2ban.service
In the above jail.local configuration, we set up like if anyone tried and failed remote ssh login more than 3 times in 300 seconds then their IP should block for next 600 seconds. It means fail2ban will block that source IP in our server iptables. So they cannot try the fourth attempt through ssh from the same IP.
You can also add “ignoreip” line to whitelist any IP(s).
Step 5: Check fail2ban client status using below command.
# root@fail2ban]# fail2ban-client status
Status
|- Number of jail: 2
`- Jail list: SSH
You can also check the particular service ban configuration details by using this command.
[root@fail2ban]# fail2ban-client status SSH
Status for the jail: SSH
|- Filter
| |- Currently failed: 0
| |- Total failed: 0
| - File list: /var/log/secure
- Actions
|- Currently banned: 0
|- Total banned: 0
`- Banned IP list:
If any IPs are banned then those IPs will show here in the above command output “Banned IP list:”
You can also ban/unban known blacklisted IP(s) manually using the below command.
# fail2ban-client set SSH banip <IPAddress>
# fail2ban-client set SSH unbanip <IPAddress>
When IP blocked by fail2ban in iptables, it will show like this.
Chain f2b-SSH (1 references)
target prot opt source destination
REJECT all -- <blocked IP> 0.0.0.0/0 reject-with icmp-port-unreachable
RETURN all -- 0.0.0.0/0 0.0.0.0/0
Note: Once set up everything, test the configuration weather fail2ban is working properly or not. Try to log in from another server to your current server with the wrong passwords/users and after three attempts fail2ban should ban your attempts.