The Linux Page

End a fail2ban regex with a space

Spaces require special handling in regular expressions

Many of the examples in fail2ban make use of ^ at the start and $ at the end. In other words, the entire line is expected to match.

In many cases, though, it's not really useful to match the entire line when only a few things can be matched. That means you can't use have " $" at the end of the regular expression. (or even " +$" if one or more spaces are expected).

Instead you have to resort to a different way to allow for a space.

Note that I wrote these two regex example in double quotes to make it clear that there is a space at the start, but you actually can't write the regex in double quotes in fail2ban.

Here is an example with the solution:

failregex = \sIN=[a-z0-9]+ .* SRC=<HOST> .* PROTO=UDP .* DPT=53\s

All we have to do is use the "\s" special escape character. That means expect a whitespace. Note that a whitespace is actually defined as "[ \n]". So it includes the newline character. It may also match the "\r" and "\t" although I didn't check.

Note that since fail2ban handles log lines one at a time, matching the "\r" or "\n" isn't useful.

Now, in the expression I've shown above, trying to write it with spaces like so:

failregex =  IN=[a-z0-9]+ .* SRC=<HOST> .* PROTO=UDP .* DPT=53 

(and you can't see the one at the end... but it's there)

would not work because fail2ban will trim the string first. This makes sense as most tools that use such a syntax would do the same. This is why you need to use something such as the "\s".

If you really need to only match a space, you should be able to use the square bracket syntax as well: "[ ]", although I did not try to see whether that would work in fail2ban, there should be no reason for it to fail.

In my case, I wanted to make sure I was matching the "IN=..." parameter and not something else. And having a space after the 53 is important because without it it could mean that the port number is 5353 for example (there is 1,000 other possible ports starting with 53...)

This is probably true for many tools that use a similar syntax to fail2ban. Although I am always surprised to see that quotes (double or single) do not work in the parameters of fail2ban.