From fa404b038781d3e6f7db1dd8fe3b60f6d3954793 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 00:53:49 +0000 Subject: [PATCH] power-guard: run the sleep command as argv, never through a shell (#9602) POWER_GUARD_SLEEP_CMD was passed to subprocess.run(..., shell=True) in a daemon that runs as root, so any shell metacharacters in the environment value were executed. Parse it once at startup with shlex.split, fail closed (named error, exit 2, no polling) on an empty or unparseable value, and run the resulting argv with no shell. Co-Authored-By: Claude Opus 5.5 --- nixos/services/power-guard/power-guard.py | 39 +++++- .../services/power-guard/test_power_guard.py | 113 +++++++++++++++++- 2 files changed, 146 insertions(+), 6 deletions(-) diff --git a/nixos/services/power-guard/power-guard.py b/nixos/services/power-guard/power-guard.py index 5cbb433717..19706168df 100644 --- a/nixos/services/power-guard/power-guard.py +++ b/nixos/services/power-guard/power-guard.py @@ -22,13 +22,15 @@ Runs as root in production (systemd unit from the NixOS flake). Test hooks (env): POWER_GUARD_SYSFS (fake sysfs root), POWER_GUARD_NO_INHIBIT=1 (log inhibitor actions instead of taking a -real lock), POWER_GUARD_SLEEP_CMD (default "systemctl hybrid-sleep"). +real lock), POWER_GUARD_SLEEP_CMD (default "systemctl hybrid-sleep"; +split into argv with shlex and run without a shell, #9602). Threshold/timing overrides: POWER_GUARD_POLL, POWER_GUARD_CONFIRM, POWER_GUARD_EDGE_CONFIRM. """ import math import os +import shlex import subprocess import sys import threading @@ -92,7 +94,38 @@ def timing_from_env(name, default): CONFIRM = timing_from_env("POWER_GUARD_CONFIRM", "300") EDGE_CONFIRM = timing_from_env("POWER_GUARD_EDGE_CONFIRM", "60") NO_INHIBIT = os.environ.get("POWER_GUARD_NO_INHIBIT") == "1" -SLEEP_CMD = os.environ.get("POWER_GUARD_SLEEP_CMD", "systemctl hybrid-sleep") +DEFAULT_SLEEP_CMD = "systemctl hybrid-sleep" + + +def parse_sleep_cmd(raw): + """Split a sleep command into argv, refusing empty or malformed input. + + #9602: the daemon runs as root, so the command is never handed to a + shell. Quoting follows POSIX shell rules (shlex), but metacharacters + such as ; | && $( ) are passed through as literal arguments. + """ + try: + argv = shlex.split(raw) + except ValueError as exc: + raise ValueError( + f"POWER_GUARD_SLEEP_CMD={raw!r} cannot be parsed: {exc}" + ) from None + if not argv: + raise ValueError(f"POWER_GUARD_SLEEP_CMD={raw!r} must name a command") + return argv + + +def sleep_argv_from_env(): + """Read the sleep command once at startup, failing closed like the timings.""" + raw = os.environ.get("POWER_GUARD_SLEEP_CMD", DEFAULT_SLEEP_CMD) + try: + return parse_sleep_cmd(raw) + except ValueError as exc: + print(f"power-guard: error: {exc}", file=sys.stderr, flush=True) + raise SystemExit(2) from None + + +SLEEP_ARGV = sleep_argv_from_env() # #8183: how long release() may wait inline for a terminated child # before the reap moves to a background thread. The full reap used # to block the sampling loop for up to ~10s (wait 5s, kill, wait 5s). @@ -408,7 +441,7 @@ def main(): inh.release() if sleep_pending is not None and inh.reap_settled(): log(f"CONFIRMED: {sleep_pending}; inhibitor release settled; sleeping") - subprocess.run(SLEEP_CMD, shell=True) + subprocess.run(SLEEP_ARGV) log("sleep command issued; cooling down") critical_since = edge_since = None sleep_pending = None diff --git a/nixos/services/power-guard/test_power_guard.py b/nixos/services/power-guard/test_power_guard.py index 543f2080fd..b24bad6b57 100644 --- a/nixos/services/power-guard/test_power_guard.py +++ b/nixos/services/power-guard/test_power_guard.py @@ -15,9 +15,11 @@ """ import importlib.util +import json import math import os import random +import shlex import subprocess import sys import tempfile @@ -49,8 +51,10 @@ def load_daemon(): """Import power-guard.py with a clean, valid timing environment.""" - env_backup = {k: os.environ.get(k) for k in TIMING_VARS} - for k in TIMING_VARS: + env_backup = { + k: os.environ.get(k) for k in TIMING_VARS + ("POWER_GUARD_SLEEP_CMD",) + } + for k in env_backup: os.environ.pop(k, None) try: spec = importlib.util.spec_from_file_location("power_guard", DAEMON) @@ -178,7 +182,7 @@ def daemon_env(self, **timing): env.update( POWER_GUARD_SYSFS=str(self.sysfs), POWER_GUARD_NO_INHIBIT="1", - POWER_GUARD_SLEEP_CMD=f"touch {self.marker}", + POWER_GUARD_SLEEP_CMD=f"touch {shlex.quote(str(self.marker))}", ) env.update(timing) return env @@ -447,5 +451,108 @@ def test_stalled_child_reap_moves_off_the_calling_loop(self): ) +class ParseSleepCmdTests(unittest.TestCase): + """#9602: the sleep command is argv, parsed once, never a shell line.""" + + def test_default_is_systemctl_hybrid_sleep(self): + self.assertEqual( + pg.parse_sleep_cmd(pg.DEFAULT_SLEEP_CMD), ["systemctl", "hybrid-sleep"] + ) + + def test_quoted_words_follow_shell_quoting(self): + self.assertEqual( + pg.parse_sleep_cmd("'/opt/my sleeper' --mode \"hybrid sleep\""), + ["/opt/my sleeper", "--mode", "hybrid sleep"], + ) + + def test_shell_metacharacters_stay_literal_arguments(self): + self.assertEqual( + pg.parse_sleep_cmd("systemctl hybrid-sleep; rm -rf / && $(id) | cat"), + ["systemctl", "hybrid-sleep;", "rm", "-rf", "/", "&&", "$(id)", "|", "cat"], + ) + + def test_empty_or_blank_is_refused(self): + for raw in ("", " ", "\t\n"): + with ( + self.subTest(raw=raw), + self.assertRaisesRegex(ValueError, "must name a command"), + ): + pg.parse_sleep_cmd(raw) + + def test_unbalanced_quotes_are_refused(self): + for raw in ("systemctl 'hybrid-sleep", 'touch "x', "a\\"): + with ( + self.subTest(raw=raw), + self.assertRaisesRegex(ValueError, "cannot be parsed"), + ): + pg.parse_sleep_cmd(raw) + + +class SleepCmdDaemonTests(unittest.TestCase): + """#9602 end to end against the real daemon subprocess.""" + + setUp = DaemonSubprocessTests.setUp + daemon_env = DaemonSubprocessTests.daemon_env + run_daemon = DaemonSubprocessTests.run_daemon + + def wait_for_marker(self, env, seconds=10): + deadline = time.time() + seconds + proc = subprocess.Popen( + [sys.executable, str(DAEMON)], + env=env, + cwd=self.tmp.name, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + try: + while time.time() < deadline and not self.marker.exists(): + if proc.poll() is not None: + break + time.sleep(0.05) + finally: + proc.terminate() + proc.communicate(timeout=10) + + def test_invalid_sleep_cmd_exits_named_before_polling(self): + for raw in ("", " ", "systemctl 'hybrid-sleep"): + with self.subTest(raw=raw): + env = self.daemon_env( + POWER_GUARD_POLL="0.05", POWER_GUARD_CONFIRM="0.3" + ) + env["POWER_GUARD_SLEEP_CMD"] = raw + rc, out, err, exited = self.run_daemon(env, 10) + self.assertTrue( + exited, "daemon kept polling on an invalid sleep command" + ) + self.assertNotEqual(rc, 0) + self.assertIn("POWER_GUARD_SLEEP_CMD", err) + self.assertIn(repr(raw), err) + self.assertNotIn("Traceback", err) + self.assertNotIn("CRITICAL state entered", out) + + def test_metacharacters_reach_the_command_as_arguments_not_a_shell(self): + injected = Path(self.tmp.name) / "injected" + recorder = ( + "import json, sys; open(sys.argv[1], 'w').write(json.dumps(sys.argv[2:]))" + ) + cmd = ( + " ".join( + shlex.quote(part) + for part in (sys.executable, "-c", recorder, str(self.marker)) + ) + + f" ; touch {shlex.quote(str(injected))} && $(touch {shlex.quote(str(injected))})" + ) + env = self.daemon_env(POWER_GUARD_POLL="0.05", POWER_GUARD_CONFIRM="0.3") + env["POWER_GUARD_SLEEP_CMD"] = cmd + self.wait_for_marker(env) + self.assertTrue(self.marker.exists(), "sleep command never fired") + self.assertEqual( + json.loads(self.marker.read_text()), + [";", "touch", str(injected), "&&", "$(touch", f"{injected})"], + ) + self.assertFalse(injected.exists(), "sleep command was run through a shell") + + if __name__ == "__main__": unittest.main()