Skip to content

Instantly share code, notes, and snippets.

@miiiladiii244
Created January 1, 2025 05:14
Show Gist options
  • Save miiiladiii244/21f2f89d55f08f67664fda5f7b476500 to your computer and use it in GitHub Desktop.
Save miiiladiii244/21f2f89d55f08f67664fda5f7b476500 to your computer and use it in GitHub Desktop.
A bash script to generate and apply required rules in ufw for serving 80 and 443 to only cloudflare servers.
#!/bin/bash
# Fetch Cloudflare IP ranges
ipv4_url="https://www.cloudflare.com/ips-v4"
ipv6_url="https://www.cloudflare.com/ips-v6"
# Temporary files to store IP ranges
ipv4_file="/tmp/cloudflare_ipv4.txt"
ipv6_file="/tmp/cloudflare_ipv6.txt"
# Download the IP ranges
curl -s $ipv4_url -o $ipv4_file
curl -s $ipv6_url -o $ipv6_file
# Check if files were downloaded successfully
if [ ! -s $ipv4_file ] || [ ! -s $ipv6_file ]; then
echo "Failed to fetch Cloudflare IP ranges. Exiting."
exit 1
fi
# Add UFW rules for IPv4
while read -r ip; do
sudo ufw allow from $ip to any port 80
sudo ufw allow from $ip to any port 443
done < $ipv4_file
# Add UFW rules for IPv6
while read -r ip; do
sudo ufw allow from $ip to any port 80
sudo ufw allow from $ip to any port 443
done < $ipv6_file
# Deny all other traffic on ports 80 and 443
sudo ufw deny 80
sudo ufw deny 443
# Clean up temporary files
rm -f $ipv4_file $ipv6_file
echo "Cloudflare UFW rules have been applied."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment