Files
snap-dyndns-server/snap_dyndns.py
T
2026-10-22 13:56:15 +02:00

307 lines
11 KiB
Python

# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Snap DynDNS Server: dyndns2-style HTTP service 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 argparse
import base64
import contextlib
import hashlib
import hmac
import http
import http.client
import http.cookiejar
import http.server
import ipaddress
import json
import os
import ssl
import struct
import sys
import threading
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 the
process may prefer IPv6 for dual-stack hosts. 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),
)
@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())
)
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
_STATE_LOCK = threading.Lock()
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"
# Guards against publishing the proxy's address if client_ip_header is wrong
if not given and not ip.is_global:
print(f"snap-dyndns: {host}: connection address {ip} is not global, check client_ip_header", file=sys.stderr)
return 400, "badip"
# shortcut: explicit myip/myipv6 are only syntax-checked (private ranges accepted), tighten 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: one lock held during the INWX call, fine at this load, split per host if updates get slow
with _STATE_LOCK:
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)
INDEX_HTML = """<!DOCTYPE html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<title>Snap DynDNS Server</title>
</head>
<body>
<h1>Snap DynDNS Server</h1>
<p>This is a Dynamic DNS service. It is running with the <a href="https://src.mehl.mx/mxmehl/snap-dyndns-server">Snap DynDNS Server</a> software.</p>
<p>Please contact the site owner for more information on this specific service.</p>
</body>
</html>
"""
class RequestHandler(http.server.BaseHTTPRequestHandler):
timeout = 30 # do not let stalled connections hold a thread forever
def do_GET(self):
url = urllib.parse.urlsplit(self.path)
if url.path in ("/", "/nic", "/nic/"):
return self._reply(200, INDEX_HTML, "text/html")
if url.path != "/nic/update":
return self._reply(404, "not found")
try:
# Read per request, so devices can be added without restarting
with open(self.server.config_path, "rb") as f:
cfg = tomllib.load(f)
env = {
"QUERY_STRING": url.query,
"HTTP_AUTHORIZATION": self.headers.get("Authorization", ""),
"REMOTE_ADDR": self._client_ip(cfg),
}
status, body = handle(env, cfg)
except Exception as e: # noqa: BLE001 - always answer the client
print(f"snap-dyndns: {type(e).__name__}: {e}", file=sys.stderr)
status, body = 500, "911"
self._reply(status, body)
def _client_ip(self, cfg):
"""Address of the device: last entry of client_ip_header (added by our proxy), else the peer."""
name = cfg.get("client_ip_header")
if name:
return self.headers.get(name, "").split(",")[-1].strip()
return self.client_address[0]
def _reply(self, status, body, content_type="text/plain"):
data = (body if body.endswith("\n") else body + "\n").encode()
self.send_response(status)
self.send_header("Content-Type", f"{content_type}; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.send_header("Cache-Control", "no-store")
if status == 401:
self.send_header("WWW-Authenticate", 'Basic realm="Snap DynDNS"')
self.end_headers()
self.wfile.write(data)
def make_server(config_path, port, host="0.0.0.0"):
server = http.server.ThreadingHTTPServer((host, port), RequestHandler)
server.config_path = config_path
return server
def main(argv=None):
parser = argparse.ArgumentParser(description="Snap DynDNS Server (serves /nic/update)")
parser.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})")
parser.add_argument("-p", "--port", type=int, default=8080, help="port to listen on (default: 8080)")
args = parser.parse_args(argv)
path = os.path.expanduser(args.config)
try: # fail fast on a broken config; it is re-read on every request later
with open(path, "rb") as f:
tomllib.load(f)
except (OSError, tomllib.TOMLDecodeError) as e:
sys.exit(f"snap-dyndns: cannot use config {path}: {e}")
make_server(path, args.port).serve_forever()
if __name__ == "__main__":
main()