How to Install Fail2Ban on AlmaLinux 9

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

yum install epel-release

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

Next, install the fail2ban package.

yum install fail2ban

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

Set fail2ban to start on boot automatically,

systemctl enable fail2ban

Configuring local file settings.

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

Jail.local contains the same section where jail.conf file contains and it can override these 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,

nano /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 the server uses firewalld instead of iptables, simply comment the banaction line_

Restarting the Fail2Ban service to load new settings.

systemctl restart fail2ban

To check status

fail2ban-client status

Output:

[root@server ~]# fail2ban-client status
Status
|- Number of jail:      1
`- Jail list:   sshd
[root@server ~]# fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 7
|  |- Total failed:     158
|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned: 5
   |- Total banned:     5
   `- Banned IP list:   36.129.3.143 64.225.35.76 61.177.172.124 61.177.172.147 218.92.0.221

To view detailed information of sshd

fail2ban-client status sshd

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

nano /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 within 10 mins.

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

fail2ban-client status sshd

Output:

  [root@server ~]# fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed: 0
|  |- Total failed:     163
|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned: 6
   |- Total banned:     6
   `- Banned IP list:   36.129.3.143 64.225.35.76 61.177.172.124 61.177.172.147                            218.92.0.221 61.177.172.114 

DONE!