Categories
GNU/Linux Security Server ubuntu

Fail2Ban Custom filters and Testing Regex’s against existing Logs

Fail2ban is a tool that can automatically ban malicious bots trying to get into your server. Provided you set up filters and the ip address is logged you can use fail2ban with any application.

fail2ban is built with python2.7

Create a filter, using a regular expression:

In /etc/fail2ban/filter.d/my-custom-filter.conf:


[Definition]

failregex = ^www.example.com  -.* "POST \/user\/register HTTP\/(1.0|1.1|2)" 200

ignoreregex =

Now you want to test this for matches against a log file. Ensure that the log file has existing matches.

Make use of the command line tool fail2ban-regex:

fail2ban-regex /var/log/apache2/example-access.log /etc/fail2ban/filter.d/my-custom-filter.conf

You will get summary data like this:


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

Use   failregex file : /etc/fail2ban/filter.d/my-custom-filter.conf
Use         log file : /var/log/apache2/example-access.log

Results
=======

Failregex: 1 total
|-  #) [# of hits] regular expression
|   1) [1] ^www.example.com  -.* "POST \/user\/register HTTP\/1.0" 200
`-

Ignoreregex: 0 total

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

Lines: 23636 lines, 0 ignored, 1 matched, 23635 missed
Missed line(s): too many to print.  Use --print-all-missed to print all 23635 lines

Which lets you debug your filter regular expression to ensure it is matching the malicious log entries.

 

Finally, add the new filter to your jail.local or a new file in /etc/fail2ban/jail.d/<my_jail>.conf by appending the following:


[my-custom-filter]
enabled  = true
filter   = my-custom-filter
action   = iptables-multiport[name=NoAuthFailures, port="http,https"]
logpath  = /var/log/apache2/example-access.log
banTime  = 864000
findtime = 1800
maxRetry = 3

This sets the details about what log files must be checked with the pattern and what actions should be taken,

You can read more about the configuration of jails in the manual

Fail2ban Client

There is a good tool to check that all is sound with fail2ban on the command line:

sudo fail2ban-client -d

This checks the config is good

Then you can check the status of a specific jail with:

sudo fail2ban-client status 

eg.

sudo fail2ban-client status nginx-http-auth

Sources