Installing and Configuring Fail2Ban

    Protect your VPS from brute-force attacks with automatic IP banning

    Fail2Ban is an intrusion prevention software framework that protects Linux servers from brute-force attacks. It monitors log files for malicious activity and automatically bans IP addresses that show signs of attack by updating firewall rules.

    Key Benefits

    Automatic IP banning based on failed authentication attempts
    Customizable ban duration and thresholds
    Protection for SSH, web servers, mail servers, and more
    Low resource overhead
    Extensive logging and monitoring capabilities

    Prerequisites

    • • A RamNode VPS running Ubuntu 22.04/24.04 or AlmaLinux 8/9
    • • Root or sudo access to the server
    • • SSH access configured and working
    • • A firewall (UFW, firewalld, or iptables) installed and active

    Installation on Ubuntu

    Step 1: Update System Packages

    Begin by updating your package lists and upgrading existing packages:

    Update System
    sudo apt update
    sudo apt upgrade -y

    Step 2: Install Fail2Ban

    Install Fail2Ban from the official Ubuntu repositories:

    Install Fail2Ban
    sudo apt install fail2ban -y

    Step 3: Start and Enable the Service

    Enable Fail2Ban to start automatically on boot and start the service:

    Enable Service
    sudo systemctl enable fail2ban
    sudo systemctl start fail2ban

    Step 4: Verify Installation

    Verify
    sudo systemctl status fail2ban
    sudo fail2ban-client status

    Installation on AlmaLinux

    Step 1: Update System Packages

    Update System
    sudo dnf update -y

    Step 2: Enable EPEL Repository

    Fail2Ban is available in the EPEL (Extra Packages for Enterprise Linux) repository:

    Enable EPEL
    sudo dnf install epel-release -y

    Step 3: Install Fail2Ban

    Install Fail2Ban from the EPEL repository:

    Install Fail2Ban
    sudo dnf install fail2ban fail2ban-firewalld -y

    Note: The fail2ban-firewalld package ensures proper integration with firewalld, which is the default firewall on AlmaLinux.

    Step 4: Start and Enable the Service

    Enable Service
    sudo systemctl enable fail2ban
    sudo systemctl start fail2ban

    Step 5: Verify Installation

    Verify
    sudo systemctl status fail2ban
    sudo fail2ban-client status

    Configuration Basics

    Understanding Configuration Files

    Fail2Ban uses the following configuration structure:

    • /etc/fail2ban/fail2ban.conf – Main configuration file (do not edit directly)
    • /etc/fail2ban/jail.conf – Default jail definitions (do not edit directly)
    • /etc/fail2ban/jail.local – Your custom configuration (create this file)
    • /etc/fail2ban/jail.d/ – Directory for additional jail configurations

    Warning: Always create a jail.local file for your customizations. Never edit jail.conf directly, as updates may overwrite your changes.

    Creating Your Configuration File

    Create a new jail.local file with your custom settings:

    Create jail.local
    sudo nano /etc/fail2ban/jail.local

    Add the following base configuration:

    Base Configuration
    [DEFAULT]
    # Ban duration in seconds (1 hour)
    bantime = 3600
    
    # Time window for counting failures (10 minutes)
    findtime = 600
    
    # Number of failures before ban
    maxretry = 5
    
    # Email notifications (optional)
    destemail = admin@yourdomain.com
    sender = fail2ban@yourdomain.com
    mta = sendmail
    
    # Action to take when banning
    action = %(action_mwl)s
    
    # Whitelist your own IP addresses
    ignoreip = 127.0.0.1/8 ::1

    Configuration Parameters Explained

    ParameterDescription
    bantimeDuration of the ban in seconds. Use -1 for permanent bans.
    findtimeTime window during which failures are counted.
    maxretryNumber of failures allowed before triggering a ban.
    ignoreipIP addresses or ranges to whitelist (never ban).
    actionAction to execute when banning. Common options: action_, action_mw, action_mwl.

    SSH Jail Configuration

    SSH protection is the most common use case for Fail2Ban. Add the following to your jail.local file:

    Ubuntu SSH Jail

    Ubuntu SSH Configuration
    [sshd]
    enabled = true
    port = ssh
    filter = sshd
    logpath = /var/log/auth.log
    maxretry = 3
    bantime = 3600
    findtime = 600

    AlmaLinux SSH Jail

    AlmaLinux SSH Configuration
    [sshd]
    enabled = true
    port = ssh
    filter = sshd
    logpath = /var/log/secure
    maxretry = 3
    bantime = 3600
    findtime = 600
    backend = systemd

    Note: AlmaLinux uses /var/log/secure for authentication logs, while Ubuntu uses /var/log/auth.log. The backend = systemd option ensures proper log parsing on AlmaLinux.

    Web Server Protection

    Apache Protection

    Protect Apache from common attacks:

    Apache Jails
    [apache-auth]
    enabled = true
    port = http,https
    filter = apache-auth
    logpath = /var/log/apache2/*error.log    # Ubuntu
    #logpath = /var/log/httpd/*error_log     # AlmaLinux
    maxretry = 3
    bantime = 3600
    
    [apache-badbots]
    enabled = true
    port = http,https
    filter = apache-badbots
    logpath = /var/log/apache2/*access.log   # Ubuntu
    #logpath = /var/log/httpd/*access_log    # AlmaLinux
    maxretry = 2
    bantime = 86400
    
    [apache-noscript]
    enabled = true
    port = http,https
    filter = apache-noscript
    logpath = /var/log/apache2/*error.log    # Ubuntu
    #logpath = /var/log/httpd/*error_log     # AlmaLinux
    maxretry = 3
    bantime = 3600

    Nginx Protection

    Protect Nginx web servers:

    Nginx Jails
    [nginx-http-auth]
    enabled = true
    port = http,https
    filter = nginx-http-auth
    logpath = /var/log/nginx/*error.log
    maxretry = 3
    bantime = 3600
    
    [nginx-botsearch]
    enabled = true
    port = http,https
    filter = nginx-botsearch
    logpath = /var/log/nginx/*access.log
    maxretry = 2
    bantime = 86400
    
    [nginx-limit-req]
    enabled = true
    port = http,https
    filter = nginx-limit-req
    logpath = /var/log/nginx/*error.log
    maxretry = 5
    bantime = 3600

    Additional Service Protection

    MySQL/MariaDB

    MySQL/MariaDB Jail
    [mysqld-auth]
    enabled = true
    port = 3306
    filter = mysqld-auth
    logpath = /var/log/mysql/error.log       # Ubuntu
    #logpath = /var/log/mariadb/mariadb.log  # AlmaLinux
    maxretry = 3
    bantime = 3600

    Postfix Mail Server

    Postfix Jails
    [postfix]
    enabled = true
    port = smtp,465,submission
    filter = postfix
    logpath = /var/log/mail.log     # Ubuntu
    #logpath = /var/log/maillog     # AlmaLinux
    maxretry = 3
    bantime = 3600
    
    [postfix-sasl]
    enabled = true
    port = smtp,465,submission,imap,imaps,pop3,pop3s
    filter = postfix-sasl
    logpath = /var/log/mail.log     # Ubuntu
    #logpath = /var/log/maillog     # AlmaLinux
    maxretry = 3
    bantime = 3600

    Dovecot IMAP/POP3

    Dovecot Jail
    [dovecot]
    enabled = true
    port = pop3,pop3s,imap,imaps,submission,465,sieve
    filter = dovecot
    logpath = /var/log/mail.log     # Ubuntu
    #logpath = /var/log/maillog     # AlmaLinux
    maxretry = 3
    bantime = 3600

    Management and Monitoring

    Essential Commands

    Management Commands
    # Check overall status
    sudo fail2ban-client status
    
    # Check specific jail status
    sudo fail2ban-client status sshd
    
    # View banned IPs for a jail
    sudo fail2ban-client get sshd banned
    
    # 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
    
    # Restart the service
    sudo systemctl restart fail2ban

    Viewing Logs

    Log Commands
    # View Fail2Ban log
    sudo tail -f /var/log/fail2ban.log
    
    # Search for bans
    sudo grep 'Ban' /var/log/fail2ban.log
    
    # Count bans per jail
    sudo grep 'Ban' /var/log/fail2ban.log | awk '{print $6}' | sort | uniq -c

    Testing Your Configuration

    Test Configuration
    # Test configuration syntax
    sudo fail2ban-client -t
    
    # Check which jails are enabled
    sudo fail2ban-client status
    
    # Test regex patterns against a log file
    sudo fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf

    Advanced Configuration

    Incremental Banning

    Implement progressive ban times for repeat offenders:

    Incremental Banning
    [DEFAULT]
    # Enable ban time increment
    bantime.increment = true
    
    # Multiplier for each subsequent offense
    bantime.multipliers = 1 5 30 60 1440 10080 43200
    
    # Maximum ban time (30 days)
    bantime.maxtime = 2592000
    
    # Time window to count offenses
    bantime.rndtime = 2048

    Firewall Backend Configuration

    Specify the firewall backend based on your system:

    Firewall Backends
    [DEFAULT]
    # For UFW (Ubuntu)
    banaction = ufw
    
    # For firewalld (AlmaLinux)
    banaction = firewallcmd-ipset
    
    # For iptables (both)
    banaction = iptables-multiport

    Custom Filters

    Create custom filters for applications not covered by default:

    Create Custom Filter
    sudo nano /etc/fail2ban/filter.d/myapp.conf

    Example custom filter content:

    Custom Filter Example
    [Definition]
    failregex = ^<HOST> -.*"(GET|POST|HEAD).*HTTP.*" 401
                ^Authentication failure from <HOST>
    ignoreregex =

    Troubleshooting

    Fail2Ban Not Starting

    Check the configuration syntax and log file paths:

    Debug Startup
    sudo fail2ban-client -t
    sudo journalctl -u fail2ban -f

    Jails Not Banning

    Verify log paths exist and contain expected patterns:

    Debug Jails
    # Check if log file exists
    ls -la /var/log/auth.log
    
    # Test filter against log
    sudo fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf

    Locked Out of Your Server

    If you accidentally ban yourself, access via RamNode console:

    Recover Access
    # Stop Fail2Ban
    sudo systemctl stop fail2ban
    
    # Flush iptables rules
    sudo iptables -F
    
    # Add your IP to whitelist in jail.local
    sudo nano /etc/fail2ban/jail.local
    # Add: ignoreip = 127.0.0.1/8 YOUR_IP
    
    # Restart Fail2Ban
    sudo systemctl start fail2ban

    Warning: Always add your static IP address to the ignoreip list to prevent accidental lockouts.

    Best Practices

    1
    Always use jail.local: Never modify default configuration files directly.
    2
    Whitelist your IP: Add your static IP addresses to ignoreip to prevent self-lockouts.
    3
    Start conservative: Begin with higher maxretry values and adjust based on observed attacks.
    4
    Monitor regularly: Review logs and banned IPs to fine-tune your configuration.
    5
    Use incremental banning: Implement progressive ban times for persistent attackers.
    6
    Combine with other security measures: Use Fail2Ban alongside SSH key authentication, firewall rules, and regular updates.
    7
    Test before production: Always test new jails and filters in a staging environment first.
    8
    Keep Fail2Ban updated: Regularly update to receive new filters and security improvements.

    Complete Configuration Example

    Here is a complete jail.local configuration suitable for a web server:

    Complete jail.local Example
    [DEFAULT]
    bantime = 3600
    findtime = 600
    maxretry = 5
    ignoreip = 127.0.0.1/8 ::1 YOUR_IP_HERE
    bantime.increment = true
    bantime.multipliers = 1 5 30 60 1440
    
    [sshd]
    enabled = true
    port = ssh
    maxretry = 3
    bantime = 7200
    
    [nginx-http-auth]
    enabled = true
    port = http,https
    logpath = /var/log/nginx/*error.log
    maxretry = 3
    
    [nginx-botsearch]
    enabled = true
    port = http,https
    logpath = /var/log/nginx/*access.log
    maxretry = 2
    bantime = 86400

    Need Help?

    Contact RamNode Support for assistance with your VPS configuration.