regex for repeating patterns

82 Views Asked by At

i have a dovecot logfile which contains entrys like this:

Jun 1 04:16:24 mail dovecot: auth-worker(3158): sql(ryan,193.42.32.170): unknown user (given password: ryan)

i want to create a fail2ban filter that blocks any login attempts where username is same as given password, so far i have:

failregex = auth-worker.*,<HOST>,.* (Password mismatch|unknown user) .*given password: ryan.*

this only works fo this specific password, but i want it to work with any combination of username/password is the same to block dictionary attacks

The current regex is working, but its very limited in a usecase

2

There are 2 best solutions below

0
Patrick Janser On

You can capture the user in a named capturing group with this syntax :

(?P<group_name> ... ) where ... is your pattern.

Then, you can re-use this captured content in the rest of the pattern, by using a named backreference like this :

(?P=group_name)

So for your example, I presume the user is next to the IP address, in bold here :

Jun 1 04:16:24 mail dovecot: auth-worker(3158): sql(ryan,193.42.32.170): unknown user (given password: ryan)

If this is the case, then you can use this regular expression :

auth-worker.*?sql\((?P<user>\w+),(?P<ip>\d+(?:\.\d+){3}).*?(?:password mismatch|unknown user)\s*\(given password:\s*(?P=user)\)

I don't know how you enable the case-insensitive flag in fail2ban, but I was a bit surprised with the capital "P" on "Password mismatch". You might have to play around with this:

https://regex101.com/r/pTXjmM/1

Also check that the username pattern is valid. Here I just used \w+ but maybe your users can use other characters. And if you have IPv6, you'll have to adapt the capturing ip group, as I presume that you need it to ban it.

0
Tim Altgeld On

Fail2ban has own regex for detecting ipv4 or ipv6, so is doing it's job here already

i tinkered a little bit with it and indeed got it to work testing with fail2ban-regex

But i did another approach, i gave chatgpt a try, provided the question:

create a regular expression from the following log entry, that detects if a given username matches the same password:

Jun  1 02:47:50 mail dovecot: auth-worker(2587): sql(holly,193.42.32.97): unknown user (given password: holly)

to my very surprise, chatgpt gave me this:

^(.*?) dovecot: auth-worker\(\d+\): sql\((\w+),.*?\): unknown user \(given password: \2\)$

i tinkered a lil more with it and in the end, this is the final result:

auth-worker.*(.*?).*(\w+),<HOST>.*?\).*(Password mismatch|unknown user).*given password: \2\)