/Fail2Ban

Fail2Ban

295
v0.11.0

Fail2ban plugin for traefik

Build Status

This plugin is an implementation of a Fail2ban instance as a middleware plugin for Traefik.

Middleware

After installing the plugin, it can be configured through a Middleware, e.g.:

apiVersion: traefik.io/v1alpha1
kind: Middleware
metadata:
name: fail2ban-test
spec:
plugin:
fail2ban:
logLevel: INFO
denylist:
ip: 127.0.0.1
Add the middleware to an ingressroute
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: simplecrd
namespace: default
spec:
entryPoints:
- web
routes:
- match: Host(`fail2ban.localhost`)
kind: Rule
middlewares:
- name: fail2ban-test
services:
...

Configuration

Please note that the allowlist and denylist functionality described below can only be used concurrently with Fail2ban functionality (if you are looking for a way to allowlist or denylist IPs without using any of the Fail2ban logic, you might want to use a different plugin.)

Source Criterion

By default, the plugin uses the connection's remote IP address (r.RemoteAddr) to identify clients. When running behind a proxy or CDN (e.g. Cloudflare), the real client IP is forwarded in a request header. Use sourceCriterion to tell the plugin which header to read instead:

testData:
sourceCriterion:
requestHeaderName: "Cf-Connecting-Ip"
rules:
bantime: "3h"
findtime: "10m"
maxretry: 4
enabled: true
FieldDescription
requestHeaderNameHTTP header containing the real client IP. When empty (default) r.RemoteAddr is used.
ipStrategy.depthSelects the IP at this position from the right of the header. 1 is the rightmost IP.
ipStrategy.excludedIPsIPs or CIDRs to skip. The plugin reads the header from the right and selects the first IP that is not in this list. The plugin ignores this field when depth is set.

Note: If the configured header is missing from an incoming request, the plugin falls back to r.RemoteAddr and logs a warning.

IP strategy

A header such as X-Forwarded-For can hold several IPs: client, proxy1, proxy2. Each proxy appends the IP that it received the request from. Without ipStrategy, the plugin uses the leftmost IP. The client sends that IP, so a client can put any IP there to avoid a ban.

Use ipStrategy to select an IP that one of your proxies appended. The options work like the Traefik ipStrategy. When requestHeaderName is empty, and depth is positive or excludedIPs is not empty, the plugin reads the X-Forwarded-For header. The plugin reads all the lines of the header, from the first line to the last line.

testData:
sourceCriterion:
requestHeaderName: "X-Forwarded-For"
ipStrategy:
# Use the IP that the last proxy received the request from.
depth: 1
testData:
sourceCriterion:
ipStrategy:
# Skip the IPs of your proxies.
excludedIPs:
- "10.0.0.0/8"
- "192.168.1.7"

With X-Forwarded-For: 1.1.1.1, 2.2.2.2, 10.0.0.1:

ConfigurationClient IP
no ipStrategy1.1.1.1
depth: 110.0.0.1
depth: 22.2.2.2
depth: 4r.RemoteAddr, there is no 4th IP
excludedIPs: ["10.0.0.0/8"]2.2.2.2
excludedIPs: ["10.0.0.0/8", "2.2.2.2"]1.1.1.1

If the strategy selects no IP, or selects a value that is not a valid IP, the plugin falls back to r.RemoteAddr and logs a warning. If depth is negative or an entry in excludedIPs is not a valid IP or CIDR, the plugin does not start.

Logs

The plugin writes structured JSON log entries through the Traefik logger. A Traefik plugin has two outputs: Traefik writes the first one at its DEBUG level and the second one at its ERROR level. The logLevel option selects the lowest plugin level that goes to the second output. Thus, Traefik shows these entries with its default log configuration. Traefik shows the other entries only when its own log level is DEBUG.

testData:
logLevel: INFO
rules:
bantime: "3h"
findtime: "10m"
maxretry: 4
enabled: true
FieldDefaultDescription
logLevelERRORThe lowest plugin level that Traefik shows at its ERROR level. One of DEBUG, INFO, WARN or ERROR. The case does not matter. If the value is not known, the plugin uses ERROR and writes an error entry.
enableBlockLogstrueWhen true, the plugin writes a DEBUG entry each time it blocks a request (denylist, ban, or status-code ban). Set to false to suppress these entries.

Each entry keeps its plugin level in its level field, but Traefik labels it debug or error from the output that it used.

The plugin levels are:

LevelEntries
DEBUGEach blocked request (IP blocked).
INFOEach ban (IP banned) and each unban (IP unbanned). The plugin is disabled.
WARNA deprecated option. A missing or invalid IP in the sourceCriterion header, or no IP selected by ipStrategy.
ERRORA failure: for example, the plugin cannot write the jail file or send a notification.

