Skip to content

Instantly share code, notes, and snippets.

@mrgarymartin
Created February 23, 2018 20:35
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mrgarymartin/38618aaf27096af6959b5b9c4611779d to your computer and use it in GitHub Desktop.
Save mrgarymartin/38618aaf27096af6959b5b9c4611779d to your computer and use it in GitHub Desktop.
Updated version to whitelist all cloudflare ips in firewalld
#!/usr/bin/env bash
#https://techstat.net/automatic-whitelist-cloudflare-ips-firewalld-bash-script-via-cron-job/
SERVER_IP=xxx.xxx.xxx.xxx
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
for i in $(curl "https://www.cloudflare.com/ips-v6"); do sudo firewall-cmd --permanent --zone=public --add-rich-rule 'rule family="ipv6" source address="'$i'" port port=80 protocol=tcp accept'; done
for i in $(curl "https://www.cloudflare.com/ips-v6"); do sudo firewall-cmd --permanent --zone=public --add-rich-rule 'rule family="ipv6" source address="'$i'" port port=443 protocol=tcp accept'; done
firewall-cmd --permanent --zone=public --add-rich-rule 'rule family="ipv4" source address="'${SERVER_IP}'" port port=22 protocol=tcp accept'
firewall-cmd --permanent --change-zone=eth0 --zone=public
sudo firewall-cmd --reload
@mrgarymartin
Copy link
Author

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.
The goal in this is to make sure no naughty users ever go through my public IP.

This script assumes and does a lot.

  1. Most importantly it assumes you have no firewall rules open, so delete any before running this (don’t lock yourself out).
  2. It assumes your WAN nic is eth0.
  3. It changes the zone of the NIC to public.

Change xxx.xxx.xxx.xxx to your IP so that you can always ssh in.

Give the script proper permissions.

chmod +x /root/firewall.sh

Now set up a cron job

crontab -e

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

Run it to test
/root/firewall.sh

Verify the rules by using

firewall-cmd --list-all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment