Nginx – Block bruteforce attempts with nginx & cloudflare without rate limiting

brute-force-attacksnginx

So I discovered servers trying to bruteforce my API so I want to block them…but my specific scenario made it difficult to work with common solutions found on the internet.

1) I don't want to just rate limit, if any IP attempts to authenticate with the API and fail more than X times in ~6 hours I want to block them. No answers anymore at all. Not even 429 replies

2) I'm using cloudflare, so I need to use the CF IP header

3) I can't block the traffic based on iptables or similar solutions, since the only IPs that talk to my server are cloudflare IPs

4) The API generates nginx errors if the authentication fails with 2: no such file or directory if that helps with something

Given my scenario, what are the possible solutions?

Best Answer

There are a few things you could do, you could farm out the task to Cloudflare before it even hits your network by developing a Cloudflare Worker monitoring for abuse: https://workers.cloudflare.com/

If you want to keep the monitoring on your end you should use the nginx Real IP module to make sure you have the right IPs in your logs, Cloudflare has instructions here: https://support.cloudflare.com/hc/en-us/articles/200170786-Restoring-original-visitor-IPs-Logging-visitor-IP-addresses-with-mod-cloudflare-

Once you have the users real IPs included in your access logs you can use a program such as fail2ban to either set a ban on Cloudflare side (using their API) or by maintaining a block list in nginx using the deny directive.