Install and Configure Fail2ban on AlmaLinux 8: Best Setup
In this article, we will guide you through the process of installing and configuring Fail2ban on AlmaLinux 8. Fail2ban is a powerful, open-source intrusion prevention software framework that protects your Linux system from brute-force attacks and other automated malicious activities. It achieves this by monitoring service logs for suspicious patterns, such as repeated failed login attempts, and automatically blocking the offending IP addresses using firewall rules. This article provides a step-by-step guide to setting up Fail2ban on AlmaLinux 8 for optimal security.
You can now proceed to the guide steps below on the Orcacore website to complete the Fail2ban setup on AlmaLinux 8.
Before we begin, it’s crucial to ensure your server is properly configured with a non-root user with sudo privileges and a basic firewall. If you haven’t already done so, refer to our article on the Initial Server Setup with AlmaLinux 8 for detailed instructions.

1. Install Fail2ban on AlmaLinux 8
The Fail2ban package is readily available in the AlmaLinux default repository. To begin, update your local package index to ensure you have the latest information:
sudo dnf update -y
Next, install Fail2ban using the following command:
sudo dnf install fail2ban -y
Once the installation is complete, start and enable the Fail2ban service to ensure it runs automatically on system boot:
sudo systemctl enable --now fail2ban
Finally, verify that the service is active and running correctly:
sudo systemctl status fail2ban
The output should resemble the following:
With Fail2ban now running on your AlmaLinux 8 system, let’s proceed to configure it for optimal security.
2. Configure Fail2ban on AlmaLinux 8
The default Fail2ban installation includes two key configuration files: /etc/fail2ban/jail.conf
and /etc/fail2ban/jail.d/00-firewalld.conf
. To avoid directly modifying the default configuration, it’s best practice to create a .local
configuration file that overrides specific settings.
First, copy the jail.conf
file to create jail.local
:
sudo cp /etc/fail2ban/jail.{conf,local}
Now, open the jail.local
file with your preferred text editor (e.g., vi
, nano
):
sudo vi /etc/fail2ban/jail.local
Within this file, you can customize various settings to suit your security needs.
Fail2ban Whitelist IPs
The ignoreip
directive allows you to specify IP addresses, IP ranges, or hosts that should be excluded from banning. This is crucial for whitelisting your own IP address and those of trusted machines. Locate the ignoreip
line, uncomment it by removing the #
, and add your desired IP addresses, separated by spaces:
ignoreip = 127.0.0.1/8 ::1 123.123.123.123 192.168.1.0/24
Next, configure the ban duration using the bantime
directive. This determines how long an IP address will be banned after triggering Fail2ban’s filters. The default is 10 minutes (10m), but you can adjust it as needed:
bantime = 1d
Setting bantime
to a negative number will result in a permanent ban.
The findtime
directive specifies the time window within which failed login attempts are counted. The maxretry
directive defines the maximum number of failed attempts allowed within the findtime
before an IP address is banned. The default value of 5 is generally sufficient.
Fail2ban Email Alerts
Fail2ban can be configured to send email alerts whenever an IP address is banned. To enable this feature, you need a configured SMTP server on your AlmaLinux 8 system. Modify the action
directive to include email functionality. The default action only bans the IP:
action = %(action_mw)s
To receive email alerts with relevant logs, change the action
to:
action = %(action_mwl)s
Adjust the sender and recipient email addresses accordingly:
destemail = admin@orcacore.com
sender = root@orcacore.com
Fail2ban jails
Fail2ban utilizes the concept of "jails" to define the services it monitors. A jail specifies a service, its associated log files, and the filters to apply.
By default, most Fail2ban jails are disabled. To enable a jail, such as the one for SSH (sshd), locate the [sshd]
section and add enabled = true
after the jail title:
[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
Once you have made your desired changes, save and close the jail.local
file.
To apply the new configuration, restart the Fail2ban service:
sudo systemctl restart fail2ban
3. How To Use Fail2ban on AlmaLinux 8?
Fail2ban includes a command-line tool called fail2ban-client
that allows you to interact with the service.
To view a list of available options, use the following command:
fail2ban-client -h
This tool can be used to ban and unban IP addresses, modify settings, restart the service, and perform other administrative tasks.
To check the status of a specific jail, such as sshd
, use the following command:
sudo fail2ban-client status sshd
To unban an IP address from a jail, use the following command:
sudo fail2ban-client set sshd unbanip 23.34.45.56
To manually ban an IP address, use the following command:
sudo fail2ban-client set sshd banip 23.34.45.56
Conclusion
This article has demonstrated how to install and configure Fail2ban on AlmaLinux 8. You’ve learned how to set up Fail2ban to protect your server from brute-force attacks by monitoring logs and automatically blocking malicious IP addresses. Fail2ban enhances security by creating firewall rules to prevent repeated failed login attempts, making your server more secure.
Hope you enjoy it. Please subscribe to us on Facebook, YouTube, and Twitter.
Also, you may like to read the following articles:
Whitelist IPs in Fail2ban on Ubuntu and Debian
Installing Fail2ban on Debian 12
Set up Fail2ban on AlmaLinux 9
Setup Guide For Fail2ban on Ubuntu 22.04
Install Fail2ban on Rocky Linux 8
FAQs
How does Fail2Ban work?
It scans log files for failed login attempts and temporarily blocks offending IPs using firewall rules.
Where is the Fail2Ban configuration file located?
The main config file is /etc/fail2ban/jail.conf
, but you should create a custom file /etc/fail2ban/jail.local
to override settings.
Does Fail2Ban work with Firewalld?
Yes, Fail2Ban integrates with Firewalld to block malicious IPs automatically.
Alternative Solutions to Brute-Force Attack Prevention
While Fail2ban is an excellent tool for mitigating brute-force attacks, it’s not the only approach. Here are two alternative solutions:
1. Using a Web Application Firewall (WAF)
A Web Application Firewall (WAF) sits between your server and the internet, inspecting HTTP traffic and filtering out malicious requests. A WAF can identify and block brute-force attempts at the application level, often before they even reach your server’s authentication mechanisms. Unlike Fail2ban, which primarily works by analyzing logs after failed attempts, a WAF can proactively prevent attacks based on traffic patterns and known attack signatures. Many WAFs offer rate limiting, challenge-response mechanisms (like CAPTCHAs), and other security features that make brute-forcing significantly harder.
Explanation:
A WAF provides a more holistic approach to security compared to Fail2ban. It operates at the application layer, analyzing the actual HTTP requests. This allows it to detect sophisticated attacks that might bypass Fail2ban’s log analysis. For example, a WAF can identify attempts to exploit known vulnerabilities, inject malicious code, or bypass authentication mechanisms. Furthermore, WAFs often come with pre-configured rulesets that address common web application vulnerabilities, making them easier to deploy and manage.
Implementation (Example using ModSecurity with Apache):
While a full WAF configuration is beyond the scope of this article, here’s a basic example of how to implement rate limiting using ModSecurity, a popular open-source WAF, on an Apache web server.
First, install ModSecurity and the OWASP Core Rule Set (CRS):
sudo dnf install mod_security mod_security-apache
sudo dnf install owasp-modsecurity-crs
Then, enable ModSecurity in your Apache configuration. This often involves adding or modifying lines in /etc/httpd/conf.d/mod_security.conf
or similar. Refer to your distribution’s ModSecurity documentation for exact steps.
Next, create a ModSecurity rule to limit the number of login attempts per IP address within a specific timeframe. You’ll need to edit your virtual host configuration file (e.g., /etc/httpd/conf/httpd.conf
or /etc/httpd/conf.d/your_site.conf
) and add something similar to this within the <VirtualHost>
block:
<IfModule mod_security2.c>
SecRuleEngine On
SecAction "initcol:ip=%{REMOTE_ADDR},nolog,pass,initcol:user=%{REMOTE_ADDR},nolog,pass"
<Location /login>
SecRule "REQUEST_METHOD" "POST" "chain,id:12345,msg:'Login Rate Limit',phase:2,deny,status:429,log,auditlog,setvar:ip.login_attempts=+1,expirevar:ip.login_attempts=60,chain"
SecRule "ip.login_attempts" "@gt 5" "t:none,nolog,pass"
</Location>
</IfModule>
Explanation of the Rule:
SecRuleEngine On
: Enables the ModSecurity engine.SecAction "initcol:ip=%{REMOTE_ADDR},nolog,pass,initcol:user=%{REMOTE_ADDR},nolog,pass"
: Initializes a collection named "ip" and "user" to store IP-based data.<Location /login>
: Specifies that this rule applies to the/login
URL.SecRule "REQUEST_METHOD" "POST"
: Only applies to POST requests (typically used for logins).chain
: Links this rule to the next rule.id:12345
: A unique ID for the rule.msg:'Login Rate Limit'
: A message logged when the rule is triggered.phase:2
: Specifies that the rule is executed in phase 2 (after request headers are read).deny,status:429
: Denies the request with a 429 status code (Too Many Requests).log,auditlog
: Logs the event.setvar:ip.login_attempts=+1
: Increments thelogin_attempts
variable in the "ip" collection for the current IP.expirevar:ip.login_attempts=60
: Sets thelogin_attempts
variable to expire after 60 seconds.SecRule "ip.login_attempts" "@gt 5"
: Checks if the number of login attempts exceeds 5 within 60 seconds. If so, the previous rule will trigger, denying the request.
This is a simplified example. A production WAF configuration will involve more complex rulesets to address a wider range of threats.
2. Implementing Two-Factor Authentication (2FA)
Two-Factor Authentication (2FA) adds an extra layer of security to the login process. Even if an attacker manages to guess or steal a user’s password, they will still need a second factor, such as a code generated by an authenticator app or sent via SMS, to gain access. This significantly reduces the risk of successful brute-force attacks because the attacker needs to compromise two independent authentication factors.
Explanation:
2FA is a highly effective defense against brute-force attacks because it makes password cracking alone insufficient for gaining access. The second factor provides a strong barrier, especially if it’s a time-based one-time password (TOTP) generated by an authenticator app. Even if an attacker has the password, they cannot log in without the constantly changing code.
Implementation (Example using Google Authenticator with SSH):
-
Install Google Authenticator PAM module:
sudo dnf install google-authenticator
-
Configure Google Authenticator for the user:
Log in as the user you want to enable 2FA for and run:
google-authenticator
Follow the prompts. It will generate a QR code that you scan with the Google Authenticator app (or another compatible app) on your smartphone. It will also give you emergency scratch codes. Store these scratch codes in a safe place.
-
Configure SSH to use PAM:
Edit
/etc/pam.d/sshd
and add the following line (or uncomment it if it exists):auth required pam_google_authenticator.so nullok
The
nullok
option allows users without 2FA configured to still log in with just a password. Removenullok
to require 2FA for all users. -
Enable ChallengeResponseAuthentication in SSH:
Edit
/etc/ssh/sshd_config
and make sure the following line is set:ChallengeResponseAuthentication yes
If it’s commented out (starts with
#
), uncomment it. -
Restart SSH:
sudo systemctl restart sshd
Now, when you log in via SSH, you’ll be prompted for your password and then for the verification code from your authenticator app.
These alternative solutions, a WAF and 2FA, offer robust defenses against brute-force attacks and can be used in conjunction with Fail2ban for a layered security approach. Implementing these measures significantly enhances the security posture of your AlmaLinux 8 server.