fail2ban watches logs and bans addresses that produce failed logins or scanning. It ships with many filters, but sooner or later you need your own: for a site's admin panel, an unusual application or a log whose format differs from the usual one. A filter is one regular expression and a few lines of settings. Here is how to write it and test it so that it catches attacks and does not ban your own people.

What a filter consists of

A filter lives in /etc/fail2ban/filter.d/ and describes which log lines count as an attack attempt. The ban settings — how many attempts, in what time and for how long — are set separately, in a jail. Put your files into filter.d/ and jail.d/ under new names: the standard files are overwritten when the package is updated.

# /etc/fail2ban/filter.d/nginx-scan.conf
[Definition]
failregex = ^<HOST> \S+ \S+ \[\] "(?:GET|POST|HEAD) /(?:\.env|\.git/|wp-config\.php|phpmyadmin)[^"]*" (?:403|404)
ignoreregex =

This filter catches scanners looking for .env files, the .git folder and phpMyAdmin on a site.

Three peculiarities of failregex

Expressions follow Python rules. Testing them on log lines is easy in the regex tester: in fail2ban mode it understands the tags, cuts the date the way fail2ban does and shows which addresses will be banned.

How to write the expression

Testing on a real log

Before enabling, run the filter over the log with fail2ban-regex. It shows how many lines matched and from which addresses:

sudo fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-scan.conf
# show the matched lines
sudo fail2ban-regex --print-all-matched /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-scan.conf
# systemd journal instead of a file
sudo fail2ban-regex systemd-journal /etc/fail2ban/filter.d/myapp.conf

If there are no matches but the log has attacks, the date is most often to blame: check that the expression expects the line without it. Look also at the “Date template hits” line: if fail2ban did not recognize the date format, set it in the filter with the datepattern parameter.

Enabling and checking that it works

# /etc/fail2ban/jail.d/nginx-scan.local
[nginx-scan]
enabled  = true
port     = http,https
filter   = nginx-scan
logpath  = /var/log/nginx/access.log
maxretry = 3
findtime = 10m
bantime  = 1d

Apply the settings with sudo fail2ban-client reload and look at the state: sudo fail2ban-client status nginx-scan shows the number of failures and the banned addresses. An address is unbanned with sudo fail2ban-client set nginx-scan unbanip 203.0.113.5.

Do not ban yourself. Put the office and monitoring addresses into ignoreip in the [DEFAULT] section of /etc/fail2ban/jail.local. For repeat offenders turn on bantime.increment = true — the ban grows with every repeat.

Ready jails for SSH, nginx, mail and Asterisk are built by fail2ban setup, and server log analysis helps you see which attacks already hit the server and what is worth catching.