Skip to content

Instantly share code, notes, and snippets.

@R-Nabil
Last active January 24, 2023 01:16
Show Gist options
  • Save R-Nabil/f85d96cd022f3c47507b3d7d8f342046 to your computer and use it in GitHub Desktop.
Save R-Nabil/f85d96cd022f3c47507b3d7d8f342046 to your computer and use it in GitHub Desktop.
Update UFW with Cloudflare IP, by deleting them first and recreating based on the retrieve IP list.
# Informational only
ctrDelete=0
ctrAdd=0
# The below script update UFW rules to allow only Cloudflare IP through.
# It is only done for port 443 but can easily be extended to other ports
#
# First step is to delete already existing Cloudflare UFW rules.
# It is done by looking for the ones with comment 'Cloudflare IP'
#
# Second step is to retrieve the cloudflare IP-v4 list and add them one by one.
# Note we need to ensure the correct comment 'Cloudflare IP' is also appended.
# We only allow port 443 here, as there was no need for 80
echo "Deleting UFW 'Cloudflare IP' rules"
while true ; do
result=$(ufw status numbered | grep 'Cloudflare IP' -m1)
n=$(ufw status numbered | grep -m1 'Cloudflare IP' | awk '{print $1}' | sed 's/\[//g' | sed 's/\]//g')
if [ -z "$result" ] ; then
break
else
echo "Rule found : $result"
echo "y" | ufw delete $n > /dev/null;
ctrDelete=$(( ctrDelete + 1 ))
fi
done
echo "Done deleting UFW 'Cloudflare IP' rules %0A Retrieving Cloudflare IPv4 list"
curl -s https://www.cloudflare.com/ips-v4 -o /tmp/cf_ips
echo "" >> /tmp/cf_ips
echo "Allowing Cloudflare IPv4 port 443"
ips=""
for cfip in `cat /tmp/cf_ips`;
do
echo "ufw route allow proto tcp from $cfip to any port 443 comment 'Cloudflare IP'"
ufw route allow proto tcp from $cfip to any port 443 comment 'Cloudflare IP' > /dev/null;
ctrAdd=$((ctrAdd + 1))
ips="$ips %0A $cfip"
done
text="Cloudflare IP update %0A Deleted $ctrDelete rules %0A Added $ctrAdd rules %0A $ips"
ufw reload > /dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment