#!/usr/bin/env python3 """Install the operator's loopback HTTPS name using macOS's own Apache. Run with administrator authorization. This never restarts or replaces Core. The certificate is a single-host leaf, not a general-purpose signing CA. """ import hashlib import json import os import pathlib import plistlib import socket import subprocess import sys import tempfile import time import urllib.request DOMAIN = "nodedc.missioncore" ORIGIN = "https://" + DOMAIN LABEL = "com.nodedc.mission-core.https" ROOT = pathlib.Path("/Library/Application Support/NODE.DC/MissionCoreHTTPS") LOGS = pathlib.Path("/Library/Logs/NODE.DC/MissionCoreHTTPS") PLIST = pathlib.Path("/Library/LaunchDaemons") / (LABEL + ".plist") HOSTS = pathlib.Path("/private/etc/hosts") HOST_LINE = "127.0.0.1 nodedc.missioncore # NODE.DC Mission Core HTTPS" def config(root=ROOT, logs=LOGS, https_port=443, http_port=80, upstream_port=8000): """Ports/paths can be overridden for an isolated transport qualification.""" proxy_route = ( f"http://127.0.0.1:{upstream_port}/ nocanon " "connectiontimeout=3 timeout=3600 upgrade=websocket" ) return f'''ServerRoot "/usr" ServerName {DOMAIN} Listen 127.0.0.1:{http_port} Listen 127.0.0.1:{https_port} LoadModule mpm_event_module libexec/apache2/mod_mpm_event.so LoadModule unixd_module libexec/apache2/mod_unixd.so LoadModule authz_core_module libexec/apache2/mod_authz_core.so LoadModule ssl_module libexec/apache2/mod_ssl.so LoadModule proxy_module libexec/apache2/mod_proxy.so LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so LoadModule headers_module libexec/apache2/mod_headers.so LoadModule rewrite_module libexec/apache2/mod_rewrite.so User _www Group _www PidFile "{root}/httpd.pid" DefaultRuntimeDir "{root}" Mutex "file:{root}" default ErrorLog "|/usr/sbin/rotatelogs -n 2 '{logs}/error.log' 1M" LogLevel warn ServerTokens Prod ServerSignature Off TraceEnable Off StartServers 1 ServerLimit 2 ThreadLimit 32 ThreadsPerChild 32 MinSpareThreads 16 MaxSpareThreads 32 MaxRequestWorkers 64 MaxConnectionsPerChild 10000 Timeout 600 KeepAlive On KeepAliveTimeout 5 LimitRequestBody 0 AllowEncodedSlashes NoDecode Require all denied ServerName {DOMAIN} RewriteEngine On RewriteCond %{{HTTP_HOST}} !^{DOMAIN.replace(".", "[.]")}(:{http_port})?$ [NC] RewriteRule ^ - [F,L] RewriteRule ^/(.*)$ {ORIGIN}/$1 [R=308,NE,L] ServerName {DOMAIN} SSLEngine On SSLProtocol -all +TLSv1.2 SSLCipherSuite HIGH:!aNULL:!MD5:!3DES SSLCertificateFile "{root}/server.crt" SSLCertificateKeyFile "{root}/server.key" RewriteEngine On RewriteCond %{{HTTP_HOST}} !^{DOMAIN.replace(".", "[.]")}(:{https_port})?$ [NC] RewriteRule ^ - [F,L] # Validate the public browser origin BEFORE mapping it to Core's origin. RewriteCond %{{HTTP:Origin}} !^$ RewriteCond %{{HTTP:Origin}} !^{ORIGIN.replace(".", "[.]")}(:{https_port})?$ RewriteRule ^ - [F,L] # External links may navigate to the UI; cross-site API calls remain blocked. RewriteCond %{{HTTP:Sec-Fetch-Site}} ^cross-site$ [NC] RewriteCond %{{HTTP:Sec-Fetch-Mode}} !^navigate$ [NC,OR] RewriteCond %{{REQUEST_URI}} ^/(api|ws)(/|$) [NC] RewriteRule ^ - [F,L] ProxyRequests Off ProxyPreserveHost Off ProxyAddHeaders Off RequestHeader unset Forwarded RequestHeader unset X-Forwarded-For RequestHeader unset X-Forwarded-Host RequestHeader unset X-Forwarded-Proto RequestHeader unset X-Forwarded-Port RequestHeader unset X-Real-IP RequestHeader edit Origin "^{ORIGIN.replace(".", "[.]")}(:{https_port})?$" "http://127.0.0.1:{upstream_port}" ProxyPass / {proxy_route} ProxyPassReverse / http://127.0.0.1:{upstream_port}/ Require all granted ''' def run(*args): result = subprocess.run(args, capture_output=True, text=True) if result.returncode: raise RuntimeError(f"{args[0]}: {result.stderr.strip()}") return result.stdout.strip() def atomic(path, content, mode=0o600): fd, name = tempfile.mkstemp(dir=path.parent, prefix=".https-") try: with os.fdopen(fd, "wb") as stream: stream.write(content) stream.flush() os.fsync(stream.fileno()) os.chmod(name, mode) os.replace(name, path) finally: if os.path.exists(name): os.unlink(name) def create_certificate(root): key, cert = root / "server.key", root / "server.crt" if key.exists() and cert.exists(): run("/usr/bin/openssl", "x509", "-in", str(cert), "-checkend", "2592000", "-noout") return if key.exists() or cert.exists(): raise RuntimeError("Incomplete HTTPS certificate; inspect before replacing it") spec = root / "certificate.conf" atomic( spec, f"""[req] prompt=no distinguished_name=dn x509_extensions=server [dn] CN={DOMAIN} O=NODE.DC Local Mission Core [server] subjectAltName=DNS:{DOMAIN} basicConstraints=critical,CA:FALSE keyUsage=critical,digitalSignature,keyEncipherment extendedKeyUsage=serverAuth """.encode(), ) run( "/usr/bin/openssl", "req", "-new", "-x509", "-newkey", "rsa:2048", "-nodes", "-sha256", "-days", "365", "-config", str(spec), "-keyout", str(key), "-out", str(cert), ) os.chmod(key, 0o600) os.chmod(cert, 0o644) spec.unlink() def install(): if sys.platform != "darwin" or os.geteuid() != 0: raise RuntimeError("Use macOS administrator authorization for this installer") op = urllib.request.build_opener(urllib.request.ProxyHandler({})) with op.open("http://127.0.0.1:8000/api/health", timeout=10) as response: health = json.load(response) if health.get("service") != "mission-core-control-plane" or not health.get("ok"): raise RuntimeError("Canonical Mission Core is not healthy") before = HOSTS.read_bytes() for line in before.decode().splitlines(): fields = line.split("#", 1)[0].split() if DOMAIN in fields[1:] and fields[0] != "127.0.0.1": raise RuntimeError("The requested name already resolves elsewhere in hosts") existing = ( subprocess.run( ["/bin/launchctl", "print", "system/" + LABEL], capture_output=True ).returncode == 0 ) if not existing: for port in (80, 443): with socket.socket() as probe: probe.bind(("127.0.0.1", port)) for directory in (ROOT, LOGS): directory.mkdir(parents=True, exist_ok=True) os.chmod(directory, 0o755) create_certificate(ROOT) conf = config().encode() conf_path = ROOT / "httpd.conf" if existing and conf_path.read_bytes() != conf: raise RuntimeError("Existing HTTPS configuration differs; review before restarting") atomic(conf_path, conf, 0o644) run("/usr/sbin/httpd", "-t", "-f", str(conf_path)) # Trust is configured separately in the operator's login session. macOS # refuses interactive trust authorization from this background root process. # Never install a general signing CA or disable browser certificate checks. if not any( DOMAIN in line.split("#", 1)[0].split()[1:] for line in before.decode().splitlines() ): if not (ROOT / "hosts.before").exists(): atomic(ROOT / "hosts.before", before) atomic(HOSTS, before.rstrip(b"\n") + b"\n" + HOST_LINE.encode() + b"\n", 0o644) run("/usr/bin/dscacheutil", "-flushcache") declaration = plistlib.dumps( { "Label": LABEL, "ProgramArguments": ["/usr/sbin/httpd", "-f", str(conf_path), "-D", "FOREGROUND"], "RunAtLoad": True, "KeepAlive": True, "ThrottleInterval": 5, "AbandonProcessGroup": False, "ExitTimeOut": 15, } ) if PLIST.exists() and PLIST.read_bytes() != declaration: raise RuntimeError("Existing HTTPS launch declaration differs; review it first") atomic(PLIST, declaration, 0o644) if not existing: run("/bin/launchctl", "bootstrap", "system", str(PLIST)) for _attempt in range(20): check = subprocess.run( [ "/usr/bin/curl", "--noproxy", "*", "--silent", "--show-error", "--fail", "--max-time", "5", "--cacert", str(ROOT / "server.crt"), ORIGIN + "/api/health", ], capture_output=True, text=True, ) if check.returncode == 0 and json.loads(check.stdout).get("ok"): receipt = { "url": ORIGIN, "upstream": "http://127.0.0.1:8000", "config_sha256": hashlib.sha256(conf).hexdigest(), "certificate": run( "/usr/bin/openssl", "x509", "-in", str(ROOT / "server.crt"), "-noout", "-dates", "-fingerprint", "-sha256", ), "core_restarted": False, "https_health": "verified_exact_certificate", "browser_trust": "verify_in_operator_login_session", } atomic(ROOT / "receipt.json", (json.dumps(receipt, indent=2) + "\n").encode()) print(json.dumps(receipt, indent=2)) return time.sleep(0.5) raise RuntimeError("HTTPS health failed: " + check.stderr[-500:]) if __name__ == "__main__": install()