Skip to content

Commit

Permalink
refactored cf_ufw.sh
Browse files Browse the repository at this point in the history
- Added double quotes to variable expansions to prevent word splitting and pathname expansion.
- Used "$()" for command substitution instead of using backticks, as it's the recommended way.
- Used printf instead of echo for printing to the console.
Simplified the way to append a newline to the temporary file.
  • Loading branch information
thomasvincent authored Jun 5, 2023
1 parent c06b779 commit 8f138df
Showing 1 changed file with 15 additions and 18 deletions.
33 changes: 15 additions & 18 deletions cf_ufw.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,48 +15,45 @@ RULE_COMMENT="Cloudflare"

# Check if the required tools are installed
check_dependencies() {
if ! command -v ufw > /dev/null; then
echo "UFW is not installed. Aborting."
exit 1
fi

if ! command -v curl > /dev/null; then
echo "curl is not installed. Aborting."
exit 1
fi
for cmd in ufw curl; do
if ! command -v "$cmd" > /dev/null; then
printf "Command not found in PATH: %s\n" "$cmd"
exit 1
fi
done
}

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

# 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.
if ! curl -s --retry 3 --retry-delay 5 "$CLOUDFLARE_IPv4_URL" -o "$TEMP_FILE"; then
echo "Failed to fetch IPv4 addresses. Aborting."
if ! curl -s --retry 3 --retry-delay 5 "${CLOUDFLARE_IPv4_URL}" -o "${TEMP_FILE}"; then
printf "Failed to fetch IPv4 addresses. Aborting.\n"
exit 1
fi

echo "" >> "$TEMP_FILE"
printf "\n" >> "${TEMP_FILE}"

if ! curl -s --retry 3 --retry-delay 5 "$CLOUDFLARE_IPv6_URL" >> "$TEMP_FILE"; then
echo "Failed to fetch IPv6 addresses. Aborting."
if ! curl -s --retry 3 --retry-delay 5 "${CLOUDFLARE_IPv6_URL}" >> "${TEMP_FILE}"; then
printf "Failed to fetch IPv6 addresses. Aborting.\n"
exit 1
fi

# 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 "$ALLOWED_PORTS" proto tcp comment "$RULE_COMMENT"
done < "$TEMP_FILE"
ufw allow from "${ip}" to any port "${ALLOWED_PORTS}" proto tcp comment "${RULE_COMMENT}"
done < "${TEMP_FILE}"

# Remove the temporary file containing the IP ranges.
rm "$TEMP_FILE"
rm "${TEMP_FILE}"
}

# Main function to run the script
Expand Down

0 comments on commit 8f138df

Please sign in to comment.