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.
apt install ipset
ipset create cf4 hash:net
for x in $(curl https://www.cloudflare.com/ips-v4); do ipset add cf4 $x;done
iptables -A INPUT -m set –match-set cf4 src -p tcp -m multiport –dports http,https -j ACCEPT
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.