How to add custom rule (filter + jail) for fail2ban.
1. Find regexp
First of all we need to find line in log-file with incorrect user attempt. For example line from one of my service with incorrect user password input:
Passcode incorrect; userId ; 188.8.131.52
Here you can see message from service and client IP address. So we need to transform this line into regular expression and retrieve IP address. We should use <HOST> placeholder instead IP address.
Passcode incorrect; mailId \[.*\]; <HOST>
2. Create Filter
Create new filter file in filter.d directory, for example: /etc/fail2ban/filter.d/myservice.conf with your regex:
[Definition] failregex = Passcode incorrect; mailId \[.*\]; <HOST>
If you want to exclude some lines from it, you should use ignore regex. For example:
ignoreregex = 192.168.0.1
Then test it using fail2ban-regex command:
fail2ban-regex /var/log/myservice.log /etc/fail2ban/filter.d/myservice.conf /etc/fail2ban/filter.d/myservice.conf
format: fail2ban-regex <log file> <filter> <ignore-filter>
So if you using ignore regex, you should define third param (the same filename)! Otherwise your ignore regex will not be tested!
Then you get something like this:
Lines: 15390 lines, 1 ignored, 5 matched, 15384 missed
3. Create Rule
Create new file in jail.d directory, for example myservice.conf with your rule:
# service name [myservice] # turn on /off enabled = true # ports to ban (numeric or text) port = http,https # filter from previous step filter = myservice # file to parse logpath = /var/log/myservice.log # ban rule: # 5 times on 1 minute maxretry = 5 findtime = 60 # ban on 10 minutes bantime = 600
# test it: service fail2ban restart fail2ban-client status fail2ban-client status myservice
- Custom HTTP 404 error fail2ban rules for web services: Nginx, HAProxy, HTTP.
- How to Re-ban hackers on second level.