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
This commit is contained in:
kiskaadee committed 2026-04-25 15:02:22 -05:00
1 parent a4a776ccd7
commit 306db58c32
4 files changed
+150 -46

No files matched your search

+66
View File
@@ -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`
```
+14
View File
@@ -3,12 +3,26 @@
# This script is intended to run via systemd # This script is intended to run via systemd
[Unit] [Unit]
Description=Dynu IP Monitor & Updater Description=Dynu IP Monitor & Updater
After=network-online.target
Wants=network-online.target
[Service] [Service]
Type=oneshot Type=oneshot
User=root
Group=root
StateDirectory=dynu StateDirectory=dynu
EnvironmentFile=/etc/conf.d/dynu-environment EnvironmentFile=/etc/conf.d/dynu-environment
ExecStart=/usr/local/bin/ip-monitor.sh ExecStart=/usr/local/bin/ip-monitor.sh
StandardOutput=journal StandardOutput=journal
StandardError=journal StandardError=journal
TimeoutSec=30 TimeoutSec=30
# Optional hardening (safe defaults)
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/dynu
+1 -1
View File
@@ -4,7 +4,7 @@
Description=Run Dynu updater periodically Description=Run Dynu updater periodically
[Timer] [Timer]
OnBootSec=1min OnBootSec=30s
OnUnitActiveSec=15min OnUnitActiveSec=15min
AccuracySec=10s AccuracySec=10s
Persistent=true Persistent=true
+69 -45
View File
@@ -22,88 +22,109 @@
# - Prefer fallback over retry loops # - Prefer fallback over retry loops
# - Always log observable events # - Always log observable events
#!/bin/bash
set -euo pipefail set -euo pipefail
# --- configuration --- # --- invariants ---
STATE_DIR="${STATE_DIRECTORY:-/var/lib/dynu}" : "${STATE_DIRECTORY:?must be run via systemd (StateDirectory missing)}"
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) ---
: "${DYNU_HOST:?missing}" : "${DYNU_HOST:?missing}"
: "${DYNU_USER:?missing}" : "${DYNU_USER:?missing}"
: "${DYNU_PASSWORD:?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 --- # --- logging ---
# Single-line structured logs for journald
log() { log() {
printf '%s dynu-monitor %s\n' "$(date -Iseconds)" "$*" printf '%s dynu-monitor %s\n' "$(date -Iseconds)" "$*"
} }
# --- concurrency control --- # --- concurrency control ---
# Prevent overlapping executions (e.g., slow runs or manual triggers)
exec 9>"$STATE_DIR/lock" exec 9>"$STATE_DIR/lock"
flock -n 9 || { log "event=skip reason=lock_held"; exit 0; } flock -n 9 || { log "event=skip reason=lock_held"; exit 0; }
# --- validation --- # --- validation ---
# Strict IPv4 validation (format + numeric bounds)
is_valid_ipv4() { is_valid_ipv4() {
local ip=$1 local ip=$1 a b c d
local a b c d
[[ $ip =~ ^((0|[1-9][0-9]{0,2})\.){3}(0|[1-9][0-9]{0,2})$ ]] || return 1 [[ $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" IFS='.' read -r a b c d <<< "$ip"
(( 10#$a <= 255 && 10#$b <= 255 && 10#$c <= 255 && 10#$d <= 255 )) (( 10#$a <= 255 && 10#$b <= 255 && 10#$c <= 255 && 10#$d <= 255 ))
} }
# --- providers --- # --- providers ---
# DNS-based IP discovery (fast, optional)
get_ip_from_dns() { get_ip_from_dns() {
"$DIG_CMD" +short +time=2 +tries=1 myip.opendns.com @resolver1.opendns.com \ "$DIG_CMD" +short +time=2 +tries=1 myip.opendns.com @resolver1.opendns.com \
| head -n1 | tr -d '[:space:]' | head -n1 | tr -d '[:space:]'
} }
# HTTP-based IP discovery (fallback, reliable)
get_ip_from_http() { get_ip_from_http() {
"$CURL_CMD" -s --fail --max-time 5 https://ifconfig.me \ local providers=(
| head -n1 | tr -d '[:space:]' "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 --- # --- discovery ---
RAW_IP="" RAW_IP=""
SOURCE="dns" SOURCE="dns"
# Attempt DNS if available
if [[ -n "$DIG_CMD" ]]; then if [[ -n "$DIG_CMD" ]]; then
if RAW_IP="$(get_ip_from_dns 2>/dev/null)"; then DNS_ERR_FILE=$(mktemp)
log "event=attempt source=dns value='$RAW_IP'" if ! RAW_IP="$(get_ip_from_dns 2>"$DNS_ERR_FILE")"; then
else DNS_EXIT=$?
log "event=error source=dns reason=command_failed" DNS_ERR="$(head -c 120 "$DNS_ERR_FILE")"
log "event=error source=dns exit_code=$DNS_EXIT err='${DNS_ERR:-none}'"
RAW_IP="" RAW_IP=""
else
log "event=attempt source=dns value='$RAW_IP'"
fi fi
rm -f "$DNS_ERR_FILE"
else else
log "event=skip source=dns reason=missing_dependency" log "event=skip source=dns reason=missing_dependency"
fi fi
# Fallback to HTTP if DNS result is invalid or missing
if ! is_valid_ipv4 "$RAW_IP"; then if ! is_valid_ipv4 "$RAW_IP"; then
log "event=fallback from=dns reason=invalid_or_missing_response value='$RAW_IP'" log "event=fallback from=dns reason=invalid_or_missing_response value='$RAW_IP'"
SOURCE="http" SOURCE="http"
if RAW_IP="$(get_ip_from_http 2>/dev/null)"; then
log "event=attempt source=http value='$RAW_IP'" if ! RAW_IP="$(get_ip_from_http)"; then
else log "event=error source=http reason=all_providers_failed"
log "event=error source=http reason=command_failed"
RAW_IP="" RAW_IP=""
fi fi
fi fi
# --- final validation (critical invariant) --- # --- final validation ---
if ! is_valid_ipv4 "$RAW_IP"; then if ! is_valid_ipv4 "$RAW_IP"; then
log "event=error reason=invalid_ip source=$SOURCE value='$RAW_IP'" log "event=error reason=invalid_ip source=$SOURCE value='$RAW_IP'"
exit 1 exit 1
@@ -116,7 +137,6 @@ log "event=discovered source=$SOURCE ip=$CURRENT_IP"
LAST_IP="" LAST_IP=""
if [[ -f "$LAST_IP_FILE" ]]; then if [[ -f "$LAST_IP_FILE" ]]; then
LAST_IP="$(tr -d '[:space:]' < "$LAST_IP_FILE" || true)" LAST_IP="$(tr -d '[:space:]' < "$LAST_IP_FILE" || true)"
if ! is_valid_ipv4 "$LAST_IP"; then if ! is_valid_ipv4 "$LAST_IP"; then
log "event=warning reason=invalid_last_ip value='$LAST_IP'" log "event=warning reason=invalid_last_ip value='$LAST_IP'"
LAST_IP="" LAST_IP=""
@@ -132,27 +152,31 @@ fi
log "event=change old_ip=${LAST_IP:-none} new_ip=$CURRENT_IP" log "event=change old_ip=${LAST_IP:-none} new_ip=$CURRENT_IP"
# --- update Dynu --- # --- update Dynu ---
UPDATE_RESPONSE="$( RESP_FILE=$(mktemp)
"$CURL_CMD" -s --fail --max-time 5 \
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}" \ "https://api.dynu.com/nic/update?hostname=${DYNU_HOST}&username=${DYNU_USER}&password=${DYNU_PASSWORD}&myip=${CURRENT_IP}" \
|| true || 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 --- log "event=update_response http_code=$HTTP_CODE response='$UPDATE_RESPONSE'"
if [[ -z "$UPDATE_RESPONSE" ]]; then
log "event=error reason=empty_update_response" if [[ "$HTTP_CODE" != "200" ]]; then
log "event=error reason=http_failure code=$HTTP_CODE"
exit 1 exit 1
fi fi
# Dynu success responses:
# good <ip> → updated
# nochg <ip> → already current
if [[ "$UPDATE_RESPONSE" == good* || "$UPDATE_RESPONSE" == nochg* ]]; then if [[ "$UPDATE_RESPONSE" == good* || "$UPDATE_RESPONSE" == nochg* ]]; then
TMP_FILE=$(mktemp -p "$STATE_DIR" last_ip.XXXXXX) 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" mv "$TMP_FILE" "$LAST_IP_FILE"
log "event=state_updated ip=$CURRENT_IP" log "event=state_updated ip=$CURRENT_IP"