"""A private, short-lived OpenSSH agent for one saved host generation. The key passphrase is handed to ``ssh-add`` through a one-shot inherited pipe and an askpass helper. It is never put in an argument, environment value, or file. The agent keeps the unlocked identity only for this panel process. """ from __future__ import annotations import base64 import binascii import ctypes import os import secrets import select import shutil import signal import subprocess import sys import time from pathlib import Path class SSHAgentError(Exception): """A safe, user-facing agent error that contains no credentials.""" _ASKPASS_SOURCE = b"""#!/usr/bin/python3 import os import sys try: fd = int(os.environ["VIRSH_PANEL_ASKPASS_FD"]) parts = [] size = 0 while True: part = os.read(fd, 1024) if not part: break size += len(part) if size > 1023: sys.exit(1) parts.append(part) if size == 0: sys.exit(1) os.write(1, b"".join(parts)) except (KeyError, ValueError, OSError): sys.exit(1) """ def _command(name: str) -> str: executable = shutil.which(name) if executable is None: raise SSHAgentError(f"面板服务器缺少 {name} 命令") return str(Path(executable).resolve()) def _agent_environment(socket_path: Path) -> dict[str, str]: environment = os.environ.copy() environment["SSH_AUTH_SOCK"] = str(socket_path) return environment def _safe_public_key(value: str) -> str: lines = value.splitlines() if len(lines) != 1: raise SSHAgentError("SSH agent 未能确认唯一的私钥身份") fields = lines[0].split() if len(fields) < 2 or not fields[0].startswith(("ssh-", "ecdsa-", "sk-")): raise SSHAgentError("SSH agent 返回的公钥格式无效") try: fields[0].encode("ascii") fields[1].encode("ascii") blob = base64.b64decode(fields[1], validate=True) except (binascii.Error, UnicodeEncodeError, ValueError) as exc: raise SSHAgentError("SSH agent 返回的公钥格式无效") from exc if not 16 <= len(blob) <= 8192: raise SSHAgentError("SSH agent 返回的公钥格式无效") return f"{fields[0]} {fields[1]}" class SSHAgentSession: """Own one foreground ``ssh-agent`` and its single unlocked identity.""" def __init__(self, generation: Path, key_path: Path, passphrase: str) -> None: generation = Path(generation).absolute() key_path = Path(key_path).absolute() if ( generation.is_symlink() or not generation.is_dir() or key_path.is_symlink() or not key_path.is_file() or key_path.parent != generation ): raise SSHAgentError("SSH 密钥配置目录无效") if not isinstance(passphrase, str): raise SSHAgentError("SSH 私钥口令格式无效") if any(character in passphrase for character in "\r\n\x00"): raise SSHAgentError("SSH 私钥口令不能包含换行或 NUL 字符") try: passphrase_bytes = passphrase.encode("utf-8") except UnicodeEncodeError as exc: raise SSHAgentError("SSH 私钥口令格式无效") from exc if len(passphrase_bytes) > 1023: raise SSHAgentError("SSH 私钥口令不能超过 1023 个 UTF-8 字节") self.socket_path = generation / ("agent-" + secrets.token_hex(8) + ".sock") self.public_key = "" self._process: subprocess.Popen[bytes] | None = None self._helper_path: Path | None = None self._watchdog_write_fd: int | None = None if len(os.fsencode(self.socket_path)) >= 100: raise SSHAgentError("面板数据目录路径过长,无法创建 SSH agent socket") try: self._start() self.public_key = self._load_key(key_path, passphrase_bytes) except SSHAgentError: self.close() raise except (OSError, subprocess.TimeoutExpired): self.close() raise SSHAgentError("SSH agent 启动或解锁失败") from None def _start(self) -> None: if self.socket_path.exists() or self.socket_path.is_symlink(): raise SSHAgentError("SSH agent socket 路径已被占用") try: if sys.platform == "linux": # PR_SET_PDEATHSIG observes the *creating thread*, not the # whole panel process. A FastAPI worker thread can end while # the panel remains live, so a single-threaded supervisor # watches a pipe whose writer belongs to the panel process. read_fd, write_fd = os.pipe() self._watchdog_write_fd = write_fd try: self._process = subprocess.Popen( [ sys.executable, str(Path(__file__).resolve()), "--agent-supervisor", str(read_fd), _command("ssh-agent"), str(self.socket_path), ], pass_fds=(read_fd,), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True, ) finally: os.close(read_fd) else: self._process = subprocess.Popen( [_command("ssh-agent"), "-D", "-a", str(self.socket_path)], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True, ) except OSError: raise SSHAgentError("SSH agent 无法启动") from None deadline = time.monotonic() + 3 while time.monotonic() < deadline: if self._process.poll() is not None: raise SSHAgentError("SSH agent 启动后立即退出") if self.socket_path.is_socket(): return time.sleep(0.02) raise SSHAgentError("SSH agent 启动超时") def _create_helper(self) -> Path: helper = self.socket_path.parent / ("askpass-" + secrets.token_hex(8)) flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL if hasattr(os, "O_NOFOLLOW"): flags |= os.O_NOFOLLOW descriptor = os.open(helper, flags, 0o700) try: with os.fdopen(descriptor, "wb") as output: os.fchmod(output.fileno(), 0o700) output.write(_ASKPASS_SOURCE) output.flush() os.fsync(output.fileno()) except BaseException: helper.unlink(missing_ok=True) raise self._helper_path = helper return helper def _load_key(self, key_path: Path, passphrase: bytes) -> str: helper = self._create_helper() read_fd, write_fd = os.pipe() try: if passphrase: os.write(write_fd, passphrase) os.close(write_fd) write_fd = -1 environment = _agent_environment(self.socket_path) environment.update( { "SSH_ASKPASS": str(helper), "SSH_ASKPASS_REQUIRE": "force", "VIRSH_PANEL_ASKPASS_FD": str(read_fd), } ) loaded = subprocess.run( [_command("ssh-add"), "-k", "-q", str(key_path)], env=environment, pass_fds=(read_fd,), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=12, check=False, ) finally: os.close(read_fd) if write_fd != -1: os.close(write_fd) helper.unlink(missing_ok=True) self._helper_path = None if loaded.returncode != 0: raise SSHAgentError("SSH 私钥无法解锁;请检查私钥内容和口令") listed = subprocess.run( [_command("ssh-add"), "-L"], env=_agent_environment(self.socket_path), stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, timeout=5, check=False, ) if listed.returncode != 0: raise SSHAgentError("SSH agent 未能读取已解锁的公钥") return _safe_public_key(listed.stdout) @property def alive(self) -> bool: if self._process is None or self._process.poll() is not None: return False if not self.socket_path.is_socket(): return False try: result = subprocess.run( [_command("ssh-add"), "-l"], env=_agent_environment(self.socket_path), stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2, check=False, ) except (OSError, subprocess.TimeoutExpired, SSHAgentError): return False return result.returncode == 0 def close(self) -> None: process = self._process self._process = None watchdog_write_fd = self._watchdog_write_fd self._watchdog_write_fd = None if watchdog_write_fd is not None: try: os.close(watchdog_write_fd) except OSError: pass if process is not None: try: if process.poll() is None: if watchdog_write_fd is None: process.terminate() process.wait(timeout=2) except (OSError, subprocess.TimeoutExpired): try: process.terminate() process.wait(timeout=2) except (OSError, subprocess.TimeoutExpired): try: process.kill() process.wait(timeout=2) except (OSError, subprocess.TimeoutExpired): pass if self._helper_path is not None: self._helper_path.unlink(missing_ok=True) self._helper_path = None if process is not None: try: if self.socket_path.is_socket(): self.socket_path.unlink() except OSError: pass def _agent_child(expected_parent_pid: int, agent_binary: str, socket_path: str) -> int: """Set Linux parent-death SIGTERM, then replace this process with agent.""" if sys.platform != "linux" or expected_parent_pid <= 1: return 1 try: prctl = ctypes.CDLL(None, use_errno=True).prctl prctl.argtypes = [ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong] prctl.restype = ctypes.c_int if prctl(1, signal.SIGTERM, 0, 0, 0) != 0: # PR_SET_PDEATHSIG return 1 # The supervisor may have died before prctl took effect. if os.getppid() != expected_parent_pid: return 1 os.execv(agent_binary, [agent_binary, "-D", "-a", socket_path]) except (AttributeError, OSError): return 1 return 1 def _agent_supervisor(read_fd: int, agent_binary: str, socket_path: str) -> int: """End the agent when the panel closes its pipe, including on SIGKILL.""" if sys.platform != "linux" or read_fd < 3: return 1 child: subprocess.Popen[bytes] | None = None try: child = subprocess.Popen( [ sys.executable, str(Path(__file__).resolve()), "--agent-child", str(os.getpid()), agent_binary, socket_path, ], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True, ) poller = select.poll() poller.register(read_fd, select.POLLIN | select.POLLHUP | select.POLLERR) while True: if child.poll() is not None: return 1 if poller.poll(100): return 0 except (OSError, ValueError): return 1 finally: if child is not None and child.poll() is None: try: child.terminate() child.wait(timeout=2) except (OSError, subprocess.TimeoutExpired): try: child.kill() child.wait(timeout=2) except (OSError, subprocess.TimeoutExpired): pass try: if Path(socket_path).is_socket(): Path(socket_path).unlink() except OSError: pass try: os.close(read_fd) except OSError: pass if __name__ == "__main__": if len(sys.argv) == 5 and sys.argv[1] == "--agent-supervisor": raise SystemExit(_agent_supervisor(int(sys.argv[2]), sys.argv[3], sys.argv[4])) if len(sys.argv) == 5 and sys.argv[1] == "--agent-child": raise SystemExit(_agent_child(int(sys.argv[2]), sys.argv[3], sys.argv[4])) raise SystemExit(1)