ddns: take the public IP from Njal.la only and give it to LiveKit

The Hub no longer asks a STUN server, a public DNS resolver or a "what
is my IP" service for the home IP address. The DDNS update asks Njal.la
to use the address the request comes from ("&auto"), reads back the
address Njal.la says it recorded and saves it to
/var/lib/secrets/external-ip. Njal.la is the only third party that
learns the address; it has to, to publish it.

- Add app/sovran_systemsos_web/ddns_update.py, installed as
  /etc/sovran/ddns-update.py and run by sovran-ddns-update.service. It
  runs curl --ipv4 without redirects, accepts only a public IPv4
  address, and rewrites the file atomically and only when the address
  changes. Stored "&a=${IP}" URLs are converted when they are used and
  "&quiet" is dropped.
- Rewrite modules/core/njalla.nix around that runner and delete
  modules/core/public-ip.nix. Setting a sovran_systemsOS.publicIP.*
  option now fails with a message that says where the address comes
  from. Activation removes the old scripts in /var/lib/sovran. The
  existing external-ip file keeps working.
- server.py reads the saved address and starts
  sovran-ddns-update.service after a domain is saved, instead of looking
  the address up itself.
- Element calling uses sovran_systemsOS.elementCalling.externalIP if
  set, otherwise the saved address, and fails with a clear message when
  neither exists or the address is not public. It no longer falls back
  to STUN. livekit-external-ip.path re-runs livekit-turn-setup and
  starts LiveKit when the address changes.
