FALVARIX
FALVARIX
devops --real --no-hype

Advanced Fail2ban Configuration for Linux Servers

Advanced Fail2ban Configuration for Linux Servers

Advanced Fail2ban Configuration on Linux Servers

Open the authentication log on any server with a public IP that’s been running for a few hours. You’ll see hundreds of login attempts like root, admin, ubuntu or postgres, coming from addresses you’ve never seen before. It’s not a targeted attack against you. These are bots sweeping the entire IPv4 space nonstop, and your server is just one more name on the list.

Fail2ban is one of the oldest and most effective tools against this noise, but most installations stick to the defaults: a sshd with five attempts and a ten-minute ban. That stops the clumsiest bot and not much else. In this guide we’ll configure it the way it’s done in production, with progressive bans, repeat offenders, custom filters and alerts.

What Fail2ban does and where its usefulness ends

Fail2ban reads logs (or the systemd journal), detects patterns using regular expressions and, once a threshold is exceeded, runs an action, usually adding a firewall rule that blocks the IP for a set time. Everything is organized into three pieces:

  • Filter: the regular expression that defines what counts as a hostile attempt.
  • Action: what gets executed on a ban (nftables rule, API call, email alert).
  • Jail: the combination of filter, action and thresholds for a specific service.

It’s worth being clear about its limits from the start. Fail2ban is a reactive defense: it acts after seeing failed attempts. It doesn’t replace structural measures (key-based authentication, a restrictive firewall, updates), and slow, distributed attacks—with a single attempt per IP—barely trigger it. Its value lies in reducing noise surface and quickly cutting off anyone who keeps trying. Use it as one layer within defense in depth.

Installation and good starting practices

On Debian, Ubuntu and derivatives, install it from the official repositories of Debian or your distribution:

sudo apt update && sudo apt install fail2ban

Golden rule: never edit jail.conf. It gets overwritten on updates. Create your configuration in /etc/fail2ban/jail.local or, even better for environments managed with Ansible, in separate files inside /etc/fail2ban/jail.d/. That way your changes are versionable and auditable.

Base configuration in jail.local

Here’s a solid starting point for a modern server:

