How to Block All Except Cloudflare From Your Webserver

Today I’m going to show you how to quickly whitelist all of Cloudflare’s prefixes so that direct connection to your site is dropped. My goal in this is to make sure no naughty users ever go through my public IP.

Please forgive the ugly bash since I usually just stick to Powershell 🙂

 

First I’ll install nano my favorite editor #yea yea I know real people use vi whatever

yum install nano -y

 

Second I’ll create the bash script

nano /root/firewall.sh

 

Next I’ll paste this script in there.

Note:

This script assumes and does a lot. Most importantly it assumes you have no firewall rules open, so delete any before running this (don’t lock yourself out).

Second, it assumes your WAN nic is eth0.

Third, it changes the zone of the NIC to public.

Fourth, you should change “myip” to your IP so that you can always ssh in.

for i in $(curl "https://www.cloudflare.com/ips-v4"); do sudo firewall-cmd --permanent --zone=public --add-rich-rule 'rule family="ipv4" source address="'$i'" port port=80 protocol=tcp accept'; done
for i in $(curl "https://www.cloudflare.com/ips-v4"); do sudo firewall-cmd --permanent --zone=public --add-rich-rule 'rule family="ipv4" source address="'$i'" port port=443 protocol=tcp accept'; done
firewall-cmd --permanent --zone=public --add-rich-rule 'rule family="ipv4" source address="myip" port port=22 protocol=tcp accept'
firewall-cmd --permanent --change-zone=eth0 --zone=public
sudo firewall-cmd --reload

 

Give the script proper permissions.

chmod +x /root/firewall.sh

Now set up a cron job

crontab -e

hit “i” to start editing then paste the following in the last line.

12 0 * * * root /root/firewall.sh

hit “esc” and type “x!” then hit enter to exit.

Run it to test

/root/firewall.sh

verify the rules by using

firewall-cmd --list-all