Using fail2ban to scan for SSH Accepted Connections and write the username to auth.log

in flag

I have a small server that authenticate users as root using their ssh-keys stored in authorized_keys file. I also run fail2ban.

I made a convention to have a nickname written after the public_key of each user in the authorized_keys file.

I would like to know if it would be possible to have fail2ban to scan for accepted connections and, instead of jailing the user, to write a line with his nickname to /var/log/auth.log, perhaps using logger -p "Timestamp Accepted SSH connection from nickname"


jp flag
This might require more details on what you have already tried, including your configuration and example of the logging.
il flag

However I don't know why you need it, where sshd already writes real user name in the form like:

Accepted publickey for username from IP ...

If you don't have it, may be you can try to set sshd_config' loglevel to VERBOSE.

But back to fail2ban, sure it is possible. As for jail you'd need to specify something like this (along with others):

failregex = ^\s*\S+ sshd\[\d+\]: Accepted publickey for <F-USER>\S+</F-USER> from <ADDR>
maxretry = 1
findtime = 1
bantime = 1
enabled = true
action = ssh-accept-mon-log

Here how you can check the RE and captured groups:

$ what='Jul 12 19:50:00 srv sshd[274594]: Accepted publickey for admin from port 59120 ssh2: ECDSA-CERT:...'
$ fail2ban-regex -o '<F-USER> : <ip>' "$what" '^\s*\S+ sshd\[\d+\]: Accepted publickey for <F-USER>\S+</F-USER> from <HOST>'
admin :

As an action you need to use something like this:

actionban = logger -p "<time> Accepted SSH connection from <F-USER>"

Just note that it would not log more than 1 entry per IP per second (due to bantime), so may be you'd try some solution from fail2ban :: wiki :: How to ban something other than host (IP-address), like user or mail, etc.

For instance RE from this example will use "session-ID" (matched with <F-ID>\d+</F-ID>) as a failure ID instead of IP address, so would "ban" by this ID (and therefore safe against too fast entries):

$ fail2ban-regex -o '<F-USER> : <fid> : <ip>' "$what" '^\s*\S+ sshd\[<F-ID>\d+</F-ID>\]: Accepted publickey for <F-USER>\S+</F-USER> from <ADDR>'
admin : 274594 :

Also consider this RFE - fail2ban#2304 for alternate approach (or alternative with ignorecommand etc).


Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.