From 8f138dfb9acb367e417be90b036c87671ae4bbb5 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Sun, 4 Jun 2023 21:02:09 -0700 Subject: [PATCH] refactored cf_ufw.sh - 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. --- cf_ufw.sh | 33 +++++++++++++++------------------ 1 file changed, 15 insertions(+), 18 deletions(-) diff --git a/cf_ufw.sh b/cf_ufw.sh index 2ebac4b..19dc789 100644 --- a/cf_ufw.sh +++ b/cf_ufw.sh @@ -15,21 +15,18 @@ 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 } @@ -37,26 +34,26 @@ check_permissions() { # 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