12

I am using Fail2Ban and I have configured it as needed. This is reading logs from nginx/error.log and is acting depending on configs about maxretry and timing sets. The question is that is this possible to have different rules depending on status codes?

For instance, I want to block anyone getting 10 404 Status code in 5 minutes, but to block anyone getting 3 403 Status code.

Any help would be highly appreciated, thanks in advance.

Parsa Samet
  • 227
  • 1
  • 3
  • 8

1 Answers1

19

You should add a filter in /etc/fail2ban/filter.d/ with a relevant name - e.g. nginx-{403,404}.conf.

They should contain something like the following lines :

nginx-403.conf :

[Definition]
failregex = ^<HOST> -.*"(GET|POST|HEAD).*HTTP.*" 403
ignoreregex =

nginx-404.conf :

[Definition]
failregex = ^<HOST> -.*"(GET|POST|HEAD).*HTTP.*" 404
ignoreregex =

Then you should call them from your jail.local file, create this file if it is not yet present (which extends the default jail.conf file):

For 403 :

[nginx-403]

enabled = true
port    = http,https
logpath = /var/log/nginx/access.log
maxretry = 5
findtime = 300

And for 404 :

[nginx-404]

enabled = true
port    = http,https
logpath = /var/log/nginx/access.log
maxretry = 10
findtime = 300

Note: if you are running an old version of Fail2Ban (version 0.8.x and lower), you also need to define filter in your config. In newer versions the jail heading in square brackets also identifies the filter being used.

  • 4
    the `filter` lines are no longer needed in the jail files - see optimising fail2ban filters http://www.the-art-of-web.com/system/fail2ban-filters/ – Stuart Cardall Dec 16 '17 at 16:21
  • 2
    how does it ban? – chovy Feb 25 '19 at 05:09
  • 2
    @chovy to quote from that webpage linked by the previous commenter, "In Fail2Ban 0.9.x the jail heading in square brackets also identifies the filter being used." – ahron May 14 '20 at 09:33
  • @chovy Maybe you mean if you add the config above to your jail.local which extends your jail.conf file (let me also update the answer). Meaning in jail.config there should be a default action defined (which is _action, meaning ban only). Moreover, findtime and maxretry is used to decide when to ban. A host is banned if it has generated "maxretry" during the last "findtime" in seconds. Hope this helps. – Melroy van den Berg Nov 11 '22 at 23:23