Skip to main content

Security and hardening · Intermediate · 17 min

Write custom Fail2ban jails and filters for your own apps

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Fail2ban 1.1.0

You will have Fail2ban 1.1 banning repeated failed sign-ins to your own app and to an nginx basic-auth area, with filters you tested against sample logs, your own addresses allow-listed, and longer bans for repeat offenders.

On this page

Fail2ban ships filters for SSH, mail servers and common web servers, but it knows nothing about your own app. If your sign-in page is the thing being hammered, the sshd jail does not help. The fix is a filter of your own: a pattern that recognises your app's failed sign-in line, plus a jail that says which log to read and how many failures earn a ban.

In this tutorial you protect a small app called ledger that sits behind nginx. You write a filter for its JSON log line and prove it with fail2ban-regex before it goes anywhere near the firewall. You add a second jail for nginx basic-auth failures, allow-list your own addresses, make repeat offenders wait longer, and then trip the app jail on purpose to see a ban happen. Replace ledger, its log path and its field names with your own as you go.

Step 1 · Collect sample lines from your app

A filter is only as good as the lines you test it on. Start with real lines from your app's log, including lines that must not match, such as successful sign-ins.

Make sure Fail2ban is installed and current. If you followed the previous tutorial this changes nothing:

Bash
sudo apt-get update
sudo apt-get install -y fail2ban
fail2ban-client --version | head -n 1

The version line starts with Fail2Ban v1.1.

The ledger app writes one JSON object per line to /var/log/ledger/app.log. A failed password and a failed two-factor code look like this:

JSON
{"time":"2026-11-18T10:00:01Z","level":"warn","event":"login_failed","ip":"198.51.100.7","user":"admin"}

Two details matter before you write any pattern:

  • The ip field must hold the real client address. Behind nginx your app sees every request coming from 127.0.0.1 unless it reads the address nginx passes on (for example proxy_set_header X-Real-IP $remote_addr; and the app trusting that header only from 127.0.0.1). If the app logs 127.0.0.1, Fail2ban either never bans (localhost is allow-listed) or bans nothing useful.
  • Fields the app controls (time, level, event, ip) should come before fields an attacker controls (user). That lets you anchor the pattern so a crafted username cannot plant a different address in the match.

Copy a handful of lines from your own log into a scratch file. To follow along exactly, use these six, which mix failures, a success, an IPv6 address and a username crafted to look like an ip field:

Bash
mkdir -p ~/fail2ban-demo
cat > ~/fail2ban-demo/ledger-sample.log <<'LOG'
{"time":"2026-11-18T09:58:12Z","level":"info","event":"login_ok","ip":"192.0.2.10","user":"amara"}
{"time":"2026-11-18T10:00:01Z","level":"warn","event":"login_failed","ip":"198.51.100.7","user":"admin"}
{"time":"2026-11-18T10:00:04.512Z","level":"warn","event":"login_failed","ip":"198.51.100.7","user":"root"}
{"time":"2026-11-18T10:00:09Z","level":"warn","event":"totp_failed","ip":"2001:db8::23","user":"kofi"}
{"time":"2026-11-18T10:00:15Z","level":"warn","event":"login_failed","ip":"198.51.100.7","user":"\"ip\":\"203.0.113.99\""}
{"time":"2026-11-18T10:01:30Z","level":"info","event":"password_reset_sent","ip":"192.0.2.10","user":"amara"}
LOG

Check it worked

Bash
wc -l ~/fail2ban-demo/ledger-sample.log

The output starts with 6. Four of those lines are failures (three from 198.51.100.7, one from 2001:db8::23) and two are not. Your filter has to get exactly that split.

Step 2 · Write the filter for the JSON line

A filter file has three settings that matter here:

  • datepattern tells Fail2ban where the timestamp is and how to read it. Fail2ban uses the timestamp to decide whether a failure falls inside findtime, so a filter that cannot read the date never bans.
  • failregex is one or more patterns that mean "this address failed". <ADDR> stands for the address; it matches IPv4 and IPv6 addresses only, never a hostname, so Fail2ban never does a DNS lookup on something an attacker wrote.
  • ignoreregex lists lines to skip even when they match. You do not need one here.

