Skip to content

The agent that grows with you

fix(cron): close NUL-padded script bypass in lifecycle guard

Meng Chee92edb861be3d
diff --git a/cron/lifecycle_guard.py b/cron/lifecycle_guard.py
index 3599a935d03..2930f68c3de 100644
--- a/cron/lifecycle_guard.py
+++ b/cron/lifecycle_guard.py
@@ -714,6 +714,38 @@ def _resolve_script_directory(script_path: str) -> Optional[str]:
return None
+_BINARY_MAGICS = (
+ b"\x7fELF", # ELF — Linux/BSD executables and shared objects
+ b"\xfe\xed\xfa\xce", # Mach-O 32-bit
+ b"\xfe\xed\xfa\xcf", # Mach-O 64-bit
+ b"\xce\xfa\xed\xfe", # Mach-O 32-bit, byte-swapped
+ b"\xcf\xfa\xed\xfe", # Mach-O 64-bit, byte-swapped
+ b"\xca\xfe\xba\xbe", # Mach-O universal ("fat") binary
+ b"MZ", # PE/COFF — Windows .exe/.dll
+ b"!<arch>", # static archive (.a)
+ b"\x1f\x8b", # gzip
+ b"PK\x03\x04", # zip (also .jar/.whl/.egg)
+)
+
+
+def _has_binary_magic(data: bytes) -> bool:
+ """Return True when *data* starts with a known compiled-binary signature.
+
+ Deliberately narrower than "contains a NUL byte": a shell script that
+ happens to hold a NUL is still executed by ``bash``, so treating every
+ NUL-bearing file as an unscannable binary lets a padded script bypass the
+ lifecycle scan entirely.
+
+ A shebang always wins — an interpreted script is never a binary, however
+ odd its payload. File extensions are deliberately *not* consulted: a
+ suffixless shell script must still be scanned (and, if oversized, still
+ fail closed).
+ """
+ if data.startswith(b"#!"):
+ return False
+ return data.startswith(_BINARY_MAGICS)
+
+
def _read_referenced_script(path: Path) -> tuple[Optional[str], bool]:
"""Return ``(text, unsafe)`` using bounded, regular-file-only reads.
@@ -779,16 +811,25 @@ def _read_referenced_script(path: Path) -> tuple[Optional[str], bool]:
return None, False
finally:
os.close(descriptor)
- # A NUL byte in the first chunk means this is a binary (ELF/Mach-O/
- # PE), not a shell script — scanning its decoded contents would
- # tokenize machine code and feed junk paths into the recursion
- # (including a `ValueError: embedded null byte` from Path.resolve,
- # #76762). Treat it as "nothing to scan" rather than unsafe: a binary
- # executed by the user is not a referenced *shell script*.
- if b"\x00" in data:
+ # Identify binaries by MAGIC NUMBER, not by the mere presence of a NUL.
+ #
+ # "contains a NUL" and "is a compiled binary" are different questions, and
+ # the gap between them is a guard bypass: `bash` executes a *text* script
+ # straight past an embedded NUL, so a single pad byte in a shell script made
+ # the scan skip a file that still runs its lifecycle command. Match on the
+ # signature instead (ELF/Mach-O/PE/static archive/compressed), and treat a
+ # NUL-bearing *text* file as a script whose NULs are stripped before
+ # scanning — stripping can only splice tokens together, never apart, so it
+ # fails closed.
+ if _has_binary_magic(data):
return None, False
+ # Check the size BEFORE stripping: stripping shrinks the buffer, so doing it
+ # first would let an oversized file slip under the threshold and skip this
+ # fail-closed branch.
if len(data) > _MAX_REFERENCED_SCRIPT_BYTES:
return None, True
+ if b"\x00" in data:
+ data = data.replace(b"\x00", b"")
return data.decode("utf-8", errors="replace"), False
diff --git a/tests/hermes_cli/test_gateway_restart_loop.py b/tests/hermes_cli/test_gateway_restart_loop.py
index 8545fc9af94..a43756951d3 100644
--- a/tests/hermes_cli/test_gateway_restart_loop.py
+++ b/tests/hermes_cli/test_gateway_restart_loop.py
@@ -879,6 +879,24 @@ class TestLifecycleGuardModule:
is True
)
+ def test_nul_padded_script_is_still_scanned(self, tmp_path):
+ """A NUL byte in a *text* script must not disable the scan.
+
+ The #76762 binary check treated any NUL in the first chunk as "compiled
+ binary, nothing to scan" — but ``bash`` executes a text script straight
+ past an embedded NUL, so one pad byte bypassed the guard entirely while
+ the script still ran its lifecycle command.
+ """
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+ script = tmp_path / "padded.sh"
+ script.write_bytes(b"#!/bin/bash\n# pad\x00\nhermes gateway restart\n")
+ assert (
+ contains_gateway_lifecycle_command_or_referenced_script(f"bash {script}")
+ is True
+ )
+
def test_source_builtin_sourced_script_is_scanned(self, tmp_path):
"""The `source` spelling must stay blocked (it already was)."""
from cron.lifecycle_guard import (
@@ -904,6 +922,84 @@ class TestLifecycleGuardModule:
is False
)
+ def test_nul_padded_script_without_shebang_is_scanned(self, tmp_path):
+ """Same bypass without a shebang — bash still runs it, so still scan.
+
+ Keying the fix on a leading ``#!`` alone is insufficient: a shebang-less
+ file with a NUL on any line but the first executes normally.
+ """
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+ script = tmp_path / "padded_noshebang.sh"
+ script.write_bytes(b"# ok\n# pad\x00\nhermes gateway restart\n")
+ assert (
+ contains_gateway_lifecycle_command_or_referenced_script(f"bash {script}")
+ is True
+ )
+
+ def test_elf_binary_is_not_scanned_as_script(self, tmp_path):
+ """#76762 must stay fixed: a real binary is nothing-to-scan, no crash.
+
+ Its decoded machine code must never be tokenized as shell text, and the
+ guard must not fail closed on an innocent interpreter invocation.
+ """
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+ binary = tmp_path / "tool"
+ binary.write_bytes(b"\x7fELF\x02\x01\x01\x00" + b"\x00" * 64 + b"/usr/bin/x\x00")
+ assert (
+ contains_gateway_lifecycle_command_or_referenced_script(f"{binary} --version")
+ is False
+ )
+
+ def test_macho_binary_is_not_scanned_as_script(self, tmp_path):
+ """Same for Mach-O, including the universal/fat signature (macOS)."""
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+ for name, magic in (
+ ("macho64", b"\xcf\xfa\xed\xfe"),
+ ("machofat", b"\xca\xfe\xba\xbe"),
+ ):
+ binary = tmp_path / name
+ binary.write_bytes(magic + b"\x00" * 64)
+ assert (
+ contains_gateway_lifecycle_command_or_referenced_script(
+ f"{binary} --version"
+ )
+ is False
+ )
+
+ def test_oversized_nul_bearing_text_still_fails_closed(self, tmp_path):
+ """An oversized *text* script must keep failing closed.
+
+ Stripping NULs must not let a too-large file skip the size guard — the
+ binary check runs first, the size check still applies afterwards.
+ """
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+ script = tmp_path / "huge.sh"
+ script.write_bytes(b"#!/bin/bash\n# \x00" + b"x" * (1024 * 1024 + 64) + b"\n")
+ assert (
+ contains_gateway_lifecycle_command_or_referenced_script(f"bash {script}")
+ is True
+ )
+
+ def test_clean_script_without_lifecycle_command_not_blocked(self, tmp_path):
+ """Sanity: the change must not false-block innocent scripts."""
+ from cron.lifecycle_guard import (
+ contains_gateway_lifecycle_command_or_referenced_script,
+ )
+ script = tmp_path / "safe.sh"
+ script.write_bytes(b"#!/bin/bash\necho hello\n")
+ assert (
+ contains_gateway_lifecycle_command_or_referenced_script(f"bash {script}")
+ is False
+ )
+
def test_prompt_with_command_raises(self):
from cron.lifecycle_guard import GatewayLifecycleBlocked, check_gateway_lifecycle
with pytest.raises(GatewayLifecycleBlocked) as exc: