From e8408adfc7354b3e5b7cc4c94a4ef5a6a860ee7c Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 12:22:14 +0200 Subject: [PATCH 01/10] feat: complete rewrite of server component --- .gitignore | 10 +- .htaccess | 24 ++-- README.md | 144 ++++++++++++++------- config.cfg.sample | 11 -- config.toml.sample | 24 ++++ index.html | 12 -- screen-inwx-id.png | Bin 60473 -> 0 bytes snap_dyndns.py | 217 +++++++++++++++++++++++++++++++ test_snap_dyndns.py | 305 ++++++++++++++++++++++++++++++++++++++++++++ update.api | 49 ------- update.cgi | 10 ++ update.php | 108 ---------------- update.sh | 80 ------------ users.db.sample | 3 - 14 files changed, 673 insertions(+), 324 deletions(-) delete mode 100644 config.cfg.sample create mode 100644 config.toml.sample delete mode 100644 index.html delete mode 100644 screen-inwx-id.png create mode 100644 snap_dyndns.py create mode 100644 test_snap_dyndns.py delete mode 100644 update.api create mode 100755 update.cgi delete mode 100644 update.php delete mode 100755 update.sh delete mode 100644 users.db.sample diff --git a/.gitignore b/.gitignore index df77f16..f2d793f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ -debug.log -update.log -users.db -config.cfg +__pycache__/ +config.toml +state.json +state.json.lock +state.json.tmp +.env diff --git a/.htaccess b/.htaccess index 0b89b59..a8e6eea 100644 --- a/.htaccess +++ b/.htaccess @@ -1,15 +1,15 @@ -# Only allow web access to update.php and index.html - - Order Deny,Allow - Deny from all - +# SPDX-FileCopyrightText: 2016 Max Mehl +# SPDX-License-Identifier: AGPL-3.0-or-later - - Order Allow,Deny - Allow from all - +# Run update.cgi as CGI and hand the Authorization header to it +Options +ExecCGI +AddHandler cgi-script .cgi +CGIPassAuth On - - Order Allow,Deny - Allow from all +# Optional: config location if it is not ~/etc/snap-dyndns/config.toml +# SetEnv SNAP_DYNDNS_CONFIG /home/USER/etc/snap-dyndns/config.toml + +# Only update.cgi may be requested, nothing else of this repository + + Require all denied diff --git a/README.md b/README.md index 24da01f..68aca6a 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,125 @@ # Snap DynDNS Server using INWX domains -**Snap DynDNS Server** enables you to set up your own simple Dynamic DNS service. It requires you to use domains managed by the registrar InterNetworX (inwx.de) and their API. This server may be simply customised to be able to work with other domain sellers and their specific APIs. +**Snap DynDNS Server** is a tiny Dynamic DNS service for domains managed by the registrar InterNetworX (inwx.de). It is a single Python CGI script without dependencies beyond the standard library, made for shared hosting such as Uberspace. -It can set the IP of any existing domain entry, may it be IPv4 or IPv6 (and theoretically all kinds INWX supports). All domains of the clients have to be part of the same INWX account. +The server is a credential broker: your INWX API login only exists on the server, while each device gets its own random token that can update exactly one hostname. A device that gets lost or compromised can be cut off by deleting one section from the config. -The idea of the service is to enable compatibility with as many client devices as possible. So clients only would need to send a GET or POST request to your service which contains their individual user data (which you can create freely) and their desired IP address for their domain. +It speaks the common dyndns2 protocol (HTTP Basic Auth, `myip`/`myipv6`, `good`/`nochg` answers), so routers like the AVM FritzBox, ddclient, and plain `curl` work. The matching client is [Snap DynDNS client](https://src.mehl.mx/mxmehl/snap-dyndns-client), a small shell script for cron. -This server has a client application as counterpart, named [Snap DynDNS client](https://src.mehl.mx/mxmehl/snap-dyndns-client). Using the latter, you will be able to retrieve the IP of your computer and send it to this service which in return updates the domain for you. +## How it works + +1. A device sends `GET /update.cgi` with its hostname and token as Basic Auth. Without `myip`/`myipv6`, the server uses the IP the request came from. +2. The server compares the SHA-256 of the token with the config. +3. If the IP equals the last one it stored, it answers `nochg` right away. INWX is not contacted, so polling every minute is cheap. +4. Otherwise it logs in to INWX, looks up the record by name and type, updates it, and only then stores the new IP. If INWX fails, the device gets `911` and retries on its next run. + +The record (A and/or AAAA) has to exist at INWX already. The server picks A or AAAA depending on the IP family, and keeps the TTL you set there. ## Requirements -The installation requires the possibility to execute PHP and Bash files. It also requires curl to be installed. There's no need for a database to be installed as everything is handled by flat text files. +- Apache with CGI and `.htaccess` support (Uberspace 7 has both) +- Python 3.11 or newer, no packages needed +- An INWX account or API sub-account. If 2FA is enabled, the TOTP shared secret is needed as well. IP-restricted API accounts work if the server's IP is allowed. -The code has been tested with PHP 5.5, CentOS 7, and Apache 2.2.15. Please be aware to migrate the `.htaccess` file if you use other webservers so the sensitive files like `config.cfg` and `users.db` are safe. +## Installation on Uberspace -## Installation +Clone the repository into a web-accessible directory, e.g. the document root of a dedicated (sub)domain: -Clone the git repository to your server and move them to a public web-accessible folder of your choice. Now rename/copy the files `config.cfg.sample` and `users.db.sample` to `config.cfg` and `users.db` respectively. Open them in an editor and modify the settings so they match your data. +``` +git clone https://src.mehl.mx/mxmehl/snap-dyndns-server /var/www/virtual/myuser/dyndns.mydomain.net +``` -### config.cfg +The `.htaccess` in the repository enables CGI, passes the `Authorization` header to the script, and denies access to every file except `update.cgi`. If your Python is not at `/usr/bin/python3.14`, adjust the shebang of `update.cgi`. -In this file you have to put your inwx.de username and password. It is needed to login to the API and update the IP of your domain entry. +Create the config **outside** the web root and make it private: -### users.db +``` +mkdir -p ~/etc/snap-dyndns +cp /var/www/virtual/myuser/dyndns.mydomain.net/config.toml.sample ~/etc/snap-dyndns/config.toml +chmod 600 ~/etc/snap-dyndns/config.toml +``` -In this file you can create users which can use your service. Unauthorized requests which do not match any of the content here will not work. Each line matches one existing single domain entry in your INWX account. It is not necessary the DynDNS domain names to be part of the same domain (`example.com`), they can also be different ones – they just have to be part of the same INWX account (please tell me if you need this to be improved, it shouldn't be a big deal). +If you prefer another location, uncomment `SetEnv SNAP_DYNDNS_CONFIG` in `.htaccess`. The state file with the last known IPs is written next to the config (`state_file` in the config). -#### Gather INWX domain ID +### Adding a device -Given you own the domain example.com which you can administrate in your INWX account. For each client, you can create a subdomain, in this example `user1.example.com` and `user2.example.com`. For INWX, each domain has a unique ID. To find out this ID, you will have to use a tool like Firebug or the in-built web inspector tools by Firefox or Chromium. Use the *inspect element* feature, hover over the subdomain line in your nameserver/DNS settings (where you can define the IPs, currently on `https://www.inwx.de/de/nameserver2`), and in the id attribute of the `
`-element you should find a string with around 9 numbers. This number is the domain entry's ID. Please see the screenshot for how it should look like. +Generate a token and its hash: -![That's how you get the ID of your single domain](screen-inwx-id.png) +``` +python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())' +``` -Back in `users.db`, type in the domain name (`user1.example.com`) and its INWX ID. For username and password, you can freely create one and give to your users. Each request to your service requires the correct domain name, a username and a password. Only if all three match, the IP change request will be executed. +Put the hash into a new section of `config.toml` and give the token to the device: + +```toml +[hosts."user1.example.com"] +token_sha256 = "" +``` + +The hostname is the Basic Auth user name, the token the password. The INWX zone is guessed as the last two labels of the hostname. For zones such as `example.co.uk` set `zone = "example.co.uk"` in that section. ## Usage -Please feel free to use [Snap DynDNS client](https://src.mehl.mx/mxmehl/snap-dyndns-client) which is the perfect combination for this server application. - -Please note: You cannot define whether it shall be an A, AAAA or whatever record. You would have to do that in the INWX webpanel once, the ID should stay the same. - -### curl - -You can use curl with a POST request: - - curl -X POST -d "domain=user1.example.com&user=myuser&pass=mypassword&ip=1.2.3.4" "https://yourdyndnsservice.net/update.php" - -You can also use GET requests which is **not** recommended. The advantage of POST requests is that the request is encrypted via SSL if you use a HTTPS domain. GET requests can be intercepted quite easily which is bad because you send sensitive data. A GET request would look like this - - curl -d "domain=user1.example.com&user=myuser&pass=mypassword&ip=1.2.3.4" "https://yourdyndnsservice.net/update.php" - -This will send following data to your **Snap DynDNS server** which is running under the domain `https://yourdyndnsservice.net` in this example: - -* `domain=user1.example.com`: This is the client's personal DynDNS domain -* `user=myuser`: This is the client's username which you can define freely -* `pass=mypassword`: This is the client's personal password which you can define freely. -* `ip=1.2.3.4`: This is the IP which shall be set to this single domain - -## AVM FritzBox - -In the AVM Fritz!Boxes you can choose a custom DynDNS provider. In order to connect it with your Snap DynDNS server, use following data: +With curl (the `-u` option keeps the credentials out of the URL): ``` -Update-URL: yourdyndnsservice.net/update.php?domain=&user=&pass=&ip= -Domainname: user1.example.com -Username: myuser -Password: mypassword +curl -fsS -u user1.example.com:TOKEN "https://dyndns.mydomain.net/update.cgi" +curl -fsS -u user1.example.com:TOKEN "https://dyndns.mydomain.net/update.cgi?myip=1.2.3.4" ``` -Be sure to not add an URI scheme like `https://`, the device will throw an error. The IP address is set automatically by the device. Note that you can also set your IPv6 address by using `` in the URL. +Parameters, all optional: + +- `hostname`: must equal the Basic Auth user name +- `myip`: IPv4 or IPv6 address to set, defaults to the address of the request +- `myipv6`: IPv6 address, to update A and AAAA in one request + +Answers (HTTP status in brackets): + +- `good ` (200): the record was updated +- `nochg ` (200): the IP is what the server stored last, INWX was not contacted +- `badauth` (401): unknown hostname or wrong token +- `nohost` (404): hostname mismatch, or the record does not exist at INWX +- `badip` (400): the IP could not be parsed +- `911` (502 or 500): INWX or the server config failed, see the Apache error log + +### AVM FritzBox + +Choose a custom DynDNS provider: + +``` +Update-URL: https://dyndns.mydomain.net/update.cgi?hostname=&myip=&myipv6= +Domain name: user1.example.com +User name: user1.example.com +Password: TOKEN +``` + +### ddclient + +``` +protocol=dyndns2 +server=dyndns.mydomain.net +script=/dyn/update.cgi +ssl=yes +login=user1.example.com +password=TOKEN +user1.example.com +``` + +## Known limits + +- The IP is only checked for syntax, private and reserved addresses are accepted. +- Missing records are not created, add them at INWX first. +- If you change a record at INWX by hand, the server does not notice. Delete `state.json` or change the IP to resync. +- Only one request updates at a time (a file lock is held during the INWX call), which is plenty for a personal setup. + +## Development + +``` +uv run --python 3.14 python -m unittest -v +``` + +The tests use a fake INWX server. An additional smoke test runs against the INWX OT&E test system and is skipped unless `INWX_OTE_USER`, `INWX_OTE_PASS` and `INWX_OTE_HOST` (an existing A record in that account) are set in the environment. It restores the record afterwards. + +## License + +AGPL-3.0-or-later, see `LICENSE`. diff --git a/config.cfg.sample b/config.cfg.sample deleted file mode 100644 index e6853f2..0000000 --- a/config.cfg.sample +++ /dev/null @@ -1,11 +0,0 @@ -# INWX USERNAME -USERNAME=myusername - -# INWX PASSWORD -PASSWORD=mypassword - -# API-Host -APIHOST=https://api.domrobot.com/xmlrpc/ - -# Activate debugging? Use true or false -DEBUG=false diff --git a/config.toml.sample b/config.toml.sample new file mode 100644 index 0000000..d83840e --- /dev/null +++ b/config.toml.sample @@ -0,0 +1,24 @@ +# Copy to ~/etc/snap-dyndns/config.toml (outside the web root) and chmod 600. + +# Where the last known IPs are cached (default shown) +state_file = "~/etc/snap-dyndns/state.json" + +[inwx] +user = "api-user" +pass = "api-password" +# Only needed if the INWX account has 2FA enabled (base32 secret of the authenticator) +# totp_secret = "JBSWY3DPEHPK3PXP" +# Default is the live API. Use the OT&E test system for experiments: +# api = "https://api.ote.domrobot.com/jsonrpc/" + +# One section per hostname. The hostname is the Basic Auth user, the token the password. +# The record (A and/or AAAA) must already exist at INWX. +# Generate a token and its hash with: +# python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())' +[hosts."user1.example.com"] +token_sha256 = "replace-with-sha256-hex-of-the-token" +# INWX zone, defaults to the last two labels of the hostname +# zone = "example.co.uk" + +[hosts."user2.example.com"] +token_sha256 = "replace-with-another-hash" diff --git a/index.html b/index.html deleted file mode 100644 index b081b84..0000000 --- a/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - Snap DynDNS Server - - -

Snap DynDNS Server

-

This is a Dynamic DNS service. It is running with the Snap DynDNS Server software.

-

Please contact the site owner for more information on this specific service.

- - diff --git a/screen-inwx-id.png b/screen-inwx-id.png deleted file mode 100644 index 338d9b32f434f092a75e0733647ae13417119fc0..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 60473 zcmce-Wl)@3*EUE(2*C*i50D((-7QFPm&V=Q-GV2&wFfb?*;v$MLFtGYCFfX{?yatcp$x?=a zzg{^CNhrSo|9QPJ`U-wVclxa6q-1O2G* z$<^)M)NR|zQT%zs4wm=_bRiT%kr(xu$4YNsV8waRv5pm~mHb1E=)$0*ATlZSR!~9Y zGh7adjE9U6Wv-CNh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x<56?uIasU7T diff --git a/snap_dyndns.py b/snap_dyndns.py new file mode 100644 index 0000000..ecab47c --- /dev/null +++ b/snap_dyndns.py @@ -0,0 +1,217 @@ +# SPDX-FileCopyrightText: 2016 Max Mehl +# 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.cookiejar +import ipaddress +import json +import os +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}" + + +@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( + 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 + + +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") diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py new file mode 100644 index 0000000..8e9dfac --- /dev/null +++ b/test_snap_dyndns.py @@ -0,0 +1,305 @@ +# SPDX-FileCopyrightText: 2016 Max Mehl +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Run with: uv run --python 3.14 python -m unittest -v + +The OT&E smoke test is skipped unless INWX_OTE_USER, INWX_OTE_PASS and +INWX_OTE_HOST (an existing A record there) are set in the environment. +""" + +import base64 +import hashlib +import io +import json +import os +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import snap_dyndns as sd + +TOKEN = "s3cret" +HOST = "home.example.com" + + +def basic(user, token): + return "Basic " + base64.b64encode(f"{user}:{token}".encode()).decode() + + +def make_cfg(tmp, **inwx): + return { + "state_file": os.path.join(tmp, "state.json"), + "inwx": {"user": "u", "pass": "p", **inwx}, + "hosts": {HOST: {"token_sha256": hashlib.sha256(TOKEN.encode()).hexdigest()}}, + } + + +def make_env(query=f"hostname={HOST}", remote="1.2.3.4", auth=None): + return { + "QUERY_STRING": query, + "REMOTE_ADDR": remote, + "HTTP_AUTHORIZATION": auth or basic(HOST, TOKEN), + } + + +class TotpTest(unittest.TestCase): + def test_rfc6238_vector(self): + secret = base64.b32encode(b"12345678901234567890").decode() + self.assertEqual(sd.totp(secret, now=59), "287082") + + +class HandleTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.cfg = make_cfg(tmp.name) + self.calls = [] + self.fail = None + + def update(self, cfg, zone, name, rtype, ip): + self.calls.append((zone, name, rtype, ip)) + if self.fail: + raise self.fail + return True + + def run_handle(self, **kw): + return sd.handle(make_env(**kw), self.cfg, self.update) + + def test_first_update_then_nochg(self): + self.assertEqual(self.run_handle(), (200, "good 1.2.3.4")) + self.assertEqual(self.run_handle(), (200, "nochg 1.2.3.4")) + self.assertEqual(self.calls, [("example.com", HOST, "A", "1.2.3.4")]) + + def test_ip_change_updates_again(self): + self.run_handle() + self.assertEqual(self.run_handle(remote="5.6.7.8"), (200, "good 5.6.7.8")) + self.assertEqual(len(self.calls), 2) + + def test_ipv6_connection_updates_aaaa(self): + self.assertEqual(self.run_handle(remote="2001:db8::1"), (200, "good 2001:db8::1")) + self.assertEqual(self.calls[0][2], "AAAA") + + def test_myip_overrides_remote_addr(self): + self.run_handle(query=f"hostname={HOST}&myip=9.9.9.9") + self.assertEqual(self.calls[0][3], "9.9.9.9") + + def test_dual_stack(self): + status, body = self.run_handle(query=f"hostname={HOST}&myip=9.9.9.9&myipv6=2001:db8::2") + self.assertEqual((status, body), (200, "good 9.9.9.9\ngood 2001:db8::2")) + self.assertEqual([c[2] for c in self.calls], ["A", "AAAA"]) + + def test_hostname_param_optional(self): + self.assertEqual(self.run_handle(query="")[0], 200) + + def test_zone_override(self): + self.cfg["hosts"][HOST]["zone"] = "example.co.uk" + self.run_handle() + self.assertEqual(self.calls[0][0], "example.co.uk") + + def test_bad_credentials(self): + for auth in (basic(HOST, "wrong"), basic("other.example.com", TOKEN), "Basic !!!", "Bearer x"): + self.assertEqual(self.run_handle(auth=auth), (401, "badauth"), auth) + self.assertEqual(self.calls, []) + + def test_missing_auth(self): + env = make_env() + del env["HTTP_AUTHORIZATION"] + self.assertEqual(sd.handle(env, self.cfg, self.update), (401, "badauth")) + + def test_hostname_mismatch(self): + self.assertEqual(self.run_handle(query="hostname=other.example.com"), (404, "nohost")) + + def test_invalid_ip(self): + self.assertEqual(self.run_handle(query=f"hostname={HOST}&myip=1.2.3.4;rm"), (400, "badip")) + self.assertEqual(self.calls, []) + + def test_missing_record(self): + self.fail = sd.NoHost("gone") + self.assertEqual(self.run_handle(), (404, "nohost")) + + def test_inwx_failure_keeps_state_and_retries(self): + self.fail = sd.InwxError("boom") + self.assertEqual(self.run_handle(), (502, "911")) + self.fail = None + self.assertEqual(self.run_handle(), (200, "good 1.2.3.4")) + self.assertEqual(len(self.calls), 2) + + +class FakeInwx(ThreadingHTTPServer): + """Minimal INWX JSON-RPC stand-in with cookie session and optional 2FA.""" + + def __init__(self, tfa_secret=None): + super().__init__(("127.0.0.1", 0), FakeInwxHandler) + self.tfa_secret = tfa_secret + self.unlocked = False + self.calls = [] + self.records = [ + {"id": 1, "name": HOST, "type": "A", "content": "10.0.0.1"}, + {"id": 2, "name": "other.example.com", "type": "A", "content": "10.0.0.2"}, + ] + self.url = f"http://127.0.0.1:{self.server_port}/jsonrpc/" + threading.Thread(target=self.serve_forever, daemon=True).start() + + +class FakeInwxHandler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_POST(self): + srv = self.server + req = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + method, p = req["method"], req["params"] + srv.calls.append(method) + cookie, code, res = None, 1000, {} + if method == "account.login": + if (p["user"], p["pass"]) != ("u", "p"): + code = 2200 + cookie = "sid=abc; Path=/" + srv.unlocked = srv.tfa_secret is None + res = {"tfa": "GOOGLE-AUTH" if srv.tfa_secret else "0"} + elif "sid=abc" not in self.headers.get("Cookie", ""): + code = 2002 + elif method == "account.unlock": + valid = {sd.totp(srv.tfa_secret, now=__import__("time").time() + d) for d in (-30, 0, 30)} + srv.unlocked = p["tan"] in valid + code = 1000 if srv.unlocked else 2200 + elif not srv.unlocked: + code = 2200 + elif method == "nameserver.info": + res = {"record": [r for r in srv.records if r["name"] == p["name"] and r["type"] == p["type"]]} + elif method == "nameserver.updateRecord": + for r in srv.records: + if r["id"] == p["id"]: + r["content"] = p["content"] + body = json.dumps({"code": code, "msg": "x", "resData": res}).encode() + self.send_response(200) + if cookie: + self.send_header("Set-Cookie", cookie) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +class InwxClientTest(unittest.TestCase): + def start(self, **kw): + srv = FakeInwx(**kw) + self.addCleanup(srv.server_close) + self.addCleanup(srv.shutdown) + return srv + + def cfg(self, srv, **inwx): + return {"inwx": {"user": "u", "pass": "p", "api": srv.url, **inwx}} + + def test_update_changes_record(self): + srv = self.start() + self.assertTrue(sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "1.2.3.4")) + self.assertEqual(srv.records[0]["content"], "1.2.3.4") + self.assertEqual(srv.calls[-1], "account.logout") + + def test_same_content_skips_update(self): + srv = self.start() + self.assertFalse(sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "10.0.0.1")) + self.assertNotIn("nameserver.updateRecord", srv.calls) + + def test_two_factor(self): + secret = base64.b32encode(b"12345678901234567890").decode() + srv = self.start(tfa_secret=secret) + self.assertTrue( + sd.inwx_update(self.cfg(srv, totp_secret=secret), "example.com", HOST, "A", "1.2.3.4") + ) + self.assertIn("account.unlock", srv.calls) + + def test_two_factor_without_secret(self): + srv = self.start(tfa_secret="GEZDGNBVGY3TQOJQ") + with self.assertRaises(sd.InwxError): + sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "1.2.3.4") + self.assertEqual(srv.calls[-1], "account.logout") + + def test_missing_record(self): + srv = self.start() + with self.assertRaises(sd.NoHost): + sd.inwx_update(self.cfg(srv), "example.com", HOST, "AAAA", "2001:db8::1") + + def test_api_error_hides_password(self): + srv = self.start() + cfg = self.cfg(srv) + cfg["inwx"]["pass"] = "wrong-password" + with self.assertRaises(sd.InwxError) as ctx: + sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4") + self.assertNotIn("wrong-password", str(ctx.exception)) + + def test_end_to_end_only_changes_reach_inwx(self): + srv = self.start() + with tempfile.TemporaryDirectory() as tmp: + cfg = make_cfg(tmp, api=srv.url) + for _ in range(3): + sd.handle(make_env(), cfg) + self.assertEqual(srv.calls.count("nameserver.updateRecord"), 1) + self.assertEqual(srv.calls.count("account.login"), 1) + + +class MainTest(unittest.TestCase): + def run_main(self, env, cfg_text): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "config.toml") + with open(path, "w") as f: + f.write(cfg_text.replace("STATE", os.path.join(tmp, "state.json"))) + out = io.StringIO() + sd.main({**env, "SNAP_DYNDNS_CONFIG": path}, out) + return out.getvalue() + + CFG = f""" +state_file = "STATE" +[inwx] +user = "u" +pass = "p" +api = "http://127.0.0.1:1/" +[hosts."{HOST}"] +token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" +""" + + def test_unauthorized_has_challenge(self): + out = self.run_main(make_env(auth=basic(HOST, "bad")), self.CFG) + head, _, body = out.partition("\n\n") + self.assertTrue(head.startswith("Status: 401 Unauthorized")) + self.assertIn('WWW-Authenticate: Basic realm="Snap DynDNS"', head) + self.assertEqual(body, "badauth\n") + + def test_unreachable_inwx_is_911(self): + out = self.run_main(make_env(), self.CFG) + self.assertTrue(out.startswith("Status: 502 Bad Gateway\n")) + self.assertTrue(out.endswith("\n\n911\n")) + + def test_broken_config_is_500(self): + out = self.run_main(make_env(), "not = [valid") + self.assertTrue(out.startswith("Status: 500 Internal Server Error\n")) + + +@unittest.skipUnless( + all(os.environ.get(k) for k in ("INWX_OTE_USER", "INWX_OTE_PASS", "INWX_OTE_HOST")), + "set INWX_OTE_USER, INWX_OTE_PASS, INWX_OTE_HOST to run against the INWX OT&E system", +) +class OteSmokeTest(unittest.TestCase): + def test_lookup_by_name_and_update(self): + host = os.environ["INWX_OTE_HOST"].lower() + zone = os.environ.get("INWX_OTE_ZONE") or ".".join(host.split(".")[-2:]) + cfg = { + "inwx": { + "user": os.environ["INWX_OTE_USER"], + "pass": os.environ["INWX_OTE_PASS"], + "api": "https://api.ote.domrobot.com/jsonrpc/", + } + } + with sd.inwx_session(cfg) as call: + original = sd.find_record(call, zone, host, "A")["content"] + test_ip = "192.0.2.1" if original != "192.0.2.1" else "192.0.2.2" + try: + self.assertTrue(sd.inwx_update(cfg, zone, host, "A", test_ip)) + with sd.inwx_session(cfg) as call: + self.assertEqual(sd.find_record(call, zone, host, "A")["content"], test_ip) + finally: + sd.inwx_update(cfg, zone, host, "A", original) + + +if __name__ == "__main__": + unittest.main() diff --git a/update.api b/update.api deleted file mode 100644 index 6ef226a..0000000 --- a/update.api +++ /dev/null @@ -1,49 +0,0 @@ - - - nameserver.updateRecord - - - - - - user - - %USER% - - - - lang - - en - - - - pass - - %PASSWD% - - - - id - - %DNSID% - - - - content - - %NEWIP% - - - - ttl - - 3600 - - - - - - - - diff --git a/update.cgi b/update.cgi new file mode 100755 index 0000000..2e30de7 --- /dev/null +++ b/update.cgi @@ -0,0 +1,10 @@ +#!/usr/bin/python3.14 +# SPDX-FileCopyrightText: 2016 Max Mehl +# SPDX-License-Identifier: AGPL-3.0-or-later +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) +from snap_dyndns import main + +main() diff --git a/update.php b/update.php deleted file mode 100644 index 7a83d7d..0000000 --- a/update.php +++ /dev/null @@ -1,108 +0,0 @@ - -************************************************************************ -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU Affero General Public License as -* published by the Free Software Foundation, either version 3 of the -* License, or (at your option) any later version. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU Affero General Public License for more details. -* -* You should have received a copy of the GNU Affero General Public -* License along with this program. If not, see -* . -* -************************************************************************ -* -* This file receives the requests, sanitises them, forwards the input -* to update.sh and prints the results. It is also responsible for -* debug logs. -* -***********************************************************************/ -?> -$output"; -} - - -// DEBUGGING -if($debug === true) { -$date = date("Y-m-d H:i:s"); -$browser = $_SERVER['HTTP_USER_AGENT']; -$postdata = print_r($_POST, TRUE); -$getdata = print_r($_GET, TRUE); - -$debug = -// basic info -'$date: ' . $date . '
' . -'$browser: ' . $browser . '
' . -'$debug: ' . $debug . '
' . -'$method: ' . $method . '
' . -// Specific set variables -'$domain: ' . $domain . '
' . -'$ip: ' . $ip . '
' . -'$user: ' . $user . '
' . -'$pass: ' . $pass . '
' . -// all POST and GET -'$postdata: ' . $postdata . '
' . -'$getdata: ' . $getdata . '
' -; - -echo "

Debug information:

"; -print_r($debug); // Show debug in browser - -$debug_log = str_replace('
', "\r\n", $debug); // - -file_put_contents('debug.log', $debug_log, FILE_APPEND | LOCK_EX); -} - -?> diff --git a/update.sh b/update.sh deleted file mode 100755 index dacdd55..0000000 --- a/update.sh +++ /dev/null @@ -1,80 +0,0 @@ -#!/bin/bash -######################################################################## -# Copyright (C) 2016 Max Mehl -######################################################################## -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Affero General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Affero General Public License for more details. -# -# You should have received a copy of the GNU Affero General Public -# License along with this program. If not, see -# . -# -######################################################################## -# -# This file uses the data forwarded by update.php, validates the given -# login data in the user database, and does the API call to the INWX -# API. -# -######################################################################## - - -cd "$(dirname "$(readlink -f "$0")")" - -# Test if config.cfg exists and set needed variables -if [ ! -e config.cfg ]; then echo "Missing config.cfg file. Edit and rename config.cfg.sample"; exit 1; fi -source config.cfg - -# Check dependencies -deperrors='' -for depend in curl; do - if ! command -v "$depend" >/dev/null 2>&1; then - deperrors="$depend $deperrors" - fi -done -if [ -n "$deperrors" ]; then - cat <<-EOF - This program depends on some other programs to function. - Not all of those programs could be located on your system. - Please use your package manager to install the following programs: - EOF - echo "$deperrors" - exit 1 -fi - -USERDB=users.db - -DOMAIN="$1" -NEWIP="$2" -U_USER="$3" -U_PASS="$4" - -E=$(grep "^$DOMAIN;" $USERDB) - -if [ "$E" != "" ]; then - DNSID=$(echo $E | cut -d";" -f2) - E_USER=$(echo $E | cut -d";" -f3) - E_PASS=$(echo $E | cut -d";" -f4) - - # Check if user as given correct user and password - if [ "$U_USER" == "$E_USER" ] && [ "$U_PASS" == "$E_PASS" ]; then - DATA=$(cat update.api | sed "s/%PASSWD%/$PASSWORD/g;s/%USER%/$USERNAME/g;s/%DNSID%/$DNSID/g;s/%NEWIP%/$NEWIP/g") - curl -X POST -d "$DATA" "$APIHOST" --header "Content-Type:text/xml" --insecure > update.log - echo "" >> update.log - echo "Updated IP address for $DNSID ($DOMAIN) to $NEWIP." >> update.log - echo "Success: Updated $DOMAIN to $NEWIP." - else - echo "Wrong user or password." - fi -else - echo "Domain does not exist in database" -fi - - diff --git a/users.db.sample b/users.db.sample deleted file mode 100644 index a47fe0e..0000000 --- a/users.db.sample +++ /dev/null @@ -1,3 +0,0 @@ -# DOMAIN; DOMAIN-ID; USER; PASSWORD -user1.example.com;123456789;myuser;mypassword -user2.example.com;987654321;otheruser;otherpassword -- 2.36.6 From 9314781b08140a1abe64a5426e97b40f4865c9b6 Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 13:23:52 +0200 Subject: [PATCH 02/10] fix: connect to INWX via IPv4 only to simplify IP allowlists --- snap_dyndns.py | 21 ++++++++++++++++++++- test_snap_dyndns.py | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/snap_dyndns.py b/snap_dyndns.py index ecab47c..3fad631 100644 --- a/snap_dyndns.py +++ b/snap_dyndns.py @@ -13,10 +13,12 @@ import fcntl import hashlib import hmac import http +import http.client import http.cookiejar import ipaddress import json import os +import ssl import struct import sys import time @@ -50,13 +52,30 @@ def totp(secret, now=None): 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), + ) + + @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( - urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()) + _IPv4Https, urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()) ) def call(method, params): diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py index 8e9dfac..7f15ba6 100644 --- a/test_snap_dyndns.py +++ b/test_snap_dyndns.py @@ -8,12 +8,15 @@ INWX_OTE_HOST (an existing A record there) are set in the environment. import base64 import hashlib +import http.client import io import json import os +import socket import tempfile import threading import unittest +from unittest import mock from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import snap_dyndns as sd @@ -125,6 +128,24 @@ class HandleTest(unittest.TestCase): self.assertEqual(len(self.calls), 2) +class Ipv4BindTest(unittest.TestCase): + """Checks the premise of _IPv4Https: binding to 0.0.0.0 skips IPv6 addresses.""" + + def test_source_address_skips_ipv6(self): + try: + server = socket.create_server(("::1", 0), family=socket.AF_INET6) + except OSError: + self.skipTest("no IPv6 loopback") + self.addCleanup(server.close) + port = server.getsockname()[1] + try: + socket.create_connection(("localhost", port), timeout=2).close() + except OSError: + self.skipTest("localhost does not resolve to ::1") + with self.assertRaises(OSError): + socket.create_connection(("localhost", port), timeout=2, source_address=("0.0.0.0", 0)) + + class FakeInwx(ThreadingHTTPServer): """Minimal INWX JSON-RPC stand-in with cookie session and optional 2FA.""" @@ -228,6 +249,20 @@ class InwxClientTest(unittest.TestCase): sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4") self.assertNotIn("wrong-password", str(ctx.exception)) + def test_https_connection_is_ipv4_only(self): + seen = {} + + class FakeConnection(http.client.HTTPSConnection): + def __init__(self, *args, **kwargs): + seen.update(kwargs) + raise OSError("stop here") + + cfg = {"inwx": {"user": "u", "pass": "p", "api": "https://inwx.invalid/"}} + with mock.patch("http.client.HTTPSConnection", FakeConnection): + with self.assertRaises(OSError): + sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4") + self.assertEqual(seen["source_address"], ("0.0.0.0", 0)) + def test_end_to_end_only_changes_reach_inwx(self): srv = self.start() with tempfile.TemporaryDirectory() as tmp: -- 2.36.6 From 7a2d7c6650635eb8f6c48fc462342fb2650465a7 Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 13:49:04 +0200 Subject: [PATCH 03/10] chore: rewrite as service, as CGI caused too many issues --- .gitignore | 1 - .htaccess | 15 ------ README.md | 86 +++++++++++++++++++------------ config.toml.sample | 6 +++ snap_dyndns.py | 103 ++++++++++++++++++++++++++++--------- snap_dyndns_host.py | 96 +++++++++++++++++++++++++++++++++++ test_snap_dyndns.py | 96 ++++++++++++++++++++++++++--------- test_snap_dyndns_host.py | 107 +++++++++++++++++++++++++++++++++++++++ update.cgi | 10 ---- 9 files changed, 413 insertions(+), 107 deletions(-) delete mode 100644 .htaccess create mode 100644 snap_dyndns_host.py create mode 100644 test_snap_dyndns_host.py delete mode 100755 update.cgi diff --git a/.gitignore b/.gitignore index f2d793f..96d06c0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ __pycache__/ config.toml state.json -state.json.lock state.json.tmp .env diff --git a/.htaccess b/.htaccess deleted file mode 100644 index a8e6eea..0000000 --- a/.htaccess +++ /dev/null @@ -1,15 +0,0 @@ -# SPDX-FileCopyrightText: 2016 Max Mehl -# SPDX-License-Identifier: AGPL-3.0-or-later - -# Run update.cgi as CGI and hand the Authorization header to it -Options +ExecCGI -AddHandler cgi-script .cgi -CGIPassAuth On - -# Optional: config location if it is not ~/etc/snap-dyndns/config.toml -# SetEnv SNAP_DYNDNS_CONFIG /home/USER/etc/snap-dyndns/config.toml - -# Only update.cgi may be requested, nothing else of this repository - - Require all denied - diff --git a/README.md b/README.md index 68aca6a..b925b13 100644 --- a/README.md +++ b/README.md @@ -1,70 +1,94 @@ # Snap DynDNS Server using INWX domains -**Snap DynDNS Server** is a tiny Dynamic DNS service for domains managed by the registrar InterNetworX (inwx.de). It is a single Python CGI script without dependencies beyond the standard library, made for shared hosting such as Uberspace. +**Snap DynDNS Server** is a tiny Dynamic DNS service for domains managed by the registrar InterNetworX (inwx.de). It is a single Python file without dependencies beyond the standard library, made to run as a small service on shared hosting such as Uberspace. The server is a credential broker: your INWX API login only exists on the server, while each device gets its own random token that can update exactly one hostname. A device that gets lost or compromised can be cut off by deleting one section from the config. -It speaks the common dyndns2 protocol (HTTP Basic Auth, `myip`/`myipv6`, `good`/`nochg` answers), so routers like the AVM FritzBox, ddclient, and plain `curl` work. The matching client is [Snap DynDNS client](https://src.mehl.mx/mxmehl/snap-dyndns-client), a small shell script for cron. +It speaks the common dyndns2 protocol (HTTP Basic Auth, `myip`/`myipv6`, `good`/`nochg` answers) on `/nic/update`, so routers like the AVM FritzBox, ddclient, and plain `curl` work. The matching client is [Snap DynDNS client](https://src.mehl.mx/mxmehl/snap-dyndns-client), a small shell script for cron. ## How it works -1. A device sends `GET /update.cgi` with its hostname and token as Basic Auth. Without `myip`/`myipv6`, the server uses the IP the request came from. +1. A device sends `GET /nic/update` with its hostname and token as Basic Auth. Without `myip`/`myipv6`, the server uses the IP the request came from. 2. The server compares the SHA-256 of the token with the config. 3. If the IP equals the last one it stored, it answers `nochg` right away. INWX is not contacted, so polling every minute is cheap. 4. Otherwise it logs in to INWX, looks up the record by name and type, updates it, and only then stores the new IP. If INWX fails, the device gets `911` and retries on its next run. -The record (A and/or AAAA) has to exist at INWX already. The server picks A or AAAA depending on the IP family, and keeps the TTL you set there. +The record (A and/or AAAA) has to exist at INWX already. The server picks A or AAAA depending on the IP family, and keeps the TTL you set there. The connection to INWX uses IPv4 only, so an IP-restricted INWX API account only needs the server's IPv4 address on its allow-list. ## Requirements -- Apache with CGI and `.htaccess` support (Uberspace 7 has both) - Python 3.11 or newer, no packages needed -- An INWX account or API sub-account. If 2FA is enabled, the TOTP shared secret is needed as well. IP-restricted API accounts work if the server's IP is allowed. +- A way to run a service behind HTTPS, e.g. supervisord plus a reverse proxy (Uberspace has both) +- An INWX account or API sub-account. If 2FA is enabled, the TOTP shared secret is needed as well. IP-restricted API accounts work if the server's IPv4 address is allowed. + +The server speaks plain HTTP and expects a reverse proxy in front that terminates TLS. Never expose it without HTTPS, as the token is sent with every request. ## Installation on Uberspace -Clone the repository into a web-accessible directory, e.g. the document root of a dedicated (sub)domain: +Clone the repository anywhere outside the web root: ``` -git clone https://src.mehl.mx/mxmehl/snap-dyndns-server /var/www/virtual/myuser/dyndns.mydomain.net +git clone https://src.mehl.mx/mxmehl/snap-dyndns-server ~/snap-dyndns-server ``` -The `.htaccess` in the repository enables CGI, passes the `Authorization` header to the script, and denies access to every file except `update.cgi`. If your Python is not at `/usr/bin/python3.14`, adjust the shebang of `update.cgi`. - -Create the config **outside** the web root and make it private: +Create the config and make it private: ``` mkdir -p ~/etc/snap-dyndns -cp /var/www/virtual/myuser/dyndns.mydomain.net/config.toml.sample ~/etc/snap-dyndns/config.toml +cp ~/snap-dyndns-server/config.toml.sample ~/etc/snap-dyndns/config.toml chmod 600 ~/etc/snap-dyndns/config.toml ``` -If you prefer another location, uncomment `SetEnv SNAP_DYNDNS_CONFIG` in `.htaccess`. The state file with the last known IPs is written next to the config (`state_file` in the config). +Create the service, using a free port between 1024 and 65535 (here 8080), in `~/etc/services.d/snap-dyndns.ini`: + +```ini +[program:snap-dyndns] +command=/usr/bin/python3.14 %(ENV_HOME)s/snap-dyndns-server/snap_dyndns.py --config %(ENV_HOME)s/etc/snap-dyndns/config.toml --port 8080 +autostart=yes +autorestart=yes +``` + +If your Python is not at `/usr/bin/python3.14`, adjust the path. Start the service and register it as a web backend for the `/nic` path of your domain: + +``` +supervisorctl reread +supervisorctl update +uberspace web backend set yourdyndnsservice.net/nic --http --port 8080 +``` + +Check with `supervisorctl status` and `uberspace web backend list`. Errors and requests are logged to `~/logs/` (or `supervisorctl tail snap-dyndns stderr`). + +### Client IP address + +Behind the reverse proxy the TCP peer is the proxy, not the device. On Uberspace the proxy puts the device's address into `X-Forwarded-For`, which is already set in `config.toml.sample`: + +```toml +client_ip_header = "X-Forwarded-For" +``` + +The server uses the last entry of that header, the one added by your own proxy. Entries before it are controlled by the client and ignored. If the header is missing, or the address is not a global one, the answer is `badip` and a log line instead of a wrong DNS record. Check once that the `good ` answer shows your real public IP. + +With another proxy, stop the service (`supervisorctl stop snap-dyndns`), run `nc -l 8080` and open the URL once from outside. `nc` prints the raw request including all headers, so you can see in which one your public IP appears. ### Adding a device -Generate a token and its hash: +The helper creates a random token, stores only its SHA-256 in the config and prints the token once: ``` -python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())' +python3 ~/snap-dyndns-server/snap_dyndns_host.py user1.example.com ``` -Put the hash into a new section of `config.toml` and give the token to the device: +Give the printed token to the device, for the [client](https://src.mehl.mx/mxmehl/snap-dyndns-client) it is the `hostname:token` entry shown in the output. The same command for an existing host replaces its token, and the old one stops working immediately. Use `-c` for a config in another location and `-z example.co.uk` for a new host whose INWX zone is not the last two labels of its name. Comments and the rest of the config stay untouched. The config is read on every request, so no restart is needed. -```toml -[hosts."user1.example.com"] -token_sha256 = "" -``` - -The hostname is the Basic Auth user name, the token the password. The INWX zone is guessed as the last two labels of the hostname. For zones such as `example.co.uk` set `zone = "example.co.uk"` in that section. +The hostname is the Basic Auth user name, the token the password. Without the helper, generate a token and hash yourself with `python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'` and add a section `[hosts."user1.example.com"]` with `token_sha256 = ""`. ## Usage With curl (the `-u` option keeps the credentials out of the URL): ``` -curl -fsS -u user1.example.com:TOKEN "https://dyndns.mydomain.net/update.cgi" -curl -fsS -u user1.example.com:TOKEN "https://dyndns.mydomain.net/update.cgi?myip=1.2.3.4" +curl -fsS -u user1.example.com:TOKEN "https://yourdyndnsservice.net/nic/update" +curl -fsS -u user1.example.com:TOKEN "https://yourdyndnsservice.net/nic/update?myip=1.2.3.4" ``` Parameters, all optional: @@ -79,15 +103,15 @@ Answers (HTTP status in brackets): - `nochg ` (200): the IP is what the server stored last, INWX was not contacted - `badauth` (401): unknown hostname or wrong token - `nohost` (404): hostname mismatch, or the record does not exist at INWX -- `badip` (400): the IP could not be parsed -- `911` (502 or 500): INWX or the server config failed, see the Apache error log +- `badip` (400): the IP could not be parsed, or the address of the request is not a global one +- `911` (502 or 500): INWX or the server config failed, see the log ### AVM FritzBox Choose a custom DynDNS provider: ``` -Update-URL: https://dyndns.mydomain.net/update.cgi?hostname=&myip=&myipv6= +Update-URL: https://yourdyndnsservice.net/nic/update?hostname=&myip=&myipv6= Domain name: user1.example.com User name: user1.example.com Password: TOKEN @@ -97,8 +121,7 @@ Password: TOKEN ``` protocol=dyndns2 -server=dyndns.mydomain.net -script=/dyn/update.cgi +server=yourdyndnsservice.net ssl=yes login=user1.example.com password=TOKEN @@ -107,10 +130,11 @@ user1.example.com ## Known limits -- The IP is only checked for syntax, private and reserved addresses are accepted. +- Explicit `myip`/`myipv6` values are only checked for syntax, private and reserved addresses are accepted there. - Missing records are not created, add them at INWX first. - If you change a record at INWX by hand, the server does not notice. Delete `state.json` or change the IP to resync. -- Only one request updates at a time (a file lock is held during the INWX call), which is plenty for a personal setup. +- Only one request updates at a time (a lock is held during the INWX call), which is plenty for a personal setup. +- The built-in HTTP server is meant to sit behind a reverse proxy. Do not expose its port directly. ## Development diff --git a/config.toml.sample b/config.toml.sample index d83840e..f7423f0 100644 --- a/config.toml.sample +++ b/config.toml.sample @@ -3,6 +3,12 @@ # Where the last known IPs are cached (default shown) state_file = "~/etc/snap-dyndns/state.json" +# Header in which the reverse proxy puts the address of the device. The last entry is used. +# X-Forwarded-For is what Uberspace's proxy sets. Without this line the TCP peer's address is used, +# which is the proxy behind a web backend. +# Addresses that are not global (e.g. the proxy's) are rejected unless the device sends myip. +client_ip_header = "X-Forwarded-For" + [inwx] user = "api-user" pass = "api-password" diff --git a/snap_dyndns.py b/snap_dyndns.py index 3fad631..e98b8af 100644 --- a/snap_dyndns.py +++ b/snap_dyndns.py @@ -1,26 +1,28 @@ # SPDX-FileCopyrightText: 2016 Max Mehl # SPDX-License-Identifier: AGPL-3.0-or-later -"""Snap DynDNS Server: dyndns2-style CGI broker that updates INWX records. +"""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 fcntl 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 @@ -55,8 +57,8 @@ def totp(secret, now=None): 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 + 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. """ @@ -150,6 +152,9 @@ def _check_auth(env, cfg): return None +_STATE_LOCK = threading.Lock() + + def _load_state(path): try: with open(path) as f: @@ -184,7 +189,11 @@ def handle(env, cfg, update=inwx_update): ip = ipaddress.ip_address(raw) except ValueError: return 400, "badip" - # shortcut: syntax-only check (private/reserved IPs are accepted), reject them if clients misbehave + # 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:]) @@ -192,9 +201,8 @@ def handle(env, cfg, update=inwx_update): 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) + # 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: @@ -216,21 +224,66 @@ def handle(env, cfg, update=inwx_update): 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)) +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 != "/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): + data = (body + "\n").encode() + self.send_response(status) + self.send_header("Content-Type", "text/plain; 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: - 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") + 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() diff --git a/snap_dyndns_host.py b/snap_dyndns_host.py new file mode 100644 index 0000000..595e7be --- /dev/null +++ b/snap_dyndns_host.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2016 Max Mehl +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Add a host to the Snap DynDNS config, or replace its token. + +Generates a random token, stores only its SHA-256 in the config and prints the +token once. The token is what the client needs; the server never sees it again. +""" + +import argparse +import hashlib +import os +import re +import secrets +import sys +import tempfile +import tomllib + +from snap_dyndns import DEFAULT_CONFIG + +NAME = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$") + + +def set_host(text, host, digest, zone=None): + """Return (new_text, created) with host's token_sha256 set to digest. + + Works on the text, so comments and formatting stay. Raises ValueError if + an existing section is not in the usual `[hosts."name"]` form. + """ + exists = host in tomllib.loads(text).get("hosts", {}) + if not exists: + section = f'\n[hosts."{host}"]\ntoken_sha256 = "{digest}"\n' + if zone: + section += f'zone = "{zone}"\n' + return text.rstrip("\n") + "\n" + section, True + if zone: + raise ValueError(f"{host} already exists, change its zone by hand") + + lines = text.split("\n") + header = f'[hosts."{host}"]' + start = next((i for i, line in enumerate(lines) if line.strip() == header), None) + if start is None: + raise ValueError(f"cannot find the line {header} in the config, edit {host} by hand") + for i in range(start + 1, len(lines)): + if lines[i].lstrip().startswith("["): + break + if re.match(r"\s*token_sha256\s*=", lines[i]): + lines[i] = f'token_sha256 = "{digest}"' + return "\n".join(lines), False + raise ValueError(f"no token_sha256 line in the section of {host}, edit it by hand") + + +def write_config(path, text): + """Replace the file atomically, keeping its permissions (the config holds secrets).""" + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(path))) + try: + with os.fdopen(fd, "w") as f: + f.write(text) + os.chmod(tmp, os.stat(path).st_mode & 0o777) + os.replace(tmp, path) + except BaseException: + os.unlink(tmp) + raise + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("hostname", help="e.g. home.example.com; an existing host gets a new token") + parser.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})") + parser.add_argument("-z", "--zone", help="INWX zone for a new host, if not the last two labels of the hostname") + args = parser.parse_args(argv) + + host = args.hostname.lower() + for value in (host, args.zone): + if value and not NAME.match(value): + sys.exit(f"invalid name: {value}") + path = os.path.expanduser(args.config) + + token = secrets.token_urlsafe(32) + digest = hashlib.sha256(token.encode()).hexdigest() + try: + with open(path) as f: + new_text, created = set_host(f.read(), host, digest, args.zone) + tomllib.loads(new_text) # never write a config that does not parse + write_config(path, new_text) + except (OSError, ValueError) as e: # TOMLDecodeError is a ValueError + sys.exit(f"{path}: {e}") + + print(f"{'Added' if created else 'Replaced the token of'} {host} in {path}") + print("The server reads the config on every request, no restart needed.") + print(f"Token (shown only once): {token}") + print(f"Client entry for HOSTS: {host}:{token}") + + +if __name__ == "__main__": + main() diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py index 7f15ba6..1cc73df 100644 --- a/test_snap_dyndns.py +++ b/test_snap_dyndns.py @@ -9,7 +9,6 @@ INWX_OTE_HOST (an existing A record there) are set in the environment. import base64 import hashlib import http.client -import io import json import os import socket @@ -79,7 +78,7 @@ class HandleTest(unittest.TestCase): self.assertEqual(len(self.calls), 2) def test_ipv6_connection_updates_aaaa(self): - self.assertEqual(self.run_handle(remote="2001:db8::1"), (200, "good 2001:db8::1")) + self.assertEqual(self.run_handle(remote="2606:4700:4700::1111"), (200, "good 2606:4700:4700::1111")) self.assertEqual(self.calls[0][2], "AAAA") def test_myip_overrides_remote_addr(self): @@ -112,6 +111,14 @@ class HandleTest(unittest.TestCase): def test_hostname_mismatch(self): self.assertEqual(self.run_handle(query="hostname=other.example.com"), (404, "nohost")) + def test_non_global_connection_address_is_rejected(self): + for remote in ("127.0.0.1", "10.0.0.5", "::1", ""): + self.assertEqual(self.run_handle(remote=remote), (400, "badip"), remote) + self.assertEqual(self.calls, []) + + def test_explicit_ip_may_be_private(self): + self.assertEqual(self.run_handle(query=f"hostname={HOST}&myip=192.168.1.5", remote="127.0.0.1")[0], 200) + def test_invalid_ip(self): self.assertEqual(self.run_handle(query=f"hostname={HOST}&myip=1.2.3.4;rm"), (400, "badip")) self.assertEqual(self.calls, []) @@ -273,41 +280,80 @@ class InwxClientTest(unittest.TestCase): self.assertEqual(srv.calls.count("account.login"), 1) -class MainTest(unittest.TestCase): - def run_main(self, env, cfg_text): - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "config.toml") - with open(path, "w") as f: - f.write(cfg_text.replace("STATE", os.path.join(tmp, "state.json"))) - out = io.StringIO() - sd.main({**env, "SNAP_DYNDNS_CONFIG": path}, out) - return out.getvalue() +class ServerTest(unittest.TestCase): + """Real HTTP requests against make_server() with a fake INWX behind it.""" - CFG = f""" -state_file = "STATE" + def start(self, **config): + inwx = FakeInwx() + tmp = tempfile.TemporaryDirectory() + path = os.path.join(tmp.name, "config.toml") + with open(path, "w") as f: + f.write( + f'''state_file = "{tmp.name}/state.json" +{"".join(f'{k} = "{v}"' + chr(10) for k, v in config.items())} [inwx] user = "u" pass = "p" -api = "http://127.0.0.1:1/" +api = "{inwx.url}" [hosts."{HOST}"] token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" -""" +''' + ) + server = sd.make_server(path, 0, "127.0.0.1") + threading.Thread(target=server.serve_forever, daemon=True).start() + for cleanup in (tmp.cleanup, inwx.server_close, inwx.shutdown, server.server_close, server.shutdown): + self.addCleanup(cleanup) + self.inwx = inwx + return server + + def get(self, server, path="/nic/update?hostname=" + HOST, **headers): + headers.setdefault("Authorization", basic(HOST, TOKEN)) + conn = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5) + conn.request("GET", path, headers=headers) + response = conn.getresponse() + return response.status, response.getheader("WWW-Authenticate"), response.read().decode() + + def test_update_via_forwarded_header_then_nochg(self): + server = self.start(client_ip_header="X-Forwarded-For") + # Only the last entry (added by our proxy) counts, earlier ones are client-controlled + headers = {"X-Forwarded-For": "6.6.6.6, 1.2.3.4"} + self.assertEqual(self.get(server, **headers), (200, None, "good 1.2.3.4\n")) + self.assertEqual(self.get(server, **headers), (200, None, "nochg 1.2.3.4\n")) + self.assertEqual(self.inwx.calls.count("nameserver.updateRecord"), 1) + + def test_loopback_peer_without_header_is_rejected(self): + server = self.start() + self.assertEqual(self.get(server), (400, None, "badip\n")) + + def test_missing_configured_header_is_rejected(self): + server = self.start(client_ip_header="X-Forwarded-For") + self.assertEqual(self.get(server), (400, None, "badip\n")) def test_unauthorized_has_challenge(self): - out = self.run_main(make_env(auth=basic(HOST, "bad")), self.CFG) - head, _, body = out.partition("\n\n") - self.assertTrue(head.startswith("Status: 401 Unauthorized")) - self.assertIn('WWW-Authenticate: Basic realm="Snap DynDNS"', head) - self.assertEqual(body, "badauth\n") + server = self.start() + status, challenge, body = self.get(server, Authorization=basic(HOST, "bad")) + self.assertEqual((status, challenge, body), (401, 'Basic realm="Snap DynDNS"', "badauth\n")) + + def test_other_paths_are_not_found(self): + server = self.start() + self.assertEqual(self.get(server, "/")[0], 404) def test_unreachable_inwx_is_911(self): - out = self.run_main(make_env(), self.CFG) - self.assertTrue(out.startswith("Status: 502 Bad Gateway\n")) - self.assertTrue(out.endswith("\n\n911\n")) + server = self.start(client_ip_header="X-Forwarded-For") + self.inwx.shutdown() + self.inwx.server_close() + status, _, body = self.get(server, **{"X-Forwarded-For": "1.2.3.4"}) + self.assertEqual((status, body), (502, "911\n")) def test_broken_config_is_500(self): - out = self.run_main(make_env(), "not = [valid") - self.assertTrue(out.startswith("Status: 500 Internal Server Error\n")) + server = self.start() + with open(server.config_path, "w") as f: + f.write("not = [valid") + self.assertEqual(self.get(server), (500, None, "911\n")) + + def test_main_refuses_unreadable_config(self): + with self.assertRaises(SystemExit): + sd.main(["--config", "/nonexistent/config.toml"]) @unittest.skipUnless( diff --git a/test_snap_dyndns_host.py b/test_snap_dyndns_host.py new file mode 100644 index 0000000..bd54aff --- /dev/null +++ b/test_snap_dyndns_host.py @@ -0,0 +1,107 @@ +# SPDX-FileCopyrightText: 2016 Max Mehl +# SPDX-License-Identifier: AGPL-3.0-or-later +import contextlib +import hashlib +import io +import os +import stat +import tempfile +import tomllib +import unittest + +import snap_dyndns_host as sh + +CONFIG = """\ +# my comment +state_file = "/tmp/state.json" + +[inwx] +user = "u" +pass = "p" + +[hosts."a.example.com"] +token_sha256 = "aaaa" + +# keep this comment +[hosts."b.example.com"] +zone = "example.com" +token_sha256 = "bbbb" # trailing +""" + + +class SetHostTest(unittest.TestCase): + def test_new_host_is_appended(self): + text, created = sh.set_host(CONFIG, "c.example.co.uk", "cccc", zone="example.co.uk") + self.assertTrue(created) + hosts = tomllib.loads(text)["hosts"] + self.assertEqual(hosts["c.example.co.uk"], {"token_sha256": "cccc", "zone": "example.co.uk"}) + self.assertEqual(hosts["a.example.com"], {"token_sha256": "aaaa"}) + self.assertTrue(text.startswith(CONFIG.rstrip("\n"))) + + def test_existing_host_gets_new_hash_only(self): + text, created = sh.set_host(CONFIG, "b.example.com", "new", None) + self.assertFalse(created) + parsed = tomllib.loads(text)["hosts"] + self.assertEqual(parsed["b.example.com"], {"zone": "example.com", "token_sha256": "new"}) + self.assertEqual(parsed["a.example.com"]["token_sha256"], "aaaa") + self.assertIn("# keep this comment", text) + + def test_existing_host_with_unusual_header_is_refused(self): + odd = CONFIG.replace('[hosts."a.example.com"]', "[hosts.'a.example.com']") + with self.assertRaises(ValueError): + sh.set_host(odd, "a.example.com", "new") + + def test_zone_for_existing_host_is_refused(self): + with self.assertRaises(ValueError): + sh.set_host(CONFIG, "a.example.com", "new", zone="example.com") + + def test_config_without_hosts(self): + text, created = sh.set_host('[inwx]\nuser = "u"\npass = "p"', "a.example.com", "aaaa") + self.assertTrue(created) + self.assertEqual(tomllib.loads(text)["hosts"]["a.example.com"]["token_sha256"], "aaaa") + + +class MainTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.path = os.path.join(tmp.name, "config.toml") + with open(self.path, "w") as f: + f.write(CONFIG) + os.chmod(self.path, 0o600) + + def run_main(self, *args): + out = io.StringIO() + with contextlib.redirect_stdout(out): + sh.main(["-c", self.path, *args]) + return out.getvalue() + + def test_printed_token_matches_stored_hash(self): + output = self.run_main("New.Example.com") + token = output.split("Token (shown only once): ")[1].split("\n")[0] + self.assertIn(f"Client entry for HOSTS: new.example.com:{token}", output) + with open(self.path, "rb") as f: + stored = tomllib.load(f)["hosts"]["new.example.com"]["token_sha256"] + self.assertEqual(stored, hashlib.sha256(token.encode()).hexdigest()) + + def test_rotation_changes_the_hash_and_keeps_permissions(self): + self.run_main("a.example.com") + with open(self.path, "rb") as f: + self.assertNotEqual(tomllib.load(f)["hosts"]["a.example.com"]["token_sha256"], "aaaa") + self.assertEqual(stat.S_IMODE(os.stat(self.path).st_mode), 0o600) + + def test_invalid_hostname_leaves_config_untouched(self): + for bad in ('x"] \n[evil', "no_dots", "a..b", "-a.example.com"): + with self.assertRaises(SystemExit): + self.run_main(bad) + with open(self.path) as f: + self.assertEqual(f.read(), CONFIG) + + def test_missing_config(self): + os.unlink(self.path) + with self.assertRaises(SystemExit): + self.run_main("a.example.com") + + +if __name__ == "__main__": + unittest.main() diff --git a/update.cgi b/update.cgi deleted file mode 100755 index 2e30de7..0000000 --- a/update.cgi +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/python3.14 -# SPDX-FileCopyrightText: 2016 Max Mehl -# SPDX-License-Identifier: AGPL-3.0-or-later -import os -import sys - -sys.path.insert(0, os.path.dirname(os.path.realpath(__file__))) -from snap_dyndns import main - -main() -- 2.36.6 From 186fe7f9ee4449b15a46eb631d7a1c750256b821 Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 13:56:15 +0200 Subject: [PATCH 04/10] feat: also add page for / --- README.md | 2 ++ snap_dyndns.py | 23 ++++++++++++++++++++--- test_snap_dyndns.py | 9 ++++++++- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b925b13..2a7497c 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,8 @@ uberspace web backend set yourdyndnsservice.net/nic --http --port 8080 Check with `supervisorctl status` and `uberspace web backend list`. Errors and requests are logged to `~/logs/` (or `supervisorctl tail snap-dyndns stderr`). +The service also answers `/` with a short start page, but with the backend registered for `/nic` only `/nic` and `/nic/` reach it. To show the page on the domain's root as well, register the whole domain instead: `uberspace web backend set yourdyndnsservice.net --http --port 8080`. + ### Client IP address Behind the reverse proxy the TCP peer is the proxy, not the device. On Uberspace the proxy puts the device's address into `X-Forwarded-For`, which is already set in `config.toml.sample`: diff --git a/snap_dyndns.py b/snap_dyndns.py index e98b8af..dc99315 100644 --- a/snap_dyndns.py +++ b/snap_dyndns.py @@ -224,11 +224,28 @@ def handle(env, cfg, update=inwx_update): return 200, "\n".join(lines) +INDEX_HTML = """ + + + + Snap DynDNS Server + + +

Snap DynDNS Server

+
+

Please contact the site owner for more information on this specific service.

+ + +""" + + 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: @@ -253,10 +270,10 @@ class RequestHandler(http.server.BaseHTTPRequestHandler): return self.headers.get(name, "").split(",")[-1].strip() return self.client_address[0] - def _reply(self, status, body): - data = (body + "\n").encode() + 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", "text/plain; charset=utf-8") + 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: diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py index 1cc73df..e55a357 100644 --- a/test_snap_dyndns.py +++ b/test_snap_dyndns.py @@ -334,9 +334,16 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" status, challenge, body = self.get(server, Authorization=basic(HOST, "bad")) self.assertEqual((status, challenge, body), (401, 'Basic realm="Snap DynDNS"', "badauth\n")) + def test_start_page_without_credentials(self): + server = self.start() + for path in ("/", "/nic", "/nic/"): + status, challenge, body = self.get(server, path, Authorization="") + self.assertEqual((status, challenge), (200, None), path) + self.assertIn("

Snap DynDNS Server

", body) + def test_other_paths_are_not_found(self): server = self.start() - self.assertEqual(self.get(server, "/")[0], 404) + self.assertEqual(self.get(server, "/elsewhere")[0], 404) def test_unreachable_inwx_is_911(self): server = self.start(client_ip_header="X-Forwarded-For") -- 2.36.6 From 8bc1cfaf27bfd60bcb29ff877ddb9e5d4a3a7172 Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 14:09:28 +0200 Subject: [PATCH 05/10] fix: make helper script ask for confirmation on overwrite --- README.md | 2 +- snap_dyndns_host.py | 45 ++++++++++++++++++++++++++++++++---- test_snap_dyndns_host.py | 50 ++++++++++++++++++++++++++++++++++------ 3 files changed, 84 insertions(+), 13 deletions(-) mode change 100644 => 100755 snap_dyndns_host.py diff --git a/README.md b/README.md index 2a7497c..05a911b 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,7 @@ The helper creates a random token, stores only its SHA-256 in the config and pri python3 ~/snap-dyndns-server/snap_dyndns_host.py user1.example.com ``` -Give the printed token to the device, for the [client](https://src.mehl.mx/mxmehl/snap-dyndns-client) it is the `hostname:token` entry shown in the output. The same command for an existing host replaces its token, and the old one stops working immediately. Use `-c` for a config in another location and `-z example.co.uk` for a new host whose INWX zone is not the last two labels of its name. Comments and the rest of the config stay untouched. The config is read on every request, so no restart is needed. +Give the printed token to the device, for the [client](https://src.mehl.mx/mxmehl/snap-dyndns-client) it is the `hostname:token` entry shown in the output. For an existing host it asks before replacing the token (`-y` skips the question), and the old token stops working immediately. Use `-c` for a config in another location and `-z example.co.uk` for a new host whose INWX zone is not the last two labels of its name. Comments and the rest of the config stay untouched. The config is read on every request, so no restart is needed. The hostname is the Basic Auth user name, the token the password. Without the helper, generate a token and hash yourself with `python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'` and add a section `[hosts."user1.example.com"]` with `token_sha256 = ""`. diff --git a/snap_dyndns_host.py b/snap_dyndns_host.py old mode 100644 new mode 100755 index 595e7be..81b9ea2 --- a/snap_dyndns_host.py +++ b/snap_dyndns_host.py @@ -40,7 +40,9 @@ def set_host(text, host, digest, zone=None): header = f'[hosts."{host}"]' start = next((i for i, line in enumerate(lines) if line.strip() == header), None) if start is None: - raise ValueError(f"cannot find the line {header} in the config, edit {host} by hand") + raise ValueError( + f"cannot find the line {header} in the config, edit {host} by hand" + ) for i in range(start + 1, len(lines)): if lines[i].lstrip().startswith("["): break @@ -63,11 +65,36 @@ def write_config(path, text): raise +def confirm(question): + """Ask on the terminal; anything but yes, including no input, means no.""" + try: + return input(question).strip().lower() in ("y", "yes") + except EOFError: + return False + + def main(argv=None): parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) - parser.add_argument("hostname", help="e.g. home.example.com; an existing host gets a new token") - parser.add_argument("-c", "--config", default=DEFAULT_CONFIG, help=f"config file (default: {DEFAULT_CONFIG})") - parser.add_argument("-z", "--zone", help="INWX zone for a new host, if not the last two labels of the hostname") + parser.add_argument( + "hostname", help="e.g. home.example.com; an existing host gets a new token" + ) + parser.add_argument( + "-c", + "--config", + default=DEFAULT_CONFIG, + help=f"config file (default: {DEFAULT_CONFIG})", + ) + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="replace the token of an existing host without asking", + ) + parser.add_argument( + "-z", + "--zone", + help="INWX zone for a new host, if not the last two labels of the hostname", + ) args = parser.parse_args(argv) host = args.hostname.lower() @@ -80,7 +107,15 @@ def main(argv=None): digest = hashlib.sha256(token.encode()).hexdigest() try: with open(path) as f: - new_text, created = set_host(f.read(), host, digest, args.zone) + text = f.read() + exists = host in tomllib.loads(text).get("hosts", {}) + if ( + exists + and not args.yes + and not confirm(f"{host} already exists. Replace its token? [y/N] ") + ): + sys.exit("Aborted, config unchanged") + new_text, created = set_host(text, host, digest, args.zone) tomllib.loads(new_text) # never write a config that does not parse write_config(path, new_text) except (OSError, ValueError) as e: # TOMLDecodeError is a ValueError diff --git a/test_snap_dyndns_host.py b/test_snap_dyndns_host.py index bd54aff..ed28395 100644 --- a/test_snap_dyndns_host.py +++ b/test_snap_dyndns_host.py @@ -8,6 +8,7 @@ import stat import tempfile import tomllib import unittest +from unittest import mock import snap_dyndns_host as sh @@ -31,10 +32,14 @@ token_sha256 = "bbbb" # trailing class SetHostTest(unittest.TestCase): def test_new_host_is_appended(self): - text, created = sh.set_host(CONFIG, "c.example.co.uk", "cccc", zone="example.co.uk") + text, created = sh.set_host( + CONFIG, "c.example.co.uk", "cccc", zone="example.co.uk" + ) self.assertTrue(created) hosts = tomllib.loads(text)["hosts"] - self.assertEqual(hosts["c.example.co.uk"], {"token_sha256": "cccc", "zone": "example.co.uk"}) + self.assertEqual( + hosts["c.example.co.uk"], {"token_sha256": "cccc", "zone": "example.co.uk"} + ) self.assertEqual(hosts["a.example.com"], {"token_sha256": "aaaa"}) self.assertTrue(text.startswith(CONFIG.rstrip("\n"))) @@ -42,7 +47,9 @@ class SetHostTest(unittest.TestCase): text, created = sh.set_host(CONFIG, "b.example.com", "new", None) self.assertFalse(created) parsed = tomllib.loads(text)["hosts"] - self.assertEqual(parsed["b.example.com"], {"zone": "example.com", "token_sha256": "new"}) + self.assertEqual( + parsed["b.example.com"], {"zone": "example.com", "token_sha256": "new"} + ) self.assertEqual(parsed["a.example.com"]["token_sha256"], "aaaa") self.assertIn("# keep this comment", text) @@ -56,9 +63,13 @@ class SetHostTest(unittest.TestCase): sh.set_host(CONFIG, "a.example.com", "new", zone="example.com") def test_config_without_hosts(self): - text, created = sh.set_host('[inwx]\nuser = "u"\npass = "p"', "a.example.com", "aaaa") + text, created = sh.set_host( + '[inwx]\nuser = "u"\npass = "p"', "a.example.com", "aaaa" + ) self.assertTrue(created) - self.assertEqual(tomllib.loads(text)["hosts"]["a.example.com"]["token_sha256"], "aaaa") + self.assertEqual( + tomllib.loads(text)["hosts"]["a.example.com"]["token_sha256"], "aaaa" + ) class MainTest(unittest.TestCase): @@ -85,11 +96,36 @@ class MainTest(unittest.TestCase): self.assertEqual(stored, hashlib.sha256(token.encode()).hexdigest()) def test_rotation_changes_the_hash_and_keeps_permissions(self): - self.run_main("a.example.com") + self.run_main("a.example.com", "--yes") with open(self.path, "rb") as f: - self.assertNotEqual(tomllib.load(f)["hosts"]["a.example.com"]["token_sha256"], "aaaa") + self.assertNotEqual( + tomllib.load(f)["hosts"]["a.example.com"]["token_sha256"], "aaaa" + ) self.assertEqual(stat.S_IMODE(os.stat(self.path).st_mode), 0o600) + def test_existing_host_asks_and_replaces_on_yes(self): + with mock.patch("builtins.input", return_value="y") as ask: + self.run_main("a.example.com") + self.assertIn("already exists", ask.call_args.args[0]) + self.assertNotEqual(self.stored_hash("a.example.com"), "aaaa") + + def test_existing_host_is_kept_on_no_or_without_input(self): + for answer in ("", "n", EOFError()): + with ( + mock.patch("builtins.input", side_effect=[answer]), + self.assertRaises(SystemExit), + ): + self.run_main("a.example.com") + self.assertEqual(self.stored_hash("a.example.com"), "aaaa") + + def test_new_host_does_not_ask(self): + with mock.patch("builtins.input", side_effect=AssertionError("asked")): + self.run_main("fresh.example.com") + + def stored_hash(self, host): + with open(self.path, "rb") as f: + return tomllib.load(f)["hosts"][host]["token_sha256"] + def test_invalid_hostname_leaves_config_untouched(self): for bad in ('x"] \n[evil', "no_dots", "a..b", "-a.example.com"): with self.assertRaises(SystemExit): -- 2.36.6 From c43f0dd6998d9bf946a9e3e4c8bc8f18616ada32 Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 14:09:43 +0200 Subject: [PATCH 06/10] chore: improve logging and type fixes --- snap_dyndns.py | 31 ++++++++++--- test_snap_dyndns.py | 109 ++++++++++++++++++++++++++++++++------------ 2 files changed, 106 insertions(+), 34 deletions(-) diff --git a/snap_dyndns.py b/snap_dyndns.py index dc99315..ba0c3bf 100644 --- a/snap_dyndns.py +++ b/snap_dyndns.py @@ -27,6 +27,7 @@ import time import tomllib import urllib.parse import urllib.request +from typing import cast API_LIVE = "https://api.domrobot.com/jsonrpc/" DEFAULT_CONFIG = "~/etc/snap-dyndns/config.toml" @@ -191,7 +192,10 @@ def handle(env, cfg, update=inwx_update): 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) + 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) @@ -218,6 +222,8 @@ def handle(env, cfg, update=inwx_update): 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 + old_ip = state.get(host, {}).get(rtype, "unknown") + print(f"snap-dyndns: {host}: {rtype} {old_ip} -> {ip}", file=sys.stderr) state.setdefault(host, {})[rtype] = ip _save_state(state_path, state) lines.append(f"good {ip}") @@ -239,6 +245,10 @@ INDEX_HTML = """ """ +class Server(http.server.ThreadingHTTPServer): + config_path: str + + class RequestHandler(http.server.BaseHTTPRequestHandler): timeout = 30 # do not let stalled connections hold a thread forever @@ -250,7 +260,7 @@ class RequestHandler(http.server.BaseHTTPRequestHandler): 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: + with open(cast(Server, self.server).config_path, "rb") as f: cfg = tomllib.load(f) env = { "QUERY_STRING": url.query, @@ -283,15 +293,24 @@ class RequestHandler(http.server.BaseHTTPRequestHandler): def make_server(config_path, port, host="0.0.0.0"): - server = http.server.ThreadingHTTPServer((host, port), RequestHandler) + server = Server((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)") + 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 diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py index e55a357..cd7e6f5 100644 --- a/test_snap_dyndns.py +++ b/test_snap_dyndns.py @@ -15,8 +15,9 @@ import socket import tempfile import threading import unittest -from unittest import mock from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import cast +from unittest import mock import snap_dyndns as sd @@ -56,12 +57,12 @@ class HandleTest(unittest.TestCase): self.addCleanup(tmp.cleanup) self.cfg = make_cfg(tmp.name) self.calls = [] - self.fail = None + self.error = None def update(self, cfg, zone, name, rtype, ip): self.calls.append((zone, name, rtype, ip)) - if self.fail: - raise self.fail + if self.error: + raise self.error return True def run_handle(self, **kw): @@ -78,7 +79,10 @@ class HandleTest(unittest.TestCase): self.assertEqual(len(self.calls), 2) def test_ipv6_connection_updates_aaaa(self): - self.assertEqual(self.run_handle(remote="2606:4700:4700::1111"), (200, "good 2606:4700:4700::1111")) + self.assertEqual( + self.run_handle(remote="2606:4700:4700::1111"), + (200, "good 2606:4700:4700::1111"), + ) self.assertEqual(self.calls[0][2], "AAAA") def test_myip_overrides_remote_addr(self): @@ -86,7 +90,9 @@ class HandleTest(unittest.TestCase): self.assertEqual(self.calls[0][3], "9.9.9.9") def test_dual_stack(self): - status, body = self.run_handle(query=f"hostname={HOST}&myip=9.9.9.9&myipv6=2001:db8::2") + status, body = self.run_handle( + query=f"hostname={HOST}&myip=9.9.9.9&myipv6=2001:db8::2" + ) self.assertEqual((status, body), (200, "good 9.9.9.9\ngood 2001:db8::2")) self.assertEqual([c[2] for c in self.calls], ["A", "AAAA"]) @@ -99,7 +105,12 @@ class HandleTest(unittest.TestCase): self.assertEqual(self.calls[0][0], "example.co.uk") def test_bad_credentials(self): - for auth in (basic(HOST, "wrong"), basic("other.example.com", TOKEN), "Basic !!!", "Bearer x"): + for auth in ( + basic(HOST, "wrong"), + basic("other.example.com", TOKEN), + "Basic !!!", + "Bearer x", + ): self.assertEqual(self.run_handle(auth=auth), (401, "badauth"), auth) self.assertEqual(self.calls, []) @@ -109,7 +120,9 @@ class HandleTest(unittest.TestCase): self.assertEqual(sd.handle(env, self.cfg, self.update), (401, "badauth")) def test_hostname_mismatch(self): - self.assertEqual(self.run_handle(query="hostname=other.example.com"), (404, "nohost")) + self.assertEqual( + self.run_handle(query="hostname=other.example.com"), (404, "nohost") + ) def test_non_global_connection_address_is_rejected(self): for remote in ("127.0.0.1", "10.0.0.5", "::1", ""): @@ -117,20 +130,27 @@ class HandleTest(unittest.TestCase): self.assertEqual(self.calls, []) def test_explicit_ip_may_be_private(self): - self.assertEqual(self.run_handle(query=f"hostname={HOST}&myip=192.168.1.5", remote="127.0.0.1")[0], 200) + self.assertEqual( + self.run_handle( + query=f"hostname={HOST}&myip=192.168.1.5", remote="127.0.0.1" + )[0], + 200, + ) def test_invalid_ip(self): - self.assertEqual(self.run_handle(query=f"hostname={HOST}&myip=1.2.3.4;rm"), (400, "badip")) + self.assertEqual( + self.run_handle(query=f"hostname={HOST}&myip=1.2.3.4;rm"), (400, "badip") + ) self.assertEqual(self.calls, []) def test_missing_record(self): - self.fail = sd.NoHost("gone") + self.error = sd.NoHost("gone") self.assertEqual(self.run_handle(), (404, "nohost")) def test_inwx_failure_keeps_state_and_retries(self): - self.fail = sd.InwxError("boom") + self.error = sd.InwxError("boom") self.assertEqual(self.run_handle(), (502, "911")) - self.fail = None + self.error = None self.assertEqual(self.run_handle(), (200, "good 1.2.3.4")) self.assertEqual(len(self.calls), 2) @@ -150,7 +170,9 @@ class Ipv4BindTest(unittest.TestCase): except OSError: self.skipTest("localhost does not resolve to ::1") with self.assertRaises(OSError): - socket.create_connection(("localhost", port), timeout=2, source_address=("0.0.0.0", 0)) + socket.create_connection( + ("localhost", port), timeout=2, source_address=("0.0.0.0", 0) + ) class FakeInwx(ThreadingHTTPServer): @@ -170,11 +192,11 @@ class FakeInwx(ThreadingHTTPServer): class FakeInwxHandler(BaseHTTPRequestHandler): - def log_message(self, *args): + def log_message(self, format: str, *args: object) -> None: pass def do_POST(self): - srv = self.server + srv = cast(FakeInwx, self.server) req = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) method, p = req["method"], req["params"] srv.calls.append(method) @@ -188,13 +210,22 @@ class FakeInwxHandler(BaseHTTPRequestHandler): elif "sid=abc" not in self.headers.get("Cookie", ""): code = 2002 elif method == "account.unlock": - valid = {sd.totp(srv.tfa_secret, now=__import__("time").time() + d) for d in (-30, 0, 30)} + valid = { + sd.totp(srv.tfa_secret, now=__import__("time").time() + d) + for d in (-30, 0, 30) + } srv.unlocked = p["tan"] in valid code = 1000 if srv.unlocked else 2200 elif not srv.unlocked: code = 2200 elif method == "nameserver.info": - res = {"record": [r for r in srv.records if r["name"] == p["name"] and r["type"] == p["type"]]} + res = { + "record": [ + r + for r in srv.records + if r["name"] == p["name"] and r["type"] == p["type"] + ] + } elif method == "nameserver.updateRecord": for r in srv.records: if r["id"] == p["id"]: @@ -220,20 +251,26 @@ class InwxClientTest(unittest.TestCase): def test_update_changes_record(self): srv = self.start() - self.assertTrue(sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "1.2.3.4")) + self.assertTrue( + sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "1.2.3.4") + ) self.assertEqual(srv.records[0]["content"], "1.2.3.4") self.assertEqual(srv.calls[-1], "account.logout") def test_same_content_skips_update(self): srv = self.start() - self.assertFalse(sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "10.0.0.1")) + self.assertFalse( + sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "10.0.0.1") + ) self.assertNotIn("nameserver.updateRecord", srv.calls) def test_two_factor(self): secret = base64.b32encode(b"12345678901234567890").decode() srv = self.start(tfa_secret=secret) self.assertTrue( - sd.inwx_update(self.cfg(srv, totp_secret=secret), "example.com", HOST, "A", "1.2.3.4") + sd.inwx_update( + self.cfg(srv, totp_secret=secret), "example.com", HOST, "A", "1.2.3.4" + ) ) self.assertIn("account.unlock", srv.calls) @@ -265,9 +302,11 @@ class InwxClientTest(unittest.TestCase): raise OSError("stop here") cfg = {"inwx": {"user": "u", "pass": "p", "api": "https://inwx.invalid/"}} - with mock.patch("http.client.HTTPSConnection", FakeConnection): - with self.assertRaises(OSError): - sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4") + with ( + mock.patch("http.client.HTTPSConnection", FakeConnection), + self.assertRaises(OSError), + ): + sd.inwx_update(cfg, "example.com", HOST, "A", "1.2.3.4") self.assertEqual(seen["source_address"], ("0.0.0.0", 0)) def test_end_to_end_only_changes_reach_inwx(self): @@ -301,7 +340,13 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" ) server = sd.make_server(path, 0, "127.0.0.1") threading.Thread(target=server.serve_forever, daemon=True).start() - for cleanup in (tmp.cleanup, inwx.server_close, inwx.shutdown, server.server_close, server.shutdown): + for cleanup in ( + tmp.cleanup, + inwx.server_close, + inwx.shutdown, + server.server_close, + server.shutdown, + ): self.addCleanup(cleanup) self.inwx = inwx return server @@ -311,7 +356,11 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" conn = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=5) conn.request("GET", path, headers=headers) response = conn.getresponse() - return response.status, response.getheader("WWW-Authenticate"), response.read().decode() + return ( + response.status, + response.getheader("WWW-Authenticate"), + response.read().decode(), + ) def test_update_via_forwarded_header_then_nochg(self): server = self.start(client_ip_header="X-Forwarded-For") @@ -332,7 +381,9 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" def test_unauthorized_has_challenge(self): server = self.start() status, challenge, body = self.get(server, Authorization=basic(HOST, "bad")) - self.assertEqual((status, challenge, body), (401, 'Basic realm="Snap DynDNS"', "badauth\n")) + self.assertEqual( + (status, challenge, body), (401, 'Basic realm="Snap DynDNS"', "badauth\n") + ) def test_start_page_without_credentials(self): server = self.start() @@ -384,7 +435,9 @@ class OteSmokeTest(unittest.TestCase): try: self.assertTrue(sd.inwx_update(cfg, zone, host, "A", test_ip)) with sd.inwx_session(cfg) as call: - self.assertEqual(sd.find_record(call, zone, host, "A")["content"], test_ip) + self.assertEqual( + sd.find_record(call, zone, host, "A")["content"], test_ip + ) finally: sd.inwx_update(cfg, zone, host, "A", original) -- 2.36.6 From af8fe5e4c084b121ddd5dd0768142d8ee33efaa8 Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 14:19:43 +0200 Subject: [PATCH 07/10] feat: add proper logging --- snap_dyndns.py | 85 ++++++++++++++++++++++++++++++--------------- test_snap_dyndns.py | 43 ++++++++++++++++++++++- 2 files changed, 99 insertions(+), 29 deletions(-) diff --git a/snap_dyndns.py b/snap_dyndns.py index ba0c3bf..f0d195b 100644 --- a/snap_dyndns.py +++ b/snap_dyndns.py @@ -135,20 +135,27 @@ def inwx_update(cfg, zone, name, rtype, ip): # --- Request handling ------------------------------------------------------- -def _check_auth(env, cfg): - """Return the authenticated hostname or None.""" +def _check_auth(env, cfg, note): + """Return the authenticated hostname or None. note() gets the reason for a refusal.""" header = env.get("HTTP_AUTHORIZATION", "") if not header.lower().startswith("basic "): + note("badauth: missing or malformed Authorization header") return None try: user, _, token = base64.b64decode(header[6:]).decode().partition(":") except ValueError: + note("badauth: undecodable Authorization header") 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: + 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: return user.lower() return None @@ -171,15 +178,22 @@ def _save_state(path, state): os.replace(tmp, path) -def handle(env, cfg, update=inwx_update): - """Process one request. Return (http_status, body).""" +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) query = urllib.parse.parse_qs(env.get("QUERY_STRING", "")) - host = _check_auth(env, cfg) + host = _check_auth(env, cfg, note) if host is None: return 401, "badauth" requested = query.get("hostname", [host])[0].lower() if requested != host: + note( + f"{host}: nohost: hostname parameter {requested[:64]!r} does not match the login" + ) return 404, "nohost" # One IP per record type; without myip/myipv6 the connection's address is used. @@ -189,12 +203,12 @@ def handle(env, cfg, update=inwx_update): try: ip = ipaddress.ip_address(raw) except ValueError: + note(f"{host}: badip: invalid address {raw[:64]!r}") 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, + note( + f"{host}: badip: connection address {ip} is not global, check client_ip_header" ) return 400, "badip" # shortcut: explicit myip/myipv6 are only syntax-checked (private ranges accepted), tighten if clients misbehave @@ -209,21 +223,21 @@ def handle(env, cfg, update=inwx_update): with _STATE_LOCK: state = _load_state(state_path) for rtype, ip in ips.items(): - if state.get(host, {}).get(rtype) == ip: + old_ip = state.get(host, {}).get(rtype) + if old_ip == 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) + note(f"{host}: nohost: {e}") return 404, "nohost" except (InwxError, OSError, ValueError) as e: - print(f"snap-dyndns: {host}: {e}", file=sys.stderr) + note(f"{host}: 911: {rtype} update to {ip} failed: {e}") return 502, "911" # shortcut: cache goes stale if the record is edited by hand at INWX, delete state.json to resync - old_ip = state.get(host, {}).get(rtype, "unknown") - print(f"snap-dyndns: {host}: {rtype} {old_ip} -> {ip}", file=sys.stderr) + note(f"{host}: good {rtype} {old_ip or 'unknown'} -> {ip}") state.setdefault(host, {})[rtype] = ip _save_state(state_path, state) lines.append(f"good {ip}") @@ -256,23 +270,38 @@ class RequestHandler(http.server.BaseHTTPRequestHandler): url = urllib.parse.urlsplit(self.path) if url.path in ("/", "/nic", "/nic/"): return self._reply(200, INDEX_HTML, "text/html") + notes = [] + ip = self.client_address[0] if url.path != "/nic/update": - return self._reply(404, "not found") - 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) - 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" + 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) + 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") diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py index cd7e6f5..1d3fe80 100644 --- a/test_snap_dyndns.py +++ b/test_snap_dyndns.py @@ -7,8 +7,10 @@ INWX_OTE_HOST (an existing A record there) are set in the environment. """ import base64 +import contextlib import hashlib import http.client +import io import json import os import socket @@ -181,6 +183,7 @@ class FakeInwx(ThreadingHTTPServer): def __init__(self, tfa_secret=None): super().__init__(("127.0.0.1", 0), FakeInwxHandler) self.tfa_secret = tfa_secret + self.wrong_login = False self.unlocked = False self.calls = [] self.records = [ @@ -202,7 +205,7 @@ class FakeInwxHandler(BaseHTTPRequestHandler): srv.calls.append(method) cookie, code, res = None, 1000, {} if method == "account.login": - if (p["user"], p["pass"]) != ("u", "p"): + if srv.wrong_login or (p["user"], p["pass"]) != ("u", "p"): code = 2200 cookie = "sid=abc; Path=/" srv.unlocked = srv.tfa_secret is None @@ -392,6 +395,44 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" self.assertEqual((status, challenge), (200, None), path) self.assertIn("

Snap DynDNS Server

", body) + def logged(self, server, *args, **kw): + """Run get() and return (response, text written to stderr).""" + err = io.StringIO() + with contextlib.redirect_stderr(err): + response = self.get(server, *args, **kw) + return response, err.getvalue() + + def test_log_names_the_reason(self): + server = self.start(client_ip_header="X-Forwarded-For") + xff = {"X-Forwarded-For": "1.2.3.4"} + _, log = self.logged(server, Authorization=basic(HOST, "bad"), **xff) + self.assertRegex(log, rf"1\.2\.3\.4 401 {HOST}: badauth: wrong token") + _, log = self.logged(server, Authorization=basic("who.example.com", "x"), **xff) + self.assertIn("401 badauth: unknown host 'who.example.com'", log) + _, log = self.logged(server, "/nic/update?hostname=other.example.com", **xff) + self.assertIn( + "404 home.example.com: nohost: hostname parameter 'other.example.com'", log + ) + _, log = self.logged(server, **xff) + self.assertIn("200 home.example.com: good A unknown -> 1.2.3.4", log) + + def test_nochg_is_not_logged(self): + server = self.start(client_ip_header="X-Forwarded-For") + xff = {"X-Forwarded-For": "1.2.3.4"} + self.get(server, **xff) + response, log = self.logged(server, **xff) + self.assertEqual(response[2], "nochg 1.2.3.4\n") + self.assertEqual(log, "") + + def test_log_names_the_inwx_failure(self): + server = self.start(client_ip_header="X-Forwarded-For") + self.inwx.wrong_login = True + _, log = self.logged(server, **{"X-Forwarded-For": "1.2.3.4"}) + self.assertIn( + "502 home.example.com: 911: A update to 1.2.3.4 failed: account.login: 2200", + log, + ) + def test_other_paths_are_not_found(self): server = self.start() self.assertEqual(self.get(server, "/elsewhere")[0], 404) -- 2.36.6 From 835f1642d90274e6af1fe4947eda37eaead0e7ec Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 14:27:54 +0200 Subject: [PATCH 08/10] feat: helper script to create new records if they don't exist --- README.md | 10 ++++--- snap_dyndns.py | 30 +++++++++++++++++++- snap_dyndns_host.py | 54 +++++++++++++++++++++++++++++++++-- test_snap_dyndns.py | 61 +++++++++++++++++++++++++++++++++++++--- test_snap_dyndns_host.py | 55 ++++++++++++++++++++++++++++++++++++ 5 files changed, 198 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 05a911b..41ae864 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ It speaks the common dyndns2 protocol (HTTP Basic Auth, `myip`/`myipv6`, `good`/ 3. If the IP equals the last one it stored, it answers `nochg` right away. INWX is not contacted, so polling every minute is cheap. 4. Otherwise it logs in to INWX, looks up the record by name and type, updates it, and only then stores the new IP. If INWX fails, the device gets `911` and retries on its next run. -The record (A and/or AAAA) has to exist at INWX already. The server picks A or AAAA depending on the IP family, and keeps the TTL you set there. The connection to INWX uses IPv4 only, so an IP-restricted INWX API account only needs the server's IPv4 address on its allow-list. +The record (A and/or AAAA) has to exist at INWX; the helper script below creates it for new hosts. The server picks A or AAAA depending on the IP family, and keeps the TTL of the record. The connection to INWX uses IPv4 only, so an IP-restricted INWX API account only needs the server's IPv4 address on its allow-list. ## Requirements @@ -74,12 +74,14 @@ With another proxy, stop the service (`supervisorctl stop snap-dyndns`), run `nc ### Adding a device -The helper creates a random token, stores only its SHA-256 in the config and prints the token once: +The helper creates a random token, stores only its SHA-256 in the config, prints the token once, and makes sure the DNS record exists at INWX: ``` python3 ~/snap-dyndns-server/snap_dyndns_host.py user1.example.com ``` +If the A record does not exist at INWX yet, it is created with the TTL 300 and a placeholder address, which the first update of the device replaces. An existing record is left alone. Use `-t A,AAAA` to handle both types, `--ttl` for another TTL of new records, and `--no-dns` to skip INWX completely. If INWX cannot be reached, nothing is changed in the config. The helper needs the INWX login from the config and is therefore best run on the server itself, as an IP-restricted INWX account refuses logins from elsewhere. + Give the printed token to the device, for the [client](https://src.mehl.mx/mxmehl/snap-dyndns-client) it is the `hostname:token` entry shown in the output. For an existing host it asks before replacing the token (`-y` skips the question), and the old token stops working immediately. Use `-c` for a config in another location and `-z example.co.uk` for a new host whose INWX zone is not the last two labels of its name. Comments and the rest of the config stay untouched. The config is read on every request, so no restart is needed. The hostname is the Basic Auth user name, the token the password. Without the helper, generate a token and hash yourself with `python3 -c 'import secrets,hashlib;t=secrets.token_urlsafe(32);print(t, hashlib.sha256(t.encode()).hexdigest())'` and add a section `[hosts."user1.example.com"]` with `token_sha256 = ""`. @@ -133,7 +135,7 @@ user1.example.com ## Known limits - Explicit `myip`/`myipv6` values are only checked for syntax, private and reserved addresses are accepted there. -- Missing records are not created, add them at INWX first. +- The server itself never creates records, only the helper script does when adding a host. - If you change a record at INWX by hand, the server does not notice. Delete `state.json` or change the IP to resync. - Only one request updates at a time (a lock is held during the INWX call), which is plenty for a personal setup. - The built-in HTTP server is meant to sit behind a reverse proxy. Do not expose its port directly. @@ -144,7 +146,7 @@ user1.example.com uv run --python 3.14 python -m unittest -v ``` -The tests use a fake INWX server. An additional smoke test runs against the INWX OT&E test system and is skipped unless `INWX_OTE_USER`, `INWX_OTE_PASS` and `INWX_OTE_HOST` (an existing A record in that account) are set in the environment. It restores the record afterwards. +The tests use a fake INWX server. An additional smoke test runs against the INWX OT&E test system and is skipped unless `INWX_OTE_USER`, `INWX_OTE_PASS` and `INWX_OTE_HOST` (an existing A record in that account) are set in the environment. It restores the record afterwards and removes the record it creates for the helper test. ## License diff --git a/snap_dyndns.py b/snap_dyndns.py index f0d195b..e6cd9bf 100644 --- a/snap_dyndns.py +++ b/snap_dyndns.py @@ -132,6 +132,34 @@ def inwx_update(cfg, zone, name, rtype, ip): return True +PLACEHOLDER = {"A": "192.0.2.1", "AAAA": "2001:db8::1"} # documentation addresses + + +def zone_of(host, entry): + """INWX zone of a hostname: the host's `zone` setting, else its last two labels.""" + return entry.get("zone") or ".".join(host.split(".")[-2:]) + + +def ensure_record(cfg, zone, name, rtype, ttl=300): + """Create the record with a placeholder address if missing. Return (created, record).""" + with inwx_session(cfg) as call: + try: + return False, find_record(call, zone, name, rtype) + except NoHost: + content = PLACEHOLDER[rtype] + call( + "nameserver.createRecord", + { + "domain": zone, + "type": rtype, + "name": name, + "content": content, + "ttl": ttl, + }, + ) + return True, {"content": content, "ttl": ttl} + + # --- Request handling ------------------------------------------------------- @@ -214,7 +242,7 @@ def handle(env, cfg, update=inwx_update, note=None): # 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:]) + zone = zone_of(host, cfg["hosts"][host]) state_path = os.path.expanduser(cfg.get("state_file", DEFAULT_STATE)) os.makedirs(os.path.dirname(state_path), exist_ok=True) diff --git a/snap_dyndns_host.py b/snap_dyndns_host.py index 81b9ea2..68db4ca 100755 --- a/snap_dyndns_host.py +++ b/snap_dyndns_host.py @@ -5,6 +5,7 @@ Generates a random token, stores only its SHA-256 in the config and prints the token once. The token is what the client needs; the server never sees it again. +Also makes sure the DNS record exists at INWX, which needs the server's IP. """ import argparse @@ -16,7 +17,7 @@ import sys import tempfile import tomllib -from snap_dyndns import DEFAULT_CONFIG +from snap_dyndns import DEFAULT_CONFIG, InwxError, ensure_record, zone_of NAME = re.compile(r"^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$") @@ -90,6 +91,23 @@ def main(argv=None): action="store_true", help="replace the token of an existing host without asking", ) + parser.add_argument( + "-t", + "--types", + default="A", + help="record types to check and create, A or AAAA or A,AAAA (default: A)", + ) + parser.add_argument( + "--ttl", + type=int, + default=300, + help="TTL of records created at INWX (default: 300)", + ) + parser.add_argument( + "--no-dns", + action="store_true", + help="do not touch INWX, e.g. when not running on the server", + ) parser.add_argument( "-z", "--zone", @@ -101,6 +119,9 @@ def main(argv=None): for value in (host, args.zone): if value and not NAME.match(value): sys.exit(f"invalid name: {value}") + types = [t.strip().upper() for t in args.types.split(",")] + if not set(types) <= {"A", "AAAA"}: + sys.exit(f"invalid record types: {args.types}") path = os.path.expanduser(args.config) token = secrets.token_urlsafe(32) @@ -116,11 +137,38 @@ def main(argv=None): ): sys.exit("Aborted, config unchanged") new_text, created = set_host(text, host, digest, args.zone) - tomllib.loads(new_text) # never write a config that does not parse - write_config(path, new_text) + cfg = tomllib.loads(new_text) # never write a config that does not parse except (OSError, ValueError) as e: # TOMLDecodeError is a ValueError sys.exit(f"{path}: {e}") + # DNS first: if INWX is not reachable, nothing has been changed yet + if not args.no_dns: + zone = zone_of(host, cfg["hosts"][host]) + try: + for rtype in types: + was_created, record = ensure_record(cfg, zone, host, rtype, args.ttl) + if was_created: + print( + f"DNS: created {rtype} record {host} ({record['content']} is a placeholder, " + f"TTL {record['ttl']}), the first update sets the real address" + ) + else: + print( + f"DNS: {rtype} record {host} exists " + f"({record['content']}, TTL {record.get('ttl')})" + ) + except (InwxError, OSError, KeyError, ValueError) as e: + sys.exit( + f"INWX: {type(e).__name__}: {e}\nNothing was changed in the config. The INWX " + "account is usually restricted to the server's IP, so run this there, " + "or use --no-dns." + ) + + try: + write_config(path, new_text) + except OSError as e: + sys.exit(f"{path}: {e}") + print(f"{'Added' if created else 'Replaced the token of'} {host} in {path}") print("The server reads the config on every request, no restart needed.") print(f"Token (shown only once): {token}") diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py index 1d3fe80..555f39f 100644 --- a/test_snap_dyndns.py +++ b/test_snap_dyndns.py @@ -13,6 +13,7 @@ import http.client import io import json import os +import secrets import socket import tempfile import threading @@ -229,6 +230,13 @@ class FakeInwxHandler(BaseHTTPRequestHandler): if r["name"] == p["name"] and r["type"] == p["type"] ] } + elif method == "nameserver.createRecord": + srv.records.append( + { + "id": 100 + len(srv.records), + **{k: p[k] for k in ("name", "type", "content", "ttl")}, + } + ) elif method == "nameserver.updateRecord": for r in srv.records: if r["id"] == p["id"]: @@ -283,6 +291,27 @@ class InwxClientTest(unittest.TestCase): sd.inwx_update(self.cfg(srv), "example.com", HOST, "A", "1.2.3.4") self.assertEqual(srv.calls[-1], "account.logout") + def test_ensure_record_creates_missing_record_once(self): + srv = self.start() + created, record = sd.ensure_record(self.cfg(srv), "example.com", HOST, "AAAA") + self.assertEqual( + (created, record), (True, {"content": sd.PLACEHOLDER["AAAA"], "ttl": 300}) + ) + self.assertEqual(srv.records[-1]["ttl"], 300) + self.assertEqual( + sd.ensure_record(self.cfg(srv), "example.com", HOST, "AAAA")[0], False + ) + self.assertEqual(srv.calls.count("nameserver.createRecord"), 1) + + def test_ensure_record_keeps_existing_record(self): + srv = self.start() + created, record = sd.ensure_record( + self.cfg(srv), "example.com", HOST, "A", ttl=60 + ) + self.assertFalse(created) + self.assertEqual(record["content"], "10.0.0.1") + self.assertNotIn("nameserver.createRecord", srv.calls) + def test_missing_record(self): srv = self.start() with self.assertRaises(sd.NoHost): @@ -460,16 +489,21 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" "set INWX_OTE_USER, INWX_OTE_PASS, INWX_OTE_HOST to run against the INWX OT&E system", ) class OteSmokeTest(unittest.TestCase): - def test_lookup_by_name_and_update(self): - host = os.environ["INWX_OTE_HOST"].lower() - zone = os.environ.get("INWX_OTE_ZONE") or ".".join(host.split(".")[-2:]) - cfg = { + def setUp(self): + self.host = os.environ["INWX_OTE_HOST"].lower() + self.zone = os.environ.get("INWX_OTE_ZONE") or ".".join( + self.host.split(".")[-2:] + ) + self.cfg = { "inwx": { "user": os.environ["INWX_OTE_USER"], "pass": os.environ["INWX_OTE_PASS"], "api": "https://api.ote.domrobot.com/jsonrpc/", } } + + def test_lookup_by_name_and_update(self): + cfg, zone, host = self.cfg, self.zone, self.host with sd.inwx_session(cfg) as call: original = sd.find_record(call, zone, host, "A")["content"] test_ip = "192.0.2.1" if original != "192.0.2.1" else "192.0.2.2" @@ -482,6 +516,25 @@ class OteSmokeTest(unittest.TestCase): finally: sd.inwx_update(cfg, zone, host, "A", original) + def test_ensure_record_creates_once_and_is_cleaned_up(self): + cfg, zone = self.cfg, self.zone + name = f"snap-test-{secrets.token_hex(3)}.{zone}" + try: + self.assertTrue(sd.ensure_record(cfg, zone, name, "A")[0]) + with sd.inwx_session(cfg) as call: + record = sd.find_record(call, zone, name, "A") + self.assertEqual( + (record["content"], int(record["ttl"])), (sd.PLACEHOLDER["A"], 300) + ) + self.assertFalse(sd.ensure_record(cfg, zone, name, "A")[0]) + finally: + with ( + sd.inwx_session(cfg) as call, + contextlib.suppress(sd.NoHost), + ): + record = sd.find_record(call, zone, name, "A") + call("nameserver.deleteRecord", {"id": record["id"]}) + if __name__ == "__main__": unittest.main() diff --git a/test_snap_dyndns_host.py b/test_snap_dyndns_host.py index ed28395..319daa6 100644 --- a/test_snap_dyndns_host.py +++ b/test_snap_dyndns_host.py @@ -80,6 +80,14 @@ class MainTest(unittest.TestCase): with open(self.path, "w") as f: f.write(CONFIG) os.chmod(self.path, 0o600) + # Never talk to the real INWX from tests + patcher = mock.patch.object( + sh, + "ensure_record", + return_value=(True, {"content": "192.0.2.1", "ttl": 300}), + ) + self.ensure = patcher.start() + self.addCleanup(patcher.stop) def run_main(self, *args): out = io.StringIO() @@ -126,6 +134,53 @@ class MainTest(unittest.TestCase): with open(self.path, "rb") as f: return tomllib.load(f)["hosts"][host]["token_sha256"] + def test_creates_missing_record_with_default_ttl(self): + output = self.run_main("fresh.example.com") + args = self.ensure.call_args.args + self.assertEqual(args[1:], ("example.com", "fresh.example.com", "A", 300)) + self.assertIn("DNS: created A record fresh.example.com", output) + + def test_types_ttl_and_zone_are_passed_on(self): + self.run_main( + "fresh.example.co.uk", "-z", "example.co.uk", "-t", "a,aaaa", "--ttl", "60" + ) + calls = [c.args[1:] for c in self.ensure.call_args_list] + self.assertEqual( + calls, + [ + ("example.co.uk", "fresh.example.co.uk", "A", 60), + ("example.co.uk", "fresh.example.co.uk", "AAAA", 60), + ], + ) + + def test_existing_record_is_reported_not_changed(self): + self.ensure.return_value = (False, {"content": "1.2.3.4", "ttl": 3600}) + output = self.run_main("fresh.example.com") + self.assertIn("A record fresh.example.com exists (1.2.3.4, TTL 3600)", output) + + def test_zone_of_existing_host_comes_from_config(self): + self.run_main("b.example.com", "--yes") + self.assertEqual(self.ensure.call_args.args[1], "example.com") + + def test_no_dns_skips_inwx(self): + self.run_main("fresh.example.com", "--no-dns") + self.ensure.assert_not_called() + + def test_inwx_failure_changes_nothing(self): + self.ensure.side_effect = sh.InwxError( + "account.login: 2200 Authentication error" + ) + with self.assertRaises(SystemExit) as ctx: + self.run_main("fresh.example.com") + self.assertIn("Nothing was changed", str(ctx.exception)) + with open(self.path) as f: + self.assertEqual(f.read(), CONFIG) + + def test_invalid_record_type(self): + with self.assertRaises(SystemExit): + self.run_main("fresh.example.com", "-t", "MX") + self.ensure.assert_not_called() + def test_invalid_hostname_leaves_config_untouched(self): for bad in ('x"] \n[evil', "no_dots", "a..b", "-a.example.com"): with self.assertRaises(SystemExit): -- 2.36.6 From d51185078fa19491f068fd4b1c23add470db4223 Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 14:33:47 +0200 Subject: [PATCH 09/10] chore: adapt logging line --- snap_dyndns.py | 2 +- test_snap_dyndns.py | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/snap_dyndns.py b/snap_dyndns.py index e6cd9bf..e9c7b34 100644 --- a/snap_dyndns.py +++ b/snap_dyndns.py @@ -322,7 +322,7 @@ class RequestHandler(http.server.BaseHTTPRequestHandler): # 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)}", + f"{time.strftime('[%Y-%m-%d %H:%M:%S]')} {ip}: {status} - {'; '.join(notes)}", file=sys.stderr, ) self._reply(status, body) diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py index 555f39f..92d824b 100644 --- a/test_snap_dyndns.py +++ b/test_snap_dyndns.py @@ -435,15 +435,19 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" server = self.start(client_ip_header="X-Forwarded-For") xff = {"X-Forwarded-For": "1.2.3.4"} _, log = self.logged(server, Authorization=basic(HOST, "bad"), **xff) - self.assertRegex(log, rf"1\.2\.3\.4 401 {HOST}: badauth: wrong token") + self.assertRegex( + log, + rf"^\[\d{{4}}-\d\d-\d\d \d\d:\d\d:\d\d\] 1\.2\.3\.4: 401 - {HOST}: badauth: wrong token\n$", + ) _, log = self.logged(server, Authorization=basic("who.example.com", "x"), **xff) - self.assertIn("401 badauth: unknown host 'who.example.com'", log) + self.assertIn("1.2.3.4: 401 - badauth: unknown host 'who.example.com'", log) _, log = self.logged(server, "/nic/update?hostname=other.example.com", **xff) self.assertIn( - "404 home.example.com: nohost: hostname parameter 'other.example.com'", log + "1.2.3.4: 404 - home.example.com: nohost: hostname parameter 'other.example.com'", + log, ) _, log = self.logged(server, **xff) - self.assertIn("200 home.example.com: good A unknown -> 1.2.3.4", log) + self.assertIn("1.2.3.4: 200 - home.example.com: good A unknown -> 1.2.3.4", log) def test_nochg_is_not_logged(self): server = self.start(client_ip_header="X-Forwarded-For") @@ -458,7 +462,7 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" self.inwx.wrong_login = True _, log = self.logged(server, **{"X-Forwarded-For": "1.2.3.4"}) self.assertIn( - "502 home.example.com: 911: A update to 1.2.3.4 failed: account.login: 2200", + "1.2.3.4: 502 - home.example.com: 911: A update to 1.2.3.4 failed: account.login: 2200", log, ) -- 2.36.6 From ccfe8f37c96233af4622781398c426e716f02a70 Mon Sep 17 00:00:00 2001 From: Max Mehl Date: Thu, 22 Oct 2026 15:09:08 +0200 Subject: [PATCH 10/10] chore: add note on missing records --- snap_dyndns.py | 2 +- test_snap_dyndns.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/snap_dyndns.py b/snap_dyndns.py index e9c7b34..76a0497 100644 --- a/snap_dyndns.py +++ b/snap_dyndns.py @@ -259,7 +259,7 @@ def handle(env, cfg, update=inwx_update, note=None): update(cfg, zone, host, rtype, ip) except NoHost as e: # shortcut: missing records are not created, add nameserver.createRecord if wanted - note(f"{host}: nohost: {e}") + note(f"{host}: nohost: {e}, create it at INWX first") return 404, "nohost" except (InwxError, OSError, ValueError) as e: note(f"{host}: 911: {rtype} update to {ip} failed: {e}") diff --git a/test_snap_dyndns.py b/test_snap_dyndns.py index 92d824b..f4ebb94 100644 --- a/test_snap_dyndns.py +++ b/test_snap_dyndns.py @@ -449,6 +449,26 @@ token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" _, log = self.logged(server, **xff) self.assertIn("1.2.3.4: 200 - home.example.com: good A unknown -> 1.2.3.4", log) + def test_log_names_the_missing_record(self): + server = self.start(client_ip_header="X-Forwarded-For") + # Only an A record exists, the device also reports IPv6 + response, log = self.logged( + server, **{"X-Forwarded-For": "2606:4700:4700::1111"} + ) + self.assertEqual(response[0], 404) + self.assertIn( + "2606:4700:4700::1111: 404 - home.example.com: nohost: " + "no AAAA record home.example.com in zone example.com, create it at INWX first", + log, + ) + + def test_log_reports_both_results_of_a_combined_request(self): + server = self.start() + query = f"/nic/update?hostname={HOST}&myip=1.2.3.4&myipv6=2606:4700:4700::1111" + _, log = self.logged(server, query) + self.assertIn("good A unknown -> 1.2.3.4; ", log) + self.assertIn("nohost: no AAAA record", log) + def test_nochg_is_not_logged(self): server = self.start(client_ip_header="X-Forwarded-For") xff = {"X-Forwarded-For": "1.2.3.4"} -- 2.36.6

This is a Dynamic DNS service. It is running with the Snap DynDNS Server software.