"""`/proc` parsing and the safety guards on signalling. The identity check is what makes it safe to signal a pid the daemon did not spawn, so it gets tests against a synthetic `/proc` as well as the real one. BUG-02 removed one of its three conditions, so these tests have two jobs rather than one: they pin down that an `exec`ing wrapper no longer trips the gate, and they pin down — in the same file, from the same synthetic `/proc` — that a genuinely recycled pid is still refused. Dropping a condition without the second half would leave a check that cannot fail, which is worse than the bug. """ from __future__ import annotations import hashlib import os import signal import subprocess import sys import time from pathlib import Path import pytest from hhstreamd import procmon def fake_proc(root: Path, pid: int, *, comm: str, sid: int, pgid: int, starttime: int, cmdline: bytes): """Write a plausible `/proc/` for the parser to read.""" directory = root / str(pid) directory.mkdir(parents=True, exist_ok=True) fields = ["0"] * 50 fields[0] = "S" # field 3: state fields[1] = "1" # field 4: ppid fields[2] = str(pgid) # field 5 fields[3] = str(sid) # field 6 fields[19] = str(starttime) # field 22 (directory / "stat").write_text(f"{pid} ({comm}) " + " ".join(fields) + "\n") (directory / "cmdline").write_bytes(cmdline) return directory def test_stat_parsing_survives_a_comm_containing_spaces_and_parentheses(tmp_path: Path): """`comm` is attacker-adjacent: a process can rename itself to ") 1 2 3 (". Splitting the whole line on whitespace would read the wrong fields and the daemon would then signal the wrong process group. """ fake_proc( tmp_path, 42, comm="evil (name) with ) spaces", sid=7, pgid=9, starttime=12345, cmdline=b"/bin/x\0", ) stat = procmon.read_stat(42, proc=str(tmp_path)) assert stat.comm == "evil (name) with ) spaces" assert stat.pgid == 9 assert stat.sid == 7 assert stat.starttime == 12345 def test_a_missing_process_reads_as_none(tmp_path: Path): assert procmon.read_stat(999, proc=str(tmp_path)) is None assert procmon.read_cmdline(999, proc=str(tmp_path)) is None assert procmon.identity(999, proc=str(tmp_path)) is None assert procmon.is_alive(999, proc=str(tmp_path)) is False def test_a_truncated_stat_line_is_rejected_rather_than_misparsed(tmp_path: Path): directory = tmp_path / "7" directory.mkdir() (directory / "stat").write_text("7 (short) S 1 2\n") assert procmon.read_stat(7, proc=str(tmp_path)) is None def test_cmdline_is_split_on_nul_without_a_trailing_empty_item(tmp_path: Path): fake_proc(tmp_path, 8, comm="x", sid=8, pgid=8, starttime=1, cmdline=b"/bin/x\0-a\0-b\0") assert procmon.cmdline_argv(8, proc=str(tmp_path)) == ["/bin/x", "-a", "-b"] def test_the_cmdline_hash_is_of_the_raw_bytes(tmp_path: Path): raw = b"/bin/x\0-a\0" fake_proc(tmp_path, 9, comm="x", sid=9, pgid=9, starttime=1, cmdline=raw) assert procmon.cmdline_hash(9, proc=str(tmp_path)) == hashlib.sha256(raw).hexdigest() # --------------------------------------------------------------------------- # the identity check (BUG-02) # --------------------------------------------------------------------------- def leader(root: Path, pid: int, *, starttime: int, cmdline: bytes, comm: str = "x"): """A session leader, as `start_new_session=True` produces: sid == pgid == pid.""" return fake_proc( root, pid, comm=comm, sid=pid, pgid=pid, starttime=starttime, cmdline=cmdline ) def test_the_gate_is_starttime_corroborated_by_a_leaders_sid_and_pgid(tmp_path: Path): """What is checked is stated explicitly, so weakening it cannot be silent.""" raw = b"/bin/x\0" leader(tmp_path, 10, starttime=999, cmdline=raw) verdict = procmon.check( 10, proc=str(tmp_path), starttime=999, sid=10, pgid=10, cmdline_sha256=hashlib.sha256(raw).hexdigest(), ) assert verdict.ok is True assert verdict.reason is None assert verdict.checked == ("starttime", "sid", "pgid") assert verdict.mismatched == () assert verdict.cmdline_drifted is False @pytest.mark.parametrize( "live,mismatched", [ # A different process was created on this pid: it cannot share the # creation instant of the one that is recorded. (dict(sid=10, pgid=10, starttime=1000), "starttime"), # ...and if the clocks did collide, it is not in our session either. (dict(sid=77, pgid=77, starttime=999), "sid"), (dict(sid=10, pgid=77, starttime=999), "pgid"), ], ) def test_a_recycled_pid_is_still_refused(tmp_path: Path, live: dict, mismatched: str): """The protection BUG-02 had to keep: a pid that is not ours is not signalled. The brief's construction: a pid cannot be forced to be recycled on demand, so the record is held fixed — a session leader on pid 10, created at tick 999 — and `/proc` is made to describe a process that **cannot** be that one while it is alive. Each surviving condition is shown to refuse on its own. """ fake_proc(tmp_path, 10, comm="stranger", cmdline=b"/bin/other\0", **live) verdict = procmon.check(10, proc=str(tmp_path), starttime=999, sid=10, pgid=10) assert verdict.ok is False, "a pid that is not ours must never be signalled" assert verdict.reason == "pid_reuse_detected" assert verdict.unresolved is True assert mismatched in verdict.mismatched def test_the_gate_cannot_be_satisfied_by_the_cmdline_alone(tmp_path: Path): """A recycled pid is refused *even when the command line matches exactly*. The converse of dropping the condition: it was never what made the check safe, and removing it takes nothing away. """ raw = b"/bin/x\0" fake_proc(tmp_path, 10, comm="x", sid=10, pgid=10, starttime=1000, cmdline=raw) verdict = procmon.check( 10, proc=str(tmp_path), starttime=999, sid=10, pgid=10, cmdline_sha256=hashlib.sha256(raw).hexdigest(), ) assert verdict.ok is False assert verdict.reason == "pid_reuse_detected" assert verdict.cmdline_drifted is False, "identical argv, and still refused" def test_a_wrapper_script_exec_does_not_look_like_pid_reuse(tmp_path: Path): """BUG-02 itself, at the level of the check. The recorded argv is the wrapper's, the live argv is the real binary's, and everything the kernel owns is unchanged. This is a healthy process. """ launched = b"/run/current-system/sw/bin/chromium\0--ozone-platform=wayland\0" live = b"/nix/store/abc-chromium-unwrapped/libexec/chromium/chromium\0" leader(tmp_path, 2661433, starttime=15780209, cmdline=live, comm="chromium") verdict = procmon.check( 2661433, proc=str(tmp_path), starttime=15780209, sid=2661433, pgid=2661433, cmdline_sha256=hashlib.sha256(launched).hexdigest(), ) assert verdict.ok is True, "an exec'ing wrapper is not evidence of pid reuse" assert verdict.cmdline_drifted is True, "the drift is still reported, just not acted on" def test_the_cmdline_can_never_refuse_on_its_own(tmp_path: Path): """The condition that was dropped is dropped: no value of it refuses.""" raw = b"/bin/real\0" leader(tmp_path, 10, starttime=999, cmdline=raw) for recorded_hash in ["0" * 64, hashlib.sha256(b"/bin/wrapper\0").hexdigest(), ""]: verdict = procmon.check( 10, proc=str(tmp_path), starttime=999, sid=10, pgid=10, cmdline_sha256=recorded_hash, ) assert verdict.ok is True assert "cmdline_sha256" not in verdict.checked def test_sid_and_pgid_are_only_checked_for_a_leader(tmp_path: Path): """An adopted non-leader may lawfully `setsid()`; that is not pid reuse. `setsid()` and `setpgid()` both fail with EPERM for a session/group leader, so the recorded values are immutable exactly when they equal the recorded pid — and are checked exactly then. """ # Recorded as a member of someone else's session, then it calls setsid(). fake_proc(tmp_path, 10, comm="x", sid=5, pgid=5, starttime=999, cmdline=b"/bin/x\0") verdict = procmon.check(10, proc=str(tmp_path), starttime=999, sid=5, pgid=5) assert verdict.ok is True assert verdict.checked == ("starttime",), "a non-leader's sid/pgid are not evidence" def test_a_record_with_no_starttime_is_refused_rather_than_waved_through(tmp_path: Path): """BUG-02 item 5: no evidence means refuse loudly, never "probably fine".""" leader(tmp_path, 10, starttime=999, cmdline=b"/bin/x\0") for missing in (None, 0, -1): verdict = procmon.check(10, proc=str(tmp_path), starttime=missing, sid=10, pgid=10) assert verdict.ok is False assert verdict.reason == "identity_unknown" assert verdict.unresolved is True def test_a_vanished_process_reports_gone_not_pid_reuse(tmp_path: Path): """The difference matters: one is routine, the other is alarming.""" verdict = procmon.check(404, proc=str(tmp_path), starttime=1, sid=404, pgid=404) assert (verdict.ok, verdict.reason) == (False, "gone") assert verdict.unresolved is False, "an exit is not something to shout about" def test_a_zombie_is_gone_not_alive(tmp_path: Path): """A zombie holds its pid but can never be signalled into doing anything.""" directory = leader(tmp_path, 10, starttime=999, cmdline=b"/bin/x\0") stat = (directory / "stat").read_text().replace(") S ", ") Z ", 1) (directory / "stat").write_text(stat) verdict = procmon.check(10, proc=str(tmp_path), starttime=999, sid=10, pgid=10) assert (verdict.ok, verdict.reason) == (False, "gone") def test_verify_still_answers_ok_and_reason_for_callers_that_want_no_detail(tmp_path: Path): leader(tmp_path, 10, starttime=999, cmdline=b"/bin/x\0") assert procmon.verify(10, proc=str(tmp_path), starttime=999, sid=10, pgid=10) == (True, None) assert procmon.verify(10, proc=str(tmp_path), starttime=998, sid=10, pgid=10) == ( False, "pid_reuse_detected", ) def test_the_real_process_verifies_against_itself(): me = os.getpid() identity = procmon.identity(me) assert identity is not None assert identity.sid == os.getsid(me) assert identity.pgid == os.getpgid(me) verdict = procmon.check( me, starttime=identity.starttime, sid=identity.sid, pgid=identity.pgid, cmdline_sha256=identity.cmdline_sha256, ) assert verdict.ok is True assert "starttime" in verdict.checked def test_a_real_exec_does_not_change_starttime_but_does_change_the_cmdline(): """The claim the whole fix rests on, measured on a real process. A process that `exec`s something else keeps its pid, its session id, its process group and its `starttime`; only its command line is replaced. The handshake over stdin is what makes it deterministic — the child is blocked in `readline()` while the "before" identity is taken, so there is no race with the `exec` and no sleep sized by guesswork. If this ever stops being true, the gate is unsound and this test says so. """ child = ( "import os, sys\n" "sys.stdout.write(str(os.getpid()) + chr(10)); sys.stdout.flush()\n" "sys.stdin.readline()\n" # held here while the parent looks at us "os.execv(sys.executable, [sys.executable, '-c', 'import time; time.sleep(30)'])\n" ) process = subprocess.Popen( [sys.executable, "-c", child], stdin=subprocess.PIPE, stdout=subprocess.PIPE, start_new_session=True, ) try: pid = int(process.stdout.readline()) before = procmon.identity(pid) assert before is not None assert before.sid == before.pgid == pid, "start_new_session gives a leader" process.stdin.write(b"go\n") process.stdin.flush() deadline = time.monotonic() + 10.0 while True: after = procmon.identity(pid) assert after is not None, "the process exec'd into nothing" if after.cmdline_sha256 != before.cmdline_sha256: break assert time.monotonic() < deadline, "the exec never happened" time.sleep(0.01) assert after.starttime == before.starttime, "starttime must survive exec" assert after.sid == before.sid == pid, "the session id must survive exec" assert after.pgid == before.pgid == pid, "the process group must survive exec" # And the gate agrees: the identity recorded before the exec still # verifies afterwards, with the drift reported but not acted on. verdict = procmon.check( pid, starttime=before.starttime, sid=before.sid, pgid=before.pgid, cmdline_sha256=before.cmdline_sha256, ) assert verdict.ok is True assert verdict.cmdline_drifted is True finally: process.kill() process.wait(timeout=5) # --------------------------------------------------------------------------- # signalling guards # --------------------------------------------------------------------------- @pytest.mark.parametrize("sid", [0, 1, -1, None]) def test_the_sweep_refuses_session_ids_that_would_select_the_machine(sid): """sid 0 or 1 would match init and most of everything else.""" assert procmon.session_members(sid) == [] assert procmon.sweep_session(sid) == [] @pytest.mark.parametrize("pgid", [0, 1, -1, None]) def test_killpg_refuses_the_dangerous_process_groups(pgid): """killpg(0) means "every process in my own group" — including the daemon.""" assert procmon.killpg(pgid, signal.SIGTERM) is False def test_the_sweep_finds_processes_by_session_id(tmp_path: Path): for pid, sid in [(100, 55), (101, 55), (102, 66)]: fake_proc(tmp_path, pid, comm="x", sid=sid, pgid=pid, starttime=1, cmdline=b"/bin/x\0") assert procmon.session_members(55, proc=str(tmp_path)) == [100, 101] assert procmon.session_members(66, proc=str(tmp_path)) == [102] assert procmon.session_members(55, proc=str(tmp_path), exclude={100}) == [101] def test_signalling_a_dead_pid_is_not_an_error(): assert procmon.kill_pid(2**22 - 1, signal.SIGKILL) in (False, True) def test_pidfd_open_yields_none_rather_than_raising_when_it_cannot_be_used(): """The caller falls back to a /proc poll on None, so it must never raise. This covers both reasons for None: the kernel lacking the syscall, and the process being gone between the liveness check and the open. """ assert procmon.pidfd_open(2**22 - 1) is None fd = procmon.pidfd_open(os.getpid()) if fd is None: assert not procmon.HAVE_PIDFD else: os.close(fd)