#!/usr/bin/env python3 """Read-only VM SSH preflight; never accepts or installs SSH host keys.""" import ipaddress import os from pathlib import Path import re import stat import subprocess import tempfile ROOT = Path(__file__).resolve().parents[1] FIELDS = { "hostname", "address", "os_version", "architecture", "access_method", "username", "password", "ssh_key_path", "port", "vmid", } def load_config(path): if path.is_symlink() or path.parent.is_symlink(): raise ValueError("credential symlinks are not supported") for item, mode in ((path.parent, 0o700), (path, 0o600)): if stat.S_IMODE(item.stat().st_mode) != mode or item.stat().st_uid != os.getuid(): raise ValueError("credential ownership or permissions are unsafe") rules = (ROOT / ".gitignore").read_text().splitlines() if not any(x.strip() in ("credentials/", "/credentials/", "credentials", "/credentials") for x in rules): raise ValueError("credential ignore rule is missing") values = {} for line in path.read_text().splitlines(): line = line.strip() if not line or line.startswith("#"): continue match = re.fullmatch(r"([a-z_]+)\s*[:=]\s*(.*)", line) if not match or match[1] not in FIELDS or match[1] in values: raise ValueError("invalid or duplicate credential field (contents withheld)") value = match[2].strip() if value[:1] in ("'", '"'): if len(value) < 2 or value[-1] != value[0]: raise ValueError("unmatched credential quote") value = value[1:-1] if any(ord(c) < 32 or ord(c) == 127 for c in value): raise ValueError("control character in credential field") values[match[1]] = value address = values.get("address", "") try: ipaddress.ip_address(address) except ValueError: if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,252}", address): raise ValueError("invalid VM address") from None if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_.-]*", values.get("username", "")): raise ValueError("invalid SSH username") if not values.get("port", "22").isdigit() or not 1 <= int(values.get("port", "22")) <= 65535: raise ValueError("invalid SSH port") return values def run(args, **kwargs): return subprocess.run(args, capture_output=True, timeout=30, **kwargs) def fingerprints(address, port): # Unauthenticated scan: fingerprints are for human comparison, never trust input. scan = run(["ssh-keyscan", "-T", "5", "-p", port, address]) keys = b"\n".join(x for x in scan.stdout.splitlines() if x and not x.startswith(b"#")) if not keys: print("UNCONFIRMED_HOSTKEY: scan returned no public keys; connectivity remains unverified") return result = run(["ssh-keygen", "-l", "-E", "sha256", "-f", "-"], input=keys) for line in result.stdout.decode(errors="replace").splitlines(): parts = line.split() if len(parts) >= 2 and parts[1].startswith("SHA256:"): print("UNCONFIRMED_HOSTKEY:", parts[0], parts[1], parts[-1]) def main(): config = load_config(ROOT / "credentials/linux-vm.conf") address, port = config["address"], config.get("port", "22") known = Path.home() / ".ssh/known_hosts" lookup = address if port == "22" else f"[{address}]:{port}" found = run(["ssh-keygen", "-F", lookup, "-f", str(known)]) if known.is_file() else None if found is None or found.returncode != 0: print("BLOCKED: no existing trusted VM host key in user known_hosts; no authentication attempted") fingerprints(address, port) return 2 ssh = ["ssh", "-F", "/dev/null", "-T", "-p", port, "-o", "StrictHostKeyChecking=yes", "-o", f"UserKnownHostsFile={known}", "-o", "GlobalKnownHostsFile=/dev/null", "-o", "ConnectTimeout=10", "-o", "ConnectionAttempts=1", "-o", "ForwardAgent=no", "-o", "ClearAllForwardings=yes", "-o", "LogLevel=ERROR"] key = config.get("ssh_key_path", "") if key: key_path = Path(key).expanduser() if not key_path.is_file(): raise ValueError("configured SSH identity file is missing") ssh += ["-i", str(key_path), "-o", "IdentitiesOnly=yes"] # No hostname, username, home path, process command lines, or remote secrets in output. remote = """set -eu printf 'ARCH='; uname -m printf 'KERNEL='; uname -s printf 'GLIBC='; getconf GNU_LIBC_VERSION 2>/dev/null || true printf 'OS_ID='; sed -n 's/^ID=//p' /etc/os-release printf 'OS_VERSION='; sed -n 's/^VERSION_ID=//p' /etc/os-release test -n "$(hostname)" && printf 'HOSTNAME_READ=ok\n' test -d "$HOME" && printf 'USER_HOME=present\n' if command -v ss >/dev/null 2>&1; then if ss -H -ltn | awk '{print $4}' | grep -Eq '(^|:)18443$'; then printf 'PORT_18443=occupied\n' else printf 'PORT_18443=free\n'; fi else printf 'PORT_18443=unknown_no_ss\n'; fi """ target = f"{config['username']}@{address}" result = run(ssh + ["-o", "BatchMode=yes", target, remote]) if result.returncode and b"Permission denied" in result.stderr and config.get("password"): with tempfile.TemporaryDirectory(prefix="rmm-ssh-", dir=ROOT / "credentials") as directory: secret = Path(directory) / "password" secret.write_text(config["password"] + "\n") secret.chmod(0o600) askpass = Path(directory) / "askpass" askpass.write_text('#!/bin/sh\nexec cat "$RMM_SSH_PASSWORD_FILE"\n') askpass.chmod(0o700) env = dict(os.environ, SSH_ASKPASS=str(askpass), SSH_ASKPASS_REQUIRE="force", DISPLAY="rmm-preflight:0", RMM_SSH_PASSWORD_FILE=str(secret)) result = run(ssh + ["-o", "BatchMode=no", "-o", "NumberOfPasswordPrompts=1", "-o", "PreferredAuthentications=password", target, remote], env=env, stdin=subprocess.DEVNULL, start_new_session=True) if result.returncode: if b"Host key verification failed" in result.stderr or b"REMOTE HOST IDENTIFICATION HAS CHANGED" in result.stderr: print("BLOCKED: SSH host key verification failed; no trust changes made") fingerprints(address, port) else: print("BLOCKED: SSH authentication, connectivity, or remote preflight failed; private stderr withheld") return 2 for line in result.stdout.decode(errors="replace").splitlines(): if re.fullmatch(r"(?:ARCH|KERNEL|GLIBC|OS_ID|OS_VERSION|HOSTNAME_READ|USER_HOME|PORT_18443)=[A-Za-z0-9_. \"-]{1,100}", line): print(line) print("SSH_READ_ONLY_PREFLIGHT=passed; no tunnel, deployment, package or system changes performed") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except (ValueError, OSError, subprocess.TimeoutExpired): print("BLOCKED: local validation/tool execution failed (private details withheld)") raise SystemExit(2) from None