One behaviour surprises people: Fail2ban cuts the timestamp out of the line before it runs failregex. The capture group in datepattern (the part in round brackets) is what gets cut, so by the time failregex runs, the line starts {"time":"","level":.... The pattern below allows for that with "time":"[^"]*", which matches an empty value or a full one.

In Fail2ban config files a literal % is written %%, so the date codes appear as %%Y, %%m and so on. (?:\.%%f)? accepts an optional fraction of a second, and %%z reads the trailing Z as UTC.

Bash
sudo tee /etc/fail2ban/filter.d/ledger-auth.conf > /dev/null <<'CONF'
# Failed sign-ins and failed two-factor codes from the ledger app.
# Log format: one JSON object per line, fields in a fixed order,
# app-controlled fields before user-controlled ones.
[Definition]
datepattern = ^\{"time":"(%%Y-%%m-%%dT%%H:%%M:%%S(?:\.%%f)?%%z)"

failregex = ^\{"time":"[^"]*","level":"warn","event":"(?:login_failed|totp_failed)","ip":"<ADDR>"

ignoreregex =
CONF

The pattern is anchored at the start of the line with ^ and spells out every field before ip. Because JSON escapes quotes inside strings, a username such as "ip":"203.0.113.99" appears in the log as \"ip\":\"203.0.113.99\", and it sits after the real ip field anyway. An unanchored pattern such as "ip":"<ADDR>" on its own is weaker: change the logger's field order one day and it could start matching text the attacker typed.

Check it worked

Run the filter against the sample file:

Bash
fail2ban-regex ~/fail2ban-demo/ledger-sample.log /etc/fail2ban/filter.d/ledger-auth.conf

The summary near the end reads Lines: 6 lines, 0 ignored, 4 matched, 2 missed, and the date template section shows your pattern with 6 hits. If the date template hits are 0, Fail2ban could not read the timestamp: compare the datepattern with a real line character by character.

Now see which addresses it would count:

Bash
fail2ban-regex -o ip ~/fail2ban-demo/ledger-sample.log /etc/fail2ban/filter.d/ledger-auth.conf

You see 198.51.100.7 three times and 2001:db8::23 once. 203.0.113.99, the address hidden in the crafted username, does not appear. Run the same two commands against a copy of your real log before you go further.

Step 3 · Test the nginx basic-auth filter

Nginx logs basic-auth failures to its error log, and Fail2ban ships a filter for them called nginx-http-auth. Test it the same way rather than trusting it. These three lines are in nginx's error-log format: a wrong password, an unknown user, and a request with no credentials at all.

Bash
cat > ~/fail2ban-demo/nginx-error-sample.log <<'LOG'
2026/11/18 10:02:11 [error] 812#812: *41 user "admin": password mismatch, client: 198.51.100.23, server: ledger.example.com, request: "GET /admin/ HTTP/1.1", host: "ledger.example.com"
2026/11/18 10:02:15 [error] 812#812: *42 user "backup" was not found in "/etc/nginx/.htpasswd", client: 198.51.100.23, server: ledger.example.com, request: "GET /admin/ HTTP/1.1", host: "ledger.example.com"
2026/11/18 10:02:20 [error] 812#812: *43 no user/password was provided for basic authentication, client: 192.0.2.10, server: ledger.example.com, request: "GET /admin/ HTTP/1.1", host: "ledger.example.com"
LOG
fail2ban-regex ~/fail2ban-demo/nginx-error-sample.log nginx-http-auth

Check it worked

The summary reads Lines: 3 lines, 0 ignored, 2 matched, 1 missed. The missed line is the request with no credentials, and that is deliberate: a browser sends one of those every time it first meets a password prompt, so counting them would ban ordinary visitors.

On your server, run it against the real file with sudo fail2ban-regex /var/log/nginx/error.log nginx-http-auth. If you have mistyped your own password recently, you will see it matched.

Step 4 · Allow-list your own addresses first

Do this before you enable any new jail. A jail on ports 80 and 443 that bans your office address takes your own app away from you, and with the recidive jail later in this tutorial a ban can cover every port, SSH included.

ignoreip takes single addresses and CIDR ranges, separated by spaces. Replace 203.0.113.5 (one fixed address) and 192.0.2.0/28 (a VPN or office range) with your own. Fail2ban reads jail.d/*.local files after jail.local, so this list replaces the one you wrote in the previous tutorial: copy across any address from there that you still need.

Bash
sudo tee /etc/fail2ban/jail.d/allowlist.local > /dev/null <<'CONF'
[DEFAULT]
# Never banned by any jail. Replace the two documentation entries with your own.
ignoreip = 127.0.0.1/8 ::1 203.0.113.5 192.0.2.0/28
CONF

A note on shared addresses: many mobile networks, including most across Africa, put hundreds of customers behind one public IPv4 address (carrier-grade NAT). One ban on that address can lock out every customer of that network in that area for as long as the ban lasts. Keep the app jail's first ban short, as below, and do the per-account protection inside the app itself, as in /tutorials/defend-sign-in-against-credential-stuffing. Fail2ban is the backstop for noisy sources, not the only control.

Check it worked

Bash
sudo fail2ban-client -t

The last line is OK: configuration test is successful. If it reports a problem in allowlist.local, the usual cause is a comma between addresses: use spaces.

Step 5 · Add jails for the app and for nginx

A jail ties a filter to a log file and sets the limits. Put your jails in their own file under jail.d/, so jail.local from the previous tutorial stays as it is.

Bash
sudo tee /etc/fail2ban/jail.d/ledger.local > /dev/null <<'CONF'
[ledger]
enabled  = true
filter   = ledger-auth
logpath  = /var/log/ledger/app.log
backend  = auto
port     = http,https
maxretry = 5
findtime = 10m
bantime  = 15m

[nginx-http-auth]
enabled  = true
backend  = auto
port     = http,https
maxretry = 4
findtime = 10m
CONF

What each line does:

  • filter = ledger-auth names the file you wrote, without .conf.
  • backend = auto makes the jail watch the file itself. Ubuntu's defaults point Fail2ban at the systemd journal, which suits SSH but not apps that write their own log files.
  • port = http,https is what gets blocked. The app is reached through nginx, so a ban closes ports 80 and 443 to that address and leaves SSH alone.
  • Five failures in ten minutes earn a 15-minute ban. A real user who forgets a password rarely gets to five that fast; a script gets there in a second.
  • nginx-http-auth already has its log path (/var/log/nginx/*error.log) in Fail2ban's defaults, so you only turn it on and set limits.

If a CDN or load balancer sits in front of nginx, firewall bans do not work: every request reaches the server from the CDN's addresses. Block at the CDN instead, and use Fail2ban only for traffic that arrives directly.

Check it worked

Bash
sudo fail2ban-client -t

The test ends with OK: configuration test is successful. The error people meet most often here is Have not found any log file for ledger jail: the path in logpath does not exist yet. Fix the path, or let the app write its first line, then test again.

Step 6 · Make repeat offenders wait longer

Two features handle addresses that come back after a ban, and they do different jobs:

  • bantime.increment makes each new ban for the same address longer. It looks up past bans in Fail2ban's database. With it on, Fail2ban also counts each failure from an address it has banned before more heavily, so that address is banned again sooner.
  • The recidive jail reads Fail2ban's own log. An address banned three times in a day, by any jail, is banned from every port for a week.
Bash
sudo tee /etc/fail2ban/jail.d/repeat-offenders.local > /dev/null <<'CONF'
[DEFAULT]
bantime.increment = true
# Multiplier for the first ban, then each repeat; the last one keeps applying.
bantime.multipliers = 1 6 24 144
bantime.maxtime = 1w
# Count past bans from every jail, not only the one banning now.
bantime.overalljails = true

[recidive]
enabled  = true
backend  = auto
maxretry = 3
findtime = 1d
bantime  = 1w
CONF

With the app jail's bantime = 15m, the multipliers give 15 minutes for a first ban, then 90 minutes, 6 hours and 36 hours, and never more than the one-week bantime.maxtime. Separate the multipliers with single spaces. overalljails means an address caught by the nginx jail starts its next app ban further up the scale.

The database forgets bans after one day by default, which would reset the scale every night. Keep a month of history:

Bash
sudo mkdir -p /etc/fail2ban/fail2ban.d
sudo tee /etc/fail2ban/fail2ban.d/history.local > /dev/null <<'CONF'
[DEFAULT]
# Keep ban history for bantime.increment (the default is 1d).
dbpurgeage = 30d
CONF

Check it worked

Bash
sudo fail2ban-client -t

The configuration test passes. Remember that recidive bans on every port, SSH included, which is why your addresses went into ignoreip first.

Step 7 · Load the jails and trip one on purpose

Reload Fail2ban so it picks up the new files. A reload keeps current bans in place.

Bash
sudo systemctl reload fail2ban
Bash
sudo fail2ban-client status
sudo fail2ban-client get ledger ignoreip

The first command shows Number of jail: 4 and a jail list with ledger, nginx-http-auth, recidive and sshd. The second lists the addresses the ledger jail will never ban, including your own.

Now trip the app jail with five failures from the documentation address 198.51.100.7, stamped with the current time. The lines carry the username f2b-drill so anyone reading the app log later can tell they were a drill:

Bash
for i in 1 2 3 4 5; do
  printf '{"time":"%s","level":"warn","event":"login_failed","ip":"198.51.100.7","user":"f2b-drill"}\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" | sudo tee -a /var/log/ledger/app.log > /dev/null
done
sleep 5
Bash
sudo fail2ban-client status ledger

Check it worked

The ledger status shows Total failed: 5, Currently banned: 1 and 198.51.100.7 in the Banned IP list. The firewall now drops that address on ports 80 and 443; sudo nft list ruleset shows it in a set inside the f2b-table table.

The ban is also a line in Fail2ban's own log, which is what the recidive jail counts. Check that the recidive filter sees it:

Bash
sudo fail2ban-regex -o ip /var/log/fail2ban.log recidive

It prints 198.51.100.7. Two more bans of that address within a day and recidive would block it everywhere for a week.

Lift the drill ban:

Bash
sudo fail2ban-client set ledger unbanip 198.51.100.7

It replies 1. Unbanning also deletes this address's ban record for the jail, so a manual unban resets its place on the multiplier scale. An address whose ban runs out by itself keeps its history, and its next ban lasts 90 minutes.

Troubleshooting

  • Total failed stays at 0 after the drill: the jail is not reading the file. Check logpath, check backend = auto is in the jail, and run sudo fail2ban-regex /var/log/ledger/app.log ledger-auth to see whether the live lines match.
  • The jail matches lines but never bans: the timestamps are being read wrongly, so failures look older than findtime. fail2ban-regex shows the date template hits; if your app logs local time without an offset, make it log UTC with Z.
  • Found a match but no valid date/time found: the datepattern does not fit your line. Adjust it to your real format and test again.

Next steps

  • Make the app log failures in a form analysts and Fail2ban can both use: /tutorials/log-security-events-an-analyst-can-use.
  • Protect accounts inside the app, which Fail2ban cannot do on its own: /tutorials/defend-sign-in-against-credential-stuffing.
  • Revisit the SSH jail and the basics of reading and lifting bans: /tutorials/block-brute-force-logins-with-fail2ban.
  • Close every port your app does not need: /tutorials/set-up-ufw-firewall-ubuntu-26-04.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Operational and Technology Management

Get new tutorials

New tutorials, about twice a month.