Skip to content

Instantly share code, notes, and snippets.

@rraallvv
Last active November 19, 2022 22:44
Show Gist options
  • Save rraallvv/602ea1ed32f40074c1c509b5161da77d to your computer and use it in GitHub Desktop.
Save rraallvv/602ea1ed32f40074c1c509b5161da77d to your computer and use it in GitHub Desktop.
Open public ports to Cloudflare for Firewalld
#!/usr/bin/env bash
# Instructions:
#
# 1) Place this script in the /root/ directory, give it proper permissions.
# $ sudo chmod +x /root/open-cloudflare.sh
#
# 2) Open the cron job editor
# $ sudo crontab -e
#
# 3) Add the following to the last line
# 12 0 * * * root /root/open-cloudflare.sh
# Actual script:
# remove all public rules first
IFS=$'\n'
for i in $(sudo firewall-cmd --list-rich-rules --zone=public); do
echo "removing '$i'"
sudo firewall-cmd --permanent --zone=public --remove-rich-rule "$i"
done
#echo "reloading..."
#sudo firewall-cmd --reload
#exit 1
# add new rules
# IPv4 HTTP
echo "adding IPv4 HTTP"
for i in $(curl "https://www.cloudflare.com/ips-v4"); do
echo "adding '$i'"
sudo firewall-cmd --permanent --zone=public --add-rich-rule 'rule family="ipv4" source address="'$i'" port port=80 protocol=tcp accept';
done
# IPv4 HTTPS
echo "adding IPv4 HTTPS"
for i in $(curl "https://www.cloudflare.com/ips-v4"); do
echo "adding '$i'"
sudo firewall-cmd --permanent --zone=public --add-rich-rule 'rule family="ipv4" source address="'$i'" port port=443 protocol=tcp accept';
done
# SSH
#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
echo "reloading..."
sudo firewall-cmd --reload
@jonaylton
Copy link

jonaylton commented Jul 15, 2021

I avoided deleting all ports using script as it could potentially lock me out.
So after running the script I manually removed the unused entries of firewall and only let SSH Port public opened

PS.: Also check if you have any public accessible port using the following command:

sudo firewall-cmd --zone=public --list-ports

If yes, remove one by one:

firewall-cmd --permanent --zone=public --remove-port=PORT/tcp

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