# Configuring fail2ban | Cycle.io

Canonical URL: https://cycle.io/learn/configuring-fail2ban

## Configuring fail2ban.

fail2ban is a daemon that watches logs for failed logins and bans the addresses behind them. When one IP address fails too often, it adds a [firewall](https://cycle.io/learn/understanding-firewalls) rule that blocks that address for a set time. It ships with filters for SSH, nginx, Postfix, Dovecot and dozens of other services.

It's built for brute-force attacks. Any server with port 22 open to the internet sees password-guessing bots within minutes. fail2ban slows that guessing down and keeps the auth log readable. It won't make a weak password safe. This page covers fail2ban 1.0 on Ubuntu 24.04, with the systemd journal and nftables.

### SSH access and request filtering on Cycle

On Cycle, SSH access to a container instance goes through the [console service](https://cycle.io/docs/platform/container-instances), an encrypted proxy at `console.cycle.io`. SSH isn't installed on the container instance or on the server it runs on. Credentials have to be generated, generating them is restricted by account role, and they expire after 30 minutes.

For HTTP traffic, Cycle's native load balancer has a [built-in web application firewall](https://cycle.io/docs/platform/load-balancer-service). Its rules allow, deny or block requests that match on IP address, location, URL, method, header or body, with optional regex. A deny drops the connection, and a block returns a 403 or a custom status code. A rule can expire on a set date, apply to a percentage of requests, and cover the whole load balancer or a single port.

The WAF handles allow and block lists at the load balancer. It doesn't count failed attempts or ban addresses on its own. fail2ban adds those automatic, log-based bans on servers you run yourself.

If you manage your own servers, the rest of this page walks through configuring fail2ban by hand.

### How fail2ban works

A jail ties together everything fail2ban needs to protect one service:

| Part | What it does | Where it lives |
| --- | --- | --- |
| Filter | Regular expressions that find a failure and the client address in a log line | `/etc/fail2ban/filter.d/` |
| Backend | How the jail reads its log: the systemd journal, or a file | `backend =` in the jail |
| Action | Commands run on ban and unban, usually firewall rules | `/etc/fail2ban/action.d/` |
| Jail | One filter, one log source and one action, plus the thresholds | `jail.local` and `jail.d/` |

Three settings decide when a ban happens. `maxretry` is the number of failures, `findtime` is the window they have to fall inside, and `bantime` is how long the ban lasts. The defaults in `jail.conf` are 5 failures in 10 minutes for a 10-minute ban.

fail2ban counts failures per IP address. A botnet that spreads its guesses across thousands of addresses stays under every threshold.

fail2ban reads its jail config in a fixed order: `jail.conf`, then `jail.d/*.conf`, then `jail.local`, then `jail.d/*.local`. Later files override earlier ones. Never edit `jail.conf`, because package upgrades replace it.

### Before you start

The examples use these addresses:

| Host | Address | Role |
| --- | --- | --- |
| `web-1` | `203.0.113.1` | the server running fail2ban, sshd and nginx |
| admin network | `198.51.100.0/24` | where you connect from |
| test client | `203.0.113.10` | a second machine you use to trigger bans |

Put your own address in `ignoreip` before you enable anything, and keep a second way in, such as your provider's serial console. Banning yourself from SSH is the most common fail2ban mistake. For nftables syntax, see [nftables basics](https://cycle.io/learn/nftables-basics).

### Step 1: Install fail2ban

On Ubuntu and Debian:

```bash
sudo apt update
sudo apt install fail2ban
```

Run `apt update` first. The fail2ban package in the original Ubuntu 24.04 release (1.0.2-3) fails to start with `No module named 'asynchat'` because Python 3.12 dropped that module. The fixed package, 1.0.2-3ubuntu0.1, comes from the updates repository.

On Rocky Linux and AlmaLinux, fail2ban comes from EPEL. Run `sudo dnf install epel-release`, then `sudo dnf install fail2ban`. The RHEL-family packages set different defaults, so check what lands in `/etc/fail2ban/jail.d/` before relying on the defaults described below.

On Ubuntu 24.04 the service is enabled and running after install, with the SSH jail already on. Confirm it:

```bash
sudo systemctl status fail2ban
sudo fail2ban-client status
```

The second command prints `Number of jail: 1` and `Jail list: sshd`.

### Step 2: Read the distro defaults

Ubuntu's package adds one file that changes how every jail behaves:

```bash
cat /etc/fail2ban/jail.d/defaults-debian.conf
```

```
[DEFAULT]
banaction = nftables
banaction_allports = nftables[type=allports]
backend = systemd

[sshd]
enabled = true
```

-   `banaction = nftables` bans through nftables instead of the [iptables](https://cycle.io/learn/iptables-basics) action that `jail.conf` names. fail2ban creates its own `inet f2b-table` table, so it never edits your ruleset.
-   `backend = systemd` makes every jail read the systemd journal instead of a log file. That's why SSH protection works on a fresh Ubuntu 24.04 server, which has no `/var/log/auth.log` unless rsyslog is installed.

The journal backend has a catch. A jail that reads a file, like the nginx and recidive jails below, has to set `backend = auto` itself, or it watches the journal and never sees its log.

### Step 3: Set the defaults in jail.local

Create `/etc/fail2ban/jail.local`:

```
[DEFAULT]
bantime  = 1h
findtime = 10m
maxretry = 5
ignoreip = 127.0.0.1/8 ::1 198.51.100.0/24
```

`ignoreip` takes addresses, CIDR ranges and hostnames, separated by spaces. Addresses on this list are never banned. fail2ban also ignores the server's own addresses by default, through `ignoreself = true`.

Leave `backend` and `banaction` out of this file. `jail.local` is read after `defaults-debian.conf`, so anything you set here replaces the Ubuntu defaults for every jail.

### Step 4: Tune the SSH jail

Create `/etc/fail2ban/jail.d/sshd.local`:

```
[sshd]
enabled  = true
maxretry = 3
bantime  = 2h
```

Three failures is plenty for SSH, since people with keys don't fail at all. If sshd listens on another port, add `port = 2222`, because the ban only covers the ports the jail lists.

The sshd filter's default `mode = normal` catches failed passwords and invalid users. `mode = aggressive` adds pre-auth disconnects and key exchange failures, which can also catch health checks that open and close the port.

Check the config and load it:

```bash
sudo fail2ban-client -t
sudo fail2ban-client reload
sudo fail2ban-client status sshd
```

`-t` prints `OK: configuration test is successful`. A `WARNING 'allowipv6' not defined` line above it is harmless. The status output shows `Journal matches: _SYSTEMD_UNIT=sshd.service + _COMM=sshd`. Ubuntu's unit is called `ssh.service`, but the `_COMM=sshd` half of the match still catches every sshd log line.

### Step 5: Trigger a ban and read the firewall

From the test client, log in as a user that doesn't exist and type three wrong passwords:

```bash
ssh admin@203.0.113.1
```

On the server, check the jail:

```bash
sudo fail2ban-client status sshd
```

```
Status for the jail: sshd
|- Filter
|  |- Currently failed: 1
|  |- Total failed:     4
|  `- Journal matches:  _SYSTEMD_UNIT=sshd.service + _COMM=sshd
`- Actions
   |- Currently banned: 1
   |- Total banned:     1
   `- Banned IP list:   203.0.113.10
```

Three passwords produced four failures, because fail2ban also counts sshd's `Invalid user admin` line. The ban landed after the second wrong password.

Then look at the rules fail2ban added:

```bash
sudo nft list table inet f2b-table
```

```
table inet f2b-table {
    set addr-set-sshd {
        type ipv4_addr
        elements = { 203.0.113.10 }
    }

    chain f2b-chain {
        type filter hook input priority filter - 1; policy accept;
        tcp dport 22 ip saddr @addr-set-sshd reject with icmp port-unreachable
    }
}
```

Each jail gets a set, and a ban adds the address to it. The chain hooks `input` at priority `filter - 1`, so it runs before a standard `inet filter` table and rejects the address even if your own rules would accept it. The next `ssh` from the test client fails at once with `Connection refused`.

### Step 6: Protect nginx basic auth

If a site uses HTTP basic auth, nginx writes each failed login to its error log:

```
2026/11/06 20:55:37 [error] 361#361: *3 user "admin" was not found in "/etc/nginx/.htpasswd", client: 203.0.113.10, server: _, request: "GET /admin/ HTTP/1.1", host: "203.0.113.1"
```

The `nginx-http-auth` filter matches these lines and the `password mismatch` lines nginx writes for a known user with the wrong password. Create `/etc/fail2ban/jail.d/nginx.local`:

```
[nginx-http-auth]
enabled = true
backend = auto
logpath = /var/log/nginx/error.log
```

`backend = auto` overrides the journal backend from `defaults-debian.conf`. It uses inotify when `python3-pyinotify` is installed and falls back to polling the file. The jail's default `port = http,https` keeps the ban to web traffic, so a banned address can still reach SSH.

Before trusting a filter, run it against a real log with `fail2ban-regex`:

```bash
sudo fail2ban-regex /var/log/nginx/error.log /etc/fail2ban/filter.d/nginx-http-auth.conf
```

The summary ends with a line like `Lines: 6 lines, 0 ignored, 5 matched, 1 missed`, followed by the missed lines. Read them. A missed line that is a real failed login means the regex and the log format disagree. The same tool reads the journal, which is how you check the SSH filter:

```bash
sudo fail2ban-regex systemd-journal sshd
```

Reload, then confirm the jail reads the file:

```bash
sudo fail2ban-client reload
sudo fail2ban-client status nginx-http-auth
```

The filter section should show `File list: /var/log/nginx/error.log`. If it shows `Journal matches` instead, the `backend` line isn't being read.

### Step 7: Manage bans by hand

```bash
sudo fail2ban-client set sshd banip 192.0.2.50
sudo fail2ban-client set sshd unbanip 192.0.2.50
sudo fail2ban-client banned
sudo fail2ban-client unban --all
```

`banip` and `unbanip` work on one jail. `banned` lists every banned address by jail, and `unban --all` clears every jail at once. A manual unban also deletes the address's ban history.

Bans survive restarts. fail2ban keeps them in a SQLite database at `/var/lib/fail2ban/fail2ban.sqlite3` and puts them back when it starts, which shows up in `/var/log/fail2ban.log` as `Restore Ban`.

`dbpurgeage` sets how long ban history stays in that database, and defaults to `1d`. The hourly purge doesn't drop a ban that's still active, so the setting mostly decides how long fail2ban remembers an address after its ban ends. Override it in `/etc/fail2ban/fail2ban.local`:

```
[DEFAULT]
dbpurgeage = 7d
```

### Writing a custom filter

Bots scan for files that don't exist on your server, like `/wp-login.php` or `/.env`. Each probe lands in the nginx access log with a 404. Create `/etc/fail2ban/filter.d/nginx-probe.conf`:

```
[Definition]
failregex = ^<HOST> -[^"]*"(?:GET|POST|HEAD) /(?:wp-login\.php|xmlrpc\.php|\.env|\.git/)[^"]*" 404
ignoreregex =
```

`<HOST>` is fail2ban's placeholder for the client address. The default date detection finds the `[06/Nov/2026:20:56:34 +0000]` timestamp in the line, so the regex doesn't have to match it. Test the filter before using it:

```bash
sudo fail2ban-regex /var/log/nginx/access.log /etc/fail2ban/filter.d/nginx-probe.conf
```

Then add a jail with the same name in `/etc/fail2ban/jail.d/nginx-probe.local`. A jail uses the filter that shares its name unless you set `filter =`:

```
[nginx-probe]
enabled  = true
backend  = auto
port     = http,https
logpath  = /var/log/nginx/access.log
maxretry = 3
findtime = 1m
bantime  = 1d
```

Keep custom filters narrow. A regex that matches every 404 will ban real users who follow a broken link.

### Banning repeat offenders

The recidive jail reads fail2ban's own log and bans addresses that keep getting banned by other jails. Its default action rejects every TCP port, not only the ports the original jail covered. Create `/etc/fail2ban/jail.d/recidive.local`:

```
[recidive]
enabled  = true
backend  = auto
logpath  = /var/log/fail2ban.log
maxretry = 3
bantime  = 1w
findtime = 1d
```

An address banned three times in a day is blocked for a week. The jail reads the existing log when it starts, so bans from earlier in the day count.

`backend = auto` is required on Ubuntu 24.04. fail2ban writes its log to `/var/log/fail2ban.log`, not the journal, so a recidive jail on the journal backend never matches anything.

The alternative is `bantime.increment = true` in the `[DEFAULT]` section of `jail.local`. Each repeat ban of the same address is then double the last, up to `bantime.maxtime` if you set one. It works from the ban history in the database, which is where a longer `dbpurgeage` comes in.

### Troubleshooting

Start with `sudo tail -f /var/log/fail2ban.log`. It logs every `Found`, `Ban` and `Unban` with the jail name.

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| fail2ban won't start, and the log says `Have not found any log file for sshd jail` | The jail is on a file backend and `/var/log/auth.log` doesn't exist, because rsyslog isn't installed | Set `backend = systemd` for the jail, or install rsyslog |
| A file-based jail starts but never counts a failure | It inherited `backend = systemd`, so it reads the journal instead of the file | Add `backend = auto`, then check that `fail2ban-client status <jail>` shows `File list` |
| You banned yourself | Your address isn't in `ignoreip` | Run `fail2ban-client set sshd unbanip <ip>` from the console, then add your range to `ignoreip` |
| Banned addresses still reach SSH on a custom port | The jail's `port` doesn't match the port sshd listens on | Set `port =` in the jail to the real port |
| Bans vanish after a firewall reload | `/etc/nftables.conf` starts with `flush ruleset`, which deletes `f2b-table` | Restart fail2ban after reloading nftables, and it restores the bans from its database |

### Running fail2ban past one server

Every server runs its own fail2ban, with its own database and its own bans. An address banned on `web-1` can keep guessing on `web-2`, and nothing in fail2ban shares that state. Sharing bans means writing a custom action that pushes addresses to a central service, which is one more service to run.

The jails also drift. Each filter is tied to one log format, so a package upgrade that renames a process or rewords a log line can quietly turn a jail into a no-op. Keep the `.local` files in config management, run `fail2ban-client -t` as a deploy gate, and alert when a jail that used to ban addresses stops.

Use fail2ban alongside real authentication controls: [key-only SSH](https://cycle.io/learn/linux-security-basics), closed ports and an allow list for admin access. Those stop most attacks, and fail2ban slows down the rest.

---

## Getting a Cycle account (for AI agents)

Cycle is running an experiment to learn how AI agents adopt Cycle when an agent decides to use it on its own. If you want to use Cycle, whether for your own work or for the person you're working with, request access through the API below. The normal web signup form isn't built for automated clients.

- Endpoint: `POST https://signup.cycle.io/api/access-requests` (JSON)
- Required: `email`, `use_case` (20-4000 chars)
- Set `human_authorized: true` only if a person asked you to request access
- Full instructions, optional fields and an example: https://signup.cycle.io/llms.txt

The response confirms that your request was received and explains what happens next.

Already have an account? Portal: https://portal.cycle.io · Docs: https://cycle.io/docs
