Files
snap-dyndns-server/snap_dyndns.py
T

354 lines
12 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 HTTP service that updates INWX records.
2026-10-22 12:22:14 +02:00
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
2026-10-22 12:22:14 +02:00
import base64
import contextlib
import hashlib
import hmac
import http
import http.client
2026-10-22 12:22:14 +02:00
import http.cookiejar
import http.server
2026-10-22 12:22:14 +02:00
import ipaddress
import json
import os
import ssl
2026-10-22 12:22:14 +02:00
import struct
import sys
import threading
2026-10-22 12:22:14 +02:00
import time
import tomllib
import urllib.parse
import urllib.request
2026-10-22 14:09:43 +02:00
from typing import cast
2026-10-22 12:22:14 +02:00
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),
)
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 -------------------------------------------------------
2026-10-22 14:19:43 +02:00
def _check_auth(env, cfg, note):
"""Return the authenticated hostname or None. note() gets the reason for a refusal."""
2026-10-22 12:22:14 +02:00
header = env.get("HTTP_AUTHORIZATION", "")
if not header.lower().startswith("basic "):
2026-10-22 14:19:43 +02:00
note("badauth: missing or malformed Authorization header")
2026-10-22 12:22:14 +02:00
return None
try:
user, _, token = base64.b64decode(header[6:]).decode().partition(":")
except ValueError:
2026-10-22 14:19:43 +02:00
note("badauth: undecodable Authorization header")
2026-10-22 12:22:14 +02:00
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.
2026-10-22 14:19:43 +02:00
ok = hmac.compare_digest(given, expected)
if host is None:
note(f"badauth: unknown host {user[:64]!r}")
elif not ok:
note(f"{user.lower()}: badauth: wrong token")
else:
2026-10-22 12:22:14 +02:00
return user.lower()
return None
_STATE_LOCK = threading.Lock()
2026-10-22 12:22:14 +02:00
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)
2026-10-22 14:19:43 +02:00
def handle(env, cfg, update=inwx_update, note=None):
"""Process one request. Return (http_status, body).
note(text) receives one human-readable line per outcome for the log.
"""
note = note or (lambda text: None)
2026-10-22 12:22:14 +02:00
query = urllib.parse.parse_qs(env.get("QUERY_STRING", ""))
2026-10-22 14:19:43 +02:00
host = _check_auth(env, cfg, note)
2026-10-22 12:22:14 +02:00
if host is None:
return 401, "badauth"
requested = query.get("hostname", [host])[0].lower()
if requested != host:
2026-10-22 14:19:43 +02:00
note(
f"{host}: nohost: hostname parameter {requested[:64]!r} does not match the login"
)
2026-10-22 12:22:14 +02:00
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:
2026-10-22 14:19:43 +02:00
note(f"{host}: badip: invalid address {raw[:64]!r}")
2026-10-22 12:22:14 +02:00
return 400, "badip"
# Guards against publishing the proxy's address if client_ip_header is wrong
if not given and not ip.is_global:
2026-10-22 14:19:43 +02:00
note(
f"{host}: badip: connection address {ip} is not global, check client_ip_header"
2026-10-22 14:09:43 +02:00
)
return 400, "badip"
# shortcut: explicit myip/myipv6 are only syntax-checked (private ranges accepted), tighten if clients misbehave
2026-10-22 12:22:14 +02:00
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:
2026-10-22 12:22:14 +02:00
state = _load_state(state_path)
for rtype, ip in ips.items():
2026-10-22 14:19:43 +02:00
old_ip = state.get(host, {}).get(rtype)
if old_ip == ip:
2026-10-22 12:22:14 +02:00
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
2026-10-22 14:19:43 +02:00
note(f"{host}: nohost: {e}")
2026-10-22 12:22:14 +02:00
return 404, "nohost"
except (InwxError, OSError, ValueError) as e:
2026-10-22 14:19:43 +02:00
note(f"{host}: 911: {rtype} update to {ip} failed: {e}")
2026-10-22 12:22:14 +02:00
return 502, "911"
# shortcut: cache goes stale if the record is edited by hand at INWX, delete state.json to resync
2026-10-22 14:19:43 +02:00
note(f"{host}: good {rtype} {old_ip or 'unknown'} -> {ip}")
2026-10-22 12:22:14 +02:00
state.setdefault(host, {})[rtype] = ip
_save_state(state_path, state)
lines.append(f"good {ip}")
return 200, "\n".join(lines)
2026-10-22 13:56:15 +02:00
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>
"""
2026-10-22 14:09:43 +02:00
class Server(http.server.ThreadingHTTPServer):
config_path: str
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)
2026-10-22 13:56:15 +02:00
if url.path in ("/", "/nic", "/nic/"):
return self._reply(200, INDEX_HTML, "text/html")
2026-10-22 14:19:43 +02:00
notes = []
ip = self.client_address[0]
if url.path != "/nic/update":
2026-10-22 14:19:43 +02:00
status, body = 404, "not found"
notes.append(f"not found: {url.path[:100]!r}")
else:
try:
# Read per request, so devices can be added without restarting
with open(cast(Server, self.server).config_path, "rb") as f:
cfg = tomllib.load(f)
ip = self._client_ip(cfg) or "-"
env = {
"QUERY_STRING": url.query,
"HTTP_AUTHORIZATION": self.headers.get("Authorization", ""),
"REMOTE_ADDR": ip,
}
status, body = handle(env, cfg, note=notes.append)
except Exception as e: # noqa: BLE001 - always answer the client
notes.append(f"500: {type(e).__name__}: {e}")
status, body = 500, "911"
# One line per noteworthy request: time, device address, HTTP status, what happened.
# A plain nochg is not noteworthy, devices poll every minute.
if notes:
print(
f"{time.strftime('%Y-%m-%d %H:%M:%S')} {ip} {status} {'; '.join(notes)}",
file=sys.stderr,
)
self._reply(status, body)
2026-10-22 14:19:43 +02:00
def log_request(self, code="-", size="-"):
"""Silence the default access log, do_GET writes a more useful line."""
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]
2026-10-22 13:56:15 +02:00
def _reply(self, status, body, content_type="text/plain"):
data = (body if body.endswith("\n") else body + "\n").encode()
self.send_response(status)
2026-10-22 13:56:15 +02:00
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"):
2026-10-22 14:09:43 +02:00
server = Server((host, port), RequestHandler)
server.config_path = config_path
return server
def main(argv=None):
2026-10-22 14:09:43 +02:00
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
2026-10-22 12:22:14 +02:00
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()