Cybersecurity guides, explanations and reader checklists on whilenetworking.com

Defensive Task: Configuring Fail2Ban on Linux Servers to Auto-Ban IPs After Failed SSH Logins

In the landscape of defensive cybersecurity, brute-force attacks against SSH (Secure Shell) remain one of the most persistent threats. Attackers utilize…

In the landscape of defensive cybersecurity, brute-force attacks against SSH (Secure Shell) remain one of the most persistent threats. Attackers utilize automated scripts to guess passwords, aiming to gain unauthorized access to servers. Relying solely on manual monitoring is insufficient for modern threat landscapes. This guide details the configuration of Fail2Ban, an open-source intrusion prevention tool, to automatically detect and ban malicious IP addresses attempting to breach your Linux server via SSH.

Understanding Fail2Ban Architecture

Fail2Ban operates by scanning log files for patterns indicative of attacks. When it detects a specific number of failed login attempts within a defined time window, it triggers an action—typically adding the offending IP address to a firewall blocklist. For this implementation, we will focus on integrating Fail2Ban with iptables or nftables, the standard firewalls found on most Linux distributions like Ubuntu and CentOS.

The core workflow involves three components:
1. Log Analysis: Fail2Ban reads logs from /var/log/auth.log (Debian/Ubuntu) or /var/log/secure (RHEL/CentOS).
2. Filtering: It uses filters to identify lines containing “Failed password” and extract the source IP.
3. Action: Upon reaching the threshold, it sends a command to the firewall to drop traffic from that IP for a set duration or permanently.

Prerequisites and Environment Setup

Before proceeding, ensure your environment is prepared for safe testing. This configuration should always be performed in an authorized lab environment or on production servers with explicit change-management approval.

Prerequisites:
* A Linux server running Debian, Ubuntu, RHEL, or CentOS.
* Root or sudo access to install packages and modify system files.
* An active firewall service (e.g., ufw, firewalld, or raw iptables).

Installation Steps:
Update your package repositories and install Fail2Ban. The command syntax varies slightly by distribution.

# For Debian/Ubuntu based systems
sudo apt update
sudo apt install fail2ban -y

# For RHEL/CentOS/Fedora based systems
sudo dnf install fail2ban -y

Once installed, start the service and enable it to run on boot:

sudo systemctl enable fail2ban
sudo systemctl start fail2ban

Customizing the SSH Filter for Precision

The default configuration often works well, but advanced practitioners may need to tune the filter to reduce false positives or handle specific log formats. The primary configuration file is located at /etc/fail2ban/jail.local. We will create a custom jail specifically for SSH.

Edit the main jail configuration file:

sudo nano /etc/fail2ban/jail.local

Inside this file, locate the [sshd] section or add a new one if it is commented out. A robust configuration looks like this:

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
action = iptables-allports

Configuration Breakdown:
* enabled = true: Activates the jail.
* port = ssh: Tells Fail2Ban to monitor port 22, though it primarily analyzes logs rather than port states.
* filter = sshd: Uses the built-in filter designed for SSH authentication logs.
* logpath: Specifies where the auth logs reside. Adjust this if your /etc/rsyslog.conf directs logs elsewhere (e.g., /var/log/messages).
* maxretry = 3: The critical threshold. The IP will be banned after 3 failed attempts. Lowering this increases security but may hinder legitimate users with unstable connections; raising it reduces alert fatigue.
* bantime = 3600: Bans the IP for 1 hour (3600 seconds).
* findtime = 600: The window of time over which maxretry counts are evaluated. Here, 3 failures within 10 minutes trigger a ban.
* action = iptables-allports: The action taken upon banning. This adds the IP to the DROP rule in the INPUT chain.

Verification and Expected Results

After saving your configuration, restart Fail2Ban to apply changes:

sudo systemctl restart fail2ban

