You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/tests/test_ssh_agent.py

211 lines
7.4 KiB
Python

"""Exercise passphrase loading without a remote SSH server."""
from __future__ import annotations
import errno
import os
import select
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path
import pytest
from virsh_panel.ssh_agent import SSHAgentError, SSHAgentSession
@pytest.fixture
def encrypted_key() -> tuple[Path, Path, str]:
for command in ("ssh-agent", "ssh-add", "ssh-keygen"):
if shutil.which(command) is None:
pytest.skip(f"{command} is unavailable")
temporary_root = "/private/tmp" if Path("/private/tmp").is_dir() else "/tmp"
with tempfile.TemporaryDirectory(prefix="vp-agent-", dir=temporary_root) as directory:
generation = Path(directory) / "generation"
generation.mkdir(mode=0o700)
probe_path = generation / "probe.sock"
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
try:
probe.bind(str(probe_path))
except OSError as exc:
if sys.platform == "darwin" and exc.errno in {errno.EACCES, errno.EPERM}:
pytest.skip("test environment forbids local Unix sockets")
raise
probe_path.unlink()
key_path = generation / "id_private"
passphrase = "integration-test-only-phrase"
subprocess.run(
["ssh-keygen", "-q", "-t", "ed25519", "-N", passphrase, "-f", str(key_path)],
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
check=True,
timeout=10,
)
yield generation, key_path, passphrase
def test_load_encrypted_key_and_close(encrypted_key: tuple[Path, Path, str]) -> None:
generation, key_path, passphrase = encrypted_key
session = SSHAgentSession(generation, key_path, passphrase)
socket_path = session.socket_path
try:
assert socket_path.parent == generation
assert socket_path.is_socket()
assert session.alive
assert session.public_key.startswith("ssh-ed25519 ")
assert not list(generation.glob("askpass-*"))
listed = subprocess.run(
["ssh-add", "-L"],
env={**os.environ, "SSH_AUTH_SOCK": str(socket_path)},
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
check=True,
timeout=5,
)
assert listed.stdout.startswith(session.public_key)
finally:
session.close()
assert not session.alive
assert not socket_path.exists()
def test_wrong_passphrase_cleans_up(encrypted_key: tuple[Path, Path, str]) -> None:
generation, key_path, _passphrase = encrypted_key
with pytest.raises(SSHAgentError, match="无法解锁"):
SSHAgentSession(generation, key_path, "incorrect-test-only-phrase")
assert not list(generation.glob("agent-*.sock"))
assert not list(generation.glob("askpass-*"))
def test_two_sessions_do_not_share_socket(encrypted_key: tuple[Path, Path, str]) -> None:
generation, key_path, passphrase = encrypted_key
first = SSHAgentSession(generation, key_path, passphrase)
second = SSHAgentSession(generation, key_path, passphrase)
try:
assert first.socket_path != second.socket_path
first.close()
assert second.alive
finally:
first.close()
second.close()
@pytest.mark.parametrize("bad", ["x\ny", "x\ry", "x\x00y", "x" * 1024])
def test_rejects_unsafe_passphrase(
encrypted_key: tuple[Path, Path, str], bad: str
) -> None:
generation, key_path, _passphrase = encrypted_key
with pytest.raises(SSHAgentError):
SSHAgentSession(generation, key_path, bad)
assert not list(generation.glob("agent-*.sock"))
def test_passphrase_is_not_in_arguments_or_environment(
encrypted_key: tuple[Path, Path, str], monkeypatch: pytest.MonkeyPatch
) -> None:
generation, key_path, passphrase = encrypted_key
original_run = subprocess.run
observed: list[dict[str, object]] = []
def checking_run(argv: list[str], **kwargs: object) -> subprocess.CompletedProcess[object]:
if Path(argv[0]).name == "ssh-add" and "-q" in argv:
observed.append(kwargs)
assert passphrase not in repr(argv)
assert passphrase not in repr(kwargs.get("env"))
assert kwargs.get("pass_fds")
assert kwargs.get("stdin") == subprocess.DEVNULL
return original_run(argv, **kwargs)
monkeypatch.setattr(subprocess, "run", checking_run)
session = SSHAgentSession(generation, key_path, passphrase)
try:
assert session.alive
assert len(observed) == 1
finally:
session.close()
@pytest.mark.skipif(sys.platform != "linux", reason="Linux parent-death watchdog")
def test_linux_agent_survives_creator_thread_exit(
encrypted_key: tuple[Path, Path, str]
) -> None:
generation, key_path, passphrase = encrypted_key
created: dict[str, object] = {}
def create() -> None:
try:
created["session"] = SSHAgentSession(generation, key_path, passphrase)
except Exception as exc:
created["error"] = exc
thread = threading.Thread(target=create)
thread.start()
thread.join(timeout=20)
assert not thread.is_alive()
error = created.get("error")
if isinstance(error, BaseException):
raise error
session = created["session"]
assert isinstance(session, SSHAgentSession)
try:
# Direct PR_SET_PDEATHSIG on the app-spawned agent would kill it when
# this worker thread exits, even though the panel process is alive.
time.sleep(0.2)
assert session.alive
finally:
session.close()
@pytest.mark.skipif(sys.platform != "linux", reason="Linux parent-death watchdog")
def test_linux_agent_ends_after_panel_sigkill(
encrypted_key: tuple[Path, Path, str]
) -> None:
generation, key_path, passphrase = encrypted_key
child_code = (
"import sys,time\n"
"from pathlib import Path\n"
"from virsh_panel.ssh_agent import SSHAgentSession\n"
"session=SSHAgentSession(Path(sys.argv[1]),Path(sys.argv[2]),"
"sys.stdin.readline().rstrip('\\n'))\n"
"print(session.socket_path, flush=True)\n"
"time.sleep(60)\n"
)
panel = subprocess.Popen(
[sys.executable, "-c", child_code, str(generation), str(key_path)],
cwd=str(Path(__file__).resolve().parents[1]),
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
assert panel.stdin is not None
panel.stdin.write(passphrase + "\n")
panel.stdin.close()
assert panel.stdout is not None
readable, _, _ = select.select([panel.stdout], [], [], 15)
assert readable, "panel subprocess did not report its agent socket"
socket_name = panel.stdout.readline().strip()
assert socket_name, "panel subprocess exited before starting its agent"
agent_socket = Path(socket_name)
assert agent_socket.is_socket()
os.kill(panel.pid, signal.SIGKILL)
panel.wait(timeout=5)
deadline = time.monotonic() + 5
while agent_socket.exists() and time.monotonic() < deadline:
time.sleep(0.05)
assert not agent_socket.exists(), "agent socket survived the panel process"
finally:
if panel.poll() is None:
panel.kill()
panel.wait(timeout=5)