chore: rewrite as service, as CGI caused too many issues

This commit is contained in:
mxmehl committed 2026-10-22 13:49:04 +02:00
1 parent 9314781b08
commit 7a2d7c6650
9 files changed
+413 -107

No files matched your search

-1
View File
@@ -1,6 +1,5 @@
__pycache__/ __pycache__/
config.toml config.toml
state.json state.json
state.json.lock
state.json.tmp state.json.tmp
.env .env
-15
View File
@@ -1,15 +0,0 @@
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# 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
<FilesMatch "^(?!update\.cgi$)">
Require all denied
</FilesMatch>
+55 -31
View File
@@ -1,70 +1,94 @@
# Snap DynDNS Server using INWX domains # 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. 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 ## 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. 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. 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. 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 ## Requirements
- Apache with CGI and `.htaccess` support (Uberspace 7 has both)
- Python 3.11 or newer, no packages needed - 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 ## 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 and make it private:
Create the config **outside** the web root and make it private:
``` ```
mkdir -p ~/etc/snap-dyndns 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 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 <ip>` 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 ### 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 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 = "<hash>"`.
[hosts."user1.example.com"]
token_sha256 = "<hash>"
```
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 ## Usage
With curl (the `-u` option keeps the credentials out of the URL): 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://yourdyndnsservice.net/nic/update"
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?myip=1.2.3.4"
``` ```
Parameters, all optional: Parameters, all optional:
@@ -79,15 +103,15 @@ Answers (HTTP status in brackets):
- `nochg <ip>` (200): the IP is what the server stored last, INWX was not contacted - `nochg <ip>` (200): the IP is what the server stored last, INWX was not contacted
- `badauth` (401): unknown hostname or wrong token - `badauth` (401): unknown hostname or wrong token
- `nohost` (404): hostname mismatch, or the record does not exist at INWX - `nohost` (404): hostname mismatch, or the record does not exist at INWX
- `badip` (400): the IP could not be parsed - `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 Apache error log - `911` (502 or 500): INWX or the server config failed, see the log
### AVM FritzBox ### AVM FritzBox
Choose a custom DynDNS provider: Choose a custom DynDNS provider:
``` ```
Update-URL: https://dyndns.mydomain.net/update.cgi?hostname=<domain>&myip=<ipaddr>&myipv6=<ip6addr> Update-URL: https://yourdyndnsservice.net/nic/update?hostname=<domain>&myip=<ipaddr>&myipv6=<ip6addr>
Domain name: user1.example.com Domain name: user1.example.com
User name: user1.example.com User name: user1.example.com
Password: TOKEN Password: TOKEN
@@ -97,8 +121,7 @@ Password: TOKEN
``` ```
protocol=dyndns2 protocol=dyndns2
server=dyndns.mydomain.net server=yourdyndnsservice.net
script=/dyn/update.cgi
ssl=yes ssl=yes
login=user1.example.com login=user1.example.com
password=TOKEN password=TOKEN
@@ -107,10 +130,11 @@ user1.example.com
## Known limits ## 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. - 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. - 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 ## Development
+6
View File
@@ -3,6 +3,12 @@
# Where the last known IPs are cached (default shown) # Where the last known IPs are cached (default shown)
state_file = "~/etc/snap-dyndns/state.json" 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] [inwx]
user = "api-user" user = "api-user"
pass = "api-password" pass = "api-password"
+78 -25
View File
@@ -1,26 +1,28 @@
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx> # SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# SPDX-License-Identifier: AGPL-3.0-or-later # 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). Clients authenticate with HTTP Basic Auth (user = hostname, password = token).
The INWX credentials never leave this server, and INWX is only contacted when The INWX credentials never leave this server, and INWX is only contacted when
the IP of a hostname actually changed. the IP of a hostname actually changed.
""" """
import argparse
import base64 import base64
import contextlib import contextlib
import fcntl
import hashlib import hashlib
import hmac import hmac
import http import http
import http.client import http.client
import http.cookiejar import http.cookiejar
import http.server
import ipaddress import ipaddress
import json import json
import os import os
import ssl import ssl
import struct import struct
import sys import sys
import threading
import time import time
import tomllib import tomllib
import urllib.parse import urllib.parse
@@ -55,8 +57,8 @@ def totp(secret, now=None):
class _IPv4Https(urllib.request.HTTPSHandler): class _IPv4Https(urllib.request.HTTPSHandler):
"""HTTPS that only connects via IPv4. """HTTPS that only connects via IPv4.
The INWX API account is restricted to the server's IPv4 address, but a The INWX API account is restricted to the server's IPv4 address, but the
confined CGI process may prefer IPv6. Binding to 0.0.0.0 makes process may prefer IPv6 for dual-stack hosts. Binding to 0.0.0.0 makes
socket.create_connection() skip every IPv6 address. socket.create_connection() skip every IPv6 address.
""" """
@@ -150,6 +152,9 @@ def _check_auth(env, cfg):
return None return None
_STATE_LOCK = threading.Lock()
def _load_state(path): def _load_state(path):
try: try:
with open(path) as f: with open(path) as f:
@@ -184,7 +189,11 @@ def handle(env, cfg, update=inwx_update):
ip = ipaddress.ip_address(raw) ip = ipaddress.ip_address(raw)
except ValueError: except ValueError:
return 400, "badip" 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) ips["A" if ip.version == 4 else "AAAA"] = str(ip)
zone = cfg["hosts"][host].get("zone") or ".".join(host.split(".")[-2:]) 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) os.makedirs(os.path.dirname(state_path), exist_ok=True)
lines = [] lines = []
# shortcut: lock is held during the INWX call, fine at this load, split if updates ever get slow # shortcut: one lock held during the INWX call, fine at this load, split per host if updates get slow
with open(f"{state_path}.lock", "a") as lock: with _STATE_LOCK:
fcntl.flock(lock, fcntl.LOCK_EX)
state = _load_state(state_path) state = _load_state(state_path)
for rtype, ip in ips.items(): for rtype, ip in ips.items():
if state.get(host, {}).get(rtype) == ip: if state.get(host, {}).get(rtype) == ip:
@@ -216,21 +224,66 @@ def handle(env, cfg, update=inwx_update):
return 200, "\n".join(lines) return 200, "\n".join(lines)
def main(env=os.environ, out=sys.stdout): class RequestHandler(http.server.BaseHTTPRequestHandler):
"""CGI entry point.""" timeout = 30 # do not let stalled connections hold a thread forever
try:
path = os.path.expanduser(env.get("SNAP_DYNDNS_CONFIG", DEFAULT_CONFIG)) 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: with open(path, "rb") as f:
cfg = tomllib.load(f) tomllib.load(f)
status, body = handle(env, cfg) except (OSError, tomllib.TOMLDecodeError) as e:
except Exception as e: # noqa: BLE001 - a CGI must always answer sys.exit(f"snap-dyndns: cannot use config {path}: {e}")
print(f"snap-dyndns: {type(e).__name__}: {e}", file=sys.stderr) make_server(path, args.port).serve_forever()
status, body = 500, "911"
headers = [
f"Status: {status} {http.HTTPStatus(status).phrase}", if __name__ == "__main__":
"Content-Type: text/plain; charset=utf-8", main()
"Cache-Control: no-store",
]
if status == 401:
headers.append('WWW-Authenticate: Basic realm="Snap DynDNS"')
out.write("\n".join(headers) + "\n\n" + body + "\n")
+96
View File
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# 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()
+71 -25
View File
@@ -9,7 +9,6 @@ INWX_OTE_HOST (an existing A record there) are set in the environment.
import base64 import base64
import hashlib import hashlib
import http.client import http.client
import io
import json import json
import os import os
import socket import socket
@@ -79,7 +78,7 @@ class HandleTest(unittest.TestCase):
self.assertEqual(len(self.calls), 2) self.assertEqual(len(self.calls), 2)
def test_ipv6_connection_updates_aaaa(self): 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") self.assertEqual(self.calls[0][2], "AAAA")
def test_myip_overrides_remote_addr(self): def test_myip_overrides_remote_addr(self):
@@ -112,6 +111,14 @@ class HandleTest(unittest.TestCase):
def test_hostname_mismatch(self): 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", ""):
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): 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, []) self.assertEqual(self.calls, [])
@@ -273,41 +280,80 @@ class InwxClientTest(unittest.TestCase):
self.assertEqual(srv.calls.count("account.login"), 1) self.assertEqual(srv.calls.count("account.login"), 1)
class MainTest(unittest.TestCase): class ServerTest(unittest.TestCase):
def run_main(self, env, cfg_text): """Real HTTP requests against make_server() with a fake INWX behind it."""
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""" def start(self, **config):
state_file = "STATE" 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] [inwx]
user = "u" user = "u"
pass = "p" pass = "p"
api = "http://127.0.0.1:1/" api = "{inwx.url}"
[hosts."{HOST}"] [hosts."{HOST}"]
token_sha256 = "{hashlib.sha256(TOKEN.encode()).hexdigest()}" 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): def test_unauthorized_has_challenge(self):
out = self.run_main(make_env(auth=basic(HOST, "bad")), self.CFG) server = self.start()
head, _, body = out.partition("\n\n") status, challenge, body = self.get(server, Authorization=basic(HOST, "bad"))
self.assertTrue(head.startswith("Status: 401 Unauthorized")) self.assertEqual((status, challenge, body), (401, 'Basic realm="Snap DynDNS"', "badauth\n"))
self.assertIn('WWW-Authenticate: Basic realm="Snap DynDNS"', head)
self.assertEqual(body, "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): def test_unreachable_inwx_is_911(self):
out = self.run_main(make_env(), self.CFG) server = self.start(client_ip_header="X-Forwarded-For")
self.assertTrue(out.startswith("Status: 502 Bad Gateway\n")) self.inwx.shutdown()
self.assertTrue(out.endswith("\n\n911\n")) 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): def test_broken_config_is_500(self):
out = self.run_main(make_env(), "not = [valid") server = self.start()
self.assertTrue(out.startswith("Status: 500 Internal Server Error\n")) 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( @unittest.skipUnless(
+107
View File
@@ -0,0 +1,107 @@
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# 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()
-10
View File
@@ -1,10 +0,0 @@
#!/usr/bin/python3.14
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
# 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()