Several middlewares can share one jail, so the jail entries do not follow logLevel. Traefik writes the jail warnings at its DEBUG level and the jail errors at its ERROR level.

To see each ban and each unban without the Traefik DEBUG logs, set logLevel: INFO. An entry looks like this:

{"time":"2026-12-01T09:25:27Z","level":"info","msg":"Plugin: FailToBan: IP banned","ip":"192.0.2.1","reason":"4 requests in 10m0s, maxretry is 4","bantime":"3h0m0s"}

Jail

A jail is the list of the IPs that the plugin follows and bans. By default, Traefik makes one instance of the middleware for each router, and each instance has its own jail. Thus a ban on sub1.example.com does not apply to sub2.example.com. The jail is also lost when Traefik restarts.

To share one jail between routers, give them the same jail configuration:

testData:
jail:
- type: inMemory
configuration:
path: "/data/fail2ban/jail.csv"
rules:
bantime: "3h"
findtime: "10m"
maxretry: 4
FieldDefaultDescription
typeThe jail type. Only inMemory is available.
configuration.path""The jail file. The middlewares with the same path share the same jail. When empty, the middlewares share a jail in memory, without a file.

Each middleware keeps its own rules. If a middleware bans an IP, the other middlewares that share the jail also block that IP until their own bantime ends.

The jail file holds one ban on each line, in the format <ip>[,<time>]:

# A line that starts with "#" is a comment.
203.0.113.7
198.51.100.4,2026-12-01T10:00:00Z
  • The time is the start of the ban, in RFC 3339 format. If the line has no time, the ban starts when the plugin reads the line.
  • At start, the plugin reads all the file. Then it reads the new lines every 10 seconds.
  • The plugin adds a line to the file for each new ban. Thus the bans stay after a restart of Traefik.
  • Other tools can add lines to the file to ban IPs, for example a fail2ban action or a script that reads the logs of your login page.
  • The plugin does not remove lines from the file. If the file gets too large, rotate or truncate it. The plugin then reads the file again from the start.
  • A relative path starts from the working directory of Traefik. Traefik must be able to write in the directory of the file.
  • Each Traefik instance keeps its jail in its own memory. Two Traefik instances that use the same file share the bans only through the file, with a delay of up to 10 seconds.

Only one jail is available for each middleware at this time.

Allowlist

You can allowlist some IP using this:

testData:
allowlist:
files:
- "tests/test-ipfile.txt"
ip:
- "::1"
- "127.0.0.1"

Where you can use some IP in an array of files or directly in the configuration.

If you have a single IP, this: ip: 127.0.0.1 should also work.

Denylist

Like allowlist, you can denylist some IP using this:

testData:
denylist:
files:
- "tests/test-ipfile.txt"
ip:
- "::1"
- "127.0.0.1"

Where you can use some IP in an array of files or directly in the configuration.

Fail2ban

We plan to use all default fail2ban configuration but at this time only a few features are implemented:

testData:
rules:
urlregexps:
- regexp: "/no"
mode: block
- regexp: "/yes"
mode: allow
bantime: "3h"
findtime: "10m"
maxretry: 4
enabled: true
statuscode: "400,401,403-499"

Where:

  • findtime: is the time slot used to count requests (if there is too many requests with the same ip in this slot of time, the ip goes into ban). You can use 'smart' strings: "4h", "2m", "1s", ...
  • bantime: correspond to the amount of time the IP is in Ban mode.
  • maxretry: number of request before Ban mode.
  • enabled: allow to enable or disable the plugin (must be set to true to enable the plugin).
  • urlregexp: a regexp list to block / allow requests with regexps on the url
  • statuscode: a comma separated list of status code (or range of status codes) to consider as a failed request. If it is empty, each request counts toward maxretry.

URL Regexp

Urlregexp are used to defined witch part of your website will be either allowed, blocked or filtered :

  • allow : all requests where the url match the regexp will be forwarded to the backend without any check
  • block : all requests where the url match the regexp will be stopped
No definitions
testData:
rules: {}

By default, fail2ban will be applied.

Multiple definition
testData:
rules:
urlregexps:
- regexp: "/whoami"
mode: allow
- regexp: "/do-not-access"
mode: block

In the case where you define multiple regexp on the same url, the order of process will be :

  1. Block
  2. Allow

In this example, all requests to /do-not-access will be denied and all requests to /whoami will be allowed without any fail2ban interaction.

Status code

When this configuration is set (i.e., statuscode is not empty), the plugin will wait for the request to be completed and check the status code of the response. If the status code is in the list of status codes, the request will be considered as a failed request.

Note that the request is considered completed when the response is back sent to the plugin, therefore, the request went through the middleware, traefik, to the backend, and back to the middleware.

