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:
sudo apt-get update
sudo apt-get install -y fail2ban
fail2ban-client --version | head -n 1The 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:
{"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
ipfield must hold the real client address. Behind nginx your app sees every request coming from127.0.0.1unless it reads the address nginx passes on (for exampleproxy_set_header X-Real-IP $remote_addr;and the app trusting that header only from127.0.0.1). If the app logs127.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:
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"}
LOGCheck it worked
wc -l ~/fail2ban-demo/ledger-sample.logThe 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:
datepatterntells Fail2ban where the timestamp is and how to read it. Fail2ban uses the timestamp to decide whether a failure falls insidefindtime, so a filter that cannot read the date never bans.failregexis 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.ignoreregexlists 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.
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 =
CONFThe 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:
fail2ban-regex ~/fail2ban-demo/ledger-sample.log /etc/fail2ban/filter.d/ledger-auth.confThe 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:
fail2ban-regex -o ip ~/fail2ban-demo/ledger-sample.log /etc/fail2ban/filter.d/ledger-auth.confYou 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.
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-authCheck 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.
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
CONFA 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
sudo fail2ban-client -tThe 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.
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
CONFWhat each line does:
filter = ledger-authnames the file you wrote, without.conf.backend = automakes 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,httpsis 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-authalready 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
sudo fail2ban-client -tThe 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.incrementmakes 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
recidivejail reads Fail2ban's own log. An address banned three times in a day, by any jail, is banned from every port for a week.
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
CONFWith 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:
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
CONFCheck it worked
sudo fail2ban-client -tThe 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.
sudo systemctl reload fail2bansudo fail2ban-client status
sudo fail2ban-client get ledger ignoreipThe 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:
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 5sudo fail2ban-client status ledgerCheck 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:
sudo fail2ban-regex -o ip /var/log/fail2ban.log recidiveIt 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:
sudo fail2ban-client set ledger unbanip 198.51.100.7It 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 failedstays at 0 after the drill: the jail is not reading the file. Checklogpath, checkbackend = autois in the jail, and runsudo fail2ban-regex /var/log/ledger/app.log ledger-authto 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-regexshows the date template hits; if your app logs local time without an offset, make it log UTC withZ. Found a match but no valid date/time found: thedatepatterndoes 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.
Related tutorials
- Validate file uploads before you store or serve themYou will take a FastAPI image upload route that trusts everything the browser sends, prove its flaws with pytest, and rebuild it with size limits, type checks from the file's own bytes, Pillow re-encoding, random storage names and safe download headers.
- Use SSH certificates instead of copying keys to every serverYou will run a small SSH certificate authority with ssh-keygen, log in to an Ubuntu 26.04 server with an eight-hour user certificate, give the server a host certificate so clients stop asking about fingerprints, and revoke a certificate the server then refuses.
- Understand CodeQL and GitHub code scanningYou will install the CodeQL 2.27.6 bundle, build CodeQL databases for a small Express app and a Flask app, run the security-extended queries, trace a finding from user input to a dangerous call in the SARIF output, fix it and prove the alert is gone, and know what GitHub code scanning adds on top.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials