🛡️ Fail2Ban

Intrusion Prevention Software Framework for Ubuntu Servers

📋 Overview

Fail2Ban is an intrusion prevention software framework that protects computer servers from brute force attacks. It operates by monitoring log files for selected entries and then running scripts based on those entries, adding an additional layer of security to your server.

Key Functionality: Fail2Ban excels at defending against brute force attacks, where attackers try massive amounts of login attempts to guess passwords. It continuously scans log files of various services for suspicious activity, such as failed login attempts.

🔄 How Fail2Ban Works

Fail2Ban Workflow

1. Monitor
Scan log files for suspicious activity
2. Detect
Identify rule violations
3. Action
Block offending IP address
4. Release
Unban after timeout period
Automated Protection: Fail2Ban automates the process of identifying and blocking potential threats, making your server more secure without constant manual intervention.

📊 Architecture Diagram

Attack Layer
Malicious Login Attempts from Various IP Addresses
Service Layer
SSH, FTP, Apache, etc. (Generate Log Files)
Fail2Ban Layer
Monitors Logs → Applies Filters → Executes Actions
Firewall Layer
iptables/firewalld (Blocks Malicious IPs)
Protected Server
Secure Ubuntu Server Environment

⚙️ Installation Process

Important Note: With the release of Ubuntu 20.04/24.04, Python-related issues between Ubuntu and Fail2Ban became apparent. Until the release of Ubuntu 24.04.1, Fail2Ban cannot be installed using APT but rather must be installed using dpkg (Debian Package Manager).
Step 1: Download the DEB Package

Visit the GitHub releases page and download the latest .deb file:

wget -O fail2ban.deb [GitHub_URL]

Example: As of July 2024, the latest release is version 1.1.0

Step 2: Install Using dpkg
sudo dpkg -i fail2ban.deb

The -i flag indicates installation of a package

Step 3: Install Missing Dependencies
sudo apt install -f

This command identifies and automatically installs any missing dependencies

Step 4: Verify Installation
sudo systemctl status fail2ban

Expected output: active (running)

Future Updates: Once installed via dpkg, you can update Fail2Ban using standard APT commands:
sudo apt update
sudo apt upgrade

🔧 Configuration

Fail2Ban configuration files are located in the /etc/fail2ban directory. The main configuration file is jail.conf, but you should never modify it directly. Instead, create an override file called jail.local.

Creating the Override File

cd /etc/fail2ban
sudo cp jail.conf jail.local
sudo nano jail.local

Key Configuration Parameters

Parameter Default Value Recommended Value Description
bantime 10 minutes 7 days (7d) Duration to ban an offending host
findtime 10 minutes 3 hours (3h) Time window for counting retry attempts
maxretry 5 3 Number of attempts before banning
Configuration Logic: If you exceed maxretry attempts within the findtime window, your host will be banned for bantime.

Example: With maxretry=3, findtime=3h, bantime=7d → If you make 3 failed attempts within 3 hours, you'll be banned for 7 days.

Whitelisting Your IP Address

Important: If your ISP provides a static IP address, you should whitelist it to prevent accidental lockouts.
# In jail.local, find and uncomment:
ignoreip = 127.0.0.1/8 ::1 [YOUR_STATIC_IP]

Enabling SSH Protection

To protect SSH from brute force attacks, configure the SSH jail:

[sshd]
mode = aggressive
enabled = true
port = ssh
logpath = %(sshd_log)s
backend = %(sshd_backend)s

Normal Mode

Uses standard detection rules, balancing security and convenience. May allow some borderline attempts.

Aggressive Mode

Prioritizes security over convenience. Uses strict filters and targets specific attack vectors like port scans.

Activating Configuration Changes

sudo systemctl restart fail2ban

📁 Log File Monitoring

Fail2Ban tracks all activity in its log file located at /var/log/fail2ban.log

Viewing Log Files

cat Command

sudo cat /var/log/fail2ban.log

Displays entire log file at once. Best for small files.

less Command

sudo less /var/log/fail2ban.log

View one page at a time. Use Page Up/Down, Home/End to navigate. Press 'q' to quit.

Sample Log File Output

2024-07-15 10:23:45,123 fail2ban.server [INFO] Creating new jail 'sshd'
2024-07-15 10:23:45,124 fail2ban.jail [INFO] Jail 'sshd' started
2024-07-15 14:32:11,456 fail2ban.filter [INFO] [sshd] Found 192.168.1.100
2024-07-15 14:35:22,789 fail2ban.filter [INFO] [sshd] Found 192.168.1.100
2024-07-15 14:38:33,012 fail2ban.actions [NOTICE] [sshd] Ban 192.168.1.100
2024-07-22 14:38:33,345 fail2ban.actions [NOTICE] [sshd] Unban 192.168.1.100

In this example, IP address 192.168.1.100 was detected making failed login attempts. After the third attempt, it was banned and then automatically unbanned after the configured ban period.

🔍 Monitoring Banned IPs

sudo fail2ban-client status sshd

This command displays:

90 Currently Banned IPs
3 Max Retry Attempts
7 Ban Duration (Days)

🆘 Unbanning Your IP Address