Here is a little schema to explain the process
sequenceDiagram
actor C as Client
participant A as Middleware
participant B as Backend
C->>A: Request
A->>B: Request
B->>A: Response
A->>A: Check status code
critical [Check status code]
option Invalid status code
A--X C: Log error
option valid status code
A->>C: Log error
end

Schema

First request, IP is added to the Pool, and the findtime timer is started:

A |------------->
  ↑

Second request, findtime is not yet finished thus the request is fine:

A |--x---------->
     ↑

Third request, maxretry is now full, this request is fine but the next wont.

A |--x--x------->
        ↑

Fourth request, too bad, now it's jail time, next request will go through after bantime:

A |--x--x--x---->
           ↓
B          |------------->

Fifth request, the IP is in Ban mode, nothing happen:

A |--x--x--x---->
B          |--x---------->
              ↑

Last request, the bantime is now over, another findtime is started:

A |--x--x--x---->            |------------->
                             ↑
B          |--x---------->

Notifications

The plugin can send a notification when it bans an IP, and another one when the ban ends. A notification goes to Telegram, Discord, an email address, or any HTTP endpoint (a webhook). You can enable several channels at once.

testData:
rules:
bantime: "3h"
findtime: "10m"
maxretry: 4
notifications:
allowedTypes: ["ban", "unban"]
webhook:
enabled: true
url: "https://example.com/fail2ban"
method: "POST"
headers:
Authorization: "Bearer my-token"
templates:
ban: '{"action": "ban", "ip": "{{.IP}}", "duration": "{{.Duration}}"}'
unban: '{"action": "unban", "ip": "{{.IP}}"}'
FieldDefaultDescription
allowedTypes["ban", "unban"]The events to send. The values are ban and unban.
webhook.enabledfalseSend each event to webhook.url.
webhook.urlThe URL that gets the request. It is required.
webhook.methodPOSTThe HTTP method of the request.
webhook.headersThe headers of the request. The default Content-Type is application/json.
webhook.templates.banSee TemplatesThe body of the request for a ban.
webhook.templates.unbanSee TemplatesThe body of the request for an unban.
telegram.enabledfalseSend each event to a Telegram chat.
telegram.botTokenThe token of the Telegram bot.
telegram.chatIdThe chat that gets the message.
telegram.baseUrlhttps://api.telegram.orgThe Telegram API URL.
telegram.templatesSee TemplatesThe text of the message, in Telegram HTML.
discord.enabledfalseSend each event to a Discord webhook.
discord.webhookUrlThe Discord webhook URL. It is required.
discord.usernameThe name of the sender in Discord.
discord.avatarUrlThe avatar of the sender in Discord.
discord.titleThe title of the message.
email.enabledfalseSend each event by email, with SMTP and STARTTLS.
email.serverThe SMTP server, without the port.
email.portThe SMTP port, for example 587.
email.usernameThe SMTP user.
email.passwordThe SMTP password.
email.fromThe sender address.
email.toThe recipient address.
email.subjectThe subject, after Fail2Ban Alert: .
email.templatesSee TemplatesThe body of the email, in HTML.

How the plugin sends the notifications:

  • The middleware that bans the IP sends the ban notification. If several middlewares share a jail, the other middlewares do not send a notification for this ban.
  • The unban notification goes out when the bantime of the middleware ends.
  • The plugin sends the notifications in the background, one at a time. A request has a timeout of 10 seconds. If a request fails, the plugin logs the error and does not send it again.
  • If Traefik reloads its configuration, the plugin still sends the unban notifications of the earlier bans.
  • If Traefik restarts, the plugin does not send the unban notifications of the bans that started before the restart. The bans that the plugin reads from a jail file do not send a notification.

Templates

A template is a Go template. It can use these fields:

FieldDescription
{{.Type}}The event type: ban or unban.
{{.IP}}The IP address.
{{.Message}}The reason for the event, for example 4 requests in 10m0s, maxretry is 4.
{{.Timestamp}}The time of the event. For example, {{.Timestamp.Format "2006-01-02 15:04:05"}}.
{{.Duration}}The bantime, for a ban event.

If a template is empty or does not parse, the plugin uses the default template:

# ban
🚫 IP Ban Alert
IP: {{.IP}}
Reason: {{.Message}}
Time: {{.Timestamp.Format "2006-01-02 15:04:05"}}
Duration: {{.Duration}}
# unban
✅ IP Unban Alert
IP: {{.IP}}
Reason: {{.Message}}
Time: {{.Timestamp.Format "2006-01-02 15:04:05"}}

Discord does not use templates. Its message shows the IP address and, for a ban, the ban duration.

How to dev

$ docker compose up

Authors

Tom MoulardClément DavidMartin HuvelleAlexandre Bossut-Lasry