feat(fleet): add shared WireGuard profiles and bounded rover transport
Add portable shared WireGuard profiles while retaining Tailscale and Worker boundaries. Bound rover command/telemetry delivery, recovery and diagnostic capture across Core and Node.
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
"""Pinned third-party client build; all outputs remain in owned product staging."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
BUILD = REPO / ".runtime/wireguard-build"
|
||||
OUT = REPO / "apps/wireguard-client/build/macos-arm64"
|
||||
SOURCES = {
|
||||
"wireguard-go": ("0.0.20250522", "f333402bd9cbe0f3eeb02507bd14e23d7d639280"),
|
||||
"wireguard-tools": ("v1.0.20260223", "49ce333da02056ae7b22ee2aeb6afe8aaed79b19"),
|
||||
}
|
||||
|
||||
def run(args, cwd=None, env=None):
|
||||
subprocess.run(args, cwd=cwd, env=env, check=True)
|
||||
|
||||
|
||||
def main():
|
||||
BUILD.mkdir(parents=True, exist_ok=True)
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
for name, (tag, commit) in SOURCES.items():
|
||||
target = BUILD / name
|
||||
if not target.exists():
|
||||
run(["git", "clone", "--quiet", "--depth", "1", "--branch", tag, "https://git.zx2c4.com/" + name, str(target)])
|
||||
found = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=target, text=True).strip()
|
||||
if found != commit:
|
||||
raise ValueError("Third-party source identity differs")
|
||||
go = REPO / "apps/node-agent/build/_toolchain/go/bin/go"
|
||||
env = dict(os.environ, GOMAXPROCS="2", GOMEMLIMIT="512MiB", GOCACHE=str(BUILD / "go-cache"),
|
||||
GOPATH=str(BUILD / "go-modules"), CGO_ENABLED="0", GOOS="darwin", GOARCH="arm64")
|
||||
run([str(go), "build", "-p", "1", "-trimpath", "-ldflags=-s -w", "-o", str(OUT / "wireguard-go"), "."], BUILD / "wireguard-go", env)
|
||||
run(["make", "-j1", "wg"], BUILD / "wireguard-tools/src")
|
||||
shutil.copy2(BUILD / "wireguard-tools/src/wg", OUT / "wg")
|
||||
for binary in (OUT / "wg", OUT / "wireguard-go"):
|
||||
run(["codesign", "--force", "--sign", "-", str(binary)])
|
||||
licenses = OUT / "licenses"
|
||||
licenses.mkdir(exist_ok=True)
|
||||
for name in SOURCES:
|
||||
shutil.copy2(BUILD / name / ("LICENSE" if name == "wireguard-go" else "COPYING"), licenses / (name + ".txt"))
|
||||
manifest = {"platform": "darwin-arm64", "sources": SOURCES,
|
||||
"files": {str(p.relative_to(OUT)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in sorted(OUT.rglob("*")) if p.is_file() and p.name != "manifest.json"}}
|
||||
(OUT / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")
|
||||
print(json.dumps(manifest))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,411 @@
|
||||
"""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 = {}
|
||||
|
||||
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.
|
||||
command = "change" if is_host and prior else "add"
|
||||
run("/sbin/route", "-n", command, "-host", endpoint, gateway, "-ifa", source)
|
||||
record = {"endpoint": endpoint, "gateway": gateway, "source": source, "interface": interface}
|
||||
owned[endpoint] = record
|
||||
row["host_route"] = record
|
||||
row["physical_endpoint"] = endpoint
|
||||
self.persist()
|
||||
|
||||
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)
|
||||
exists = "HOST" in fields.get("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"):
|
||||
raise ValueError("Unknown action")
|
||||
identity = server_id(body.get("server_id"))
|
||||
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 row in self.profiles.values():
|
||||
pending = row.get("pending")
|
||||
if pending and (startup or pending["deadline"] <= time.time()):
|
||||
self.apply(row, pending["previous"])
|
||||
row["pending"] = None
|
||||
self.persist()
|
||||
elif startup and row.get("config"):
|
||||
self.apply(row, row["config"])
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Install the reviewed client payload through the standard macOS administrator prompt."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import plistlib
|
||||
import pwd
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
import socket
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path("/Library/Application Support/NODE.DC/MissionWireGuard")
|
||||
PLIST = Path("/Library/LaunchDaemons/com.nodedc.mission-wireguard.plist")
|
||||
LABEL = "com.nodedc.mission-wireguard"
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--uid", type=int, required=True)
|
||||
args = parser.parse_args()
|
||||
if os.geteuid() != 0 or platform.system() != "Darwin" or platform.machine() != "arm64" or args.uid < 500:
|
||||
raise ValueError("macOS Apple Silicon administrator installation required")
|
||||
user = pwd.getpwuid(args.uid)
|
||||
source = Path(__file__).resolve().parent
|
||||
binaries = source / "build/macos-arm64"
|
||||
manifest = json.loads((binaries / "manifest.json").read_text())
|
||||
for name, digest in manifest["files"].items():
|
||||
path = binaries / name
|
||||
if not path.resolve().is_relative_to(binaries.resolve()) or hashlib.sha256(path.read_bytes()).hexdigest() != digest:
|
||||
raise ValueError("Client payload hash mismatch")
|
||||
if ROOT.exists() and not (ROOT / "installed.json").is_file():
|
||||
raise ValueError("Foreign installation directory")
|
||||
if PLIST.exists():
|
||||
old = plistlib.loads(PLIST.read_bytes())
|
||||
if old.get("Label") != LABEL or not str(old.get("ProgramArguments", ["", "", ""])[-1]).startswith(str(ROOT)):
|
||||
raise ValueError("Foreign launch daemon")
|
||||
identity = hashlib.sha256((source / "helper.py").read_bytes() + json.dumps(manifest, sort_keys=True).encode()).hexdigest()
|
||||
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
ROOT.chmod(0o700)
|
||||
release = ROOT / "releases" / identity
|
||||
release.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
for name in ("wg", "wireguard-go"):
|
||||
shutil.copy2(binaries / name, release / name)
|
||||
(release / name).chmod(0o700)
|
||||
shutil.copy2(source / "helper.py", release / "helper.py")
|
||||
(release / "helper.py").chmod(0o600)
|
||||
(release / "owner.json").write_text(json.dumps({"uid": args.uid, "gid": user.pw_gid}))
|
||||
(release / "owner.json").chmod(0o600)
|
||||
value = {"Label": LABEL, "ProgramArguments": ["/usr/bin/python3", "-I", str(release / "helper.py")],
|
||||
"RunAtLoad": True, "KeepAlive": True, "ThrottleInterval": 10,
|
||||
"ProcessType": "Background", "Umask": 63}
|
||||
previous = PLIST.read_bytes() if PLIST.exists() else None
|
||||
try:
|
||||
subprocess.run(["/bin/launchctl", "bootout", "system/" + LABEL], capture_output=True)
|
||||
PLIST.write_bytes(plistlib.dumps(value))
|
||||
PLIST.chmod(0o644)
|
||||
subprocess.run(["/bin/launchctl", "bootstrap", "system", str(PLIST)], check=True, capture_output=True)
|
||||
for attempt in range(40):
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) as connection:
|
||||
connection.settimeout(1)
|
||||
connection.connect("/var/run/ndc-mission-wireguard.sock")
|
||||
connection.sendall(b'{"action":"health"}\n')
|
||||
result=json.loads(connection.recv(4096))
|
||||
if result.get("result",{}).get("sha256") != hashlib.sha256((release / "helper.py").read_bytes()).hexdigest():
|
||||
raise ValueError("Helper identity mismatch")
|
||||
break
|
||||
except Exception:
|
||||
if attempt == 39: raise ValueError("Installed helper did not become ready")
|
||||
time.sleep(.25)
|
||||
(ROOT / "installed.json").write_text(json.dumps({"artifact": identity, "uid": args.uid, "label": LABEL}))
|
||||
(ROOT / "installed.json").chmod(0o600)
|
||||
except Exception:
|
||||
subprocess.run(["/bin/launchctl", "bootout", "system/" + LABEL], capture_output=True)
|
||||
if previous:
|
||||
PLIST.write_bytes(previous)
|
||||
subprocess.run(["/bin/launchctl", "bootstrap", "system", str(PLIST)], capture_output=True)
|
||||
else:
|
||||
PLIST.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,19 @@
|
||||
import importlib.util
|
||||
import pathlib
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
class SocketOwnershipTest(unittest.TestCase):
|
||||
def test_no_fowner_capability_is_required_after_chown(self):
|
||||
spec=importlib.util.spec_from_file_location('wg_helper',pathlib.Path(__file__).with_name('helper.py'))
|
||||
module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module)
|
||||
state={'owner':0,'mode':0o700}
|
||||
def chmod(path,mode):
|
||||
if state['owner']!=0:raise PermissionError('CAP_FOWNER is deliberately absent')
|
||||
state['mode']=mode
|
||||
def chown(path,uid,gid):state['owner']=uid
|
||||
with patch.object(module.os,'chmod',chmod),patch.object(module.os,'chown',chown):
|
||||
module.secure_socket('/run/example.sock',123,123)
|
||||
self.assertEqual(state,{'owner':123,'mode':0o600})
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
Reference in New Issue
Block a user