Skip to content

Instantly share code, notes, and snippets.

@SzymonLisowiec
Forked from jakejarvis/cloudflare-ufw.sh
Last active June 9, 2023 21:47
Show Gist options
  • Save SzymonLisowiec/7d9729cfb37663572bf665994017bc0e to your computer and use it in GitHub Desktop.
Save SzymonLisowiec/7d9729cfb37663572bf665994017bc0e to your computer and use it in GitHub Desktop.
UFW rule updater to only allow HTTP and HTTPS traffic from Cloudflare IP address ranges

UFW + Cloudflare Auto-Updater

Check your current rules first (sudo ufw status numbered); if you're already allowing traffic to ports 80 and 443 from anywhere, delete those rules with sudo ufw rule delete X (replace X with appropriate rule number).

Make sure you're allowing SSH traffic for yourself before enabling! sudo ufw allow ssh to be "safe" — restrict SSH to your own IPs later if you'd like to actually be safe. ;)

Run this script once and then sudo ufw enable to lock everything down.

To run as a daily cron job:

  1. sudo crontab -e
  2. Add this line to the end: @daily /file/location/cloudflare-ufw.sh &> /dev/null
#!/bin/sh
#
# UFW rule updater to only allow HTTP and HTTPS traffic from Cloudflare IP addresses.
# Inspired by https://github.com/Paul-Reed/cloudflare-ufw/blob/master/cloudflare-ufw.sh
#
# To run as a daily cron job:
# 1. sudo crontab -e
# 2. Add this line to the end:
# @daily /this/file/location/cloudflare-ufw.sh &> /dev/null
# Fetch latest IP range lists (both v4 and v6) directly from Cloudflare
curl -s https://www.cloudflare.com/ips-v4 -o /tmp/cf_ips
echo "\n" >> /tmp/cf_ips
curl -s https://www.cloudflare.com/ips-v6 >> /tmp/cf_ips
# Restrict traffic to ports 80 (TCP) & 443 (TCP)
# UFW will skip an IP range if a rule already exists for it (which it probably does)
for ip in `cat /tmp/cf_ips`; do ufw allow proto tcp from $ip to any port 80,443 comment 'Cloudflare'; done
# Clear downloaded lists from above
rm /tmp/cf_ips
# Need to reload UFW for any new rules to take effect
ufw reload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment