How to create a custom Fail2Ban filter

Write a custom Fail2Ban filter with regex patterns to detect application-specific failed authentication attempts.

How to create a custom Fail2Ban filter

Write a custom Fail2Ban filter with regex patterns to detect application-specific failed authentication attempts.

Prerequisites

  • Fail2Ban installed and running.
  • A log file containing the patterns to match.

Step-by-Step: Create a Custom Filter in Fail2Ban

  1. Identify the log line format. Fail2Ban matches log lines using Python regular expressions. The <HOST> placeholder captures the offending IP address. Example log line:

    2026-03-30 10:15:22 WARNING Authentication failed for user admin from 203.0.113.45
  2. Create a filter file at /etc/fail2ban/filter.d/myapp.conf:

    [Definition]
    failregex = ^.*Authentication failed for user .* from <HOST>$
    ignoreregex =
  3. Test the filter against the log file before activating it:

    sudo fail2ban-regex /var/log/myapp/auth.log /etc/fail2ban/filter.d/myapp.conf

    The output shows how many lines matched failregex and how many matched ignoreregex.

  4. Add a jail for the custom filter in /etc/fail2ban/jail.local:

    [myapp]
    enabled = true
    filter = myapp
    logpath = /var/log/myapp/auth.log
    maxretry = 5
    findtime = 10m
    bantime = 1h
  5. Restart Fail2Ban:

    sudo systemctl restart fail2ban

How to Verify the Custom Filter Works

sudo fail2ban-client status myapp