Modify fail2ban failregex to match failed public key authentications via ssh

Solution 1:

This line does it:

^%(__prefix_line)sConnection closed by <HOST> \[preauth\]$

Tested with the following logstring:

Apr 29 12:30:12 sendai sshd[25917]: Connection closed by 127.0.0.1 [preauth]

Successfully tested with:

$ fail2ban-regex ~/ssh.log sshd.conf 

Running tests
=============

Use regex file : sshd.conf
Use log file   : /home/user/ssh.log


Results
=======

Failregex
|- Regular expressions:
[...]
|  [12] ^\s*(?:\S+ )?(?:kernel: \[\d+\.\d+\] )?(?:@vserver_\S+ )?(?:(?:\[\d+\])?:\s+[\[\(]?sshd(?:\(\S+\))?[\]\)]?:?|[\[\(]?sshd(?:\(\S+\))?[\]\)]?:?(?:\[\d+\])?:)?\s*Connection closed by <HOST> \[preauth\]$
|
`- Number of matches:
[...]
   [12] 1 match(es)

Summary
=======

Addresses found:
[...]
[12]
    127.0.0.1 (Wed Apr 29 12:30:12 2015)
[..]

Success, the total number of match is 1

Solution 2:

No regex hacking is required (at least since fail2ban 0.10.4). In /etc/fail2ban/jail.conf is the following information:

[sshd]

# To use more aggressive sshd modes set filter parameter "mode" in jail.local:
# normal (default), ddos, extra or aggressive (combines all).
# See "tests/files/logs/sshd" or "filter.d/sshd.conf" for usage example and details.
#mode   = normal

So follow the recommendations by creating /etc/fail2ban/jail.local with your other customisations, along with one of the more stringent modes, for example,

[sshd]
mode   = aggressive

This mode now covers failed public keys.


Solution 3:

At least in openssh 7.3 the log messages also contain a port number. So I had to modify sebix's solution to the following:

^%(__prefix_line)sConnection closed by <HOST> port \d+ \[preauth\]$

Solution 4:

On Ubuntu 18.04 with OpenSSH 7.6p1 I had to extend the "cmnfailre" rules in /etc/fail2ban/filter.d/sshd.conf by

^%(__prefix_line)sConnection closed by authenticating user <F-USER>.+</F-USER> <HOST> port \d+ \[preauth\]$

to match ssh login attempts without correct ssh key:

Apr 14 15:27:15 ubuntu-server sshd[8719]: Connection closed by authenticating user root x.x.x.x port 42664 [preauth]
Apr 14 15:27:15 ubuntu-server sshd[8721]: Connection closed by authenticating user root x.x.x.x port 42666 [preauth]
Apr 14 15:27:16 ubuntu-server sshd[8723]: Connection closed by authenticating user root x.x.x.x port 42668 [preauth]
Apr 14 15:27:16 ubuntu-server sshd[8725]: Connection closed by authenticating user root x.x.x.x port 42670 [preauth]
Apr 14 15:27:17 ubuntu-server sshd[8727]: Connection closed by authenticating user root x.x.x.x port 42672 [preauth]