Skip to content

Instantly share code, notes, and snippets.

@Interstellar750
Last active April 5, 2024 08:10
Show Gist options
  • Select an option

  • Save Interstellar750/1803cdefcaa91940e87a3d27fe78f17b to your computer and use it in GitHub Desktop.

Select an option

Save Interstellar750/1803cdefcaa91940e87a3d27fe78f17b to your computer and use it in GitHub Desktop.
Use ufw to quickly add Cloudflare’s IP to your firewall whitelist

Quick use

curl -L https://gist.githubusercontent.com/Interstellar750/1803cdefcaa91940e87a3d27fe78f17b/raw/add_cf_ips.sh | sudo bash

Remove Cloudflare's IP

curl -L https://gist.githubusercontent.com/Interstellar750/1803cdefcaa91940e87a3d27fe78f17b/raw/add_cf_ips.sh > add_cf_ips.sh && sudo bash add_cf_ips.sh --remove

Command line usage

./add_cf_ips.sh [PARAMETERS]
    without any parameters
        Add Cloudflare's IP to your firewall whitelist via ufw
    --remove
        Remove Cloudflare's IP from your firewall whitelist via ufw
        
Examples:
    ./add_cf_ips.sh
    ./add_cf_ips.sh --remove
    
Required:
    curl      Get Cloudflare's IP by sending a request to api.cloudflare.com/client/v4/ips
    jq        Parse the response data and obtain the IP range
#!/bin/bash
if [ "$#" -eq 1 ]; then
if [[ "$1" == "--remove" ]]; then
remove=true
else
echo "Error: Unknown parameter '$1'."
echo "Usage: bash $0 [--remove]"
exit 1
fi
elif [ "$#" -gt 1 ]; then
echo "Error: Too many parameters."
echo "Usage: bash $0 [--remove]"
exit 1
else
remove=false
fi
if ! command -v ufw &> /dev/null; then
if [ "$(id -u)" = "0" ]; then
echo "Error: ufw is not installed. Please install ufw before running this script."
exit 1
else
echo "Error: ufw is not installed or you do not have permission to run the ufw command."
echo "If you have sudo permission, try: sudo bash $0"
exit 1
fi
fi
if ! command -v jq &> /dev/null; then
echo "Error: jq is not installed. Please install jq before running this script."
exit 1
fi
response=$(curl -s https://api.cloudflare.com/client/v4/ips)
ipv4_cidrs=$(echo "$response" | jq -r '.result.ipv4_cidrs[]')
ipv6_cidrs=$(echo "$response" | jq -r '.result.ipv6_cidrs[]')
ipv4_count=$(echo "$ipv4_cidrs" | wc -l)
ipv6_count=$(echo "$ipv6_cidrs" | wc -l)
echo "Ranges: IPv4: $ipv4_count IPv6: $ipv6_count"
for ipv4 in $ipv4_cidrs; do
if [ "$remove" = true ]; then
ufw delete allow from "$ipv4"
echo removed from "$ipv4"
else
ufw allow from "$ipv4"
echo allow from $ipv4
fi
done
for ipv6 in $ipv6_cidrs; do
if [ "$remove" = true ]; then
ufw delete allow from "$ipv6"
echo removed from $ipv6
else
ufw allow from "$ipv6"
echo allow from $ipv6
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment