Ssh – Writing a fail2ban multiline regex

fail2banpythonregexssh

I've got some troublesome hosts trying it on with an SSH server I run, and I'm trying to ban them using fail2ban. Problem is, I haven't done much work with regexes, and even less with Python regexes.

Here are the troublesome lines in my auth.log:

Nov 19 18:58:17 myhost sshd[48272]: Connection from xxx.xxx.xxx.xxx port 3284 on my.host.ip.address port 22
Nov 19 18:58:21 myhost sshd[48272]: fatal: Read from socket failed: Connection reset by peer [preauth]

I want to grab both lines in the regex, I've seen in other posts about how to do multiline stuff, but at the moment I can't even get it to match the first line! Here's a snippet from my *.conf file:

[INCLUDES]

# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf

[Init]

maxlines = 2

[Definition]

_daemon = sshd

failregex = ^%(__prefix_line)s^Connection from <HOST>*$

I understand that the "__prefix_line" is designed to catch the first "myhost sshd[PID]" bit, but all I when I run "fail2ban-regex" is:

Results
=======

Failregex: 0 total

Ignoreregex: 0 total

Date template hits:
|- [# of hits] date format
|  [115124] MONTH Day Hour:Minute:Second
`-

Lines: 115124 lines, 0 ignored, 0 matched, 115124 missed

Does anyone have any ideas?

Thanks in advance!

Best Answer

I am using fail2ban 0.9.5 on Ubuntu Server LTS 14.04 and use a nice wronguser.conf rule that bans all 'wrong/unauthorized' users for my ssh and squirrelmail (that uses 'dovecot') and looking in /var/log/auth.log for follwing multilines:

Aug 15 10:15:25 server auth: pam_unix(dovecot:auth): check pass; user unknown
Aug 15 10:15:25 server auth: pam_unix(dovecot:auth): authentication failure; logname= uid=0 euid=0 tty=dovecot ruser=alumni rhost=14.141.17.167

and

Aug 15 12:39:10 server sshd[5851]: pam_unix(sshd:auth): check pass; user unknown
Aug 15 12:39:10 server sshd[5851]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=91.224.160.106

along with single line for ssh root user ban:

Aug 15 05:50:20 server sshd[20677]: Failed password for root from 62.147.227.164 port 55253 ssh2

The rule is:

[INCLUDES]

before = common.conf

[Definition]

_daemon = (?:sshd|postfix/smptd)

failregex = ^%(__prefix_line)s[iI](?:llegal|nvalid) user .* from <HOST>\s*$
            ^%(__prefix_line)sFailed (?:password|publickey) for root from <HOST>(?: port \d*)?(?: ssh\d*)?$
            dovecot.*user unknown\n.*dovecot.*authentication failure.*rhost\=<HOST>

ingoreregex =

[Init]

maxlines = 2

it is included in jail.local as:

[wronguser]

enabled  = true
port     = 1:65535
filter   = wronguser
logpath  = /var/log/auth.log
maxretry = 1
bantime  = -1

Default apt-get fail2ban on Ubuntu LTS 14.04 is 0.8.11 and is not working with multiline regex. So you should manually install latest stable fail2ban. I did it directly from their git repo.