To verify functionality without risking server access, perform a controlled test. From a different machine or using ssh directly from a terminal, attempt to log in with an incorrect password three times.

Simulated Test Sequence:
1. Attempt Login 1: Failed password for invalid user admin from 192.0.2.55 port 54321 ssh2
2. Attempt Login 2: Failed password for invalid user admin from 192.0.2.55 port 54322 ssh2
3. Attempt Login 3: Failed password for invalid user admin from 192.0.2.55 port 54323 ssh2

Expected Output:
Upon the third failure, you should see a message in the Fail2Ban log indicating the ban has been triggered. Check the status of the jail:

sudo fail2ban-client status sshd

Illustrative Output:

Target       port     action   begin       end         found       latest       miss
sshd        22,1032   iptables-allports   Mon Jan 01 10:00:00 2024   Mon Jan 01 10:05:00 2024   Mon Jan 01 10:05:00 2024   Mon Jan 01 10:05:00 2024
IP           192.0.2.55   -         Mon Jan 01 10:05:00 2024   -             Mon Jan 01 10:05:00 2024   Mon Jan 01 10:05:00 2024

To confirm the firewall actually blocked the IP, check your active iptables rules:

sudo iptables -L INPUT -n | grep 192.0.2.55

You should see a rule in the DROP chain targeting this specific source address.

Incident Response and Manual Intervention

Automated banning is powerful, but incident response requires human oversight. Sometimes legitimate administrators or services may be temporarily locked out due to network glitches or misconfigured clients. Fail2Ban provides command-line tools to manage bans dynamically without restarting the service.

Unbanning an IP:
If a valid user needs immediate access, unbanning them is straightforward:

sudo fail2ban-client set sshd unbanip 192.0.2.55

Viewing Current Banned IPs:
To audit current blocks before making decisions:

sudo fail2ban-client status sshd | grep "Found"

Common Errors and Troubleshooting

Even in well-hardened environments, configuration errors occur. Here are common pitfalls and their fixes.

Error 1: “No such file or directory” for logpath
* Cause: The specified log file does not exist or permissions are incorrect.
* Fix: Ensure /var/log/auth.log exists. On some minimal installations, logs may go to /var/log/syslog. Update the logpath parameter accordingly.

Error 2: “Action not found” or no iptables rules added
* Cause: The firewall service is not running, or the action command syntax changed in newer versions of Fail2Ban/firewall tools.
* Fix: Ensure ufw or iptables is active. If using nftables, change the action to nftables-multiport.

Error 3: False Positives Blocking Legitimate Traffic
* Cause: The findtime window is too short, or maxretry is too low for environments with high latency.
* Fix: Increase findtime (e.g., to 900 seconds) or increase maxretry (e.g., to 5). Alternatively, create a “whitelist” by adding trusted IPs in the filter configuration to ignore them entirely.

Student Practice Task and Industry Application

For Students:
Set up a virtual lab using VirtualBox or Docker. Create two VMs: one acting as the attacker and one as the server. Install Fail2Ban on the server. From the attacker VM, write a simple bash script that loops through a list of common usernames and attempts SSH login. Observe how quickly the server IP is banned in the logs and verify the ban via iptables. Document the time elapsed between the first failed attempt and the successful block.

For Industry Practitioners:
In production environments, integrate Fail2Ban with your SIEM (Security Information and Event Management) system. Configure Fail2Ban to send email alerts or webhooks to a Slack channel when a ban is triggered. This allows for rapid incident response without needing to constantly monitor logs manually. Always review the jail.local file quarterly to ensure the ban duration aligns with your organization’s risk tolerance and compliance requirements.

Conclusion

Configuring Fail2Ban is a fundamental step in Linux server hardening. By automating the detection of brute-force attacks, you significantly reduce the attack surface for SSH vulnerabilities. Remember that security is a process, not a product; regularly review logs, adjust thresholds based on traffic patterns, and maintain clear procedures for manual intervention when necessary.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.