#!/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()