ddns/ddns.sh

474 lines
17 KiB
Shell
Executable file

#!/bin/sh
# Dynamic DNS for MozOut.
#
# Keeps an A and/or AAAA record of your domain pointing at the public IP of this network,
# through the MozOut API. POSIX sh and curl only: runs on OpenWrt routers, Raspberry Pi,
# any Linux, macOS and in Docker. Run it from cron, a systemd timer or with --loop.
#
# Settings come from environment variables or from a config file (see ddns.conf.example).
# The API key is never printed.
set -u
VERSION="1.0.1"
API_URL="https://api.mozout.com"
KEY_VAR="MOZOUT_API_KEY"
UA="mozout-ddns/$VERSION"
DEFAULT_CONFIG="/etc/mozout-ddns.conf"
usage() {
cat <<EOF
MozOut dynamic DNS $VERSION
Usage: ${0##*/} [options]
-c FILE config file (default: $DEFAULT_CONFIG, when it exists)
--loop keep running and check every DDNS_INTERVAL seconds (Docker)
--force ask the API even if the IP did not change
--dry-run show what would change, change nothing
-q only print changes and errors
-V version
-h this help
Main settings (environment or config file):
$KEY_VAR the API key, with dns:read and dns:write (or DDNS_API_KEY_FILE)
DDNS_DOMAIN your domain, such as example.com
DDNS_NAME the names to keep up to date, such as home or "home vpn" (default @)
DDNS_TYPE A, AAAA or both (default A)
DDNS_TTL seconds, 60 or more (default 300)
EOF
}
# ---------- settings ----------
CONFIG=""
LOOP=0
FORCE=0
DRY=0
QUIET=0
while [ $# -gt 0 ]; do
case "$1" in
-c) [ $# -ge 2 ] || { echo "-c needs a file" >&2; exit 2; }; CONFIG="$2"; shift ;;
--loop) LOOP=1 ;;
--force|-f) FORCE=1 ;;
--dry-run|-n) DRY=1 ;;
-q|--quiet) QUIET=1 ;;
-V|--version) echo "$VERSION"; exit 0 ;;
-h|--help) usage; exit 0 ;;
*) echo "Unknown option: $1 (see -h)" >&2; exit 2 ;;
esac
shift
done
if [ -z "$CONFIG" ] && [ -n "${DDNS_CONFIG:-}" ]; then
CONFIG="$DDNS_CONFIG"
fi
if [ -n "$CONFIG" ]; then
[ -r "$CONFIG" ] || { echo "Cannot read the config file $CONFIG" >&2; exit 2; }
# shellcheck disable=SC1090
. "$CONFIG"
elif [ -r "$DEFAULT_CONFIG" ]; then
# shellcheck disable=SC1090
. "$DEFAULT_CONFIG"
fi
eval "API_KEY=\${$KEY_VAR:-}"
if [ -z "$API_KEY" ] && [ -n "${DDNS_API_KEY_FILE:-}" ]; then
[ -r "$DDNS_API_KEY_FILE" ] || { echo "Cannot read DDNS_API_KEY_FILE" >&2; exit 2; }
API_KEY=$(tr -d ' \r\n\t' < "$DDNS_API_KEY_FILE")
fi
DOMAIN=$(printf '%s' "${DDNS_DOMAIN:-}" | tr 'A-Z' 'a-z' | sed 's/\.$//')
NAMES=$(printf '%s' "${DDNS_NAME:-@}" | tr ',' ' ')
TYPE=$(printf '%s' "${DDNS_TYPE:-A}" | tr 'a-z' 'A-Z')
TTL="${DDNS_TTL:-300}"
INTERVAL="${DDNS_INTERVAL:-300}"
FORCE_HOURS="${DDNS_FORCE_HOURS:-24}"
IP4_URLS="${DDNS_IP4_URL:-https://api.ipify.org https://ipv4.icanhazip.com}"
IP6_URLS="${DDNS_IP6_URL:-https://api6.ipify.org https://ipv6.icanhazip.com}"
DELETE_EXTRA="${DDNS_DELETE_EXTRA:-no}"
ALLOW_PRIVATE="${DDNS_ALLOW_PRIVATE:-no}"
SYSLOG="${DDNS_SYSLOG:-no}"
if [ "${DDNS_QUIET:-no}" = "yes" ]; then QUIET=1; fi
# ---------- output ----------
now() { date '+%Y-%m-%d %H:%M:%S'; }
say() {
[ "$QUIET" = 1 ] && return 0
echo "$(now) $*"
}
note() {
echo "$(now) $*"
if [ "$SYSLOG" = "yes" ] && command -v logger >/dev/null 2>&1; then logger -t "mozout-ddns" "$*"; fi
}
err() {
echo "$(now) ERROR: $*" >&2
if [ "$SYSLOG" = "yes" ] && command -v logger >/dev/null 2>&1; then logger -p user.err -t "mozout-ddns" "$*"; fi
}
# ---------- checks ----------
check_settings() {
command -v curl >/dev/null 2>&1 || { err "curl is not installed (OpenWrt: opkg install curl ca-bundle)."; return 2; }
[ -n "$API_KEY" ] || { err "No API key. Set $KEY_VAR or DDNS_API_KEY_FILE."; return 2; }
case "$API_KEY" in
sandbox_*|prod_*) ;;
*) err "The API key must start with sandbox_ or prod_."; return 2 ;;
esac
case "$DOMAIN" in
""|*[!a-z0-9.-]*|.*|*..*) err "Set DDNS_DOMAIN to your domain, such as example.com (no accents: use the xn-- form)."; return 2 ;;
esac
case "$TYPE" in
A|AAAA|BOTH) ;;
*) err "DDNS_TYPE must be A, AAAA or both."; return 2 ;;
esac
case "$TTL" in
""|*[!0-9]*) err "DDNS_TTL must be a number of seconds."; return 2 ;;
esac
if [ "$TTL" -lt 60 ] || [ "$TTL" -gt 604800 ]; then err "DDNS_TTL must be between 60 and 604800."; return 2; fi
case "$INTERVAL" in
""|*[!0-9]*) err "DDNS_INTERVAL must be a number of seconds."; return 2 ;;
esac
[ "$INTERVAL" -ge 60 ] || INTERVAL=60
case "$FORCE_HOURS" in ""|*[!0-9]*) FORCE_HOURS=24 ;; esac
for n in $NAMES; do
case "$n" in
*[!a-zA-Z0-9._@*-]*) err "Invalid name in DDNS_NAME: $n"; return 2 ;;
esac
done
return 0
}
# ---------- temporary files and state ----------
TMP=$(mktemp -d 2>/dev/null || mktemp -d -t ddns) || { echo "Cannot create a temporary folder" >&2; exit 1; }
trap 'rm -rf "$TMP"' EXIT
trap 'exit 130' INT TERM
STATE_DIR="${DDNS_STATE_DIR:-}"
if [ -z "$STATE_DIR" ]; then
if [ -w /var/lib ] || [ -d "/var/lib/mozout-ddns" ]; then
STATE_DIR="/var/lib/mozout-ddns"
else
STATE_DIR="${TMPDIR:-/tmp}/mozout-ddns-$(id -u)"
fi
fi
mkdir -p "$STATE_DIR" 2>/dev/null && chmod 700 "$STATE_DIR" 2>/dev/null
state_file() { echo "$STATE_DIR/$DOMAIN-$(echo "$1" | tr '@*' '__')-$2"; }
# Prints "fresh" when the last IP sent for this name and type is this one and is recent.
state_fresh() {
f=$(state_file "$1" "$2")
[ -r "$f" ] || return 1
read -r s_ip s_time < "$f" || return 1
[ "$s_ip" = "$3" ] || return 1
t=$(date +%s)
[ $((t - ${s_time:-0})) -lt $((FORCE_HOURS * 3600)) ]
}
state_save() { echo "$3 $(date +%s)" > "$(state_file "$1" "$2")" 2>/dev/null || true; }
# ---------- public IP ----------
is_ipv4() {
echo "$1" | awk -F. 'NF != 4 { exit 1 } { for (i = 1; i <= 4; i++) if ($i !~ /^[0-9]+$/ || $i > 255) exit 1 }'
}
is_ipv6() {
case "$1" in
*:*) case "$1" in *[!0-9a-fA-F:.]*) return 1 ;; esac; return 0 ;;
esac
return 1
}
is_private4() {
echo "$1" | awk -F. '{
if ($1 == 10 || $1 == 127 || $1 == 0) exit 0
if ($1 == 192 && $2 == 168) exit 0
if ($1 == 172 && $2 >= 16 && $2 <= 31) exit 0
if ($1 == 169 && $2 == 254) exit 0
if ($1 == 100 && $2 >= 64 && $2 <= 127) exit 0
exit 1 }'
}
# The address of a network interface, for routers whose WAN has the public IP.
iface_ip() {
command -v ip >/dev/null 2>&1 || return 1
if [ "$1" = 4 ]; then
ip -4 addr show dev "$2" 2>/dev/null | awk '/inet /{ sub(/\/.*/, "", $2); print $2; exit }'
else
ip -6 addr show dev "$2" scope global 2>/dev/null | awk '/inet6 / && !/deprecated/ && !/temporary/ { sub(/\/.*/, "", $2); print $2; exit }'
fi
}
# public_ip 4|6: fixed value, interface, or the first address service that answers.
public_ip() {
fam="$1"
if [ "$fam" = 4 ]; then fixed="${DDNS_IP4:-}"; iface="${DDNS_IFACE:-}"; urls="$IP4_URLS"; else fixed="${DDNS_IP6:-}"; iface="${DDNS_IFACE6:-${DDNS_IFACE:-}}"; urls="$IP6_URLS"; fi
ipv=""
if [ -n "$fixed" ]; then
ipv="$fixed"
elif [ -n "$iface" ]; then
ipv=$(iface_ip "$fam" "$iface")
[ -n "$ipv" ] || { err "No IPv$fam address on the interface $iface."; return 1; }
else
for u in $urls; do
ipv=$(curl -"$fam" -fsS --max-time 15 -A "$UA" "$u" 2>/dev/null | tr -d ' \r\n\t')
if [ "$fam" = 4 ] && is_ipv4 "$ipv"; then break; fi
if [ "$fam" = 6 ] && is_ipv6 "$ipv"; then break; fi
ipv=""
done
[ -n "$ipv" ] || { err "Could not find the public IPv$fam address (no answer from: $urls)."; return 1; }
fi
if [ "$fam" = 4 ]; then
is_ipv4 "$ipv" || { err "Not an IPv4 address: $ipv"; return 1; }
if [ "$ALLOW_PRIVATE" != "yes" ] && is_private4 "$ipv"; then
err "$ipv is a private address: this network is behind another router (NAT or CGNAT). Use the address service instead of DDNS_IFACE, or set DDNS_ALLOW_PRIVATE=yes."
return 1
fi
else
is_ipv6 "$ipv" || { err "Not an IPv6 address: $ipv"; return 1; }
ipv=$(echo "$ipv" | tr 'A-F' 'a-f')
fi
echo "$ipv"
}
# ---------- API ----------
HTTP_STATUS=0
uuid() {
if [ -r /proc/sys/kernel/random/uuid ]; then
cat /proc/sys/kernel/random/uuid
else
od -An -tx1 -N16 /dev/urandom | tr -d ' \n'
fi
}
# api METHOD PATH [BODY]. Answer in $TMP/body, headers in $TMP/head, status in HTTP_STATUS.
api() {
method="$1"; path="$2"; body="${3:-}"
idem=""
[ "$method" = POST ] && idem="Idempotency-Key: ddns-$(uuid)"
tries=0
while :; do
tries=$((tries + 1))
set -- -sS -X "$method" --max-time 30 --connect-timeout 15 -A "$UA" \
-H "Accept: application/json" -H "Accept-Language: en" \
-o "$TMP/body" -D "$TMP/head" -w '%{http_code}'
[ -n "$idem" ] && set -- "$@" -H "$idem"
if [ -n "$body" ]; then
printf '%s' "$body" > "$TMP/req"
set -- "$@" -H "Content-Type: application/json" --data-binary "@$TMP/req"
fi
# The key goes to curl on stdin, so it never shows in the process list.
HTTP_STATUS=$(printf 'header = "Authorization: Bearer %s"\n' "$API_KEY" | curl -K - "$@" "$API_URL$path" 2>"$TMP/curlerr")
[ -n "$HTTP_STATUS" ] || HTTP_STATUS=000
case "$HTTP_STATUS" in
429|500|502|503|000)
if [ "$tries" -lt 3 ]; then
wait_s=$(awk 'tolower($1) == "retry-after:" { gsub(/\r/, "", $2); print $2 }' "$TMP/head" 2>/dev/null | tail -n 1)
case "$wait_s" in ""|*[!0-9]*) wait_s=$((tries * 5)) ;; esac
[ "$wait_s" -gt 60 ] && wait_s=60
say "The API answered $HTTP_STATUS, trying again in $wait_s s..."
sleep "$wait_s"
continue
fi
;;
esac
return 0
done
}
simulated() { grep -qi '^x-api-simulated: *true' "$TMP/head" 2>/dev/null; }
json_str() {
awk -v k="$1" 'BEGIN { RS = "\001" } {
if (match($0, "\"" k "\"[ \t]*:[ \t]*\"[^\"]*\"")) {
s = substr($0, RSTART, RLENGTH); sub(/^"[^"]*"[ \t]*:[ \t]*"/, "", s); sub(/"$/, "", s); print s
} }' "$TMP/body"
}
# Prints one line per record with this name and type: id, value and ttl separated by tabs.
records_for() {
awk -v want_name="$1" -v want_type="$2" '
function str(s, k, v) {
if (!match(s, "\"" k "\"[ \t]*:[ \t]*\"[^\"]*\"")) return ""
v = substr(s, RSTART, RLENGTH); sub(/^"[^"]*"[ \t]*:[ \t]*"/, "", v); sub(/"$/, "", v); return v
}
function num(s, k, v) {
if (!match(s, "\"" k "\"[ \t]*:[ \t]*[0-9]+")) return ""
v = substr(s, RSTART, RLENGTH); sub(/^.*:[ \t]*/, "", v); return v
}
BEGIN { RS = "}" }
{
if (str($0, "type") == want_type && tolower(str($0, "name")) == want_name && str($0, "id") != "")
printf "%s\t%s\t%s\n", str($0, "id"), tolower(str($0, "value")), num($0, "ttl")
}' "$TMP/body"
}
api_error() {
code=$(json_str code)
msg=$(json_str message)
reason=$(json_str reason)
[ -n "$reason" ] && [ "$code" = conflict ] && code="$reason"
case "$code" in
unauthorized) hint="The API key is missing, invalid, revoked or expired." ;;
insufficient_scope) hint="The API key needs the dns:read and dns:write permissions." ;;
ip_not_allowed) hint="The API key only works from some IP addresses. A dynamic IP changes: remove the IP list of the key." ;;
not_found) hint="The domain is not on this account, is not active or does not have DNS on." ;;
account_email_domain) hint="This name receives the mail of the account email. Change it in My MozOut." ;;
cname_conflict) hint="There is a CNAME with this name. Delete it first, or choose another name." ;;
rate_limited) hint="Too many requests. Run less often." ;;
validation_failed) hint="The API did not accept the record." ;;
*) hint="" ;;
esac
if [ "$HTTP_STATUS" = 000 ]; then
err "Could not reach the API: $(head -c 200 "$TMP/curlerr" 2>/dev/null)"
else
err "$1: HTTP $HTTP_STATUS ${code:-error}${msg:+: $msg}${hint:+ $hint}"
fi
}
# ---------- key check ----------
# One GET /v1/token before touching DNS: a wrong key stops here with exit code 3,
# a key without the DNS permissions with exit code 4.
check_key() {
api GET "/v1/token"
case "$HTTP_STATUS" in
200) ;;
401) err "The API key is not valid: it was deleted, has expired or was typed wrong. Check $KEY_VAR or create a new key in My MozOut."; return 3 ;;
403) api_error "The API refused the key"; return 3 ;;
*) api_error "Checking the API key"; return 0 ;;
esac
perms=$(tr -d ' \r\n\t' < "$TMP/body" | sed -n 's/.*"permissions":\[\([^]]*\)\].*/\1/p')
missing=""
for p in dns:read dns:write; do
case "$perms" in *"\"$p\""*) ;; *) missing="${missing:+$missing, }$p" ;; esac
done
if [ -n "$missing" ]; then
err "The API key does not have the permissions DDNS needs: $missing. Add them to the key in My MozOut."
return 4
fi
[ "$(json_str mode)" = sandbox ] && say "Sandbox key: changes are simulated, the zone stays the same."
return 0
}
# ---------- update ----------
relative_name() {
n=$(echo "$1" | tr 'A-Z' 'a-z' | sed 's/\.$//')
case "$n" in
""|"@"|"$DOMAIN") echo "@" ;;
*".$DOMAIN") echo "${n%."$DOMAIN"}" ;;
*) echo "$n" ;;
esac
}
ZONE_READ=0
read_zone() {
[ "$ZONE_READ" = 1 ] && return 0
api GET "/v1/domains/$DOMAIN/dns"
if [ "$HTTP_STATUS" != 200 ]; then
api_error "Reading the zone of $DOMAIN"
return 1
fi
cp "$TMP/body" "$TMP/zone"
ZONE_READ=1
}
# update_one NAME TYPE IP
update_one() {
name="$1"; rtype="$2"; addr="$3"
fqdn="$name.$DOMAIN"; [ "$name" = "@" ] && fqdn="$DOMAIN"
if [ "$FORCE" = 0 ] && [ "$DRY" = 0 ] && state_fresh "$name" "$rtype" "$addr"; then
say "$fqdn $rtype is $addr (unchanged)."
return 0
fi
read_zone || return 1
cp "$TMP/zone" "$TMP/body"
records_for "$name" "$rtype" > "$TMP/match"
count=$(wc -l < "$TMP/match" | tr -d ' ')
data="{\"name\":\"$name\",\"type\":\"$rtype\",\"value\":\"$addr\",\"ttl\":$TTL}"
if [ "$count" = 0 ]; then
if [ -n "$(records_for "$name" CNAME)" ]; then
err "$fqdn is a CNAME, so it cannot also have an $rtype record. Delete the CNAME first, or choose another name."
return 1
fi
if [ "$DRY" = 1 ]; then note "Would create $fqdn $rtype $addr."; return 0; fi
api POST "/v1/domains/$DOMAIN/dns" "$data"
if [ "$HTTP_STATUS" != 201 ] && [ "$HTTP_STATUS" != 200 ]; then api_error "Creating $fqdn $rtype"; return 1; fi
what="Created"
else
IFS=$(printf '\t') read -r rid rvalue rttl < "$TMP/match"
if [ "$rvalue" = "$addr" ] && [ "${rttl:-$TTL}" = "$TTL" ]; then
say "$fqdn $rtype is already $addr."
[ "$DRY" = 1 ] || state_save "$name" "$rtype" "$addr"
what=""
elif [ "$DRY" = 1 ]; then
note "Would change $fqdn $rtype from $rvalue to $addr."
what=""
else
api PUT "/v1/domains/$DOMAIN/dns/$rid" "$data"
if [ "$HTTP_STATUS" != 200 ]; then api_error "Changing $fqdn $rtype"; return 1; fi
what="Changed"
fi
if [ "$count" -gt 1 ]; then
tail -n +2 "$TMP/match" | while IFS=$(printf '\t') read -r xid xvalue xttl; do
if [ "$DELETE_EXTRA" = "yes" ] && [ "$DRY" = 0 ]; then
api DELETE "/v1/domains/$DOMAIN/dns/$xid"
if [ "$HTTP_STATUS" = 200 ]; then note "Deleted the extra $fqdn $rtype $xvalue."; else api_error "Deleting $fqdn $rtype $xvalue"; fi
else
note "Warning: $fqdn has another $rtype record ($xvalue) that also answers. Delete it, or set DDNS_DELETE_EXTRA=yes."
fi
done
fi
[ -n "$what" ] || return 0
fi
if simulated; then
note "$what $fqdn $rtype $addr (simulated: Sandbox key, nothing changed in the zone)."
else
note "$what $fqdn $rtype $addr."
state_save "$name" "$rtype" "$addr"
ZONE_READ=0
fi
return 0
}
run_once() {
ZONE_READ=0
rc=0
for fam in 4 6; do
if [ "$fam" = 4 ] && [ "$TYPE" = AAAA ]; then continue; fi
if [ "$fam" = 6 ] && [ "$TYPE" = A ]; then continue; fi
rtype=A; [ "$fam" = 6 ] && rtype=AAAA
addr=$(public_ip "$fam") || { rc=1; continue; }
for n in $NAMES; do
update_one "$(relative_name "$n")" "$rtype" "$addr" || rc=1
done
done
return $rc
}
check_settings || exit $?
check_key || exit $?
if [ "$LOOP" = 1 ]; then
say "Checking every $INTERVAL s."
while :; do
run_once || true
sleep "$INTERVAL" &
wait $!
done
fi
run_once