From 306db58c32b01248e2ac4810d3c5671337db6997 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Sat, 25 Apr 2026 15:02:22 -0500 Subject: [PATCH] refactor(dynu): enhance resilience and systemd hardening - Implement multi-provider HTTP fallback loop in ip-monitor.sh - Add strict systemd sandboxing (ProtectSystem, PrivateTmp, NoNewPrivileges) - Improve error observability by capturing stderr in discovery attempts - Add atomic file sync and invariant checks for systemd execution - Update documentation to reflect hardened protocol and state management --- docs/dynu-ip-update-protocol.md | 66 ++++++++++++++++++ scripts/dynu/dynu.service | 16 ++++- scripts/dynu/dynu.timer | 2 +- scripts/dynu/ip-monitor.sh | 116 +++++++++++++++++++------------- 4 files changed, 152 insertions(+), 48 deletions(-) create mode 100644 docs/dynu-ip-update-protocol.md diff --git a/docs/dynu-ip-update-protocol.md b/docs/dynu-ip-update-protocol.md new file mode 100644 index 0000000..76994e7 --- /dev/null +++ b/docs/dynu-ip-update-protocol.md @@ -0,0 +1,66 @@ +# Dynu IP Address Update Protocol + +## Problem Definition +* **Success Criteria**: The system must detect changes in public IPv4 addresses and update Dynu records with high resilience, using strict validation and atomic state management to avoid `abuse` flags. +* **Non-Goals**: This implementation does not manage complex DNS records (MX/TXT) or IPv6 addressing. + +## ADR: Resilience & Security Hardening +**Decision**: Implement a hardened, multi-provider discovery engine via systemd. + +* **Rationale**: + * **Redundancy**: Iterating through multiple HTTP providers prevents failure if a single service (like `ifconfig.me`) goes offline. + * **Security**: Systemd sandboxing (`ProtectSystem=strict`, `NoNewPrivileges`) ensures the script operates in a "least privilege" environment. + * **Observability**: Capturing `stderr` from discovery commands into the journal allows for deep-dive debugging of network timeouts. +* **Consequences**: Slightly higher complexity in shell logic, but provides a "set and forget" infrastructure layer. + +--- + +## Implementation Details + +### 1. Directory & State Management +Runtime data is handled by systemd's `StateDirectory` directive, which manages `/var/lib/dynu` automatically. +* **State File**: `/var/lib/dynu/last_ip` (Atomic updates via `mktemp` + `mv`). +* **Locking**: Concurrency is managed via `flock` on `/var/lib/dynu/lock`. + +### 2. Core Logic: `ip-monitor.sh` +The script follows a "Fail-Fast" philosophy: +1. **Invariants**: Validates that it is running within a systemd environment. +2. **Discovery Loop**: + * Primary: DNS query via `dig` (ultra-fast). + * Fallback: Multi-URL HTTP loop (`api.ipify.org`, `ifconfig.me`, `wtfismyip.com`). +3. **Validation**: Strict regex and numeric bound checks for IPv4 format. +4. **Update**: Hits the Dynu REST API only upon confirmed IP delta. + +### 3. Hardened Systemd Orchestration + +#### Service: `dynu.service` +```ini +[Service] +Type=oneshot +User=root +StateDirectory=dynu +EnvironmentFile=/etc/conf.d/dynu-environment +ExecStart=/usr/local/bin/ip-monitor.sh +# Hardening +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/var/lib/dynu +``` + +#### Timer: `dynu.timer` +```ini +[Timer] +OnBootSec=30s +OnUnitActiveSec=15min +Persistent=true +``` + +--- + +## Verification and Monitoring +* **Live Logs**: `journalctl -u dynu.service -f` +* **Check State**: `cat /var/lib/dynu/last_ip` +* **Simulate Update**: `echo "1.1.1.1" > /var/lib/dynu/last_ip && systemctl start dynu.service` +``` \ No newline at end of file diff --git a/scripts/dynu/dynu.service b/scripts/dynu/dynu.service index 497382c..cf3febb 100644 --- a/scripts/dynu/dynu.service +++ b/scripts/dynu/dynu.service @@ -3,12 +3,26 @@ # This script is intended to run via systemd [Unit] Description=Dynu IP Monitor & Updater +After=network-online.target +Wants=network-online.target [Service] Type=oneshot +User=root +Group=root + StateDirectory=dynu EnvironmentFile=/etc/conf.d/dynu-environment + ExecStart=/usr/local/bin/ip-monitor.sh + StandardOutput=journal StandardError=journal -TimeoutSec=30 \ No newline at end of file +TimeoutSec=30 + +# Optional hardening (safe defaults) +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/var/lib/dynu \ No newline at end of file diff --git a/scripts/dynu/dynu.timer b/scripts/dynu/dynu.timer index 1626dfc..b5246a7 100644 --- a/scripts/dynu/dynu.timer +++ b/scripts/dynu/dynu.timer @@ -4,7 +4,7 @@ Description=Run Dynu updater periodically [Timer] -OnBootSec=1min +OnBootSec=30s OnUnitActiveSec=15min AccuracySec=10s Persistent=true diff --git a/scripts/dynu/ip-monitor.sh b/scripts/dynu/ip-monitor.sh index 20864dd..b85bd11 100755 --- a/scripts/dynu/ip-monitor.sh +++ b/scripts/dynu/ip-monitor.sh @@ -22,88 +22,109 @@ # - Prefer fallback over retry loops # - Always log observable events +#!/bin/bash set -euo pipefail -# --- configuration --- -STATE_DIR="${STATE_DIRECTORY:-/var/lib/dynu}" -LAST_IP_FILE="$STATE_DIR/last_ip" - -DIG_CMD=$(command -v dig || true) # optional -CURL_CMD=$(command -v curl) || { echo "curl not found"; exit 1; } -MKDIR_CMD=$(command -v mkdir) || { echo "mkdir not found"; exit 1; } - -"$MKDIR_CMD" -p "$STATE_DIR" - -# --- environment validation (fail fast) --- +# --- invariants --- +: "${STATE_DIRECTORY:?must be run via systemd (StateDirectory missing)}" : "${DYNU_HOST:?missing}" : "${DYNU_USER:?missing}" : "${DYNU_PASSWORD:?missing}" +STATE_DIR="$STATE_DIRECTORY" +LAST_IP_FILE="$STATE_DIR/last_ip" + +DIG_CMD="$(command -v dig || true)" +CURL_CMD="$(command -v curl)" || { echo "curl not found"; exit 1; } + +mkdir -p "$STATE_DIR" + # --- logging --- -# Single-line structured logs for journald log() { printf '%s dynu-monitor %s\n' "$(date -Iseconds)" "$*" } # --- concurrency control --- -# Prevent overlapping executions (e.g., slow runs or manual triggers) exec 9>"$STATE_DIR/lock" flock -n 9 || { log "event=skip reason=lock_held"; exit 0; } # --- validation --- -# Strict IPv4 validation (format + numeric bounds) is_valid_ipv4() { - local ip=$1 - local a b c d - + local ip=$1 a b c d [[ $ip =~ ^((0|[1-9][0-9]{0,2})\.){3}(0|[1-9][0-9]{0,2})$ ]] || return 1 IFS='.' read -r a b c d <<< "$ip" (( 10#$a <= 255 && 10#$b <= 255 && 10#$c <= 255 && 10#$d <= 255 )) } # --- providers --- -# DNS-based IP discovery (fast, optional) get_ip_from_dns() { "$DIG_CMD" +short +time=2 +tries=1 myip.opendns.com @resolver1.opendns.com \ | head -n1 | tr -d '[:space:]' } -# HTTP-based IP discovery (fallback, reliable) get_ip_from_http() { - "$CURL_CMD" -s --fail --max-time 5 https://ifconfig.me \ - | head -n1 | tr -d '[:space:]' + local providers=( + "https://api.ipify.org" + "https://ifconfig.me" + "https://wtfismyip.com/text" + ) + + for url in "${providers[@]}"; do + local ip err_file exit_code + err_file=$(mktemp) + + if ip="$("$CURL_CMD" -s --fail --max-time 5 "$url" 2>"$err_file")"; then + ip="$(echo "$ip" | head -n1 | tr -d '[:space:]')" + log "event=attempt source=http url='$url' value='$ip'" + + rm -f "$err_file" + + if is_valid_ipv4 "$ip"; then + echo "$ip" + return 0 + fi + else + exit_code=$? + local err + err="$(head -c 120 "$err_file")" + log "event=error source=http url='$url' exit_code=$exit_code err='${err:-none}'" + rm -f "$err_file" + fi + done + + return 1 } # --- discovery --- RAW_IP="" SOURCE="dns" -# Attempt DNS if available if [[ -n "$DIG_CMD" ]]; then - if RAW_IP="$(get_ip_from_dns 2>/dev/null)"; then - log "event=attempt source=dns value='$RAW_IP'" - else - log "event=error source=dns reason=command_failed" + DNS_ERR_FILE=$(mktemp) + if ! RAW_IP="$(get_ip_from_dns 2>"$DNS_ERR_FILE")"; then + DNS_EXIT=$? + DNS_ERR="$(head -c 120 "$DNS_ERR_FILE")" + log "event=error source=dns exit_code=$DNS_EXIT err='${DNS_ERR:-none}'" RAW_IP="" + else + log "event=attempt source=dns value='$RAW_IP'" fi + rm -f "$DNS_ERR_FILE" else log "event=skip source=dns reason=missing_dependency" fi -# Fallback to HTTP if DNS result is invalid or missing if ! is_valid_ipv4 "$RAW_IP"; then log "event=fallback from=dns reason=invalid_or_missing_response value='$RAW_IP'" - SOURCE="http" - if RAW_IP="$(get_ip_from_http 2>/dev/null)"; then - log "event=attempt source=http value='$RAW_IP'" - else - log "event=error source=http reason=command_failed" + + if ! RAW_IP="$(get_ip_from_http)"; then + log "event=error source=http reason=all_providers_failed" RAW_IP="" fi fi -# --- final validation (critical invariant) --- +# --- final validation --- if ! is_valid_ipv4 "$RAW_IP"; then log "event=error reason=invalid_ip source=$SOURCE value='$RAW_IP'" exit 1 @@ -116,7 +137,6 @@ log "event=discovered source=$SOURCE ip=$CURRENT_IP" LAST_IP="" if [[ -f "$LAST_IP_FILE" ]]; then LAST_IP="$(tr -d '[:space:]' < "$LAST_IP_FILE" || true)" - if ! is_valid_ipv4 "$LAST_IP"; then log "event=warning reason=invalid_last_ip value='$LAST_IP'" LAST_IP="" @@ -132,27 +152,31 @@ fi log "event=change old_ip=${LAST_IP:-none} new_ip=$CURRENT_IP" # --- update Dynu --- -UPDATE_RESPONSE="$( - "$CURL_CMD" -s --fail --max-time 5 \ - "https://api.dynu.com/nic/update?hostname=${DYNU_HOST}&username=${DYNU_USER}&password=${DYNU_PASSWORD}&myip=${CURRENT_IP}" \ - || true +RESP_FILE=$(mktemp) + +HTTP_CODE="$( + "$CURL_CMD" -s --max-time 5 \ + -w "%{http_code}" \ + -o "$RESP_FILE" \ + "https://api.dynu.com/nic/update?hostname=${DYNU_HOST}&username=${DYNU_USER}&password=${DYNU_PASSWORD}&myip=${CURRENT_IP}" \ + || echo "000" )" -log "event=update_response response='$UPDATE_RESPONSE'" +UPDATE_RESPONSE="$(head -c 200 "$RESP_FILE" 2>/dev/null || true)" +rm -f "$RESP_FILE" -# --- response validation --- -if [[ -z "$UPDATE_RESPONSE" ]]; then - log "event=error reason=empty_update_response" +log "event=update_response http_code=$HTTP_CODE response='$UPDATE_RESPONSE'" + +if [[ "$HTTP_CODE" != "200" ]]; then + log "event=error reason=http_failure code=$HTTP_CODE" exit 1 fi -# Dynu success responses: -# good → updated -# nochg → already current if [[ "$UPDATE_RESPONSE" == good* || "$UPDATE_RESPONSE" == nochg* ]]; then TMP_FILE=$(mktemp -p "$STATE_DIR" last_ip.XXXXXX) - echo "$CURRENT_IP" > "$TMP_FILE" + printf '%s\n' "$CURRENT_IP" > "$TMP_FILE" + sync -f "$TMP_FILE" 2>/dev/null || true mv "$TMP_FILE" "$LAST_IP_FILE" log "event=state_updated ip=$CURRENT_IP"