Whitelisting Cloudflare With IPTABLES

Many people use Cloudflare to protect their website but don’t restrict access to the web server to Cloudflare IPs. This means that whatever protection Cloudflare provides can easily be bypassed by hitting your IP directly.

That’s why you should have a firewall. And if you’re cool, you’re probably using iptables. So here’s how to make sure only Cloudflare can talk to your web ports.

1. Install ipset, which is a utility that lets you create text hashes that can be used with firewall rules.

apt install ipset

2. Create the firewall object “cf4”

ipset create cf4 hash:net

3. Populate that object with Cloudflare’s list of IPv4 addresses.

for x in $(curl https://www.cloudflare.com/ips-v4); do ipset add cf4 $x;done

4. Insert the rule into your firewall.

iptables -A INPUT -m set –match-set cf4 src -p tcp -m multiport –dports http,https -j ACCEPT

5. Regularly pull down the list and reintegrate it with the firewall

  • ipset destroy cf4

  • ipset create cf4 hash:net

  • iptables -A INPUT -m set --match-set cf4 src -p tcp -m multiport --dports http,https -j ACCEPT

  • Load your rules.

  • iptables-save

[ NOTE: I assumed you are on Ubuntu here, because I (once again) assume you’re cool. I can’t get into the way CentOS does things. ]

I recommend putting this into /etc/cron.daily/ as a script, or perhaps doing it weekly or monthly. I do it more often because I don’t like the idea of dropping packets from my proxy.

Finally—and I hope this is obvious—you need to have a DENY ALL rule at the bottom of your ruleset, otherwise it’s not a whitelist!

iptables -A INPUT -d $YOURHOST -j DROP

And don’t forget to log it as well!

Hope this helps.

Related posts: