Join our Newsletter — 33% off our NHI Course
Home› Guides› Fail2ban Guide: Brute-Force Protection for SSH and Web…
Guide Endpoint Security

Fail2ban Guide: Brute-Force Protection for SSH and Web Servers

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, under the editorial direction of Lalit Choda Updated 18 November 2026 14 min read
On this page

Fail2ban cuts the noise and cost of password guessing against SSH and web services by turning repeated failures in your logs into temporary firewall bans, but it is a rate limiter, not an authentication control. Its own documentation says plainly that it reduces the rate of failed logins but cannot remove the risk of weak authentication, and recommends two-factor or public key mechanisms for services that need real protection.

This guide shows how to install and configure Fail2ban safely: where configuration belongs, what the default values mean, how to tune ban and detection windows, how to protect SSH and common web servers, how to handle repeat offenders, and how to test filters before you trust them. It also covers what Fail2ban cannot do, so it sits in the right place in a layered design. For the account-side controls that complement it, see the Account Lockout and Brute-Force Protection Guide.

This is an independent guide from NHI Mgmt Group, based on the Fail2ban project's public documentation as of November 2026. It is not sponsored or reviewed by the Fail2ban project. Features change between releases, so confirm settings against the configuration files shipped with your version.

Key takeaways

  • Never edit jail.conf or fail2ban.conf. Put changes in jail.local, jail.d/*.local or fail2ban.local, which are parsed after the shipped files.
  • The shipped defaults are bantime = 10m, findtime = 10m and maxretry = 5. They are a starting point; most internet-facing servers need longer bans and incremental banning.
  • Set ignoreip explicitly for your management and monitoring ranges before enabling jails, so you do not lock out your own automation.
  • Use the recidive jail to ban repeat offenders across all ports for a week.
  • Test every filter against real logs with fail2ban-regex. A filter that matches nothing gives false confidence.
  • Fail2ban does little against distributed password spraying from many addresses. Key-based SSH, MFA and account-level controls do the real work.

How Fail2ban works

Fail2ban is an intrusion prevention daemon that reads log files, or the systemd journal, and looks for patterns that indicate failed authentication or abuse. When an address produces more than a set number of matching lines inside a time window, Fail2ban runs an action, typically updating firewall rules to reject new connections from that address for a set period. The project describes it as working with standard logs such as sshd and Apache, and it can be pointed at any log you can write a pattern for.

Three building blocks matter:

  • Filters in filter.d/ hold the regular expressions that match failure lines and extract the host address.
  • Actions in action.d/ define what happens on ban and unban, such as inserting a firewall rule, sending an email or reporting to an abuse service.
  • Jails in jail.conf and your .local overrides combine a filter, a log source, one or more actions and the thresholds that trigger a ban.

The server is controlled with fail2ban-client over a local socket, which by default is /var/run/fail2ban/fail2ban.sock. Ban state persists in an SQLite database, by default /var/lib/fail2ban/fail2ban.sqlite3, so bans survive restarts. IPv6 address matching has been supported since version 0.10. The project README lists Python 3.5 or later as a requirement, with optional pyinotify and systemd bindings for more efficient log monitoring.

Installing and laying out configuration safely

Install Fail2ban from your distribution's package repository so security updates arrive with the rest of the operating system. The shipped jail.conf begins with the instruction that you should not modify the file and should provide customisations in a jail.local file or a jail.d/customisation.local. The same advice applies to fail2ban.conf and fail2ban.local.

The jail.conf manual page explains the order: .conf files are parsed first, then .d directory files, then .local files, so a .local file should contain only the settings you want to change. This matters for security because package upgrades replace .conf files. If you edit them directly, an upgrade can silently revert a jail to disabled or restore default thresholds.

A clean layout for configuration management looks like this:

  • /etc/fail2ban/fail2ban.local: daemon settings such as log target and database retention.
  • /etc/fail2ban/jail.d/00-defaults.local: your [DEFAULT] overrides, including ignoreip, ban times and the ban action.
  • /etc/fail2ban/jail.d/sshd.local, nginx.local and so on: one file per service, with enabled = true and any per-jail tuning.
  • /etc/fail2ban/filter.d/*.local: overrides for shipped filters, rather than edits to the originals.

Manage these files with your configuration management tool and run fail2ban-client -t (or --test) in the pipeline to validate configuration before reload.

Understanding and tuning the defaults

The [DEFAULT] section of the shipped jail.conf sets values that every jail inherits unless overridden:

SettingShipped valueMeaning
bantime10mEffective ban duration.
findtime10mWindow before the current time in which failures count towards a ban.
maxretry5Number of failures within findtime needed to ban the address.
backendautoSelects the best log monitoring backend, starting with file based options such as pyinotify or polling.
usednswarnHow host names found in logs are handled.
ignoreipCommented outNo addresses are ignored by default apart from the host's own addresses via ignoreself.
action%(action_)sBan only, with no notification.

With the defaults, an attacker can make five guesses every ten minutes and then wait out a ten minute ban, which is still hundreds of attempts per address per day. NHI Mgmt Group suggests these starting points for an internet-facing server, to be adjusted for your user base and support tolerance:

  • bantime = 1h with incremental banning enabled, so repeat bans grow quickly.
  • findtime = 30m and maxretry = 4 for SSH.
  • An explicit ignoreip list, described below.

Incremental ban time. The shipped file includes, commented out, bantime.increment = true, bantime.factor, bantime.formula, bantime.multipliers, bantime.maxtime, bantime.rndtime and bantime.overalljails. Enabling bantime.increment makes each new ban for the same address longer than the last, and bantime.maxtime caps it. Setting bantime.overalljails = true makes the increase count bans from all jails, not only the current one. Set a bantime.maxtime such as one or four weeks, so a mistaken ban on a shared address eventually expires.

Database retention. fail2ban.conf sets dbpurgeage to 86400 seconds (24 hours) and dbmaxmatches to 10. Ban history older than dbpurgeage is purged, so incremental banning and the recidive jail can only see history that is still in the database. If you lengthen recidive's findtime or rely on long ban histories, raise dbpurgeage to match.

Allowlisting without creating a bypass

ignoreip accepts addresses, CIDR ranges, DNS names or a file: reference to a list. Use it for bastion hosts, monitoring systems, configuration management servers and your own office or VPN egress ranges. Without it, a misconfigured automation account or a vulnerability scanner can ban the very systems you need to fix the problem.

Keep the list short and specific:

  • Prefer CIDR ranges you own over DNS names, which depend on resolution and can be changed by whoever controls the zone.
  • Do not allowlist whole cloud provider ranges or shared NAT addresses; attackers rent from the same providers.
  • Review the list whenever egress addresses change, and keep it in version control.

ignorecommand lets you run a script that decides whether an address should be ignored; the address is not banned if the command exits with code 0. It runs only when ignoreself and ignoreip do not match. Treat that script as security critical code, since a bug in it can disable banning entirely.

Service accounts and automation are a common source of self-inflicted bans. A deployment tool with an expired SSH key or a monitoring check with a rotated password will fail repeatedly and get its source banned. Fix the credential rather than allowlisting the source, and track those failures as a signal of stale non-human credentials. The guide How to find unused GitHub deploy keys and SSH keys covers cleaning up the key side.

Protecting SSH

The sshd jail ships with port = ssh, a log path and backend chosen by distribution specific variables (%(sshd_log)s and %(sshd_backend)s), and a mode option. The available modes are normal (the default), ddos, extra and aggressive, which combines all. Aggressive mode catches more pre-authentication abuse, such as connections that disconnect before authenticating, at the cost of more chance of banning misbehaving legitimate clients.

A minimal jail.d/sshd.local enables the jail, sets the port if SSH does not listen on 22, and sets the mode you have tested. On distributions where sshd logs only to the journal, the backend must be systemd; the manual page explains that the systemd backend reads the journal through the systemd Python library and uses journalmatch to filter entries. If the backend cannot read the log source, the jail will run but never ban, so always confirm with a test failure.

Fail2ban is only one layer for SSH. NHI Mgmt Group recommends, in order of impact:

  1. Disable password authentication and require keys or certificates.
  2. Disable direct root login.
  3. Restrict SSH to a bastion or VPN so it is not on the open internet.
  4. Run Fail2ban to reduce log noise and slow residual guessing.

Once passwords are disabled, Fail2ban mainly reduces log volume and CPU spent on handshakes. That is still useful, because quieter logs make real anomalies easier to spot.

Protecting web services

The shipped jail.conf includes jails for common web servers. For nginx: nginx-http-auth, nginx-limit-req, nginx-botsearch, nginx-bad-request and nginx-forbidden. For Apache: apache-auth, apache-badbots, apache-noscript, apache-overflows, apache-nohome, apache-botsearch, apache-fakegooglebot, apache-modsecurity and apache-shellshock.

Useful patterns:

  • Basic authentication. nginx-http-auth and apache-auth catch failed HTTP basic authentication, often used on admin panels and staging sites.
  • Rate limit offenders. nginx-limit-req bans addresses that repeatedly hit nginx limit_req zones, turning a per-request limit into a longer firewall ban.
  • Scanners. The botsearch jails ban clients probing for common admin paths and files that do not exist on your site.
  • WAF events. apache-modsecurity bans clients that repeatedly trigger ModSecurity rules.
  • Application logins. For your own application, log failed logins with a fixed format that includes the client address, then write a custom filter. Never let the filter match on user controlled fields alone, or attackers can inject log lines that ban other addresses.

Behind a reverse proxy or CDN, web server logs may show the proxy's address rather than the client's. Banning that address blocks everyone. Make sure the web server logs the real client address from a header set only by your own trusted proxy, and that the ban action can act at the right layer. In many CDN deployments the right answer is to ban at the CDN or WAF rather than on the origin firewall.

Repeat offenders, actions and notifications

The recidive jail reads Fail2ban's own log at /var/log/fail2ban.log and bans addresses that have been banned repeatedly. It ships with bantime = 1w, findtime = 1d and banaction = %(banaction_allports)s, so a persistent attacker is blocked on all ports for a week. Enable it on every internet-facing host, and make sure fail2ban.local logs to that file rather than only to standard error.

The shipped action shortcuts are:

  • action_: ban only (the default).
  • action_mw: ban and send an email with whois information.
  • action_mwl: ban and send an email with whois information and the matched log lines.
  • action_xarf: ban and send an X-ARF abuse report.
  • action_abuseipdb: report to AbuseIPDB, which needs an API key.

Email per ban does not scale on busy hosts. A better pattern is to log bans centrally and alert on unusual volume or on bans of internal ranges. If you use a reporting action, store its API key with restricted file permissions and rotate it like any other service credential.

The ban action itself must match your firewall. The shipped default is commented out in jail.conf; the manual page uses iptables-multiport and iptables-ipset examples. Check action.d/ for the actions your version provides, choose one that matches the firewall your host actually uses, and confirm bans appear in the live rule set.

Testing and operating Fail2ban

A jail that never bans is worse than no jail, because it creates false confidence. Test each one:

  • Run fail2ban-regex /var/log/auth.log filter.d/sshd.conf, or use systemd-journal as the log argument, to see how many lines match. The tool also accepts a filter name with options, such as sshd[mode=aggressive], and --print-all-missed shows lines that did not match.
  • From a test address that is not in ignoreip, generate failures and confirm the ban appears with fail2ban-client status sshd and in the firewall rules.
  • Release the test address with fail2ban-client set sshd unbanip <IP>.

Day to day commands from the fail2ban-client manual:

TaskCommand
Check the server is alivefail2ban-client ping
List jailsfail2ban-client status
Show a jail's counters and banned addressesfail2ban-client status <JAIL>
List all banned addresses by jailfail2ban-client banned
Ban or unban manuallyfail2ban-client set <JAIL> banip <IP> / unbanip <IP>
Unban everythingfail2ban-client unban --all
Reload configurationfail2ban-client reload

Ship Fail2ban's log to your SIEM. A sudden rise in bans can indicate a campaign; bans of your own ranges can indicate a broken automation credential or a compromised internal host. If you suspect a host has already been compromised, follow How to check a Linux server for signs of compromise.

What Fail2ban does not protect against

Fail2ban counts failures per source address. That design has clear limits:

  • Distributed guessing. Password spraying and credential stuffing from botnets or residential proxies use many addresses with few attempts each, staying under maxretry. These map to MITRE ATT&CK T1110 sub-techniques; see the MITRE ATT&CK T1110 Brute Force Guide.
  • Valid credentials. A stolen key or password succeeds on the first try and produces no failure to count.
  • Volumetric attacks. Banning is too slow and too local to absorb a network flood.
  • Shared addresses. Carrier grade NAT and corporate egress mean one ban can block many legitimate users.
  • Log gaps. If the service stops logging, changes format after an upgrade or logs to a location the jail does not read, banning stops silently.

Account-level controls such as lockout thresholds, MFA and anomaly detection on successful logins close the gaps that address-based banning leaves.

Common failure patterns

  • Edited jail.conf. Package upgrades overwrite changes and quietly disable jails.
  • Wrong backend. The jail watches a log file that no longer exists because the service logs only to the journal.
  • No allowlist. Monitoring or deployment systems with stale credentials get banned during an incident.
  • Allowlisting the proxy. The reverse proxy address is allowlisted or banned, so either nobody or everybody is blocked.
  • Defaults left in place. Ten minute bans with five retries slow attackers only slightly.
  • Short database retention. recidive and incremental bans miss history purged after 24 hours.
  • Fail2ban instead of keys. Password SSH stays enabled on the assumption that banning is enough.
  • Untested custom filters. Regular expressions match nothing, or match attacker controlled text that can be used to ban others.

Practitioner checklist

  • Install Fail2ban from distribution packages and keep it patched with the operating system.
  • Keep all changes in .local files under version control and validate with fail2ban-client -t.
  • Set an explicit, narrow ignoreip for management, monitoring and automation ranges.
  • Raise bantime, enable bantime.increment with a bantime.maxtime cap, and tune findtime and maxretry.
  • Enable the sshd jail with the correct backend and a tested mode, and disable SSH password authentication.
  • Enable web jails that match your server and confirm the real client address is logged behind proxies.
  • Enable recidive and set dbpurgeage at least as long as its findtime.
  • Test every jail with fail2ban-regex and a live test ban before relying on it.
  • Forward Fail2ban logs to your SIEM and alert on spikes and on bans of internal ranges.
  • Treat repeated failures from service accounts as stale credentials to fix, not sources to allowlist.

Standards and references

Related NHI Mgmt Group resources: Account Lockout and Brute-Force Protection Guide · MITRE ATT&CK T1110 Brute Force Guide · How to check a Linux server for signs of compromise · How to find unused GitHub deploy keys and SSH keys

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick both boxes to continue.