Locked Out? If Fail2Ban bans your IP address and you cannot access your server, there are two methods to regain access.

Method 1: Get a New IP Address

Contact your ISP or reboot your router to obtain a new IP address. Most residential ISPs assign dynamic IPs that change when you restart your router.

Step 1: Check Your Current IP

Google "what is my ip" and note your current IP address

Step 2: Restart Your Router

Power off your router, wait 30 seconds, then power it back on

Step 3: Verify New IP

Check "what is my ip" again to confirm you received a new IP

Step 4: Reconnect

SSH to your server with the new IP address

Method 2: Use Console Access

Most hosting providers offer web-based console access (KVM - Keyboard Video Mouse) that allows direct access to your server, bypassing network restrictions.

Console Access Steps:
  1. Log in to your hosting provider's control panel (e.g., Vultr, DigitalOcean, AWS)
  2. Navigate to your server instance
  3. Select "View Console" or "Launch Console"
  4. Log in as root user
  5. Execute unban commands

Unbanning Commands

# Navigate to log directory
cd /var/log

# View fail2ban log to confirm your IP is banned
cat fail2ban.log

# Unban your IP address
fail2ban-client set sshd unbanip [YOUR_IP_ADDRESS]

# Verify unbanning
cat fail2ban.log
Example Unban Process:
root@server:~# fail2ban-client set sshd unbanip 192.168.1.100
1
root@server:~# cat /var/log/fail2ban.log
2024-07-15 15:45:12,789 fail2ban.actions [NOTICE] [sshd] Unban 192.168.1.100
The return value of 1 indicates successful unbanning.

📈 Real-World Performance Example

After running a server for several days with SSH open to all IP addresses (firewall set to "anywhere"), here's what Fail2Ban detected:

Attack Statistics Over 7 Days

90+ IPs Banned
270+ Failed Attempts Blocked
100% Brute Force Protection
Real Log Evidence:
[INFO] Found 37.1.2.3 - Failed SSH attempt
[INFO] Found 37.1.2.3 - Failed SSH attempt
[NOTICE] Ban 37.1.2.3 - Threshold exceeded

[INFO] Found 152.152.152.5 - Failed SSH attempt
[INFO] Found 152.152.152.5 - Failed SSH attempt
[NOTICE] Ban 152.152.152.5 - Threshold exceeded
This demonstrates Fail2Ban actively protecting your server from multiple brute force attacks from different IP addresses around the world.

🔐 Best Practices and Recommendations

✅ Do's

  • Always create jail.local instead of editing jail.conf
  • Set bantime to at least 7 days for serious security
  • Enable aggressive mode for SSH protection
  • Whitelist your static IP if you have one
  • Monitor logs regularly for attack patterns
  • Combine with cloud firewall for layered security

❌ Don'ts

  • Don't modify jail.conf directly
  • Don't set findtime too long (wastes resources)
  • Don't ignore console access setup
  • Don't whitelist dynamic IPs
  • Don't disable Fail2Ban on public-facing servers
  • Don't forget to restart after configuration changes

🛡️ Layered Security Approach

Cloud Firewall + Fail2Ban: While cloud firewalls (like Vultr's firewall) can restrict access by IP, Fail2Ban provides an additional layer of protection by:
  • Automatically detecting and blocking malicious behavior
  • Protecting against distributed attacks from multiple IPs
  • Monitoring application-level threats
  • Providing detailed attack logs and statistics

When to Use Cloud Firewall Only

If you restrict SSH access to your specific IP address using a cloud firewall, Fail2Ban becomes less critical since only your IP can attempt connections. However, Fail2Ban is still valuable as a backup security layer.

When Fail2Ban is Essential

Critical Scenarios:
  • Servers without cloud firewall capabilities
  • When SSH must be open to multiple IPs
  • Protecting services beyond SSH (FTP, Apache, etc.)
  • Dynamic IP environments where whitelisting isn't practical

📚 Common Commands Reference

Command Purpose
sudo systemctl status fail2ban Check Fail2Ban service status
sudo systemctl restart fail2ban Restart Fail2Ban service
sudo fail2ban-client status View all active jails
sudo fail2ban-client status sshd View SSH jail details and banned IPs
sudo fail2ban-client set sshd unbanip [IP] Unban a specific IP address
sudo cat /var/log/fail2ban.log View Fail2Ban activity log
sudo nano /etc/fail2ban/jail.local Edit Fail2Ban configuration

🎯 Conclusion

Fail2Ban is an essential security tool for Ubuntu servers, providing automated protection against brute force attacks. By monitoring log files and automatically blocking malicious IP addresses, it significantly reduces the attack surface of your server.

Key Takeaways:
  • Fail2Ban provides automated, real-time protection against brute force attacks
  • Proper configuration is crucial - use jail.local for all customizations
  • Recommended settings: bantime=7d, findtime=3h, maxretry=3
  • Always have a backup access method (console access) in case of lockout
  • Combine with cloud firewall for maximum security
  • Regular monitoring of logs helps identify attack patterns
Next Steps: After implementing Fail2Ban as part of your fundamental server hardening, you can proceed to more advanced hardening options and optimization steps to reduce server resource requirements under load.