#!/usr/bin/env bash # # Refresh Caddy's Cloudflare origin allowlist from Cloudflare's published # ranges. Called by chesstrainer-cloudflare-ranges.timer. # # The generated file is imported by /etc/caddy/Caddyfile: # # @cloudflare { # import cloudflare-ranges.caddy # } # # The script validates the candidate Caddyfile before reloading Caddy. If the # download or validation fails, the previous ranges stay in place. set -euo pipefail CADDYFILE="${CADDYFILE:-/etc/caddy/Caddyfile}" RANGES_FILE="${RANGES_FILE:-/etc/caddy/cloudflare-ranges.caddy}" CADDY_BIN="${CADDY_BIN:-caddy}" RELOAD_CMD="${RELOAD_CMD:-systemctl reload caddy}" LOCK_FILE="${LOCK_FILE:-/run/lock/chesstrainer-cloudflare-ranges.lock}" tmpdir="$(mktemp -d)" trap 'rm -rf "$tmpdir"' EXIT exec 9>"$LOCK_FILE" if ! flock -n 9; then echo "another Cloudflare range update is already running" >&2 exit 0 fi fetch() { local url="$1" local output="$2" curl --fail --silent --show-error --location \ --proto '=https' \ --retry 3 --retry-delay 2 --connect-timeout 10 \ "$url" --output "$output" } validate_download() { local file="$1" [[ -s "$file" ]] || return 1 # One CIDR per line. Caddy performs the real validation; this prevents # obviously malformed or injected content from being written. if grep -Evq '^[0-9A-Fa-f:.]+/[0-9]{1,3}$' "$file"; then return 1 fi } fetch "https://www.cloudflare.com/ips-v4" "$tmpdir/ips-v4" fetch "https://www.cloudflare.com/ips-v6" "$tmpdir/ips-v6" validate_download "$tmpdir/ips-v4" validate_download "$tmpdir/ips-v6" ranges="$(awk 'NF { printf "%s ", $0 }' "$tmpdir/ips-v4" "$tmpdir/ips-v6" | sed -e 's/[[:space:]]*$//')" if [[ -z "$ranges" ]]; then echo "Cloudflare returned an empty CIDR list" >&2 exit 1 fi candidate="$tmpdir/cloudflare-ranges.caddy" { echo "# Generated by deploy/update-cloudflare-ranges.sh." echo "# Source: https://www.cloudflare.com/ips-v4 and /ips-v6" echo "remote_ip $ranges" } >"$candidate" if cmp -s "$candidate" "$RANGES_FILE"; then echo "Cloudflare ranges are unchanged" exit 0 fi install -d -m 0755 "$(dirname "$RANGES_FILE")" backup="$tmpdir/previous-ranges.caddy" if [[ -e "$RANGES_FILE" ]]; then cp -a "$RANGES_FILE" "$backup" fi install -m 0644 "$candidate" "$RANGES_FILE" if ! "$CADDY_BIN" validate --config "$CADDYFILE" --adapter caddyfile; then echo "Caddy rejected the new Cloudflare ranges; restoring the previous file" >&2 if [[ -e "$backup" ]]; then install -m 0644 "$backup" "$RANGES_FILE" else rm -f "$RANGES_FILE" fi exit 1 fi read -r -a reload_command <<<"$RELOAD_CMD" if ! "${reload_command[@]}"; then echo "Caddy reload failed; restoring the previous ranges" >&2 if [[ -e "$backup" ]]; then install -m 0644 "$backup" "$RANGES_FILE" else rm -f "$RANGES_FILE" fi exit 1 fi echo "Cloudflare ranges updated and Caddy reloaded"