Linux Tutorial

Configure fail2ban for SSH Brute Force Protection on Rocky Linux 9

7views

SSH brute force attacks are one of the most common security threats facing Linux servers. Fail2ban is a powerful intrusion prevention tool that monitors log files and automatically blocks IP addresses showing malicious behavior. This guide will walk you through configuring fail2ban specifically for SSH protection on Rocky Linux 9.

Time Required: 15-20 minutes
Difficulty Level: Intermediate
Prerequisites: Root or sudo access to Rocky Linux 9 server

Step 1: Update Your System

Before installing any new software, ensure your Rocky Linux 9 system is up to date:

bash
sudo dnf update -y

This ensures you have the latest security patches and package dependencies.

Step 2: Install fail2ban

Install fail2ban from the EPEL repository:

bash
# Enable EPEL repository
sudo dnf install epel-release -y

# Install fail2ban
sudo dnf install fail2ban fail2ban-systemd -y

Verify the installation:

bash
fail2ban-client --version

Step 3: Configure fail2ban for SSH Protection

Create Local Configuration File

Never edit the default /etc/fail2ban/jail.conf file directly, as it will be overwritten during updates. Instead, create a local configuration:

bash
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Edit the Local Configuration

Open the configuration file:

bash
sudo nano /etc/fail2ban/jail.local

Find the [DEFAULT] section and configure these essential parameters:

ini
[DEFAULT]
# Ban time: 1 hour (in seconds)
bantime = 3600

# Find time: 10 minutes window
findtime = 600

# Max retry attempts before ban
maxretry = 5

# Email notifications (optional)
destemail = [email protected]
sender = [email protected]
action = %(action_mwl)s

Configure SSH Jail

Scroll down to the [sshd] section and enable it:

ini
[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s
maxretry = 3
bantime = 3600
findtime = 600

Parameter Explanations:

  • enabled: Set to true to activate SSH monitoring
  • port: Defines which port to monitor (default SSH port 22)
  • logpath: Location of SSH authentication logs
  • maxretry: Number of failed login attempts before banning
  • bantime: Duration of ban in seconds (3600 = 1 hour)
  • findtime: Time window for counting failed attempts (600 = 10 minutes)

Save and exit (Ctrl+X, then Y, then Enter in nano).

Step 4: Create Custom SSH Filter (Optional but Recommended)

For enhanced protection, create a custom filter:

bash
sudo nano /etc/fail2ban/filter.d/sshd-aggressive.conf

Add this content:

ini
[Definition]
failregex = ^%(__prefix_line)s(?:error: PAM: )?[aA]uthentication (?:failure|error|failed) for .* from <HOST>( via \S+)?\s*$
            ^%(__prefix_line)s(?:error: PAM: )?User not known to the underlying authentication module for .* from <HOST>\s*$
            ^%(__prefix_line)sFailed (?:password|publickey) for .* from <HOST>(?: port \d*)?(?: ssh\d*)?$
            ^%(__prefix_line)sROOT LOGIN REFUSED.* FROM <HOST>\s*$
            ^%(__prefix_line)s[iI](?:llegal|nvalid) user .* from <HOST>\s*$

ignoreregex =

This filter catches more aggressive attack patterns.

Step 5: Configure Firewall Integration

Ensure fail2ban works with firewalld (Rocky Linux 9’s default firewall):

bash
sudo nano /etc/fail2ban/jail.local

Add or verify this setting in the [DEFAULT] section:

ini
banaction = firewallcmd-ipset

This ensures fail2ban uses firewalld’s ipset for efficient IP blocking.

Step 6: Enable and Start fail2ban Service

Enable fail2ban to start automatically on boot:

bash
sudo systemctl enable fail2ban

Start the fail2ban service:

bash
sudo systemctl start fail2ban

Verify the service is running:

bash
sudo systemctl status fail2ban

You should see “active (running)” in green text.

Step 7: Verify SSH Jail is Active

Check that the SSH jail is properly configured and running:

bash
sudo fail2ban-client status

You should see sshd in the jail list. To view detailed statistics:

bash
sudo fail2ban-client status sshd

This shows:

  • Total failed login attempts
  • Currently banned IPs
  • Total banned IPs (historical)

Step 8: Test Your Configuration

Test Configuration Syntax

Before relying on fail2ban, test the configuration:

bash
sudo fail2ban-client -t

No errors should appear.

Simulate an Attack (Optional)

From another machine, attempt multiple failed SSH logins to verify fail2ban blocks the IP:

bash
# On another machine, try wrong password multiple times
ssh wronguser@your-server-ip

After exceeding maxretry attempts, check if the IP was banned:

bash
sudo fail2ban-client status sshd

Step 9: Monitor fail2ban Logs

Monitor fail2ban activity in real-time:

bash
sudo tail -f /var/log/fail2ban.log

You’ll see entries like:

2024-11-17 10:23:45,123 fail2ban.actions [12345]: NOTICE [sshd] Ban 192.168.1.100

Step 10: Whitelist Trusted IPs (Important!)

To prevent locking yourself out, whitelist your trusted IP addresses:

bash
sudo nano /etc/fail2ban/jail.local

Add your IPs to the [DEFAULT] section:

ini
[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 YOUR.IP.ADDRESS.HERE

Restart fail2ban:

bash
sudo systemctl restart fail2ban

Additional Security Tips

Increase Ban Time for Repeat Offenders

For persistent attackers, configure incremental banning:

ini
[sshd]
enabled = true
bantime.increment = true
bantime.factor = 1
bantime.maxtime = 5w

Enable Email Notifications

Configure fail2ban to send email alerts:

ini
[DEFAULT]
destemail = [email protected]
sendername = Fail2ban
action = %(action_mwl)s

Change Default SSH Port

Combine fail2ban with changing your SSH port from 22 to something else (e.g., 2222) for additional security.

Troubleshooting

fail2ban Not Banning IPs

  1. Check if SELinux is blocking fail2ban:
bash
sudo ausearch -m avc -ts recent | grep fail2ban
  1. Verify log file permissions:
bash
ls -la /var/log/secure
  1. Check filter regex patterns:
bash
sudo fail2ban-regex /var/log/secure /etc/fail2ban/filter.d/sshd.conf

Unban an IP Address

If you accidentally ban a legitimate IP:

bash
sudo fail2ban-client set sshd unbanip IP.ADDRESS.HERE

Service Won’t Start

Check for configuration errors:

bash
sudo journalctl -xeu fail2ban.service

Useful Commands Reference

bash
# Check fail2ban status
sudo fail2ban-client status

# View SSH jail status
sudo fail2ban-client status sshd

# Manually ban an IP
sudo fail2ban-client set sshd banip 192.168.1.100

# Manually unban an IP
sudo fail2ban-client set sshd unbanip 192.168.1.100

# Reload configuration
sudo fail2ban-client reload

# View banned IPs across all jails
sudo fail2ban-client banned

Conclusion

You’ve successfully configured fail2ban for SSH brute force protection on Rocky Linux 9. Your server is now actively monitoring authentication attempts and automatically blocking malicious IPs. Remember to regularly check your logs, keep fail2ban updated, and adjust the configuration based on your specific security needs.

For more advanced configurations and additional jails (Apache, Nginx, etc.), consult the official fail2ban documentation.

Related Resources

Thank you for visiting our website, TechsBucket. If you liked the article, then share it with others.

Leave a Response