Skip to content

Instantly share code, notes, and snippets.

@jakejarvis
Created December 6, 2019 04:35
Show Gist options
  • Save jakejarvis/d3a3468233a8b92e9087c3acf379226c to your computer and use it in GitHub Desktop.
Save jakejarvis/d3a3468233a8b92e9087c3acf379226c 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
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
@SzymonLisowiec
Copy link

Thanks for great work. I had a little problem "ERROR: Bad source address", which caused the last address not to be added. To fix it just add echo "\n" >> /tmp/cf_ips after first curl line.

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