fail2ban with opensmtpd

opensmtpd is a tricky service to create fail2ban rules for. For starters, the IP address to match is logged to a different line to the authentication state.

This regex is a multi-line match, sometimes the lines can be quite far apart because opensmtpd can be processing multiple sessions at the same time.
We use a (\w) smtp group to capture the session id and the associated host to block, and them match it \1 smtp a few lines later (\n.*)+ against the failed login attempt.

# filters/opensmtpd.conf
[INCLUDES]
before = common.conf

[Definition]
failregex = (\w) smtp connected address=<HOST>.*(\n.*)+\1 smtp failed-command command="AUTH LOGIN.*
ignoreregex =

[Init]
maxlines = 20
# jail.local
[DEFAULT]
backend = systemd
...

[opensmtpd]
enabled = true
journalmatch = SYSLOG_IDENTIFIER=smtpd

Use systemd’s filtering to minimise the number of lines we need maintain, by filtering to only the smtp logs.