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
Fail2ban
on the server running Nginx and Roboo. -
Add the
cloudflare.conf
file to youraction.d
dir. -
Edit the
cloudflare_api_manager.rb
file and set yourCLOUDFLARE_USERNAME
andCLOUDFLARE_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
banaction
to yourjail.conf
file (or any other jails):banaction = cloudflare
-
Add the
cloudflare_api_manager.rb
script to a location accessible to thefail2ban
user 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.