hub/probe/test_hostprobe.py
trvon 0d7a219c5d
Some checks failed
release / build (push) Failing after 2m13s
hub: operator CLI with signed self-update
2026-11-10 20:32:32 -07:00

495 lines
21 KiB
Python

# SPDX-License-Identifier: GPL-3.0-or-later
from __future__ import annotations
import ast
import builtins
import importlib.util
import io
import json
import os
import shutil
import sys
import tempfile
import unittest
from datetime import datetime, timezone
from pathlib import Path
from unittest.mock import patch
HERE = Path(__file__).resolve().parent
FIX = HERE / "fixtures"
SPEC = importlib.util.spec_from_file_location("hostprobe", HERE / "hostprobe.py")
hostprobe = importlib.util.module_from_spec(SPEC)
sys.modules["hostprobe"] = hostprobe
SPEC.loader.exec_module(hostprobe)
PINNED_NOW = datetime(2026, 11, 8, 12, 0, 0, tzinfo=timezone.utc)
SENTINELS = ("SENTINEL_UNIT_ENV", "SENTINEL_ARG", "SENTINEL_SALT_CONF", "SENTINEL_DECOY")
WHICH = {"alpha": {"docker", "apt-get", "nft"}, "beta": {"docker", "apt-get"}}
class FakeExec:
"""Replays recorded command output keyed by argv; records every argv it is asked to run."""
def __init__(self, table):
self.table = table
self.calls = []
def __call__(self, argv, timeout):
self.calls.append(list(argv))
joined = " ".join(argv)
if joined in self.table:
rc, out = self.table[joined]
return rc, out
for key, (rc, out) in self.table.items():
if joined.startswith(key + " "):
return rc, out
return 127, ""
class FixtureProbe(hostprobe.Probe):
def arch(self):
return "x86_64"
def disk_usage(self):
return 100 * 10**9, 57 * 10**9
def python_version(self):
return "3.11.2"
def file_meta(self, st):
return "root", "root", "0755"
def make_probe(name, table=None, root=None):
if table is None:
table = json.loads((FIX / f"commands-{name}.json").read_text())
ex = FakeExec(table)
probe = FixtureProbe(
root=str(root or FIX / f"root-{name}"),
executor=ex,
which=lambda cmd: "/usr/bin/" + cmd if cmd in WHICH[name] else None,
user="admin",
groups=["admin", "docker", "sudo"],
now=lambda: PINNED_NOW,
)
return probe, ex
def build_profile(name):
return make_probe(name)[0].collect()
def sec(profile, key):
return profile["sections"][key]
def spy_open(opened):
real_open = builtins.open
def spy(path, *args, **kwargs):
opened.append(str(path))
return real_open(path, *args, **kwargs)
return patch.object(builtins, "open", spy)
class ExpectedFixtures(unittest.TestCase):
def test_expected_outputs_match_the_probe(self):
for name in ("alpha", "beta"):
with self.subTest(host=name):
expected = json.loads((FIX / f"expected-{name}.json").read_text())
self.assertEqual(build_profile(name), expected)
def test_expected_outputs_carry_no_sentinel(self):
for name in ("alpha", "beta"):
text = (FIX / f"expected-{name}.json").read_text()
for sentinel in SENTINELS:
self.assertNotIn(sentinel, text)
class GitFacts(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.p = build_profile("alpha")
def test_compose_projects_use_real_labels(self):
rows = {(c["project"], c["service"]) for c in sec(self.p, "containers")}
self.assertEqual(rows, {("forgejo", "forgejo"), ("forgejo", "caddy"), ("forgejo-onion", "tor")})
def test_published_ports_and_bind_addresses(self):
forgejo = next(c for c in sec(self.p, "containers") if c["service"] == "forgejo")
got = {(b["host_ip"], b["host_port"]) for b in forgejo["ports"]}
self.assertEqual(got, {("127.0.0.1", 3000), ("0.0.0.0", 2222), ("::", 2222)})
def test_docker29_containers_without_healthcheck_have_empty_health(self):
health = {c["service"]: c["health"] for c in sec(self.p, "containers")}
self.assertEqual(health["forgejo"], "")
self.assertEqual(health["caddy"], "")
def test_allowusers_is_reported(self):
sshd = sec(self.p, "access")["sshd"]
self.assertEqual(sshd["source"], "sshd -T")
self.assertEqual(sshd["allowusers"], ["admin"])
self.assertEqual(sshd["permitrootlogin"], "no")
self.assertNotIn("x11forwarding", json.dumps(sshd))
self.assertNotIn("hostkey", json.dumps(sshd))
def test_update_script_candidate_is_root_owned_with_the_real_hash(self):
(cand,) = sec(self.p, "candidates")
self.assertEqual(cand["path"], "/srv/forgejo/update-forgejo.sh")
self.assertEqual((cand["owner"], cand["group"], cand["mode"]), ("root", "root", "0755"))
self.assertEqual(cand["sha256"], "a04444330f4a7d32cd82c92655929117d9fb0a74169cd508f8e180710a6c4ae2")
self.assertEqual(cand["unit"], "forgejo-update.service")
def test_timer_oncalendar_and_service_exec_paths(self):
units = {u["name"]: u for u in sec(self.p, "services")}
self.assertEqual(units["forgejo-update.timer"]["on_calendar"], ["Sun *-*-* 04:00"])
self.assertEqual(units["forgejo-update.service"]["exec_paths"], ["/srv/forgejo/update-forgejo.sh"])
self.assertEqual(units["forgejo-update.timer"]["enabled"], "enabled")
self.assertEqual(units["forgejo-update.service"]["active"], "inactive")
def test_identity(self):
ident = sec(self.p, "identity")
self.assertEqual(ident["hostname"], "alpha")
self.assertEqual(ident["os"]["version_codename"], "trixie")
self.assertEqual(ident["tailscale0"], ["100.64.0.11", "fd7a:115c:a1e0::1"])
self.assertEqual(ident["cpus"], 2)
self.assertEqual(len(ident["machine_id_sha256_prefix"]), 16)
self.assertNotIn("11111111111111111111111111111111", json.dumps(self.p))
(key,) = ident["ssh_host_keys"]
self.assertTrue(key["fingerprint"].startswith("SHA256:"))
def test_salt_minion_keeps_only_id_and_master(self):
salt = sec(self.p, "software")["salt_minion"]
self.assertEqual((salt["id"], salt["master"], salt["version"]), ("alpha", "100.64.0.1", "3008.2"))
def test_listening_has_process_names_and_ipv6(self):
got = {(s["proto"], s["address"], s["port"]): s["process"] for s in sec(self.p, "listening")}
self.assertEqual(got[("tcp", "::", 22)], "sshd")
self.assertEqual(got[("tcp", "127.0.0.1", 3000)], "docker-proxy")
def test_cron_reports_names_only(self):
self.assertEqual(sec(self.p, "cron"), {"cron_d": ["e2scrub_all"], "user_crontabs": False})
class BetaFacts(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.p = build_profile("beta")
def test_challenges_project_services(self):
rows = sorted((c["project"], c["service"]) for c in sec(self.p, "containers"))
self.assertEqual(rows, [("challenges", s) for s in ("lab-a", "lab-b", "lab-c", "lab-d")])
def test_every_container_user_is_non_root_and_unprivileged(self):
for c in sec(self.p, "containers"):
self.assertNotIn(c["user"], ("", "root", "0"))
self.assertFalse(c["privileged"])
def test_udp_range_bindings_and_missing_healthcheck(self):
p3 = next(c for c in sec(self.p, "containers") if c["service"] == "lab-d")
self.assertEqual(p3["health"], "")
udp = [b["host_port"] for b in p3["ports"] if b["proto"] == "udp"]
self.assertEqual(udp, list(range(8500, 8520)))
def test_no_allowusers_and_hub_units_are_not_candidates(self):
self.assertEqual(sec(self.p, "access")["sshd"]["allowusers"], [])
(cand,) = sec(self.p, "candidates")
self.assertEqual(cand["path"], "/usr/local/bin/forgejo-runner")
hub = next(u for u in sec(self.p, "services") if u["name"] == "security-hub-ctf-watch.timer")
self.assertTrue(hub["hub_managed"])
def test_unit_arguments_and_environment_are_dropped(self):
runner = next(u for u in sec(self.p, "services") if u["name"] == "forgejo-runner.service")
self.assertEqual(runner["exec_paths"], ["/usr/local/bin/forgejo-runner", "/var/lib/forgejo-runner/config.yml"])
self.assertEqual(runner["user"], "forgejo-runner")
self.assertNotIn("SENTINEL", json.dumps(self.p))
def test_minion_id_differs_from_hostname_as_recorded(self):
ident, salt = sec(self.p, "identity"), sec(self.p, "software")["salt_minion"]
self.assertEqual((ident["hostname"], salt["id"]), ("beta", "beta-ci"))
def test_host_keys_differ_between_hosts(self):
alpha = sec(build_profile("alpha"), "identity")["ssh_host_keys"]
beta = sec(self.p, "identity")["ssh_host_keys"]
self.assertNotEqual(alpha, beta)
class Degradation(unittest.TestCase):
def test_sudo_failure_degrades_to_unreadable(self):
table = json.loads((FIX / "commands-alpha.json").read_text())
table["sudo -n true"] = [1, ""]
table["ss -H -lntu"] = [0, "tcp LISTEN 0 4096 0.0.0.0:80 0.0.0.0:*\n"]
probe, ex = make_probe("alpha", table)
profile = probe.collect()
self.assertEqual(sec(profile, "listening")[0]["process"], None)
self.assertFalse(sec(profile, "access")["sudo_nopasswd"])
sshd = sec(profile, "access")["sshd"]
self.assertEqual(sshd["source"], "sshd_config.d names")
self.assertEqual(sshd["config_d_files"], ["99-hardening.conf"])
self.assertIsNone(sshd["allowusers"])
reasons = {(u["section"], u["item"]) for u in profile["unreadable"]}
self.assertIn(("access", "sshd -T"), reasons)
self.assertIn(("listening", "process names"), reasons)
self.assertEqual([c for c in ex.calls if c[0] == "sudo"], [["sudo", "-n", "true"]])
def test_docker_denied_without_sudo_degrades_instead_of_escalating(self):
table = json.loads((FIX / "commands-beta.json").read_text())
table["sudo -n true"] = [1, ""]
table["docker ps -a -q --no-trunc"] = [1, ""]
probe, ex = make_probe("beta", table)
profile = probe.collect()
self.assertEqual(sec(profile, "containers"), [])
self.assertIn(("containers", "docker"), {(u["section"], u["item"]) for u in profile["unreadable"]})
self.assertEqual([c for c in ex.calls if c[0] == "sudo"], [["sudo", "-n", "true"]])
def test_a_crashing_collector_is_reported_not_raised(self):
probe, _ = make_probe("alpha")
with patch.object(probe, "listening", side_effect=RuntimeError("boom")):
profile = probe.collect()
self.assertEqual(sec(profile, "listening"), [])
self.assertTrue(any(u["section"] == "listening" and "boom" in u["reason"] for u in profile["unreadable"]))
def test_missing_root_files_do_not_crash(self):
with tempfile.TemporaryDirectory() as empty:
probe, _ = make_probe("alpha", root=empty)
profile = probe.collect()
self.assertEqual(profile["schema"], 1)
self.assertTrue(profile["unreadable"])
class ReadOnlySafety(unittest.TestCase):
def test_template_uses_index_for_health_and_requests_no_env(self):
tpl = hostprobe.DOCKER_INSPECT_TEMPLATE
self.assertIn('index .State "Health"', tpl)
self.assertNotIn(".State.Health", tpl)
for forbidden in (".Config.Env", ".Config.Cmd", "Mounts", ".Args", "Entrypoint"):
self.assertNotIn(forbidden, tpl)
def test_command_allow_list_refuses_everything_else(self):
probe, ex = make_probe("alpha")
for argv in (
["cat", "/etc/hostname"],
["env"],
["docker", "exec", "x"],
["docker", "run", "x"],
["systemctl", "restart", "x"],
):
with self.assertRaises(hostprobe.ProbeError):
probe.run(argv)
self.assertEqual(ex.calls, [])
def test_every_command_actually_run_is_allowed_and_sudo_is_non_interactive(self):
for name in ("alpha", "beta"):
probe, ex = make_probe(name)
probe.collect()
self.assertTrue(ex.calls)
for argv in ex.calls:
inner = argv[2:] if argv[0] == "sudo" else argv
if argv[0] == "sudo":
self.assertEqual(argv[1], "-n")
self.assertIn(inner[0], hostprobe.ALLOWED_COMMANDS)
self.assertNotIn("-S", argv)
def test_subprocess_gets_devnull_stdin_timeout_and_a_minimal_env(self):
captured = {}
def fake_run(argv, **kw):
captured.update(kw)
class R:
returncode = 0
stdout = b"ok"
return R()
with patch.dict(os.environ, {"SECRET_TOKEN": "SENTINEL_DECOY"}):
with patch.object(hostprobe.subprocess, "run", fake_run):
self.assertEqual(hostprobe.default_exec(["true"], 5), (0, "ok"))
self.assertIs(captured["stdin"], hostprobe.subprocess.DEVNULL)
self.assertEqual(captured["timeout"], 5)
self.assertEqual(set(captured["env"]), {"PATH", "LC_ALL"})
def test_timeout_and_missing_binary_are_return_codes(self):
def boom(argv, **kw):
raise hostprobe.subprocess.TimeoutExpired(argv, 1)
with patch.object(hostprobe.subprocess, "run", boom):
self.assertEqual(hostprobe.default_exec(["true"], 1), (124, ""))
with patch.object(hostprobe.subprocess, "run", side_effect=FileNotFoundError):
self.assertEqual(hostprobe.default_exec(["true"], 1), (127, ""))
def test_runtime_budget_stops_commands(self):
probe, ex = make_probe("alpha")
probe.started -= hostprobe.MAX_RUNTIME_S
self.assertEqual(probe.run(["systemd-detect-virt"]), (124, ""))
self.assertEqual(ex.calls, [])
def test_denied_path_rules(self):
# NOTE: the password-database and private-key path cases are not listed here because the repo's
# tool-call security hook rejects those literals; see the RS07-A result file (open questions).
for path in (
"/srv/forgejo/.env",
"/srv/x/prod.env",
"/etc/sudoers",
"/etc/sudoers.d/90-cloud",
"/home/admin/.bash_history",
"/root/.zsh_history",
"/proc/1/environ",
"/opt/app/server.pem",
"/opt/app/api-token",
"/etc/salt/pki/minion/minion.pem",
):
self.assertTrue(hostprobe.denied(path), path)
for path in ("/etc/os-release", "/srv/forgejo/update-forgejo.sh", "/etc/machine-id"):
self.assertFalse(hostprobe.denied(path), path)
def test_probe_read_refuses_denied_paths_before_opening(self):
probe, _ = make_probe("alpha")
opened = []
with spy_open(opened):
for path in ("/srv/forgejo/.env", "/etc/sudoers", "/home/admin/.bash_history"):
with self.assertRaises(hostprobe.DeniedPath):
probe.read(path)
self.assertEqual(opened, [])
def test_collection_never_opens_secret_paths_even_when_decoys_exist(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "root"
shutil.copytree(FIX / "root-alpha", root)
decoys = [
"srv/forgejo/.env",
"srv/forgejo/prod.env",
"etc/sudoers",
"etc/sudoers.d/90-x",
"home/admin/.bash_history",
"etc/salt/pki/minion/minion.pem",
"proc/1/environ",
]
for rel in decoys:
(root / rel).parent.mkdir(parents=True, exist_ok=True)
(root / rel).write_text("SENTINEL_DECOY\n")
probe, _ = make_probe("alpha", root=root)
opened = []
with spy_open(opened):
profile = probe.collect()
self.assertNotIn("SENTINEL_DECOY", json.dumps(profile))
self.assertTrue(opened)
for path in opened:
self.assertFalse(hostprobe.denied(path.replace(str(root), "")), path)
def test_secret_named_script_is_listed_but_not_read(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "root"
shutil.copytree(FIX / "root-alpha", root)
unit = root / "etc/systemd/system/forgejo-update.service"
unit.write_text(unit.read_text().replace("update-forgejo.sh", "rotate-secret.sh"))
(root / "srv/forgejo/rotate-secret.sh").write_text("SENTINEL_DECOY\n")
probe, _ = make_probe("alpha", root=root)
opened = []
with spy_open(opened):
profile = probe.collect()
(cand,) = sec(profile, "candidates")
self.assertIsNone(cand["sha256"])
self.assertFalse(any(p.endswith("rotate-secret.sh") for p in opened))
def test_probe_source_has_no_write_or_environment_apis(self):
tree = ast.parse((HERE / "hostprobe.py").read_text())
names = {n.attr for n in ast.walk(tree) if isinstance(n, ast.Attribute)}
names |= {n.id for n in ast.walk(tree) if isinstance(n, ast.Name)}
for banned in (
"environ",
"getenv",
"mkdtemp",
"mkstemp",
"NamedTemporaryFile",
"rmtree",
"remove",
"unlink",
"chmod",
"makedirs",
"write_text",
"write_bytes",
):
self.assertNotIn(banned, names)
opens = [n for n in ast.walk(tree) if isinstance(n, ast.Call) and getattr(n.func, "id", None) == "open"]
self.assertTrue(opens)
for node in opens:
modes = [a.value for a in node.args[1:] if isinstance(a, ast.Constant)]
self.assertEqual(modes, ["rb"], "open() must be read-binary")
def test_script_parses_as_python38(self):
ast.parse((HERE / "hostprobe.py").read_text(), feature_version=(3, 8))
class OutputBound(unittest.TestCase):
def test_huge_container_list_is_truncated_under_two_mib(self):
profile = build_profile("alpha")
row = dict(sec(profile, "containers")[0])
profile["sections"]["containers"] = [dict(row, name="c%d" % i, image="i" * 200) for i in range(30000)]
self.assertGreater(hostprobe.encoded_size(profile), hostprobe.MAX_OUTPUT_BYTES)
bounded = hostprobe.bound_output(profile)
self.assertLessEqual(hostprobe.encoded_size(bounded), hostprobe.MAX_OUTPUT_BYTES)
self.assertTrue(any(u["section"] == "containers" and "truncated" in u["reason"] for u in bounded["unreadable"]))
self.assertGreater(len(bounded["sections"]["containers"]), 0)
def test_small_profile_is_untouched(self):
profile = build_profile("beta")
before = json.dumps(profile, sort_keys=True)
self.assertEqual(json.dumps(hostprobe.bound_output(profile), sort_keys=True), before)
def test_main_prints_one_json_line(self):
class Stub:
def collect(self):
return {"schema": 1, "sections": {}, "unreadable": [], "probed_at": "x"}
buf = io.StringIO()
with patch.object(hostprobe, "Probe", Stub), patch.object(sys, "stdout", buf):
self.assertEqual(hostprobe.main(), 0)
self.assertEqual(len(buf.getvalue().splitlines()), 1)
self.assertEqual(json.loads(buf.getvalue())["schema"], 1)
class Parsers(unittest.TestCase):
def test_fingerprint_matches_openssh_formula(self):
import base64
import hashlib
blob = b"\x00\x00\x00\x0bssh-ed25519\x00\x00\x00\x20" + bytes(range(32))
line = "ssh-ed25519 " + base64.b64encode(blob).decode() + " c"
want = "SHA256:" + base64.b64encode(hashlib.sha256(blob).digest()).decode().rstrip("=")
self.assertEqual(hostprobe.fingerprint_from_pub(line), {"type": "ssh-ed25519", "fingerprint": want})
self.assertFalse(want.endswith("="))
def test_unit_parser_keeps_only_paths_and_schedule(self):
text = (
"[Unit]\nDescription=D\n[Service]\nEnvironment=A=SENTINEL_DECOY\nEnvironmentFile=/etc/x.env\nUser=u\n"
"ExecStart=-/opt/a/run.sh --pw=SENTINEL_DECOY\n[Timer]\nOnCalendar=daily\nUnit=other.service\n"
)
got = hostprobe.parse_unit_text(text)
self.assertEqual(got["exec_paths"], ["/opt/a/run.sh"])
self.assertEqual((got["user"], got["on_calendar"], got["unit"]), ("u", ["daily"], "other.service"))
self.assertNotIn("SENTINEL_DECOY", json.dumps(got))
self.assertNotIn("/etc/x.env", json.dumps(got))
def test_ss_parser_handles_ipv6_zone_and_dedup(self):
text = (
'tcp LISTEN 0 4096 [::]:22 [::]:* users:(("sshd",pid=1,fd=3))\n'
"udp UNCONN 0 0 127.0.0.53%lo:53 0.0.0.0:*\n"
"tcp LISTEN 0 4096 [::]:22 [::]:*\n"
)
rows = hostprobe.parse_ss(text)
self.assertEqual(
[(r["proto"], r["address"], r["port"]) for r in rows], [("tcp", "::", 22), ("udp", "127.0.0.53", 53)]
)
self.assertEqual(rows[0]["process"], "sshd")
def test_sshd_t_parser_keeps_only_policy_keys(self):
got = hostprobe.parse_sshd_t("allowusers a\nallowusers b\npermitrootlogin no\nhostkey /x\nport 22\n")
self.assertEqual(got["allowusers"], ["a", "b"])
self.assertEqual(got["port"], ["22"])
self.assertNotIn("hostkey", got)
if __name__ == "__main__":
unittest.main()