Unfortunately, having mod_cloudflare installed on ones server does not mean that the server’s front-end firewall (ConfigServer Firewall in one instance for me) sees the correct remote IP address for requests routed via CloudFlare.
It appears mod_cloudflare (which is after all an Apache ‘mod’) works great for applications querying the REMOTE_ADDR server value from within Apache, but in many cases the firewall is in operation before mod_cloudflare has come into effect.
The result of all this is that an IP blocked in the local firewall is actually not blocked at all because the firewall is seeing the whitelisted CloudFlare IP in its place.
This is a major problem!
Fortunately ConfigServer Firewall provides a setting into which a script name can be entered, which is run whenever LFD (Login Failure Daemon) adds a new IP to the firewall deny list.
Also fortunately, CloudFlare provide a simple API which can be used to add IP address blocks.
So, simple solution, each time an IP is added to the local firewall, run a script which also adds it to CloudFlare.
Here’s the script I wrote to do this:
#!/bin/bash
ip=$(printf "%q" $1)
no=$(printf "%q" $6)
curl -X POST "https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules" -H "X-Auth-Email: YOU@YOUREMAIL.COM" -H "X-Auth-Key: YOURCLOUDFLAREAUTHCODE" -H "Content-Type: application/json" --data '{"mode":"block","configuration":{"target":"ip","value":"'$ip'"},"notes":"fromcsflfd"}'
Replace YOU@YOUREMAIL.COM with the email address you use to log in to CloudFlare.
Replace YOURCLOUDFLAREAUTHCODE with the Auth code you can find in your CloudFlare->Account->Settings page.
This script can be called with just an IP address as a single parameter from anywhere on your server to add an IP to CloudFlare, so you can manually add some if you wish also. However the primary aim here is to have this add LFD blocks automatically. To do this you need to edit the CSF config file:
/etc/csf/csf.conf
Find the setting BLOCK REPORT and put in the full path and extension of your new script. Here’s my edited line in csf.conf:
# Block Reporting. lfd can run an external script when it performs and IP
# address block following for example a login failure. The following setting
# is to the full path of the external script which must be executable. See
# readme.txt for format details
#
# Leave this setting blank to disable
BLOCK_REPORT = "/my-script-path/block_report.sh"
Ensure your new script can be run by root.
Re-start CSF and LFD.
Bob’s your mother’s brother!
Or is he!!
Actually there’s a problem.
This is going to end up with potentially many 1000s of IP blocks accumulating in CloudFlare’s block list. ConfigServer deals with this by unblocking the oldest blocks whenever it adds a new one. But so far we have no way of doing this on CloudFlare.