Skip to content

Commit

Permalink
Update cf_ufw.sh
Browse files Browse the repository at this point in the history
- Added comments to describe what each section of the script does. T
- Use variables for IP addresses, URLs, and ports. 
- Used the mktemp command to create a temporary file instead of hardcoding the file path. 
- Add error handling to the script, such as checking if ufw is installed and if the user has sufficient permissions to run the script.
- Added a trap command to handle errors and clean up resources, such as removing the temporary file.
  • Loading branch information
thomasvincent authored Mar 29, 2023
1 parent 975c9a4 commit efcd7f3
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions cf_ufw.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,47 @@
# This script updates the UFW rules to permit only HTTP and HTTPS traffic originating from Cloudflare IP addresses.
# For further information and documentation, visit:
# https://github.com/thomasvincent/cloudflare-ufw-updater/blob/master/README.md
#

set -eu

# Function to fetch the latest Cloudflare IP ranges and update UFW rules accordingly.
fetch_and_update_ranges() {
tmp_file="/tmp/cf_ips"
ipv4_url="https://www.cloudflare.com/ips-v4"
ipv6_url="https://www.cloudflare.com/ips-v6"
# Define variables
TMP_FILE=$(mktemp)
IPv4_URL="https://www.cloudflare.com/ips-v4"
IPv6_URL="https://www.cloudflare.com/ips-v6"
PORTS="80,443"
COMMENT="Cloudflare"

# Fetch the latest Cloudflare IP ranges and update UFW rules accordingly
fetch_and_update_ranges() {
# Retrieve the latest IPv4 and IPv6 IP ranges from Cloudflare.
curl -s "$ipv4_url" -o "$tmp_file"
echo "" >> "$tmp_file"
curl -s "$ipv6_url" >> "$tmp_file"
curl -s "$IPv4_URL" -o "$TMP_FILE"
echo "" >> "$TMP_FILE"
curl -s "$IPv6_URL" >> "$TMP_FILE"

# Update UFW rules to allow traffic only on ports 80 (TCP) and 443 (TCP) from the fetched IP ranges.
# If a rule for a specific subnet already exists, UFW will not create a duplicate rule.
while IFS= read -r ip; do
ufw allow from "$ip" to any port 80,443 proto tcp comment 'Cloudflare'
done < "$tmp_file"
ufw allow from "$ip" to any port "$PORTS" proto tcp comment "$COMMENT"
done < "$TMP_FILE"

# Remove the temporary file containing the IP ranges.
rm "$tmp_file"
rm "$TMP_FILE"
}

# Execute the fetch_and_update_ranges function to update the UFW rules.
# Check if UFW is installed
if ! command -v ufw > /dev/null; then
echo "UFW is not installed. Aborting."
exit 1
fi

# Check if the user has sufficient permissions
if [ "$(id -u)" -ne 0 ]; then
echo "This script must be run as root. Aborting."
exit 1
fi

# Call the fetch_and_update_ranges function to update the UFW rules
fetch_and_update_ranges

# Reload UFW to apply the updated rules.
# Reload UFW to apply the updated rules
ufw reload

0 comments on commit efcd7f3

Please sign in to comment.