"""Pin and manage one remote libvirt host without exposing its root SSH key. The panel runs under the local service account. Its OpenSSH user configuration points at ``current/config``; ``current`` is an atomically replaced symlink to a tested generation. Failed scans/tests never switch it. """ from __future__ import annotations import base64 import binascii import hashlib import ipaddress import json import logging import os import re import secrets import shutil import stat import subprocess import threading import time from dataclasses import dataclass, field from pathlib import Path from typing import Any, Callable, Mapping from urllib.parse import quote from .ssh_agent import SSHAgentError, SSHAgentSession SSH_ALIAS = "vp-managed" LIBVIRT_URI = f"qemu+ssh://root@{SSH_ALIAS}/system?no_tty=1" _DNS_LABEL = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\Z") _FINGERPRINT = re.compile(r"SHA256:[A-Za-z0-9+/]{43}\Z") _KEY_HEADER = re.compile(r"-----BEGIN (?:OPENSSH |RSA |EC |DSA )?PRIVATE KEY-----\Z") _GEN_NAME = re.compile(r"gen-[0-9a-f]{32}\Z") _POOL_PATH = re.compile(r"/[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*\Z") _BRIDGE_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,14}\Z") PUBLIC_POOL_KEY = re.compile(r"[0-9a-f]{32}\Z") PUBLIC_POOL_STATES = frozenset({"active", "draining", "disabled"}) MAX_PUBLIC_NETWORK_POOLS = 32 _RUNNER = Callable[..., subprocess.CompletedProcess[str]] LOG = logging.getLogger(__name__) def _uri_for_generation(path: Path) -> str: command = quote(str(path / "ssh-wrapper"), safe="/") return f"{LIBVIRT_URI}&command={command}" class RemoteHostError(Exception): """A safe, user-facing connection/configuration error.""" def __init__( self, message: str, status: int = 400, error_code: str = "host_configuration_invalid", ) -> None: super().__init__(message) self.status = status self.error_code = error_code @dataclass(frozen=True) class HostProfile: host: str port: int private_key: str = field(repr=False) host_key: str = field(repr=False) private_key_passphrase: str = field(default="", repr=False) storage_pool: str = "default" iso_pool: str = "iso" rescue_iso_pool: str = "" default_network: str = "default" region: str = "" public_pool_cidr: str = "" public_gateway: str = "" public_dns_servers: list[str] = field(default_factory=list) public_reserved_ips: list[str] = field(default_factory=list) public_vm_prefix: int | None = None @dataclass class StagedHost: path: Path metadata: dict[str, Any] tested: bool = False @property def ssh_config_file(self) -> str: return str(self.path / "config") @property def ssh_known_hosts_file(self) -> str: return str(self.path / "known_hosts") @property def ssh_target(self) -> str: return SSH_ALIAS @property def libvirt_uri(self) -> str: # libvirt's ssh transport accepts ``command=`` as the executable to # launch. The staged wrapper inserts -F so libvirt can be tested with # the candidate config before the active ~/.ssh/config is switched. return _uri_for_generation(self.path) def _validate_host(host: str) -> str: if not isinstance(host, str) or not host or len(host) > 253 or host != host.strip(): raise RemoteHostError("宿主机地址格式无效") try: ipaddress.ip_address(host) return host except ValueError: pass if not all(_DNS_LABEL.fullmatch(label) for label in host.split(".")): raise RemoteHostError("宿主机地址必须是 IP 或 DNS 名称") return host.lower() def _validate_port(port: int) -> int: if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: raise RemoteHostError("SSH 端口必须介于 1 到 65535") return port def _validate_name(value: str, label: str) -> str: if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z0-9_.-]{1,128}", value): raise RemoteHostError(f"{label}名称格式无效") if value.startswith("-") or value in {".", ".."}: raise RemoteHostError(f"{label}名称格式无效") return value def _validate_pool_selector(value: str, label: str) -> str: if isinstance(value, str) and value.startswith("/"): if ( len(value) <= 4096 and _POOL_PATH.fullmatch(value) and not any(part in {".", ".."} for part in value.split("/")) ): return value raise RemoteHostError(f"{label}必须是规范的绝对目录路径") return _validate_name(value, label) def _validate_network_selector(value: str) -> str: if isinstance(value, str) and value.startswith("bridge:"): if not _BRIDGE_NAME.fullmatch(value.removeprefix("bridge:")): raise RemoteHostError("网桥名称格式无效;请填写 bridge:br0,网桥名最长 15 字符") return value return _validate_name(value, "网络") def _validate_region(value: str) -> str: # This is an operator-supplied display label, not a provider region ID. if (not isinstance(value, str) or len(value) > 64 or value != value.strip() or any(ord(char) < 32 or ord(char) == 127 for char in value)): raise RemoteHostError("宿主机地区最多 64 字符,且不能包含控制字符或首尾空格") return value def validate_public_pool( public_pool_cidr: str, public_gateway: str, public_dns_servers: list[str], public_reserved_ips: list[str], host: str, public_vm_prefix: int | None = None, ) -> dict[str, Any]: """Validate one host's public IPv4 pool without probing live network use. The SSH host address is deliberately not persisted in the reserved list: the allocator excludes a literal host IPv4 address while allocating, so the operator can still distinguish explicit reservations from that rule. A VM prefix override changes guest network configuration, never the set of addresses this pool may allocate. """ if not isinstance(public_pool_cidr, str): raise RemoteHostError( "公网地址池格式无效", error_code="host_public_pool_invalid", ) if not isinstance(public_gateway, str): raise RemoteHostError( "公网网关格式无效", error_code="host_public_gateway_invalid", ) if not isinstance(public_dns_servers, (list, tuple)): raise RemoteHostError( "公网 DNS 必须是地址列表", error_code="host_public_dns_invalid", ) if not isinstance(public_reserved_ips, (list, tuple)): raise RemoteHostError( "保留 IP 必须是地址列表", error_code="host_public_reserved_ip_invalid", ) cidr = public_pool_cidr.strip() gateway = public_gateway.strip() dns_input = list(public_dns_servers) reserved_input = list(public_reserved_ips) if not any((cidr, gateway, dns_input, reserved_input)): if public_vm_prefix is not None: raise RemoteHostError( "启用虚拟机网卡前缀前必须配置公网地址池", error_code="host_vm_prefix_invalid", ) return { "public_pool_cidr": "", "public_gateway": "", "public_dns_servers": [], "public_reserved_ips": [], "public_vm_prefix": None, } if not cidr: raise RemoteHostError( "启用公网地址池时必须填写公网网段", error_code="host_public_pool_invalid", ) if not gateway: raise RemoteHostError( "启用公网地址池时必须填写公网网关", error_code="host_public_gateway_invalid", ) if not dns_input: raise RemoteHostError( "启用公网地址池时必须填写 DNS", error_code="host_public_dns_invalid", ) if len(reserved_input) > 254: raise RemoteHostError( "保留 IP 最多可填写 254 个地址", error_code="host_public_reserved_ip_invalid", ) try: # Providers sometimes describe a routed block using its gateway (for # example 123.123.123.113/28). Normalize that host/CIDR to its actual # network before checking membership or allocating any addresses. network = ipaddress.IPv4Network(cidr, strict=False) except (ValueError, ipaddress.AddressValueError, ipaddress.NetmaskValueError) as exc: raise RemoteHostError( "公网地址池必须填写有效的 IPv4 地址/前缀", error_code="host_public_pool_invalid", ) from exc if (not 24 <= network.prefixlen <= 30 or not network.network_address.is_global or not network.broadcast_address.is_global): raise RemoteHostError( "公网地址池必须是可路由的 IPv4 网段,前缀长度为 /24 至 /30", error_code="host_public_pool_invalid", ) if network.prefixlen == 24 and cidr.split("/", 1)[0] != str(network.network_address): raise RemoteHostError( "/24 地址池必须填写网段起始地址;如果实际只获配 /28,请填写 /28 而不是 /24", error_code="host_public_pool_invalid", ) if (public_vm_prefix is not None and (isinstance(public_vm_prefix, bool) or not isinstance(public_vm_prefix, int) or not 24 <= public_vm_prefix <= network.prefixlen)): raise RemoteHostError( "虚拟机网卡前缀须介于 /24 和地址池前缀之间", error_code="host_vm_prefix_invalid", ) def parse_ipv4(value: str, label: str) -> ipaddress.IPv4Address: error_code = { "公网网关": "host_public_gateway_invalid", "公网 DNS": "host_public_dns_invalid", "保留 IP": "host_public_reserved_ip_invalid", }.get(label, "host_public_pool_invalid") if not isinstance(value, str) or not value or value != value.strip(): raise RemoteHostError( f"{label}必须是 IPv4 地址", error_code=error_code, ) try: return ipaddress.IPv4Address(value) except (ValueError, ipaddress.AddressValueError) as exc: raise RemoteHostError( f"{label}必须是 IPv4 地址", error_code=error_code, ) from exc gateway_ip = parse_ipv4(gateway, "公网网关") if gateway_ip not in network or gateway_ip in ( network.network_address, network.broadcast_address): raise RemoteHostError( "公网网关必须位于所配置的网段内", error_code="host_public_gateway_invalid", ) def unique_ips(values: list[str], label: str, *, in_pool: bool) -> list[str]: normalized: list[str] = [] seen: set[str] = set() for value in values: address = parse_ipv4(value, label) if in_pool: if address not in network or address in ( network.network_address, network.broadcast_address): raise RemoteHostError( f"{label}必须位于所配置的网段内", error_code="host_public_reserved_ip_invalid", ) elif not address.is_global: raise RemoteHostError( f"{label}必须是可路由的公网 IPv4 地址", error_code="host_public_dns_invalid", ) address_text = str(address) if address_text not in seen: seen.add(address_text) normalized.append(address_text) return normalized dns = unique_ips(dns_input, "公网 DNS", in_pool=False) reserved = unique_ips(reserved_input, "保留 IP", in_pool=True) if len(dns) > 4: raise RemoteHostError( "公网 DNS 最多可填写 4 个地址", error_code="host_public_dns_invalid", ) if not dns: raise RemoteHostError( "启用公网地址池时必须填写 DNS", error_code="host_public_dns_invalid", ) return { "public_pool_cidr": str(network), "public_gateway": str(gateway_ip), "public_dns_servers": dns, "public_reserved_ips": reserved, "public_vm_prefix": public_vm_prefix, } def validate_public_network_pool( value: Mapping[str, Any], host: str, *, allow_legacy_key: bool = False, ) -> dict[str, Any]: """Validate one revisioned public pool stored outside the host profile. The legacy host fields remain readable during the migration window, while every new pool has a stable 32-character key. Keeping this normalization beside :func:`validate_public_pool` ensures that host save, network configuration, provisioning and restart-time restoration all enforce the same on-link IPv4 constraints. """ if not isinstance(value, Mapping): raise RemoteHostError( "公网地址池配置必须是对象", error_code="host_public_pool_invalid", ) allowed = { "pool_key", "revision", "state", "network_selector", "cidr", "gateway", "dns_servers", "reserved_ips", "guest_prefix_length", } if set(value) - allowed: raise RemoteHostError( "公网地址池包含不支持的配置字段", error_code="host_public_pool_invalid", ) pool_key = value.get("pool_key") if (not isinstance(pool_key, str) or not (PUBLIC_POOL_KEY.fullmatch(pool_key) or (allow_legacy_key and pool_key == "legacy-default"))): raise RemoteHostError( "公网地址池标识必须是 32 位小写十六进制", error_code="host_public_pool_invalid", ) revision = value.get("revision") if (isinstance(revision, bool) or not isinstance(revision, int) or not 1 <= revision <= (1 << 63) - 1): raise RemoteHostError( "公网地址池版本号无效", error_code="host_public_pool_revision_invalid", ) state = value.get("state") if not isinstance(state, str) or state not in PUBLIC_POOL_STATES: raise RemoteHostError( "公网地址池状态无效", error_code="host_public_pool_state_invalid", ) network_selector = _validate_network_selector(value.get("network_selector")) normalized = validate_public_pool( value.get("cidr"), value.get("gateway"), value.get("dns_servers"), value.get("reserved_ips"), host, value.get("guest_prefix_length"), ) if not normalized["public_pool_cidr"]: raise RemoteHostError( "公网地址池不能是空配置", error_code="host_public_pool_invalid", ) return { "pool_key": pool_key, "revision": revision, "state": state, "network_selector": network_selector, "cidr": normalized["public_pool_cidr"], "gateway": normalized["public_gateway"], "dns_servers": normalized["public_dns_servers"], "reserved_ips": normalized["public_reserved_ips"], "guest_prefix_length": ( normalized["public_vm_prefix"] if normalized["public_vm_prefix"] is not None else ipaddress.IPv4Network(normalized["public_pool_cidr"]).prefixlen ), } def validate_public_network_pools( values: list[Mapping[str, Any]], host: str, *, allow_legacy_key: bool = False, ) -> list[dict[str, Any]]: """Normalize a bounded, non-overlapping public-pool catalog.""" if not isinstance(values, list) or len(values) > MAX_PUBLIC_NETWORK_POOLS: raise RemoteHostError( f"一台宿主机最多配置 {MAX_PUBLIC_NETWORK_POOLS} 个公网地址池", error_code="host_public_pool_invalid", ) pools: list[dict[str, Any]] = [] keys: set[str] = set() networks: list[tuple[str, ipaddress.IPv4Network]] = [] for value in values: pool = validate_public_network_pool( value, host, allow_legacy_key=allow_legacy_key) if pool["pool_key"] in keys: raise RemoteHostError( "公网地址池标识重复", error_code="host_public_pool_conflict", ) network = ipaddress.IPv4Network(pool["cidr"], strict=True) if any(network.overlaps(existing) for _key, existing in networks): raise RemoteHostError( "同一宿主机的公网地址池不能重叠", error_code="host_public_pool_conflict", ) keys.add(pool["pool_key"]) networks.append((pool["pool_key"], network)) pools.append(pool) return sorted(pools, key=lambda item: item["pool_key"]) def _key_parts(line: str) -> tuple[str, str]: if not isinstance(line, str) or len(line) > 4096 or any(c in line for c in "\r\n\x00"): raise RemoteHostError("主机公钥格式无效") fields = line.split() if len(fields) == 2 and fields[0] == "ssh-ed25519": key_type, encoded = fields elif len(fields) == 3 and fields[1] == "ssh-ed25519": key_type, encoded = fields[1:] else: raise RemoteHostError("目前只支持 Ed25519 SSH 主机公钥") try: blob = base64.b64decode(encoded, validate=True) except (ValueError, binascii.Error) as exc: raise RemoteHostError("主机公钥内容无效") from exc if ( len(blob) != 51 or blob[:4] != b"\x00\x00\x00\x0b" or blob[4:15] != b"ssh-ed25519" or blob[15:19] != b"\x00\x00\x00\x20" ): raise RemoteHostError("主机公钥内容无效") return key_type, base64.b64encode(blob).decode("ascii") def _fingerprint(key: str) -> str: _key_type, encoded = _key_parts(key) digest = hashlib.sha256(base64.b64decode(encoded)).digest() return "SHA256:" + base64.b64encode(digest).decode("ascii").rstrip("=") def _validate_private_key(value: str) -> bytes: if not isinstance(value, str) or not 0 < len(value) <= 131072: raise RemoteHostError( "请提供现有 SSH 私钥,最大 128 KiB", error_code="host_private_key_format_invalid", ) value = value.replace("\r\n", "\n") if "\x00" in value or "\r" in value: raise RemoteHostError( "SSH 私钥格式无效", error_code="host_private_key_format_invalid", ) header = value.split("\n", 1)[0] if not _KEY_HEADER.fullmatch(header) or "-----END " not in value: raise RemoteHostError( "请提供 PEM 或 OpenSSH 格式的私钥", error_code="host_private_key_format_invalid", ) return (value.rstrip("\n") + "\n").encode("ascii", errors="strict") def _write_private(path: Path, content: bytes) -> None: flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL if hasattr(os, "O_NOFOLLOW"): flags |= os.O_NOFOLLOW descriptor = os.open(path, flags, 0o600) try: with os.fdopen(descriptor, "wb") as stream: stream.write(content) stream.flush() os.fsync(stream.fileno()) except BaseException: path.unlink(missing_ok=True) raise def _quoted_path(path: Path) -> str: value = str(path) if any(c in value for c in "\r\n\x00"): raise RemoteHostError("面板数据路径包含不支持的字符") return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' class RemoteHostManager: """Prepare, test, and atomically select a root-key SSH generation.""" def __init__( self, data_dir: Path, *, ssh_user_config_path: Path | None = None, ssh_binary: str = "ssh", keyscan_binary: str = "ssh-keyscan", keygen_binary: str = "ssh-keygen", runner: _RUNNER | None = None, agent_factory: Callable[[Path, Path, str], SSHAgentSession] = SSHAgentSession, ) -> None: # Canonicalize once so staged paths, the active target and cleanup # comparisons all use the same path. The final data directory itself # must not be a symlink; a trusted parent may be one. requested_data_dir = Path(data_dir).expanduser().absolute() if requested_data_dir.is_symlink(): raise RemoteHostError("面板数据目录不能是符号链接", status=500) self.data_dir = requested_data_dir.resolve(strict=False) self.ssh_user_config_path = ( Path(ssh_user_config_path).expanduser().absolute() if ssh_user_config_path is not None else self.data_dir / ".ssh" / "config" ) self.ssh_binary = ssh_binary self.keyscan_binary = keyscan_binary self.keygen_binary = keygen_binary self._run = runner or subprocess.run self._agent_factory = agent_factory self._lock = threading.RLock() self._pending: set[Path] = set() self._agents: dict[Path, SSHAgentSession] = {} self.cleanup_inactive() self._schedule_cleanup() @property def libvirt_uri(self) -> str: generation = self._current_generation() return _uri_for_generation(generation) if generation is not None else LIBVIRT_URI def _exec(self, argv: list[str], *, timeout: float) -> subprocess.CompletedProcess[str]: try: return self._run( argv, check=False, capture_output=True, text=True, timeout=timeout, ) except (OSError, subprocess.TimeoutExpired) as exc: raise RemoteHostError("SSH 命令超时或无法启动", status=502) from exc def scan(self, host: str, port: int) -> dict[str, Any]: """Scan but do not trust the public key; the operator must verify it.""" host = _validate_host(host) port = _validate_port(port) result = self._exec( [self.keyscan_binary, "-T", "8", "-p", str(port), "-t", "ed25519", host], timeout=12, ) found: set[str] = set() for line in result.stdout.splitlines(): if not line or line.startswith("#"): continue try: key_type, encoded = _key_parts(line) except RemoteHostError: continue found.add(f"{key_type} {encoded}") if result.returncode != 0 or len(found) != 1: raise RemoteHostError("无法获取唯一的 Ed25519 主机公钥,请检查地址和端口", status=502) host_key = found.pop() return { "host": host, "port": port, "key_type": "ssh-ed25519", "fingerprint": _fingerprint(host_key), "host_key": host_key, "known_hosts_line": f"{SSH_ALIAS} {host_key}", } def _ensure_storage(self) -> None: self.data_dir.mkdir(mode=0o700, parents=True, exist_ok=True) if self.data_dir.is_symlink(): raise RemoteHostError("面板数据目录不能是符号链接") self.data_dir.chmod(0o700) generations = self.data_dir / "generations" generations.mkdir(mode=0o700, exist_ok=True) if generations.is_symlink(): raise RemoteHostError("面板配置目录不能是符号链接") generations.chmod(0o700) def stage( self, profile: HostProfile | Mapping[str, Any], confirmed_fingerprint: str, ) -> StagedHost: """Re-scan and write an inactive generation after explicit verification.""" if isinstance(profile, Mapping): try: profile = HostProfile(**profile) except (TypeError, ValueError) as exc: raise RemoteHostError("宿主机配置字段无效") from exc if not isinstance(profile, HostProfile): raise RemoteHostError("宿主机配置字段无效") host = _validate_host(profile.host) port = _validate_port(profile.port) storage_pool = _validate_pool_selector(profile.storage_pool, "磁盘池") iso_pool = _validate_pool_selector(profile.iso_pool, "ISO 池") rescue_iso_pool = ( _validate_pool_selector(profile.rescue_iso_pool, "救援 ISO 池") if profile.rescue_iso_pool != "" else "" ) if rescue_iso_pool and rescue_iso_pool == iso_pool: raise RemoteHostError("救援 ISO 池不能与安装 ISO 池相同") default_network = _validate_network_selector(profile.default_network) region = _validate_region(profile.region) public_pool = validate_public_pool( profile.public_pool_cidr, profile.public_gateway, profile.public_dns_servers, profile.public_reserved_ips, host, profile.public_vm_prefix, ) if not isinstance(confirmed_fingerprint, str) or not _FINGERPRINT.fullmatch(confirmed_fingerprint): raise RemoteHostError("请确认扫描得到的 SHA256 主机指纹") try: submitted_type, submitted_encoded = _key_parts(profile.host_key) except RemoteHostError as exc: raise RemoteHostError("提交的主机公钥格式无效") from exc submitted_key = f"{submitted_type} {submitted_encoded}" scanned = self.scan(host, port) if scanned["host_key"] != submitted_key or scanned["fingerprint"] != confirmed_fingerprint: raise RemoteHostError("主机公钥或指纹在扫描后发生变化,请重新核验", status=409) self._ensure_storage() generation = self.data_dir / "generations" / ("gen-" + secrets.token_hex(16)) generation.mkdir(mode=0o700) try: key_path = generation / "id_private" if profile.private_key: try: key_bytes = _validate_private_key(profile.private_key) except UnicodeEncodeError: raise RemoteHostError( "SSH 私钥必须是 ASCII PEM 文本", error_code="host_private_key_format_invalid", ) from None else: current = self._current_generation() if current is None: raise RemoteHostError( "首次连接必须提供现有 SSH 私钥", error_code="host_private_key_required", ) try: key_bytes = (current / "id_private").read_bytes() except OSError as exc: raise RemoteHostError("已保存的 SSH 私钥无法读取", status=500) from exc _write_private(key_path, key_bytes) key_check = self._exec( [self.keygen_binary, "-y", "-P", "", "-f", str(key_path)], timeout=8, ) # Successful ssh-keygen -y is authoritative here: unencrypted # ECDSA keys produce an `ecdsa-sha2-*` public key, not `ssh-*`. encrypted = key_check.returncode != 0 or len(key_check.stdout.split()) < 2 identity_path = key_path identity_agent = "none" if encrypted: if not profile.private_key_passphrase: raise RemoteHostError( "私钥已加密或无效;请填写私钥口令后重试", error_code="host_private_key_passphrase_required", ) try: agent = self._agent_factory(generation, key_path, profile.private_key_passphrase) except SSHAgentError as exc: raise RemoteHostError( "私钥口令错误或私钥无效,无法解锁", error_code="host_private_key_invalid", ) from exc with self._lock: self._agents[generation] = agent identity_path = generation / "identity.pub" _write_private(identity_path, (agent.public_key + "\n").encode("ascii")) identity_agent = _quoted_path(agent.socket_path) known_hosts = generation / "known_hosts" _write_private(known_hosts, f"{SSH_ALIAS} {submitted_key}\n".encode("ascii")) ssh_config = generation / "config" config_text = ( f"Host {SSH_ALIAS}\n" f" HostName {host}\n" f" Port {port}\n" " User root\n" f" IdentityFile {_quoted_path(identity_path)}\n" f" UserKnownHostsFile {_quoted_path(known_hosts)}\n" " GlobalKnownHostsFile /dev/null\n" f" HostKeyAlias {SSH_ALIAS}\n" " HostKeyAlgorithms ssh-ed25519\n" " StrictHostKeyChecking yes\n" " VerifyHostKeyDNS no\n" " BatchMode yes\n" " IdentitiesOnly yes\n" f" IdentityAgent {identity_agent}\n" " PreferredAuthentications publickey\n" " PasswordAuthentication no\n" " KbdInteractiveAuthentication no\n" " GSSAPIAuthentication no\n" " ForwardAgent no\n" " ProxyCommand none\n" " ProxyJump none\n" " CanonicalizeHostname no\n" " ControlMaster no\n" " ControlPath none\n" " UpdateHostKeys no\n" " RequestTTY no\n" " ServerAliveInterval 15\n" " ServerAliveCountMax 2\n" " ConnectTimeout 10\n" ) _write_private(ssh_config, config_text.encode("ascii")) wrapper = generation / "ssh-wrapper" wrapper_text = ( "#!/usr/bin/env python3\n" "import os\n" "import sys\n" f"os.execvp({self.ssh_binary!r}, " f"[{self.ssh_binary!r}, '-F', {str(ssh_config)!r}, *sys.argv[1:]])\n" ) _write_private(wrapper, wrapper_text.encode("ascii")) wrapper.chmod(0o700) metadata = { "host": host, "port": port, "key_type": "ssh-ed25519", "fingerprint": confirmed_fingerprint, "private_key_configured": True, "private_key_encrypted": encrypted, "storage_pool": storage_pool, "iso_pool": iso_pool, "rescue_iso_pool": rescue_iso_pool, "default_network": default_network, "region": region, **public_pool, } _write_private( generation / "profile.json", json.dumps(metadata, ensure_ascii=False).encode("utf-8"), ) with self._lock: self._pending.add(generation) return StagedHost(generation, metadata) except BaseException: with self._lock: agent = self._agents.pop(generation, None) if agent is not None: agent.close() shutil.rmtree(generation) raise def test(self, staged: StagedHost) -> dict[str, Any]: """Check the staged key, pinned host key, SSH, and remote libvirt.""" self._check_staged(staged) result = self._exec( [ self.ssh_binary, "-F", staged.ssh_config_file, "-T", "-o", "ConnectTimeout=10", SSH_ALIAS, "/usr/bin/virsh -c qemu:///system list --all", ], timeout=22, ) if result.returncode != 0: # Do not reflect stderr: SSH diagnostics can contain arbitrary # remote data or paths, and never need to include the secret key. raise RemoteHostError( "SSH 或宿主机 libvirt 连接失败;请检查 root 密钥、端口、主机指纹和 virsh 服务", status=502, ) staged.tested = True return {"ok": True, "ssh": "connected", "libvirt": "available"} def _check_staged(self, staged: StagedHost) -> None: if not isinstance(staged, StagedHost) or staged.path.parent != self.data_dir / "generations": raise RemoteHostError("暂存配置无效") if staged.path.is_symlink() or not staged.path.is_dir(): raise RemoteHostError("暂存配置不存在") def _current_generation(self) -> Path | None: current = self.data_dir / "current" if not current.is_symlink(): if current.exists(): raise RemoteHostError("已保存的宿主机配置损坏", status=500) return None target = current.resolve() if target.parent != self.data_dir / "generations" or not target.is_dir(): raise RemoteHostError("已保存的宿主机配置损坏", status=500) return target def _ensure_user_ssh_config(self) -> None: ssh_dir = self.ssh_user_config_path.parent ssh_dir.mkdir(mode=0o700, parents=True, exist_ok=True) if ssh_dir.is_symlink(): raise RemoteHostError("服务账号 SSH 目录不能是符号链接", status=500) ssh_dir.chmod(0o700) destination = self.data_dir / "current" / "config" user_config = self.ssh_user_config_path if user_config.is_symlink(): if user_config.readlink() != destination: raise RemoteHostError("服务账号已有其他 SSH 配置,请勿覆盖", status=409) elif user_config.exists(): raise RemoteHostError("服务账号已有其他 SSH 配置,请勿覆盖", status=409) else: user_config.symlink_to(destination) def commit(self, staged: StagedHost) -> dict[str, Any]: """Activate a previously tested generation with one atomic symlink swap.""" with self._lock: self._check_staged(staged) if not staged.tested: raise RemoteHostError("保存前必须先测试宿主机连接", status=409) self._ensure_user_ssh_config() previous = self._current_generation() link = self.data_dir / (".current-" + secrets.token_hex(8)) link.symlink_to(staged.path) try: os.replace(link, self.data_dir / "current") finally: link.unlink(missing_ok=True) self._pending.discard(staged.path) if previous is not None and previous != staged.path: # Give in-flight API calls that obtained the old URI time to # launch SSH before removing that generation's private key. try: os.utime(previous, None) except OSError as exc: LOG.warning("could not date retired SSH generation: %s", exc) self._schedule_cleanup() return self.current() or {} def abort(self, staged: StagedHost) -> None: with self._lock: self._check_staged(staged) if self._current_generation() == staged.path: raise RemoteHostError("不能删除正在使用的宿主机配置", status=409) self._pending.discard(staged.path) agent = self._agents.pop(staged.path, None) if agent is not None: agent.close() shutil.rmtree(staged.path) def _schedule_cleanup(self) -> None: timer = threading.Timer(65, self.cleanup_inactive) timer.daemon = True timer.start() def cleanup_inactive(self, *, grace_seconds: float = 60) -> int: """Remove only retired generations owned by this manager's data tree.""" if grace_seconds < 0: raise ValueError("grace_seconds must not be negative") with self._lock: root = self.data_dir / "generations" if root.is_symlink(): raise RemoteHostError("面板配置目录损坏", status=500) if not root.exists(): return 0 if not root.is_dir(): raise RemoteHostError("面板配置目录损坏", status=500) active = self._current_generation() now = time.time() removed = 0 for entry in root.iterdir(): if ( not _GEN_NAME.fullmatch(entry.name) or entry.is_symlink() or not entry.is_dir() or entry == active or entry in self._pending ): continue try: if now - entry.stat().st_mtime < grace_seconds: continue agent = self._agents.pop(entry, None) if agent is not None: agent.close() shutil.rmtree(entry) removed += 1 except OSError as exc: LOG.warning("could not prune retired SSH generation: %s", exc) return removed def unlock_current(self, passphrase: str) -> dict[str, Any]: """Load the saved encrypted key into a process-local SSH agent.""" with self._lock: generation = self._current_generation() if generation is None: raise RemoteHostError("请先配置宿主机", 409) profile = self.current() if profile is None or not profile["private_key_encrypted"]: raise RemoteHostError("当前 SSH 私钥不需要解锁", 409) if not profile["key_locked"]: return profile try: agent = self._agent_factory(generation, generation / "id_private", passphrase) except SSHAgentError as exc: raise RemoteHostError( "私钥口令错误或私钥无效,无法解锁", error_code="host_private_key_invalid", ) from exc try: expected = (generation / "identity.pub").read_text(encoding="ascii").split() actual = agent.public_key.split() if len(expected) < 2 or actual[:2] != expected[:2]: raise RemoteHostError("已保存的私钥与公钥不匹配", 500) self._set_agent_socket(generation, agent.socket_path) except BaseException: agent.close() raise previous = self._agents.pop(generation, None) if previous is not None: previous.close() self._agents[generation] = agent return self.current() or {} @staticmethod def _set_agent_socket(generation: Path, socket_path: Path) -> None: """Atomically point the active SSH config at the newly unlocked agent.""" config = generation / "config" info = config.lstat() if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: raise RemoteHostError("已保存的 SSH 配置权限无效", 500) lines = config.read_text(encoding="ascii").splitlines(keepends=True) replacements = [index for index, line in enumerate(lines) if line.startswith(" IdentityAgent ")] if len(replacements) != 1: raise RemoteHostError("已保存的 SSH 配置损坏", 500) lines[replacements[0]] = f" IdentityAgent {_quoted_path(socket_path)}\n" temporary = generation / (".config-" + secrets.token_hex(8)) try: _write_private(temporary, "".join(lines).encode("ascii")) os.replace(temporary, config) finally: temporary.unlink(missing_ok=True) def close(self) -> None: """Stop all process-local agents on graceful panel shutdown.""" with self._lock: agents = list(self._agents.values()) self._agents.clear() for agent in agents: agent.close() def current(self) -> dict[str, Any] | None: generation = self._current_generation() if generation is None: return None try: metadata = json.loads((generation / "profile.json").read_text(encoding="utf-8")) except (OSError, ValueError) as exc: raise RemoteHostError("已保存的宿主机配置损坏", status=500) from exc fields = ( "host", "port", "key_type", "fingerprint", "private_key_configured", "storage_pool", "iso_pool", "default_network", ) if any(field not in metadata for field in fields): raise RemoteHostError("已保存的宿主机配置损坏", status=500) try: region = _validate_region(metadata.get("region", "")) rescue_iso_pool = metadata.get("rescue_iso_pool", "") if rescue_iso_pool != "": rescue_iso_pool = _validate_pool_selector(rescue_iso_pool, "救援 ISO 池") if rescue_iso_pool == metadata["iso_pool"]: raise RemoteHostError("救援 ISO 池不能与安装 ISO 池相同") public_pool = validate_public_pool( metadata.get("public_pool_cidr", ""), metadata.get("public_gateway", ""), metadata.get("public_dns_servers", []), metadata.get("public_reserved_ips", []), metadata["host"], metadata.get("public_vm_prefix"), ) except RemoteHostError as exc: raise RemoteHostError("已保存的宿主机配置损坏", status=500) from exc return { **{field: metadata[field] for field in fields}, "rescue_iso_pool": rescue_iso_pool, "region": region, **public_pool, "private_key_encrypted": bool(metadata.get("private_key_encrypted", False)), "key_locked": bool(metadata.get("private_key_encrypted", False)) and not ( generation in self._agents and self._agents[generation].alive ), "libvirt_uri": _uri_for_generation(generation), "ssh_target": SSH_ALIAS, "ssh_config_file": str(generation / "config"), "ssh_known_hosts_file": str(generation / "known_hosts"), } # A clearer name for callers that prefer "store" terminology. RemoteHostStore = RemoteHostManager