Skip to content

Whitelisting Cloudflare With IPTABLES

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.

bash
apt install ipset
  1. Create the firewall object “cf4”

bash
ipset create cf4 hash:net
  1. Populate that object with Cloudflare’s list of IPv4 addresses.

bash
for x in $(curl https://www.cloudflare.com/ips-v4); do ipset add cf4 $x;done
  1. Insert the rule into your firewall.

bash
iptables -A INPUT -m set --match-set cf4 src -p tcp -m multiport --dports http,https -j ACCEPT
  1. Regularly pull down the list and reintegrate it with the firewall

bash
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.
bash
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!

bash
iptables -A INPUT -d $YOURHOST -j DROP

And don’t forget to log it as well!

Hope this helps.