Files
snap-dyndns-server/snap_dyndns.py
T

236 lines
8.1 KiB
Python
Raw Normal View History

2026-10-22 12:22:14 +02:00
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Snap DynDNS Server: dyndns2-style CGI broker that updates INWX records.
Clients authenticate with HTTP Basic Auth (user = hostname, password = token).
The INWX credentials never leave this server, and INWX is only contacted when
the IP of a hostname actually changed.
"""
import base64
import contextlib
import fcntl
import hashlib
import hmac
import http
import http.client
2026-10-22 12:22:14 +02:00
import http.cookiejar
import ipaddress
import json
import os
import ssl
2026-10-22 12:22:14 +02:00
import struct
import sys
import time
import tomllib
import urllib.parse
import urllib.request
API_LIVE = "https://api.domrobot.com/jsonrpc/"
DEFAULT_CONFIG = "~/etc/snap-dyndns/config.toml"
DEFAULT_STATE = "~/etc/snap-dyndns/state.json"
class InwxError(Exception):
"""INWX API call failed. Messages must never contain credentials."""
class NoHost(InwxError):
"""The record to update does not exist at INWX."""
# --- INWX JSON-RPC client ---------------------------------------------------
def totp(secret, now=None):
"""RFC 6238 code (HMAC-SHA1, 30 s step, 6 digits) for a base32 secret."""
key = base64.b32decode(secret.replace(" ", "").upper())
counter = int((time.time() if now is None else now) // 30)
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
offset = digest[-1] & 15
code = (struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF) % 10**6
return f"{code:06d}"
class _IPv4Https(urllib.request.HTTPSHandler):
"""HTTPS that only connects via IPv4.
The INWX API account is restricted to the server's IPv4 address, but a
confined CGI process may prefer IPv6. Binding to 0.0.0.0 makes
socket.create_connection() skip every IPv6 address.
"""
def https_open(self, req):
return self.do_open(
http.client.HTTPSConnection,
req,
context=ssl.create_default_context(),
source_address=("0.0.0.0", 0),
)
2026-10-22 12:22:14 +02:00
@contextlib.contextmanager
def inwx_session(cfg):
"""Yield call(method, params) -> resData for a logged-in INWX session."""
inwx = cfg["inwx"]
url = inwx.get("api", API_LIVE)
opener = urllib.request.build_opener(
_IPv4Https, urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())
2026-10-22 12:22:14 +02:00
)
def call(method, params):
request = urllib.request.Request(
url,
json.dumps({"method": method, "params": params}).encode(),
{"Content-Type": "application/json"},
)
with opener.open(request, timeout=20) as response:
result = json.load(response)
if result.get("code") != 1000:
raise InwxError(f"{method}: {result.get('code')} {result.get('msg')}")
return result.get("resData") or {}
login = call(
"account.login", {"user": inwx["user"], "pass": inwx["pass"], "lang": "en"}
)
try:
if str(login.get("tfa", "0")) != "0":
if not inwx.get("totp_secret"):
raise InwxError("account requires 2FA but no totp_secret is configured")
call("account.unlock", {"tan": totp(inwx["totp_secret"])})
yield call
finally:
with contextlib.suppress(Exception):
call("account.logout", {})
def find_record(call, zone, name, rtype):
"""Return the single INWX record with this name and type, else raise NoHost."""
info = call("nameserver.info", {"domain": zone, "name": name, "type": rtype})
matches = [
r
for r in info.get("record", [])
if r.get("type") == rtype and r.get("name", "").rstrip(".").lower() == name
]
if not matches:
raise NoHost(f"no {rtype} record {name} in zone {zone}")
if len(matches) > 1:
raise InwxError(f"{len(matches)} {rtype} records named {name}, expected one")
return matches[0]
def inwx_update(cfg, zone, name, rtype, ip):
"""Set the record content to ip. Return True if INWX was changed."""
with inwx_session(cfg) as call:
record = find_record(call, zone, name, rtype)
if record.get("content") == ip:
return False
call("nameserver.updateRecord", {"id": record["id"], "content": ip})
return True
# --- Request handling -------------------------------------------------------
def _check_auth(env, cfg):
"""Return the authenticated hostname or None."""
header = env.get("HTTP_AUTHORIZATION", "")
if not header.lower().startswith("basic "):
return None
try:
user, _, token = base64.b64decode(header[6:]).decode().partition(":")
except ValueError:
return None
host = cfg.get("hosts", {}).get(user.lower())
expected = (host or {}).get("token_sha256", "").lower()
given = hashlib.sha256(token.encode()).hexdigest()
# Always compare, so unknown users and wrong tokens take the same path.
if hmac.compare_digest(given, expected) and host is not None:
return user.lower()
return None
def _load_state(path):
try:
with open(path) as f:
return json.load(f)
except FileNotFoundError:
return {}
def _save_state(path, state):
tmp = f"{path}.tmp"
with open(tmp, "w") as f:
json.dump(state, f)
os.replace(tmp, path)
def handle(env, cfg, update=inwx_update):
"""Process one request. Return (http_status, body)."""
query = urllib.parse.parse_qs(env.get("QUERY_STRING", ""))
host = _check_auth(env, cfg)
if host is None:
return 401, "badauth"
requested = query.get("hostname", [host])[0].lower()
if requested != host:
return 404, "nohost"
# One IP per record type; without myip/myipv6 the connection's address is used.
given = [query[k][0] for k in ("myip", "myipv6") if query.get(k, [""])[0]]
ips = {}
for raw in given or [env.get("REMOTE_ADDR", "")]:
try:
ip = ipaddress.ip_address(raw)
except ValueError:
return 400, "badip"
# shortcut: syntax-only check (private/reserved IPs are accepted), reject them if clients misbehave
ips["A" if ip.version == 4 else "AAAA"] = str(ip)
zone = cfg["hosts"][host].get("zone") or ".".join(host.split(".")[-2:])
state_path = os.path.expanduser(cfg.get("state_file", DEFAULT_STATE))
os.makedirs(os.path.dirname(state_path), exist_ok=True)
lines = []
# shortcut: lock is held during the INWX call, fine at this load, split if updates ever get slow
with open(f"{state_path}.lock", "a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
state = _load_state(state_path)
for rtype, ip in ips.items():
if state.get(host, {}).get(rtype) == ip:
lines.append(f"nochg {ip}")
continue
try:
update(cfg, zone, host, rtype, ip)
except NoHost as e:
# shortcut: missing records are not created, add nameserver.createRecord if wanted
print(f"snap-dyndns: {host}: {e}", file=sys.stderr)
return 404, "nohost"
except (InwxError, OSError, ValueError) as e:
print(f"snap-dyndns: {host}: {e}", file=sys.stderr)
return 502, "911"
# shortcut: cache goes stale if the record is edited by hand at INWX, delete state.json to resync
state.setdefault(host, {})[rtype] = ip
_save_state(state_path, state)
lines.append(f"good {ip}")
return 200, "\n".join(lines)
def main(env=os.environ, out=sys.stdout):
"""CGI entry point."""
try:
path = os.path.expanduser(env.get("SNAP_DYNDNS_CONFIG", DEFAULT_CONFIG))
with open(path, "rb") as f:
cfg = tomllib.load(f)
status, body = handle(env, cfg)
except Exception as e: # noqa: BLE001 - a CGI must always answer
print(f"snap-dyndns: {type(e).__name__}: {e}", file=sys.stderr)
status, body = 500, "911"
headers = [
f"Status: {status} {http.HTTPStatus(status).phrase}",
"Content-Type: text/plain; charset=utf-8",
"Cache-Control: no-store",
]
if status == 401:
headers.append('WWW-Authenticate: Basic realm="Snap DynDNS"')
out.write("\n".join(headers) + "\n\n" + body + "\n")