Files
snap-dyndns-server/snap_dyndns_host.py
T
mxmehl 0cd8438ab3 feat!: complete refactoring of server (#1)
* make a python server
* improve authentication by token/hash
* better logging
* add helper tool for new hosts

Reviewed-on: #1
Co-authored-by: Max Mehl <mail@mehl.mx>
2026-10-22 15:35:54 +02:00

180 lines
6.1 KiB
Python
Executable File

#!/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.
Also makes sure the DNS record exists at INWX, which needs the server's IP.
"""
import argparse
import hashlib
import os
import re
import secrets
import sys
import tempfile
import tomllib
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])?)+$")
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 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(
"-y",
"--yes",
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",
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}")
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)
digest = hashlib.sha256(token.encode()).hexdigest()
try:
with open(path) as f:
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)
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}")
print(f"Client entry for HOSTS: {host}:{token}")
if __name__ == "__main__":
main()