Nginx – Can Fail2ban Add Deny Rules Instead of Using iptables?

fail2bannginxreverse-proxy

I'm having one server, that is behind a reverse proxy, that I don't control.
I'd like to use fail2ban to block nginx traffic under certain conditions.

normally fail2ban useses iptables to block traffic originating from the intruder's IP

However my server is behind a reverse proxy and from my server's point of view all traffic originates from the reverse proxy:

I found following url https://forums.freebsd.org/threads/fail2ban-behind-a-proxy.55041/
that suggests tu use iptables with package intropspection like for example:

actionban = iptables -I fail2ban-<name> 1 -p tcp --dport 80 -m string --algo bm --string 'X-Forwarded-For: <ip>' -j DROP

However the reverse proxy that I cannot control forwards the traffic as https traffic, meaning, that I cannot introspect the traffic for X-Forwarded-For headers as they would be encrypted.

Thus my question.

Do others have a similar scenario and is there an existing actionban = that adds Deny rules to nginx ?

Or do I have to handcraft a script trying to do this (edit nginx the nginx configuration and reload nginx)

What other solution would allow me to tell nginx dynamically which requests (containing specific X-Forwarded-For: headers) to block

Best Answer

fail2ban can be used to run a script. That script can do anything you'd like.


Editing Deny Rules

I'm not too sure how the whole thing can work full speed, but you can easily add Deny rules in a file.

The Nginx configuration files can do an include:

include /etc/nginx/deny-rules.conf

And your script generates that deny-rules.conf, somehow... You want to add IPs to a file and then use that file to generate the deny-rules.conf file using a loop or something.

Then you have to restart Nginx so the new rules get taken in account. That's the bad part in this scheme. It's going to be slow to restart this way.


Denylisting

Another solution would be to use the following filter:

Dynamic Denylisting of IP Addresses

I never used that so I'm afraid that you'll have to read the docs and look on how to set things up and make it all happen... However, that should work at full speed. The script in your fail2ban system can take care of updating that dynamic list.

Related Topic