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>
This commit was merged in pull request #1.
This commit is contained in:
1 parent
a1c55f4574
commit
0cd8438ab3
15 files changed
+1485
-327
No files matched your search
+382
@@ -0,0 +1,382 @@
|
||||
# SPDX-FileCopyrightText: 2016 Max Mehl <mail@mehl.mx>
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""Snap DynDNS Server: dyndns2-style HTTP service that updates INWX records.
|
||||
|
||||
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 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
|
||||
import urllib.request
|
||||
from typing import cast
|
||||
|
||||
API_LIVE = "https://api.domrobot.com/jsonrpc/"
|
||||
DEFAULT_CONFIG = "~/etc/snap-dyndns/config.toml"
|
||||
DEFAULT_STATE = "~/etc/snap-dyndns/state.json"
|
||||
|
||||
|
||||
class InwxError(Exception):
|
||||
"""INWX API call failed. Messages must never contain credentials."""
|
||||
|
||||
|
||||
class NoHost(InwxError):
|
||||
"""The record to update does not exist at INWX."""
|
||||
|
||||
|
||||
# --- INWX JSON-RPC client ---------------------------------------------------
|
||||
|
||||
|
||||
def totp(secret, now=None):
|
||||
"""RFC 6238 code (HMAC-SHA1, 30 s step, 6 digits) for a base32 secret."""
|
||||
key = base64.b32decode(secret.replace(" ", "").upper())
|
||||
counter = int((time.time() if now is None else now) // 30)
|
||||
digest = hmac.new(key, struct.pack(">Q", counter), hashlib.sha1).digest()
|
||||
offset = digest[-1] & 15
|
||||
code = (struct.unpack(">I", digest[offset : offset + 4])[0] & 0x7FFFFFFF) % 10**6
|
||||
return f"{code:06d}"
|
||||
|
||||
|
||||
class _IPv4Https(urllib.request.HTTPSHandler):
|
||||
"""HTTPS that only connects via IPv4.
|
||||
|
||||
The INWX API account is restricted to the server's IPv4 address, but the
|
||||
process may prefer IPv6 for dual-stack hosts. Binding to 0.0.0.0 makes
|
||||
socket.create_connection() skip every IPv6 address.
|
||||
"""
|
||||
|
||||
def https_open(self, req):
|
||||
return self.do_open(
|
||||
http.client.HTTPSConnection,
|
||||
req,
|
||||
context=ssl.create_default_context(),
|
||||
source_address=("0.0.0.0", 0),
|
||||
)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def inwx_session(cfg):
|
||||
"""Yield call(method, params) -> resData for a logged-in INWX session."""
|
||||
inwx = cfg["inwx"]
|
||||
url = inwx.get("api", API_LIVE)
|
||||
opener = urllib.request.build_opener(
|
||||
_IPv4Https, urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
|
||||
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 -------------------------------------------------------
|
||||
|
||||
|
||||
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.
|
||||
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
|
||||
|
||||
|
||||
_STATE_LOCK = threading.Lock()
|
||||
|
||||
|
||||
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, 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, 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.
|
||||
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:
|
||||
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:
|
||||
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
|
||||
ips["A" if ip.version == 4 else "AAAA"] = str(ip)
|
||||
|
||||
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)
|
||||
|
||||
lines = []
|
||||
# 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():
|
||||
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
|
||||
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}")
|
||||
return 502, "911"
|
||||
# shortcut: cache goes stale if the record is edited by hand at INWX, delete state.json to resync
|
||||
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}")
|
||||
return 200, "\n".join(lines)
|
||||
|
||||
|
||||
INDEX_HTML = """<!DOCTYPE html>
|
||||
<html lang="en-GB">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Snap DynDNS Server</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Snap DynDNS Server</h1>
|
||||
<p>This is a Dynamic DNS service. It is running with the <a href="https://src.mehl.mx/mxmehl/snap-dyndns-server">Snap DynDNS Server</a> software.</p>
|
||||
<p>Please contact the site owner for more information on this specific service.</p>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
|
||||
class Server(http.server.ThreadingHTTPServer):
|
||||
config_path: str
|
||||
|
||||
|
||||
class RequestHandler(http.server.BaseHTTPRequestHandler):
|
||||
timeout = 30 # do not let stalled connections hold a thread forever
|
||||
|
||||
def do_GET(self):
|
||||
url = urllib.parse.urlsplit(self.path)
|
||||
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":
|
||||
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")
|
||||
if name:
|
||||
return self.headers.get(name, "").split(",")[-1].strip()
|
||||
return self.client_address[0]
|
||||
|
||||
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", f"{content_type}; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
if status == 401:
|
||||
self.send_header("WWW-Authenticate", 'Basic realm="Snap DynDNS"')
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
def make_server(config_path, port, host="0.0.0.0"):
|
||||
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)"
|
||||
)
|
||||
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:
|
||||
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()
|
||||
Reference in new issue
Block a user