- Add tests/test_ddns_update.py.
This commit is contained in:
Arena.ai Agent
2026-10-01 21:43:47 -05:00
committed by naturallaw777
parent 726fec1990
commit 2d777450e1
8 changed files with 538 additions and 539 deletions
+33 -89
View File
@@ -1,43 +1,64 @@
{ config, pkgs, lib, ... }:
{
# The public-IP detector (STUN / OpenDNS / HTTPS echo) is gone: the public
# address is whatever Njal.la reports back for the DDNS update below, and
# nothing else on the system looks it up. Fail with a pointer, instead of
# silently ignoring them, if a custom.nix still sets one of its old options.
imports = map (opt:
lib.mkRemovedOptionModule [ "sovran_systemsOS" "publicIP" opt ]
"Sovran no longer looks up the public IP: the Njal.la DDNS update reports it (modules/core/njalla.nix). To force an address for Element Calling, set sovran_systemsOS.elementCalling.externalIP."
) [ "stunServer" "stunPort" "dnsResolver" "httpsEcho" "cacheTTL" ];
# ── Ensure njalla directory exists on every build ────────────────────────
systemd.tmpfiles.rules = [
"d /var/lib/njalla 0750 root root -"
];
# ── Install the shared validation helper so the DDNS runner can import it ─
# The exact same _validate_ddns_url() function used by the Hub web application
# is installed here as a read-only system file. The DDNS runner imports it
# directly so the two code paths share one validator — no weaker inline copy.
# ── Install the DDNS runner and the validator it shares with the Hub ─────
# Both files come straight from the Hub's source tree and are installed side
# by side as read-only system files. The runner imports the exact same
# _validate_ddns_url() the Hub API uses — no weaker inline copy.
environment.etc."sovran/security_helpers.py" = {
source = ../../app/sovran_systemsos_web/security_helpers.py;
mode = "0444";
user = "root";
group = "root";
};
environment.etc."sovran/ddns-update.py" = {
source = ../../app/sovran_systemsos_web/ddns_update.py;
mode = "0444";
user = "root";
group = "root";
};
# ── Safe DDNS update service ─────────────────────────────────────────────
# Reads DDNS update URLs from the JSON store written by the Hub API and
# invokes curl directly — no shell interpolation, no script execution.
# Replaces the legacy root cron job that ran /var/lib/njalla/njalla.sh.
# Njal.la is asked to use the address the request came from ("&auto") and
# reports it back; the runner saves it to /var/lib/secrets/external-ip,
# where LiveKit and the Hub read it. See app/sovran_systemsos_web/ddns_update.py.
systemd.services.sovran-ddns-update = {
description = "Sovran Njal.la DDNS update (safe JSON-based runner)";
wants = [ "network-online.target" ];
after = [ "network-online.target" ];
# curl is not in a NixOS unit's default PATH (coreutils, findutils, grep,
# sed, systemd): without this the runner cannot start it.
path = [ pkgs.curl ];
serviceConfig = {
Type = "oneshot";
User = "root";
ExecStart = "${pkgs.python3}/bin/python3 /var/lib/sovran/ddns-update.py";
# Harden the service — it only needs network access and read access to
# /var/lib/njalla/ddns_urls.json.
ExecStart = "${pkgs.python3}/bin/python3 /etc/sovran/ddns-update.py";
# Harden the service — it needs network access, the URL store, and the
# file that receives the reported address.
NoNewPrivileges = true;
ProtectSystem = "strict";
ReadWritePaths = [ "/var/lib/njalla" "/var/lib/secrets" ];
ReadOnlyPaths = [ "/etc/sovran" ];
ProtectHome = true;
PrivateTmp = true;
RestrictAddressFamilies = [ "AF_INET" "AF_INET6" ];
# AF_UNIX: name lookups can go through nscd / systemd-resolved sockets.
RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
};
};
@@ -52,86 +73,9 @@
};
};
# Install the Python runner script at build time so the service can find it.
# The script is owned by root and not world-writable.
# Uses _validate_ddns_url() from /etc/sovran/security_helpers.py — the same
# production validator used by the Hub API — before executing any curl call.
# No shell is used; no redirects; no script execution.
# ${IP} placeholder is preserved in stored URLs and substituted at runtime;
# the URL is validated after substitution so any remaining $ is rejected.
# The runner used to be written to /var/lib/sovran by this activation script,
# next to the old public-ip.py detector. Remove those stale copies.
system.activationScripts.sovran-ddns-update-script = ''
install -d -m 0755 /var/lib/sovran
cat > /var/lib/sovran/ddns-update.py <<'PYEOF'
#!/usr/bin/env python3
"""Sovran safe DDNS update runner.
Reads ddns_urls.json, substitutes the public IP for the ''${IP} placeholder,
validates each URL using the production _validate_ddns_url() from
/etc/sovran/security_helpers.py, then calls curl per URL.
No shell interpolation. No redirects. No script execution.
"""
import ipaddress, json, os, subprocess, sys
sys.path.insert(0, '/etc/sovran')
try:
from security_helpers import _validate_ddns_url
except ImportError:
sys.exit(1) # validator missing — fail so systemd logs the misconfiguration
URLS_FILE = "/var/lib/njalla/ddns_urls.json"
try:
with open(URLS_FILE) as f:
urls = json.load(f)
if not isinstance(urls, list):
raise ValueError("not a list")
except Exception:
sys.exit(0) # no URLs configured — nothing to do
# Resolve current public IP via the shared detector — one script, one cache
# (STUN -> DNS -> opt-in HTTPS echo; see /var/lib/sovran/public-ip.py).
# The detector refreshes /var/lib/secrets/external-ip, which the Hub and
# LiveKit read as well, so the whole system shares a single detected value.
public_ip = ""
try:
r = subprocess.run(
[sys.executable, "/var/lib/sovran/public-ip.py", "check"],
capture_output=True, text=True, timeout=20,
)
raw = r.stdout.strip().splitlines()[0] if r.stdout.strip() else ""
ipaddress.ip_address(raw) # validates — raises if not a real IP
public_ip = raw
except Exception:
pass
if not public_ip:
# Last resort: the shared cache file, if the detector is unavailable.
try:
with open("/var/lib/secrets/external-ip") as f:
raw = f.read().strip()
ipaddress.ip_address(raw)
public_ip = raw
except Exception:
pass
if not public_ip:
sys.exit(0) # no IP resolved — skip to avoid sending bare ''${IP}
for raw_url in urls:
try:
# Substitute ''${IP} placeholder then validate through production validator.
# After substitution there must be no $ left; _validate_ddns_url rejects
# any remaining $ expression.
url = raw_url.replace("''${IP}", public_ip)
_validate_ddns_url(url)
subprocess.run(
["curl", "--silent", "--max-time", "15", "--fail", "--no-location", url],
timeout=20, check=False,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
)
except Exception:
pass
PYEOF
chmod 0500 /var/lib/sovran/ddns-update.py
rm -f /var/lib/sovran/ddns-update.py /var/lib/sovran/public-ip.py
'';
}
-323
View File
@@ -1,323 +0,0 @@
# ── Unified public-IP detection (privacy-first) ─────────────────────────────
#
# One script, one cache file, every consumer on the system reads the same
# value. Previously the public IP was detected independently in three places,
# each phoning home to a different third party:
# * the Hub (server.py _get_external_ip) → api.ipify.org / ifconfig.me /
# icanhazip.com over HTTPS on every /api/network call and every
# background-loop tick
# * DDNS (ddns-update.py) → myip.opendns.com via OpenDNS
# * LiveKit → STUN (its own embedded detection)
#
# This module replaces all of that with a single script
# (/var/lib/sovran/public-ip.py) that detects the IP once per TTL using the
# least-exposing mechanism available, and caches it in
# /var/lib/secrets/external-ip. Consumers (Hub, DDNS, LiveKit) read the cache
# and only invoke the script when it is missing or stale.
#
# Detection chain (first success wins, stops immediately):
# 1. pin — sovran_systemsOS.elementCalling.externalIP (baked in)
# 2. cache — /var/lib/secrets/external-ip if newer than cacheTTL
# 3. STUN — UDP binding request (one packet, no application data,
# no HTTP metadata; the same protocol every WebRTC client
# uses). Server configurable via publicIP.stunServer.
# 4. DNS — "myip.opendns.com" A query via publicIP.dnsResolver
# (single DNS query, no HTTP headers)
# 5. HTTPS echo — ONLY endpoints listed in publicIP.httpsEcho (empty by
# default → never contacted)
#
# Privacy property: while the cache is fresh, zero third parties are
# contacted. When detection runs, at most ONE party learns the IP per
# refresh interval (default 5 minutes), and the STUN/DNS mechanisms expose
# nothing beyond the bare address.
{
config,
pkgs,
lib,
...
}:
let
stunServer = config.sovran_systemsOS.publicIP.stunServer;
stunPort = config.sovran_systemsOS.publicIP.stunPort;
dnsResolver = config.sovran_systemsOS.publicIP.dnsResolver;
httpsEcho = config.sovran_systemsOS.publicIP.httpsEcho;
cacheTTL = config.sovran_systemsOS.publicIP.cacheTTL;
# Optional pin shared with element-calling (baked in at build time).
pin = if config.sovran_systemsOS.elementCalling.externalIP != null then config.sovran_systemsOS.elementCalling.externalIP else "";
echoList = lib.concatStringsSep "," (map (u: "'${u}'") httpsEcho);
in
{
options.sovran_systemsOS.publicIP = {
stunServer = lib.mkOption {
type = lib.types.str;
default = "stun.l.google.com";
description = ''
STUN server used to discover the public IP over UDP. STUN is the most
privacy-preserving detection mechanism: a single stateless packet,
no HTTP metadata. Only used when the cache is stale.
'';
};
stunPort = lib.mkOption {
type = lib.types.port;
default = 19302;
};
dnsResolver = lib.mkOption {
type = lib.types.str;
default = "resolver4.opendns.com";
description = ''
DNS resolver used as fallback (myip.opendns.com trick) when STUN is
unavailable (e.g. ISP blocks UDP egress). A single DNS query, no
HTTP headers.
'';
};
httpsEcho = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
example = [ "https://api.ipify.org" ];
description = ''
OPT-IN HTTPS endpoints that return the caller's public IP as a bare
IPv4 literal. Each listed endpoint observes this server's public IP
and HTTP metadata every time detection runs. Empty by default — no
HTTPS echo service is ever contacted unless you add one here. This is
the last-resort fallback after STUN and DNS.
'';
};
cacheTTL = lib.mkOption {
type = lib.types.int;
default = 300;
description = "Seconds the detected public IP is cached before re-detection.";
};
};
# ── Install the unified detector ──────────────────────────────────────────
# This module declares `options` above, so ALL configuration must go under
# the `config` attribute: NixOS forbids mixing bare top-level settings
# (like `system.*`) with the `options`/`config` keyword attributes in the
# same module. (Fixes: "Module ... has an unsupported attribute `system'".)
config.system.activationScripts.sovranPublicIpInstall = lib.stringAfter [ "users" ] ''
install -d -m 0755 /var/lib/sovran
cat > /var/lib/sovran/public-ip.py <<'PYEOF'
#!/usr/bin/env python3
"""sovran-public-ip — one detector, one cache, every consumer reads the same IP.
Privacy-first detection chain (first success wins):
1. pin — baked in from sovran_systemsOS.elementCalling.externalIP
2. cache — /var/lib/secrets/external-ip if newer than CACHE_TTL seconds
3. STUN — UDP binding request (one packet, no application data)
4. DNS — myip.opendns.com A query via the configured resolver
5. HTTPS — ONLY endpoints baked in from publicIP.httpsEcho (opt-in)
Usage:
public-ip.py check print current public IP (cache first; refresh if stale)
public-ip.py refresh force re-detection, update the cache file, print IP
Exit status: 0 with the IP on stdout on success; 1 if no IP is available
(cached value, if any, is still printed to stdout with a warning on stderr).
"""
import ipaddress
import os
import random
import socket
import struct
import sys
import time
import urllib.request
CACHE_FILE = "/var/lib/secrets/external-ip"
PIN = "${pin}"
STUN_SERVER = "${stunServer}"
STUN_PORT = ${toString stunPort}
DNS_RESOLVER = "${dnsResolver}"
DNS_HOST = "myip.opendns.com"
ECHO_URLS = [ ${echoList} ]
CACHE_TTL = ${toString cacheTTL}
TIMEOUT = 3.0
# ---------------------------------------------------------------------------
# Detection primitives
# ---------------------------------------------------------------------------
def is_usable_ip(text: str) -> bool:
"""True if text is a globally routable IPv4 that LiveKit may advertise."""
try:
ip = ipaddress.ip_address(text)
except ValueError:
return False
if ip.version != 4:
return False
if (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast
or ip.is_reserved or ip.is_unspecified or not ip.is_global):
return False
# RFC 6598 shared (CGNAT) space — not reachable from the internet.
if ip in ipaddress.ip_network("100.64.0.0/10"):
return False
return True
def stun_public_ip() -> str | None:
"""RFC 5389 Binding request over UDP; returns the mapped (public) IPv4."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(TIMEOUT)
try:
txid = random.randbytes(12)
req = struct.pack("!HHI", 0x0001, 0, 0) + txid # Binding request
sock.sendto(req, (STUN_SERVER, STUN_PORT))
data, _ = sock.recvfrom(2048)
except OSError:
return None
finally:
sock.close()
if len(data) < 20:
return None
mtype, _mlen = struct.unpack("!HH", data[:4])
if mtype != 0x0101: # Binding success response
return None
cookie = data[4:8]
i = 20
while i + 4 <= len(data):
atype, alen = struct.unpack("!HH", data[i : i + 4])
aval = data[i + 4 : i + 4 + alen]
if atype in (0x0001, 0x0020) and len(aval) >= 8: # MAPPED / XOR-MAPPED
family = aval[1]
if family == 0x01: # IPv4
raw = aval[4:8]
if atype == 0x0020: # XOR with magic cookie + txid prefix
raw = bytes(b ^ c for b, c in zip(raw, cookie + txid[:4]))
return socket.inet_ntop(socket.AF_INET, raw)
i += 4 + ((alen + 3) // 4) * 4
return None
def dns_public_ip() -> str | None:
"""Minimal DNS A query for myip.opendns.com against the given resolver."""
qid = random.randint(0, 0xFFFF)
qname = b"".join(bytes([len(p)]) + p.encode() for p in DNS_HOST.split(".")) + b"\x00"
query = struct.pack("!HHHHHH", qid, 0x0100, 1, 0, 0, 0) + qname + struct.pack("!HH", 1, 1)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(TIMEOUT)
try:
sock.sendto(query, (DNS_RESOLVER, 53))
data, _ = sock.recvfrom(4096)
except OSError:
return None
finally:
sock.close()
try:
if len(data) < 12:
return None
rid, _flags, _qd, an, _ns, _ar = struct.unpack("!HHHHHH", data[:12])
if rid != qid or an == 0:
return None
i = 12
for _ in range(_qd): # skip question
while data[i] != 0:
i += 1 + data[i]
i += 5
for _ in range(an):
if data[i] & 0xC0 == 0xC0:
i += 2
else:
while data[i] != 0:
i += 1 + data[i]
i += 1
rtype, _rclass, _ttl, rdlen = struct.unpack("!HHIH", data[i : i + 10])
i += 10
if rtype == 1 and rdlen == 4:
return socket.inet_ntop(socket.AF_INET, data[i : i + 4])
i += rdlen
except (IndexError, struct.error):
return None
return None
def echo_public_ip() -> str | None:
"""Opt-in HTTPS echo endpoints (baked in at build time; empty by default)."""
for url in ECHO_URLS:
try:
req = urllib.request.Request(url, headers={"User-Agent": "sovran-public-ip"})
with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
text = resp.read().decode().strip()
if is_usable_ip(text):
return text
except Exception:
continue
return None
# ---------------------------------------------------------------------------
# Cache handling
# ---------------------------------------------------------------------------
def read_cache() -> str:
try:
with open(CACHE_FILE) as f:
return f.read().strip()
except OSError:
return ""
def write_cache(ip: str) -> None:
try:
os.makedirs(os.path.dirname(CACHE_FILE), exist_ok=True)
tmp = f"{CACHE_FILE}.tmp"
with open(tmp, "w") as f:
f.write(ip + "\n")
os.replace(tmp, CACHE_FILE)
except OSError:
pass
def cache_fresh() -> bool:
try:
return time.time() - os.path.getmtime(CACHE_FILE) < CACHE_TTL
except OSError:
return False
def detect() -> str:
"""Run the chain; returns usable IP or an empty string."""
if PIN and is_usable_ip(PIN):
return PIN
for fn in (stun_public_ip, dns_public_ip, echo_public_ip):
try:
cand = fn()
except Exception:
continue
if cand and is_usable_ip(cand):
return cand
return ""
def main() -> int:
force = len(sys.argv) > 1 and sys.argv[1] == "refresh"
ip = ""
if not force and cache_fresh():
ip = read_cache()
if not ip:
ip = detect()
if ip:
write_cache(ip)
else:
stale = read_cache()
if stale:
print(stale)
print("WARNING: detection failed; using last known public IP", file=sys.stderr)
return 0
print("ERROR: could not determine a public IP (STUN/DNS unreachable)", file=sys.stderr)
return 1
print(ip)
return 0
if __name__ == "__main__":
sys.exit(main())
PYEOF
chmod 0555 /var/lib/sovran/public-ip.py
'';
}
+5 -3
View File
@@ -107,9 +107,11 @@
description = ''
Optional pin: force LiveKit to advertise this public IPv4 in its
host/TURN ICE candidates. Not required in normal operation — the
module auto-detects the public IP at runtime (HTTPS egress
detection, falling back to STUN). Set it only to override a
mis-detected address (e.g. multi-WAN/VPN setups).
address is the one Njal.la reports for the DDNS update (set up in
the Hub's Domains page), and nothing on this system looks it up
anywhere else. Set it for a fixed public address with no Njal.la
DDNS entry, or to override the reported one (e.g. multi-WAN/VPN
setups).
'';
};
};