TExcelTAD

fail2ban

fail2ban watches log files (or the journal) for signs of abuse (failed SSH logins, repeated 401s, bots probing for /wp-login.php) and bans the offending addresses in the firewall for a while. With SSH keys only (Hardening the SSH Server) brute force can't succeed anyway, so on SSH fail2ban mostly cuts log noise and wasted CPU; on web applications with password logins it is real protection. It is a brake, not a wall.

How it works

Piece Where Does
filter /etc/fail2ban/filter.d/*.conf regular expressions with a <HOST> placeholder that find "bad" lines
action /etc/fail2ban/action.d/*.conf what to do on a ban/unban: nftables, iptables, ufw, firewallcmd, e-mail, a webhook
jail /etc/fail2ban/jail.local, jail.d/*.conf ties a filter to a log source and an action, with thresholds

A jail bans an address when its filter matched maxretry times within findtime, for bantime. Never edit jail.conf (the package owns it); put your settings in jail.local or jail.d/.

ini
# /etc/fail2ban/jail.d/local.conf
[DEFAULT]
banaction = nftables-multiport
bantime   = 1h
findtime  = 10m
maxretry  = 5
ignoreip  = 127.0.0.1/8 ::1 198.51.100.0/24      # your office / VPN: never ban yourself
bantime.increment = true                          # repeat offenders get longer bans

[sshd]
enabled = true
backend = systemd                                 # read the journal instead of /var/log/auth.log

[nginx-login]
enabled  = true
filter   = nginx-login
logpath  = /var/log/nginx/access.log
port     = http,https
maxretry = 10

Testing filters with fail2ban-regex

A filter that doesn't match never bans; a filter that matches too much bans your customers. fail2ban-regex runs a filter against a log file and reports exactly which lines matched, and it needs no root and no running fail2ban, so it runs here. First the packaged sshd filter against a short auth.log:

bash · try it yourself
cat > auth.log <<'EOF'
Jan 15 10:00:01 web1 sshd[1201]: Invalid user admin from 203.0.113.7 port 50122
Jan 15 10:00:03 web1 sshd[1203]: Failed password for invalid user admin from 203.0.113.7 port 50124 ssh2
Jan 15 10:00:05 web1 sshd[1205]: Failed password for root from 198.51.100.4 port 40210 ssh2
Jan 15 10:00:07 web1 sshd[1207]: Connection closed by authenticating user root 203.0.113.7 port 50130 [preauth]
Jan 15 10:00:09 web1 sshd[1210]: Accepted publickey for deploy from 192.0.2.10 port 51000 ssh2: ED25519 SHA256:k3y
EOF
fail2ban-regex auth.log sshd | sed -n '/^Failregex/,/^`-/p;/^Lines:/p'
Failregex: 5 total
|-  #) [# of hits] regular expression
|   4) [2] ^Failed (?:<F-NOFAIL>publickey</F-NOFAIL>|\S+) for (?P<cond_inv>invalid user )?<F-USER>(?P<cond_user>\S+)|(?(cond_inv)(?:(?! from ).)*?|[^:]+)</F-USER> from <HOST>(?: (?:port \d+|on \S+)){0,2}(?: ssh\d*)?(?(cond_user): |(?:(?:(?! from ).)*)$)
|   6) [1] ^[iI](?:llegal|nvalid) user <F-USER>.*?</F-USER> from <HOST>(?: (?:port \d+|on \S+|\[preauth\])){0,3}\s*$
|  20) [1] ^<F-NOFAIL><F-MLFFORGET>(Connection (?:closed|reset)|Disconnected)</F-MLFFORGET></F-NOFAIL> (?:by|from)(?: (?:invalid|authenticating) user <F-USER>\S+|.*?</F-USER>)? <HOST>(?:(?: (?:port \d+|on \S+|\[preauth\])){0,3}\s*|\s*)$
|  21) [1] ^<F-MLFFORGET><F-MLFGAINED>Accepted \w+</F-MLFGAINED></F-MLFFORGET> for <F-USER>\S+</F-USER> from <HOST>(?:\s|$)
`-
Lines: 5 lines, 2 ignored, 3 matched, 0 missed

Three attack lines counted as failures (the numbers refer to the patterns inside the stock sshd filter). The Connection closed … [preauth] line and the successful key login matched patterns marked NOFAIL/MLFGAINED: they are recognised so they can be correlated, but they are ignored, not counted, so a successful login never brings anyone closer to a ban. Now a filter of your own: a login form that logs POST /login with status 401 in Nginx's access log:

bash · try it yourself
cat > access.log <<'EOF'
203.0.113.50 - - [15/Jan/2026:10:00:01 +0000] "POST /login HTTP/1.1" 401 512 "-" "python-requests/2.31"
203.0.113.50 - - [15/Jan/2026:10:00:02 +0000] "POST /login HTTP/1.1" 401 512 "-" "python-requests/2.31"
192.0.2.10 - - [15/Jan/2026:10:00:03 +0000] "POST /login HTTP/1.1" 302 0 "-" "Mozilla/5.0"
192.0.2.10 - - [15/Jan/2026:10:00:04 +0000] "GET /login HTTP/1.1" 401 512 "-" "Mozilla/5.0"
198.51.100.23 - - [15/Jan/2026:10:00:05 +0000] "POST /api/login HTTP/1.1" 401 88 "-" "curl/8.5.0"
203.0.113.50 - - [15/Jan/2026:10:00:06 +0000] "POST /login HTTP/1.1" 401 512 "-" "python-requests/2.31"
EOF
echo "=== too loose: any 401"
fail2ban-regex access.log '^<HOST> .* 401 ' | grep -E '^Lines:'
echo "=== precise: failed POSTs to /login"
fail2ban-regex access.log '^<HOST> \S+ \S+ \[\] "POST /login HTTP/[0-9.]+" 401 ' | grep -E '^Lines:'
fail2ban-regex --print-all-matched access.log '^<HOST> \S+ \S+ \[\] "POST /login HTTP/[0-9.]+" 401 ' | sed -n '/Matched line/,/^`-/p' | awk '/^\|  [0-9]/ {print $2}' | sort | uniq -c
=== too loose: any 401
Lines: 6 lines, 0 ignored, 5 matched, 1 missed
=== precise: failed POSTs to /login
Lines: 6 lines, 0 ignored, 3 matched, 3 missed
      3 203.0.113.50

Note the \[\] in the pattern: fail2ban first finds the timestamp in each line (that is how it knows when the failure happened) and cuts it out before applying failregex, so the brackets are empty by then. The loose pattern also counted a normal GET of the login page and an API endpoint; the precise one only counts the three failed form logins from 203.0.113.50, which with maxretry = 3 would ban exactly that address. Save the precise pattern as failregex in /etc/fail2ban/filter.d/nginx-login.conf. Anchor patterns (^<HOST>) so an attacker can't inject a fake address later in a line they control (the user agent, the URL).

Running it (sample session)

bash
$ sudo fail2ban-client -t                      # test the whole configuration
OK: configuration test is successful
$ sudo systemctl enable --now fail2ban
$ sudo fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  |- Currently failed:	3
|  |- Total failed:	1847
|  `- Journal matches:	_SYSTEMD_UNIT=ssh.service + _COMM=sshd
`- Actions
   |- Currently banned:	12
   |- Total banned:	304
   `- Banned IP list:	203.0.113.7 198.51.100.66 …
$ sudo nft list set inet f2b-table addr-set-sshd | head -4
table inet f2b-table {
	set addr-set-sshd {
		type ipv4_addr
		elements = { 203.0.113.7, 198.51.100.66, … }
$ sudo fail2ban-client set sshd unbanip 198.51.100.66
1

Bans live in an nftables set, exactly the mechanism shown in nftables. Two practical warnings: behind a load balancer or CDN, the log's client address is the proxy's unless you log the real client IP (X-Forwarded-For via Nginx's real_ip module), so fail2ban would ban your own load balancer; and bans are per server, so a fleet needs either fail2ban on every host or blocking at the edge (WAF, cloud firewall, CrowdSec's shared blocklists).

Go further: Brute Force and Password Spraying explains why per-IP bans miss a spray across many accounts.

Test yourself

A jail has maxretry = 5, findtime = 10m, bantime = 1h. When is an address banned?

  1. After 5 failures in total
  2. After 5 matching lines within 10 minutes, for one hour
  3. After 10 minutes
  4. After 1 hour of failures

Why test a filter with fail2ban-regex before enabling the jail?

  1. It speeds up fail2ban
  2. It shows exactly which log lines match, so you catch filters that miss attacks or that would ban legitimate users
  3. fail2ban won't start otherwise
  4. It installs the filter

fail2ban on a server behind a load balancer keeps banning one address that turns out to be the load balancer. Why?

  1. The load balancer attacks the server
  2. The web server logs the proxy's address, not the client's, so every failure looks like it came from the load balancer
  3. fail2ban doesn't support IPv4
  4. maxretry is too high