[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 10.0.0.0/8
backend = systemd
banaction = nftables-multiport
banaction_allports = nftables-allports

bantime = 1h
findtime = 10m
maxretry = 4

bantime.increment = true
bantime.factor = 2
bantime.maxtime = 4w

Let’s go over the key decisions:

  • ignoreip: includes your management network, the VPN or your bastion IPs. A typo in your password shouldn’t lock you out of your own server.
  • backend = systemd: reads directly from the journal, without depending on log files that rotate and, on some distributions, no longer even exist.
  • nftables-multiport: uses nftables, the current filtering backend on major distributions, instead of the legacy iptables layer.
  • bantime.increment: each repeat offense doubles the ban time, up to a maximum of four weeks. It’s the change with the best effort-to-results ratio in the whole configuration.

Tuning findtime and maxretry sensibly

A maxretry of 3 to 5 with a findtime of 10 minutes works well for SSH. For public services with legitimate users who make mistakes (web panels, webmail), be more forgiving to avoid false positives. If most of your traffic comes from offices behind shared NAT, an aggressive ban can block dozens of people at once. Adjust based on your real traffic, not on a recipe.

Protecting SSH: aggressive mode and long bans

The sshd jail accepts a parameter many people overlook, mode. In aggressive mode it combines normal detections with connection attempts that never reach authentication: clients that disconnect before login, invalid protocols or key exchange failures, typical of scanners.

[sshd]
enabled = true
mode = aggressive
port = ssh
maxretry = 3
bantime = 2h

If you changed the SSH port, specify it here. And remember that Fail2ban doesn’t fix a bad configuration: disable PasswordAuthentication, prohibit PermitRootLogin and require keys. With those measures in place, a bot will never get far enough to guess anything; Fail2ban simply reduces noise and load.

If you want to go a step further and eliminate static keys entirely, take a look at how Teleport replaces SSH keys with audited access. Combined with Fail2ban, port 22 stops being a security problem and becomes a minor annoyance.

The recidive jail: exemplary punishment for repeat offenders

A bot banned for an hour will be back tomorrow. The recidive jail watches Fail2ban’s own log and, if an IP has been banned several times over a long period, blocks it on all ports and for a long time:

[recidive]
enabled = true
backend = auto
logpath = /var/log/fail2ban.log
banaction = %(banaction_allports)s
bantime = 1w
findtime = 1d
maxretry = 3

Note backend = auto. Since we’ve defined systemd as a global value, this jail needs to read a text file again, and without that setting it won’t start correctly. It’s one of the most common mistakes when combining both options.

Protecting web services with custom filters

Bots don’t just attack SSH. A server running Nginx or Apache constantly receives requests for /.env, /.git/config, /wp-login.php or /phpmyadmin, even if you have none of that installed. Fail2ban includes filters like nginx-http-auth and nginx-botsearch, but what’s really useful is writing your own.

Create /etc/fail2ban/filter.d/nginx-scanners.conf:

[Definition]
failregex = ^<HOST> .* "(GET|POST|HEAD) [^"]*(\.env|\.git/|wp-login\.php|xmlrpc\.php|phpmyadmin|vendor/phpunit)[^"]*" (400|401|403|404)
ignoreregex =

And the corresponding jail:

[nginx-scanners]
enabled = true
port = http,https
logpath = /var/log/nginx/access.log
backend = auto
maxretry = 2
findtime = 5m
bantime = 24h

With two requests to paths your application never serves, the IP is blocked for a full day. If your application does use any of those paths (for example, if you run WordPress), remove it from the pattern.

Always validate your regular expressions

Before enabling a new filter, test it against your real logs:

fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-scanners.conf

The output shows how many lines match and which are ignored. Checking this avoids the classic scenario of a filter that’s too broad and bans your own customers on a Friday afternoon.

Containers, proxies and CDNs: the cases that break Fail2ban

This is where “tutorial-grade” configurations fail in production.

Docker. Traffic to published containers goes through the forwarding chain (FORWARD), not INPUT, so a standard ban won’t block it. For those services you need to adjust the action’s chain (for example, DOCKER-USER in iptables environments) and verify with a real test that the banned IP no longer reaches the container.

Reverse proxy or load balancer. If Nginx sits behind another proxy, the log will show the balancer’s IP and Fail2ban will end up banning your own infrastructure. Configure the real_ip module to log the real client IP before the filter reads it.

CDN. If you use a provider like Cloudflare, banning at the server firewall is useless because the attacker never connects directly. Fail2ban can trigger an action that uses the provider’s API to block at the edge, before traffic reaches your infrastructure. It’s more efficient and protects your bandwidth too.

Alerts and observability

A silent ban doesn’t help you spot patterns. Fail2ban offers actions like action_mwl, which sends an email with the alert and the relevant log lines:

[DEFAULT]
destemail = seguridad@tudominio.com
sender = fail2ban@tudominio.com
action = %(action_mwl)s

On a large fleet this generates too much email. The sensible approach is to send events to the journal and collect them with your observability stack (Loki, Elastic or similar), and reserve active alerts for abnormal spikes in bans or for the recidive jail. If your custom actions need API tokens or webhook credentials, don’t leave them in plain text in /etc/fail2ban/: manage them with a secrets manager, as we explain in our guide to migrating from Vault to OpenBao in production.

Day-to-day operations: commands you should master

These commands handle 90% of situations:

# Estado general y por jail
sudo fail2ban-client status
sudo fail2ban-client status sshd

# Desbanear una IP (por ejemplo, un compañero bloqueado)
sudo fail2ban-client set sshd unbanip 203.0.113.25

# Recargar configuración sin perder baneos activos
sudo fail2ban-client reload

# Ver las reglas que está aplicando nftables
sudo nft list ruleset | grep -A5 f2b

Always reload after validating syntax with fail2ban-client -t. And automate deployment: with Ansible or Terraform, your jails are reviewable, reproducible code, not manual tweaks forgotten on a single server.

Fail2ban hardening checklist

Before considering the server protected, verify these points:

  1. jail.local or jail.d/ instead of editing jail.conf.
  2. ignoreip with your management network and bastions.
  3. Backend and banaction consistent with your system (systemd and nftables).
  4. Incremental banning and the recidive jail active.
  5. sshd jail in aggressive mode, with password authentication disabled.
  6. Custom filters validated with fail2ban-regex.
  7. Real client IP correctly logged behind proxies and CDNs.
  8. Ban alerts and metrics integrated into your monitoring.
  9. Configuration versioned and deployed as code.

Conclusion

Fail2ban won’t turn your server into a fortress on its own, but well configured it drastically reduces the noise, load and risk generated by automated attacks. The difference between a default install and a production one lies in the details: progressive bans, a merciless recidive, filters tailored to what your server actually receives, and correct integration with proxies and containers.

Start with the sshd jail, add recidive and write a filter for your web server’s scanners. In an afternoon you’ll have a measurable layer of defense, and over time you’ll watch the volume of hostile attempts drop in the logs.

Keep reading