diff --git a/README.md b/README.md new file mode 100644 index 0000000..86c3e2c --- /dev/null +++ b/README.md @@ -0,0 +1,46 @@ +# MythicBeasts AAAA updater + +While my ISP hands out IPv6 addresses, they change every so often, +so I needed a way to keep my AAAA record up to date. + +I used kagi assistant to create this script and configuration, so it is worth +reading through it to check. + +```shell +install --mode=0644 mb-aaaa-udate.* /etc/systemd/system/ +install --mode=0755 mb-aaaa-update /usr/local/sbin/ +install --mode=0600 mb-aaaa.credentials /etc/ +install --mode=0644 mb-aaaa.env /etc/ +``` + +Edit /etc/mb-aaaa.env with the domain name (zone) you host in MythicBeasts and +the host name you want to keep up to date. + +Visit https://www.mythic-beasts.com/customer/api-users to create an API key to +be used to update your host's AAAA record. The advice is to use a different key +for each host, so give it a name unique to the host and add a "permit" to +restrict to the host, zone and AAAA record. Copy the eventual key and secret +into /etc/mb-aaaa.credentials; the key and secret will only be shown once. + +You can check that things are set up by running: +```shell +set -a +source /etc/mb-aaaa.env +set +a + +MB_DRY_RUN=1 MB_VERBOSE=1 mb-aaaa-update +``` + +This should output a line saying what would be done, then: +```shell +MB_VERBOSE=1 mb-aaaa-update +``` + +should update the record on first run and avoid making an API call on +subsequent runs unless the address has changed. + +To make this run automatically every 5 minutes (configurable in +`/etc/systemd/system/`), run: +```shell +systemctl enable --now mb-aaaa-update.timer +``` diff --git a/mb-aaaa-update b/mb-aaaa-update new file mode 100755 index 0000000..10f48c7 --- /dev/null +++ b/mb-aaaa-update @@ -0,0 +1,140 @@ +#!/usr/bin/env bash +# mb-aaaa-update — publish this host's IPv6 address to Mythic Beasts, +# but only when it differs from the last address we successfully published. +# Steady state: zero network requests. + +set -uo pipefail + +API="${MB_API:-https://api.mythic-beasts.com/dns/v2}" +ZONE="${MB_ZONE:?MB_ZONE is not set}" +HOST="${MB_HOST:?MB_HOST is not set}" # relative name, or @ for apex +TTL="${MB_TTL:-60}" +IFACE="${MB_IFACE:-}" +CREDS="${MB_CREDS:-/etc/mb-aaaa.credentials}" +STATE_DIR="${MB_STATE_DIR:-/var/lib/mb-aaaa}" +DNS_CHECK="${MB_DNS_CHECK:-0}" # 1 = ask ns1/ns2 before writing +RECHECK_AGE="${MB_RECHECK_AGE:-0}" # seconds; 0 = never re-check +VERBOSE="${MB_VERBOSE:-0}" # 1 = log no-op runs too +DRY_RUN="${MB_DRY_RUN:-0}" + +# One state file per zone+host, so several copies can share the directory. +STATE="$STATE_DIR/${ZONE//[^A-Za-z0-9.-]/_}_${HOST//[^A-Za-z0-9.-]/_}.addr" + +log() { printf '%s %s: %s\n' "$(date -Is)" "$HOST" "$*" >&2; } +vlog() { [ "$VERBOSE" = 1 ] && log "$@"; return 0; } +die() { log "ERROR: $*"; exit 1; } + +lower() { printf '%s' "$1" | tr 'A-F' 'a-f'; } + +# ------------------------------------------------------------ credentials +[ -r "$CREDS" ] || die "credentials file $CREDS missing or unreadable" +perm=$(stat -c '%a' "$CREDS") +(( 8#$perm & 8#077 )) && log "WARNING: $CREDS is group/world readable (mode $perm)" +# shellcheck disable=SC1090 +. "$CREDS" +[ -n "${KEY:-}" ] && [ -n "${SECRET:-}" ] || die "KEY/SECRET not defined in $CREDS" + +# ------------------------------------------------------------------- lock +command -v curl >/dev/null || die "curl not found" +command -v ip >/dev/null || die "ip not found" +mkdir -p "$STATE_DIR" || die "cannot create $STATE_DIR" +exec 9>"$STATE_DIR/.lock" || die "cannot open lock" +flock -n 9 || { vlog "another instance is running"; exit 0; } + +# ------------------------------------------------------- local IPv6 address +find_ipv6() { + local def + def=$(ip -6 route show default 2>/dev/null | + awk '{for (i=1;i<=NF;i++) if ($i=="dev") {print $(i+1); exit}}') + ip -6 addr show scope global 2>/dev/null | awk -v def="$def" -v want="$IFACE" ' + /^[0-9]+:/ { iface=$2; sub(/:$/,"",iface); sub(/@.*/,"",iface); next } + /inet6 / { + if ($0 ~ /(temporary|deprecated|tentative|dadfailed|optimistic)/) next + split($2, p, "/"); addr=p[1] + if (addr !~ /^(2|3)/) next # 2000::/3 only + if (want != "" && iface != want) next + print ((iface==def)?0:1), (($0 ~ /mngtmpaddr/)?0:1), addr + }' | sort -k1,1n -k2,2n -k3,3 | awk 'NR==1 {print $3}' +} + +# ------------------------------------------------- optional DNS pre-flight +# 0 = confirmed on every nameserver, 1 = differs, 2 = cannot check +dns_confirms() { + local want=$1 ns out fqdn seen=0 + [ "$HOST" = "@" ] && fqdn="$ZONE" || fqdn="$HOST.$ZONE" + command -v dig >/dev/null || return 2 + for ns in ns1.mythic-beasts.com ns2.mythic-beasts.com; do + out=$(dig +short +time=3 +tries=1 AAAA "$fqdn" "@$ns" 2>/dev/null) || continue + seen=1 + grep -qixF -- "$want" <<<"$out" || return 1 + done + [ "$seen" = 1 ] || return 2 + return 0 +} + +save_state() { + local tmp="$STATE.tmp.$$" + printf '%s\n%s\n' "$1" "$(date -Is)" >"$tmp" && + chmod 0644 "$tmp" && mv -f "$tmp" "$STATE" +} + +# -------------------------------------------------------------------- main +ADDR=$(find_ipv6) +[ -n "$ADDR" ] || { vlog "no usable global IPv6 address yet; nothing to do"; exit 0; } + +last=$(head -n 1 "$STATE" 2>/dev/null || true) + +if [ -n "$last" ] && [ "$(lower "$last")" = "$(lower "$ADDR")" ]; then + # Address unchanged. Only reach for the network if a periodic re-check is due. + if [ "$RECHECK_AGE" -gt 0 ]; then + now=$(date +%s); mtime=$(stat -c %Y "$STATE" 2>/dev/null || echo 0) + if [ $(( now - mtime )) -lt "$RECHECK_AGE" ]; then + vlog "unchanged ($ADDR), state ${last} is current; no request made" + exit 0 + fi + vlog "unchanged locally, but state is $(( now - mtime ))s old; re-checking DNS" + else + vlog "unchanged ($ADDR); no request made" + exit 0 + fi +elif [ -n "$last" ]; then + log "address changed: $last -> $ADDR" +else + log "no recorded state; publishing $ADDR" +fi + +if [ "$DNS_CHECK" = 1 ]; then + dns_confirms "$ADDR"; rc=$? + case $rc in + 0) log "authoritative DNS already matches; recording state, no write" + save_state "$ADDR"; exit 0 ;; + 2) log "dig unavailable/failed; proceeding with write" ;; + *) log "authoritative DNS differs; proceeding with write" ;; + esac +fi + +if [ "$DRY_RUN" = 1 ]; then + log "dry-run: would PUT $ADDR (ttl $TTL) to /zones/$ZONE/records/$HOST/AAAA" + exit 0 +fi + +body=$(mktemp) || die "mktemp failed" +trap 'rm -f "$body"' EXIT + +code=$(curl -sS --max-time 20 --retry 2 --retry-delay 3 \ + -u "$KEY:$SECRET" -X PUT \ + --data-urlencode "data=$ADDR" \ + --data-urlencode "ttl=$TTL" \ + -o "$body" -w '%{http_code}' \ + "$API/zones/$ZONE/records/$HOST/AAAA") || die "curl failed on PUT" + +case $code in + 200|201) log "updated to $ADDR (ttl $TTL): $(cat "$body")" ;; + 401|403) die "auth/authorisation failed (HTTP $code): $(cat "$body")" ;; + 404) die "zone or host not found (HTTP 404): $(cat "$body")" ;; + *) die "unexpected HTTP $code: $(cat "$body")" ;; +esac + +save_state "$ADDR" +exit 0 + diff --git a/mb-aaaa-update.service b/mb-aaaa-update.service new file mode 100644 index 0000000..35abc5e --- /dev/null +++ b/mb-aaaa-update.service @@ -0,0 +1,19 @@ +[Unit] +Description=Sync Mythic Beasts AAAA record (only on change) +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +EnvironmentFile=/etc/mb-aaaa.env +ExecStart=/usr/local/sbin/mb-aaaa-update +StateDirectory=mb-aaaa +StateDirectoryMode=0755 +NoNewPrivileges=yes +PrivateTmp=yes +ProtectSystem=strict +ProtectHome=yes +ProtectKernelTunables=yes +ProtectControlGroups=yes +RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX + diff --git a/mb-aaaa-update.timer b/mb-aaaa-update.timer new file mode 100644 index 0000000..87a949d --- /dev/null +++ b/mb-aaaa-update.timer @@ -0,0 +1,13 @@ +[Unit] +Description=Periodically check whether the AAAA record needs updating + +[Timer] +OnBootSec=90s +OnUnitActiveSec=5min +RandomizedDelaySec=45s +AccuracySec=30s +Unit=mb-aaaa-update.service + +[Install] +WantedBy=timers.target + diff --git a/mb-aaaa.credentials b/mb-aaaa.credentials new file mode 100644 index 0000000..eb10a7d --- /dev/null +++ b/mb-aaaa.credentials @@ -0,0 +1,3 @@ +KEY= +SECRET= + diff --git a/mb-aaaa.env b/mb-aaaa.env new file mode 100644 index 0000000..464cf22 --- /dev/null +++ b/mb-aaaa.env @@ -0,0 +1,7 @@ +MB_ZONE= +MB_HOST= +MB_TTL=60 +MB_IFACE= +# MB_DNS_CHECK=1 +# MB_RECHECK_AGE=604800 +