"""Privileged, fixed-operation WireGuard helper. Socket is owned by one operator/Node UID.""" import base64 import hashlib import ipaddress import json import os import platform import re import socket import socketserver import subprocess import threading import time from pathlib import Path DARWIN = platform.system() == "Darwin" HOME = Path("/Library/Application Support/NODE.DC/MissionWireGuard" if DARWIN else "/var/lib/mission-core-wireguard") SOCKET = "/var/run/ndc-mission-wireguard.sock" if DARWIN else "/run/mission-core-wireguard/control.sock" BIN = Path(__file__).resolve().parent WG = str(BIN / "wg") if DARWIN else "/usr/bin/wg" def run(*args, data=None, check=True): return subprocess.run(args, input=data, check=check, capture_output=True, timeout=15) def save(path, value): tmp = path.with_name(path.name + ".new") fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, "w") as out: json.dump(value, out) out.flush() os.fsync(out.fileno()) os.replace(tmp, path) descriptor = os.open(path.parent, os.O_RDONLY) try: os.fsync(descriptor) finally: os.close(descriptor) def server_id(value): if not isinstance(value, str) or not re.fullmatch(r"wg_[a-f0-9]{32}", value): raise ValueError("Invalid server identity") return value def key(value): if not isinstance(value, str) or len(value) != 44 or len(base64.b64decode(value, validate=True)) != 32: raise ValueError("Invalid WireGuard key") return value def validate(value): required = {"server_id", "address", "subnet", "server_public_key", "endpoint", "allowed_ips", "role"} if not isinstance(value, dict) or set(value) != required | (set(value) & {"interface"}): raise ValueError("Invalid connection profile") server_id(value["server_id"]) key(value["server_public_key"]) network = ipaddress.ip_network(value["subnet"]) permitted = ipaddress.ip_network("10.203.0.0/16") if network.version != 4 or network.prefixlen != 24 or not network.subnet_of(permitted): raise ValueError("Only an isolated fleet /24 is supported") address = ipaddress.ip_address(value["address"]) if address not in network or value["role"] not in ("core", "node"): raise ValueError("Invalid peer address") if (value["role"] == "core" and address != network[2]) or (value["role"] == "node" and not network[3] <= address <= network[253]): raise ValueError("Address does not match peer role") allowed = value["allowed_ips"] if not isinstance(allowed, list) or not 1 <= len(allowed) <= network.num_addresses - 4 or len(set(allowed)) != len(allowed): raise ValueError("Invalid routes") for text in allowed: peer = ipaddress.ip_network(text) if peer.prefixlen != 32 or not peer.subnet_of(network) or peer.network_address == address: raise ValueError("Only other fleet peer /32 routes are admitted") if value["role"] == "node" and peer.network_address not in (network[1], network[2]): raise ValueError("A board may reach only its Core and the tunnel gateway") endpoint = value["endpoint"] if not isinstance(endpoint, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}:51830", endpoint): raise ValueError("Invalid public WireGuard endpoint") addresses = {item[4][0] for item in socket.getaddrinfo(endpoint.split(":")[0], None, socket.AF_INET)} if not addresses or any(not ipaddress.ip_address(a).is_global for a in addresses): raise ValueError("WireGuard endpoint must be public") if value.get("interface") and (not DARWIN or not re.fullmatch(r"en[0-9]{1,2}", value["interface"])): raise ValueError("Unsupported physical interface") return sorted(addresses)[0] class Manager: def __init__(self, root=HOME): self.root = Path(root) self.root.mkdir(mode=0o700, parents=True, exist_ok=True) self.lock = threading.RLock() self.path = self.root / "profiles.json" self.profiles = json.loads(self.path.read_text()) if self.path.exists() else {} self.children = {} self.next_physical_route_check = 0.0 self.restore_retry = {} def persist(self): save(self.path, self.profiles) def prepare(self, identity): server_id(identity) if identity not in self.profiles: if len(self.profiles) >= 8: raise ValueError("Maximum eight server profiles") private = run(WG, "genkey").stdout.strip().decode() public = run(WG, "pubkey", data=(private + "\n").encode()).stdout.strip().decode() self.profiles[identity] = {"private_key": private, "public_key": public, "config": None, "pending": None, "interface": None} self.persist() return self.profiles[identity] def physical_route(self, config, endpoint, row): interface = config.get("interface") if not DARWIN or not interface: return gateway = run("/usr/sbin/ipconfig", "getoption", interface, "router").stdout.decode().split()[0] source = run("/usr/sbin/ipconfig", "getifaddr", interface).stdout.decode().strip() ipaddress.IPv4Address(gateway) ipaddress.IPv4Address(source) result = run("/sbin/route", "-n", "get", endpoint).stdout.decode() fields = dict(line.strip().split(":", 1) for line in result.splitlines() if ":" in line) # Never replace a foreign explicit /32. Only our saved host route may change. flags = fields.get("flags", "") if "HOST" in flags and "WASCLONED" in flags: # macOS caches a destination under the VPN default route. This is # not an operator-created static route. Retire only that cache entry. cached_interface = fields.get("interface", "").strip() if re.fullmatch(r"(?:utun|en)[0-9]+", cached_interface): run("/sbin/route", "-n", "delete", "-host", endpoint, "-ifscope", cached_interface, check=False) flags = "" owned = row.setdefault("host_routes", {}) if row.get("host_route"): owned.setdefault(row["host_route"]["endpoint"], row["host_route"]) prior = owned.get(endpoint) actual_gateway = fields.get("gateway", "").strip() actual_interface = fields.get("interface", "").strip() is_host = "HOST" in flags if is_host and prior and (actual_gateway != prior["gateway"] or actual_interface != prior["interface"]): raise ValueError("An owned host route was changed outside this application") if is_host and not prior: if actual_interface != interface or actual_gateway != gateway: raise ValueError("An existing host route conflicts with this connection") row["physical_endpoint"] = endpoint self.persist() return # A migrated VPS has a new destination, so it needs a new /32 even when # this profile owns a route to its previous VPS. Reboots may remove routes. record = {"endpoint": endpoint, "gateway": gateway, "source": source, "interface": interface} if is_host and prior == record: return # Stable DHCP state: no route rewrite or tunnel reconfiguration. command = "change" if is_host and prior else "add" run("/sbin/route", "-n", command, "-host", endpoint, gateway, "-ifa", source) owned[endpoint] = record row["host_route"] = record row["physical_endpoint"] = endpoint self.persist() def refresh_physical_routes(self): """Repair only our explicit VPS /32 after the selected Mac LAN changes. WireGuard keepalives cannot repair a macOS route whose cached source is an expired DHCP address. Leave peer keys, tunnel state, default routes, foreign routes and the selected physical interface unchanged. """ if not DARWIN: return with self.lock: now = time.monotonic() if now < self.next_physical_route_check: return self.next_physical_route_check = now + 5 for row in self.profiles.values(): config = row.get("config") endpoint = row.get("physical_endpoint") if not config or not config.get("interface") or row.get("pending") or not endpoint: continue owned = row.get("host_routes", {}) legacy = row.get("host_route") or {} if endpoint not in owned and legacy.get("endpoint") != endpoint: continue try: self.physical_route(config, endpoint, row) except (OSError, ValueError, IndexError, subprocess.SubprocessError): # No DHCP lease, a foreign route or a transient failure must # not disable the tunnel or prevent another profile's check. # Retry on the next bounded pass without touching the VPN. continue def retire_physical_routes(self, row): if not DARWIN: return used = {value.get("physical_endpoint") for value in self.profiles.values() if value.get("config")} for endpoint, record in list(row.get("host_routes", {}).items()): if endpoint in used: continue result = run("/sbin/route", "-n", "get", endpoint, check=False).stdout.decode() fields = dict(line.strip().split(":", 1) for line in result.splitlines() if ":" in line) if ("HOST" in fields.get("flags", "") and fields.get("gateway", "").strip() == record["gateway"] and fields.get("interface", "").strip() == record["interface"]): run("/sbin/route", "-n", "delete", "-host", endpoint, record["gateway"], check=False) del row["host_routes"][endpoint] row["host_route"] = row.get("host_routes", {}).get(row.get("physical_endpoint")) self.persist() def apply(self, row, config): if config is None: self.down(row) return endpoint = validate(config) forward = run("/usr/sbin/sysctl" if DARWIN else "/usr/sbin/sysctl", "-n", "net.inet.ip.forwarding" if DARWIN else "net.ipv4.ip_forward").stdout.strip() if forward != b"0": raise ValueError("Host forwarding must be disabled before joining the fleet") self.physical_route(config, endpoint, row) name = row.get("interface") if name: found = run(WG, "show", name, "public-key", check=False) if found.returncode == 0 and found.stdout.decode().strip() != row["public_key"]: raise ValueError("Interface identity changed") if found.returncode: name = None if not name: if DARWIN: name_file = self.root / (config["server_id"] + ".interface") name_file.unlink(missing_ok=True) env = dict(os.environ, WG_TUN_NAME_FILE=str(name_file)) child = subprocess.Popen([str(BIN / "wireguard-go"), "-f", "utun"], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) self.children[config["server_id"]] = child for _ in range(50): if name_file.exists(): name = name_file.read_text().strip() break if child.poll() is not None: raise ValueError("WireGuard interface could not start") time.sleep(0.1) if not name or not re.fullmatch(r"utun[0-9]+", name): raise ValueError("WireGuard interface startup timed out") else: name = "mcwg" + config["server_id"][3:11] # Existence without our durable record is a foreign conflict. run("/usr/sbin/ip", "link", "add", name, "type", "wireguard") row["interface"] = name self.persist() old_routes = set(row.get("routes", (row.get("config") or {}).get("allowed_ips", []))) new_routes = set(config["allowed_ips"]) text = ("[Interface]\nPrivateKey = " + row["private_key"] + "\n[Peer]\nPublicKey = " + config["server_public_key"] + "\nEndpoint = " + endpoint + ":51830\nAllowedIPs = " + ", ".join(config["allowed_ips"]) + "\nPersistentKeepalive = 20\n") path = self.root / "apply.conf" fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, 0o600) with os.fdopen(fd, "w") as out: out.write(text) try: run(WG, "setconf", name, str(path)) finally: path.unlink(missing_ok=True) # Record each owned route immediately. Never replace a foreign host route. if DARWIN: run("/sbin/ifconfig", name, "inet", config["address"], config["address"], "netmask", "255.255.255.255") run("/sbin/ifconfig", name, "mtu", "1280", "up") else: run("/usr/sbin/ip", "address", "replace", config["address"] + "/32", "dev", name) run("/usr/sbin/ip", "link", "set", name, "mtu", "1280", "up") for route in old_routes - new_routes: self.remove_route(route, name) old_routes.remove(route) row["routes"] = sorted(old_routes) self.persist() for route in new_routes: if DARWIN: result = run("/sbin/route", "-n", "get", route[:-3], check=False).stdout.decode() fields = dict(line.strip().split(":", 1) for line in result.splitlines() if ":" in line) flags = fields.get("flags", "") # A scoped cache created from another VPN's default route is # not an administrator's explicit host route. Retire only this # exact cached fleet destination before adding our /32. if "HOST" in flags and "WASCLONED" in flags: cached_interface = fields.get("interface", "").strip() if not re.fullmatch(r"(?:utun|en)[0-9]+", cached_interface): raise ValueError("Unrecognized cached route interface") run("/sbin/route", "-n", "delete", "-host", route[:-3], "-ifscope", cached_interface, check=False) flags = "" exists = "HOST" in flags own = exists and fields.get("interface", "").strip() == name else: entries = json.loads(run("/usr/sbin/ip", "-j", "route", "show", "exact", route).stdout) exists = bool(entries) own = exists and all(entry.get("dev") == name for entry in entries) if exists and not own: raise ValueError("An existing host route conflicts with this fleet") if not own: if DARWIN: run("/sbin/route", "-n", "add", "-host", route[:-3], "-interface", name) else: run("/usr/sbin/ip", "route", "add", route, "dev", name) old_routes.add(route) row["routes"] = sorted(old_routes) self.persist() row["config"] = config self.persist() self.retire_physical_routes(row) def remove_route(self, route, name): if DARWIN: run("/sbin/route", "-n", "delete", "-host", route[:-3], "-interface", name, check=False) else: run("/usr/sbin/ip", "route", "del", route, "dev", name, check=False) def down(self, row): name = row.get("interface") if name: check = run(WG, "show", name, "public-key", check=False) if check.returncode == 0 and check.stdout.decode().strip() not in ("", "(none)", row["public_key"]): raise ValueError("Refusing to remove foreign interface") if DARWIN: for route in row.get("routes", (row.get("config") or {}).get("allowed_ips", [])): run("/sbin/route", "-n", "delete", "-host", route[:-3], "-interface", name, check=False) Path("/var/run/wireguard", name + ".sock").unlink(missing_ok=True) else: run("/usr/sbin/ip", "link", "delete", name, check=False) row["interface"] = None row["routes"] = [] row["config"] = None row["physical_endpoint"] = None self.persist() self.retire_physical_routes(row) def view(self, identity, row): handshake = 0 if row.get("interface"): result = run(WG, "show", row["interface"], "latest-handshakes", check=False) if result.returncode == 0: handshake = max([int(line.split()[1]) for line in result.stdout.decode().splitlines()] or [0]) return {"server_id": identity, "public_key": row["public_key"], "config": row["config"], "interface": row["interface"], "pending": row["pending"] is not None, "last_handshake": handshake} def dispatch(self, body): if isinstance(body, dict) and body.get("action") == "health" and set(body) <= {"action", "server_id"}: return {"schema": "missioncore.wireguard-helper/v1", "sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()} if not isinstance(body, dict) or set(body) - {"action", "server_id", "config", "operation_id"}: raise ValueError("Invalid helper request") with self.lock: action = body.get("action") if action not in ( "prepare", "status", "stage", "confirm", "apply", "disable", "rollback", "forget", ): raise ValueError("Unknown action") identity = server_id(body.get("server_id")) if action == "forget": row = self.profiles.get(identity) if row is not None: if row.get("pending"): raise ValueError("A network change is pending") self.down(row) del self.profiles[identity] try: self.persist() except Exception: self.profiles[identity] = row raise self.restore_retry.pop(identity, None) return {"server_id": identity, "removed": True} row = self.prepare(identity) if action in ("stage", "apply"): config = body["config"] validate(config) if config["server_id"] != identity: raise ValueError("Different server") if action == "stage": op = body.get("operation_id") if not isinstance(op, str) or not re.fullmatch(r"[a-f0-9]{32}", op): raise ValueError("Operation identity required") if row["pending"] and row["pending"]["id"] != op: raise ValueError("Another network change is pending") if row["pending"] is None: row["pending"] = {"id": op, "previous": row["config"], "deadline": time.time() + 120} self.persist() previous = row["config"] try: self.apply(row, config) except Exception: self.apply(row, previous) row["pending"] = None self.persist() raise elif action == "rollback": record = row["pending"] or row.get("confirmed") if record and record["id"] == body.get("operation_id"): self.apply(row, record["previous"]) row["pending"] = None row["confirmed"] = None self.persist() elif action == "confirm": if row["pending"] and row["pending"]["id"] != body.get("operation_id"): raise ValueError("Operation changed") if row["pending"]: row["confirmed"] = row["pending"] row["pending"] = None self.persist() elif action == "disable": self.down(row) row["pending"] = None self.persist() return self.view(identity, row) def restore(self, startup=False): with self.lock: for identity, row in self.profiles.items(): pending = row.get("pending") rollback = pending and (startup or pending["deadline"] <= time.time()) if not (rollback or (row.get("config") and (startup or identity in self.restore_retry))): continue if not startup and time.monotonic() < self.restore_retry.get(identity, 0): continue try: self.apply(row, pending["previous"] if rollback else row["config"]) if rollback: row["pending"] = None self.persist() except Exception: # A late DHCP lease or transient route failure at boot must # not leave an apparently running helper permanently partial. self.restore_retry[identity] = time.monotonic() + 5 else: self.restore_retry.pop(identity, None) class Handler(socketserver.StreamRequestHandler): def handle(self): self.request.settimeout(10) try: raw = self.rfile.readline(16385) if not raw.endswith(b"\n") or len(raw) > 16384: raise ValueError("Invalid message") result = {"ok": True, "result": self.server.manager.dispatch(json.loads(raw))} except Exception as error: result = {"ok": False, "error": str(error) if isinstance(error, ValueError) else "System network preparation failed"} self.wfile.write(json.dumps(result).encode() + b"\n") def secure_socket(path, uid, gid): # With CAP_CHOWN but no CAP_FOWNER, chmod must precede ownership transfer. os.chmod(path, 0o600) os.chown(path, uid, gid) def main(): if os.geteuid() != 0: raise ValueError("Installed system helper required") os.umask(0o077) if DARWIN: owner = json.loads((BIN / "owner.json").read_text()) else: import pwd account = pwd.getpwnam("mission-core-node") owner = {"uid": account.pw_uid, "gid": account.pw_gid} manager = Manager() try: manager.restore(startup=True) except Exception: pass # Keep the bounded local control socket available for recovery. path = Path(SOCKET) path.parent.mkdir(parents=True, exist_ok=True) path.unlink(missing_ok=True) with socketserver.UnixStreamServer(SOCKET, Handler) as server: server.manager = manager secure_socket(SOCKET, owner["uid"], owner["gid"]) server.timeout = 1 while True: server.handle_request() try: manager.restore() except Exception: pass manager.refresh_physical_routes() if __name__ == "__main__": main()