Integrate Fail2ban with Cloudflare API (V4) to mitigate HTTP flooding and brute forcing using Nginx.
Requirements:
- Nginx
- Fail2ban
- A Cloudflare account
- Ruby
-
Signup to Cloudflare: https://www.cloudflare.com/a/sign-up
-
Go to https://www.cloudflare.com/a/account/my-account and select
View API Key. -
Setup your site(s) to use Cloudflare
-
Install
Fail2banon the server running Nginx and Roboo. -
Add the
cloudflare.conffile to youraction.ddir. -
Edit the
cloudflare_api_manager.rbfile and set yourCLOUDFLARE_USERNAMEandCLOUDFLARE_API_KEY(line 8 and 9). -
Optional add any proxy information if you need to access Cloudflare via a proxy server (line 15 to 18).
-
Add the following
banactionto yourjail.conffile (or any other jails):banaction = cloudflare -
Add the
cloudflare_api_manager.rbscript to a location accessible to thefail2banuser and set appropriate permissions. Remember that your Cloudflare API keys are stored in this script so handle with care! -
Verify that an IP is added to your Cloudflare firewall by banning an IP:
/path/to/ruby /path/to/cloudflare_api_manager.rb ban 1.2.3.4 -
Verify that the IP is removed from your Cloudflare firewall by unbanning the IP:
/path/to/ruby /path/to/cloudflare_api_manager.rb unban 1.2.3.4 -
Restart
Fail2ban
It might be a good idea to whitelist the IP range of Cloudflare in Fail2ban using the ignoreip section. A current list of the IP ranges of Cloudflare can be found here: https://www.cloudflare.com/ips/
NOTE: Not tested with IPv6.