From 24c98812ed4909dfc3000173266624b8c58c29fb Mon Sep 17 00:00:00 2001 From: Sun Shihao <75820689+sun-sh@users.noreply.github.com> Date: Thu, 22 Oct 2026 08:43:42 +0800 Subject: [PATCH] fix(skills): sniff executable binaries past leading filler bytes (#7081) * fix(skills): sniff executable binaries past leading filler bytes The executable-binary guard (package_files.is_executable_binary_prefix) matched ELF/PE/Mach-O magics strictly at file offset 0 across all three layers: archive preflight, the extraction guard, and the directory static scan. Prepending a single filler byte (newline, space, NUL, ...) evades every layer simultaneously: a whitespace-prefixed ELF still loads through ld.so, and the existing test asserting the scanner and the extraction guard agree passes for both the plain and the padded form after this fix, because both layers share this helper. The sniff now tolerates a bounded (64-byte) run of leading ASCII whitespace/NUL filler before matching, and scan windows widen from 8 to EXEC_SNIFF_BYTES so the magic plus filler always fits the probe. The cap keeps indented prose out of the false-positive zone (the existing "full magics only" tests stay green). Repro before the fix: archive with SKILL.md and assets/payload whose bytes are b'\n' + ELF header: preflight passes, extraction writes the file, the directory scan reports nothing. Tests: 10 new regression cases across test_skillscan_native.py and test_skills_installer.py; 701 related tests pass locally on py3.12. * fix(skills): clarify executable filler sniffing Address review feedback by clarifying the offset-0 probe rationale, handling UTF-8 BOM prefixes without truncating Mach-O magics, and pinning the 63/64-byte boundary. * test(skillscan): describe what the filler-prefix regression asserts The docstring said filler "must not evade the offset-0 probe", which reads oddly for a test whose payloads all sit past offset 0. State the asserted behavior instead: a bounded filler run still yields a blocking CRITICAL finding. * test(skillscan): pin executable sniff window and BOM handling * test(skillscan): cover every executable sniff entry point * test(lark): isolate windows runtime branch --- .../harness/deerflow/integrations/lark_cli.py | 4 +- .../harness/deerflow/skills/package_files.py | 53 ++++++- .../deerflow/skills/skillscan/orchestrator.py | 17 +-- backend/tests/test_lark_cli_integration.py | 65 ++++++++- backend/tests/test_skill_export.py | 21 +++ backend/tests/test_skills_installer.py | 68 +++++++++ backend/tests/test_skillscan_native.py | 129 +++++++++++++++++- 7 files changed, 341 insertions(+), 16 deletions(-) diff --git a/backend/packages/harness/deerflow/integrations/lark_cli.py b/backend/packages/harness/deerflow/integrations/lark_cli.py index 4b7a231338..86aae5ddf2 100644 --- a/backend/packages/harness/deerflow/integrations/lark_cli.py +++ b/backend/packages/harness/deerflow/integrations/lark_cli.py @@ -87,7 +87,7 @@ from deerflow.config.app_config import AppConfig from deerflow.config.paths import Paths, get_paths from deerflow.integrations.lark_broker import LARK_BROKER_URL_ENV from deerflow.skills.installer import is_symlink_member, is_unsafe_zip_member -from deerflow.skills.package_files import is_executable_binary_prefix +from deerflow.skills.package_files import EXEC_SNIFF_BYTES, is_executable_binary_prefix from deerflow.skills.parser import parse_skill_file from deerflow.skills.permissions import make_skill_tree_sandbox_readable from deerflow.skills.types import SKILL_MD_FILE, SkillCategory @@ -1302,7 +1302,7 @@ def _runtime_artifact_is_executable(relative: Path, candidate: Path) -> bool: if os.name != "nt": return candidate.stat().st_mode & 0o111 != 0 with candidate.open("rb") as handle: - prefix = handle.read(4) + prefix = handle.read(EXEC_SNIFF_BYTES) if relative == Path("bin/lark-cli"): return prefix.startswith(b"#!") return is_executable_binary_prefix(prefix) diff --git a/backend/packages/harness/deerflow/skills/package_files.py b/backend/packages/harness/deerflow/skills/package_files.py index d6511a3050..9dc7261c9d 100644 --- a/backend/packages/harness/deerflow/skills/package_files.py +++ b/backend/packages/harness/deerflow/skills/package_files.py @@ -8,6 +8,17 @@ from __future__ import annotations from pathlib import PurePath, PurePosixPath +#: Filler bytes an executable magic may hide behind: ASCII whitespace (space, +#: tab, LF, CR, vertical tab, form feed) and NUL padding. +_EXEC_SNIFF_FILLER = b" \t\n\r\x0b\x0c\x00" +#: The UTF-8 BOM is filler only as a whole sequence: its last byte ``\xbf`` +#: also opens the Mach-O fat64 little-endian magic, so it cannot be stripped +#: byte-wise. +_UTF8_BOM = b"\xef\xbb\xbf" +#: Exclusive bound on the leading-filler run: at most ``_EXEC_SNIFF_LIMIT - 1`` +#: (63) filler bytes are skipped; a run of 64 or more reports no magic. +_EXEC_SNIFF_LIMIT = 64 + CODE_SUFFIXES = frozenset({".bash", ".bat", ".cjs", ".cmd", ".hta", ".js", ".jse", ".mjs", ".php", ".pl", ".ps1", ".psm1", ".py", ".rb", ".sct", ".sh", ".ts", ".vbe", ".vbs", ".wsf", ".zsh"}) # Full magics per variant — a shorter shared prefix would also match # non-executable data files. @@ -40,6 +51,44 @@ def is_code_file(path: str | PurePath, head: bytes) -> bool: return is_code_path(path) or (not _posix(path).suffix and head.startswith(b"#!")) +#: Bytes callers should hand over so a capped filler run plus the longest +#: magic always fits the sniff window. +# At most 63 filler bytes are tolerated, so one 4-byte magic fits in 67 bytes. +EXEC_SNIFF_BYTES = (_EXEC_SNIFF_LIMIT - 1) + max(len(magic) for magic in _EXECUTABLE_MAGIC_PREFIXES) + + +def _leading_filler_length(head: bytes) -> int: + offset = 0 + while offset < len(head): + if head[offset] in _EXEC_SNIFF_FILLER: + offset += 1 + elif head.startswith(_UTF8_BOM, offset): + offset += len(_UTF8_BOM) + else: + break + return offset + + +def executable_binary_magic(prefix: bytes) -> bytes | None: + """Return the executable magic after a bounded leading-filler run. + + Native loaders require the magic at offset 0. This extends the existing + offset-0 probe to catch filler-prefixed payloads and mislabeled files that + can evade a strict first-byte check. ``_EXEC_SNIFF_LIMIT`` is a + false-positive bound for short magics such as ``MZ``, not a security limit; + a run of that many or more filler bytes is outside the sniff. + """ + offset = _leading_filler_length(prefix[:_EXEC_SNIFF_LIMIT]) + if offset >= _EXEC_SNIFF_LIMIT or offset >= len(prefix): + return None + return next((magic for magic in _EXECUTABLE_MAGIC_PREFIXES if prefix.startswith(magic, offset)), None) + + def is_executable_binary_prefix(prefix: bytes) -> bool: - """Detect ELF, PE, and Mach-O executables by magic bytes.""" - return prefix.startswith(_EXECUTABLE_MAGIC_PREFIXES) + """Detect ELF, PE, and Mach-O executables by magic bytes. + + Tolerates a bounded leading filler run (see + :func:`executable_binary_magic`); callers passing only a head window + should provide at least ``EXEC_SNIFF_BYTES`` bytes. + """ + return executable_binary_magic(prefix) is not None diff --git a/backend/packages/harness/deerflow/skills/skillscan/orchestrator.py b/backend/packages/harness/deerflow/skills/skillscan/orchestrator.py index 8d693f32a4..3a386b5807 100644 --- a/backend/packages/harness/deerflow/skills/skillscan/orchestrator.py +++ b/backend/packages/harness/deerflow/skills/skillscan/orchestrator.py @@ -26,7 +26,7 @@ from pathlib import Path, PurePosixPath, PureWindowsPath from typing import Any from urllib.parse import urlsplit -from deerflow.skills.package_files import is_code_file, is_executable_binary_prefix +from deerflow.skills.package_files import EXEC_SNIFF_BYTES, executable_binary_magic, is_code_file, is_executable_binary_prefix from deerflow.skills.package_paths import is_eval_fixture_skill_md from deerflow.skills.skillscan.models import ( FindingSeverity, @@ -266,7 +266,7 @@ def scan_archive_preflight(archive_path: Path) -> ScanResult: continue try: with zf.open(info) as member: - prefix = member.read(8) + prefix = member.read(EXEC_SNIFF_BYTES) except Exception as e: scanner_errors.append(f"{normalized}: failed to read archive member prefix: {e}") continue @@ -317,7 +317,7 @@ def scan_skill_dir(skill_dir: Path) -> ScanResult: findings.append(_finding("package-undecodable-script", file=rel_path, evidence=evidence)) # A decoded executable is string-table noise that reads as secrets # and URLs; its CRITICAL executable finding already blocks it. - if is_executable_binary_prefix(file_bytes[:8]): + if is_executable_binary_prefix(file_bytes[:EXEC_SNIFF_BYTES]): continue try: @@ -358,8 +358,8 @@ def _scan_file_package_properties(rel_path: str, file_bytes: bytes, file_size: i findings.append(_finding("package-git-directory", file=rel_path, evidence=".git")) if _is_nested_archive_name(rel_path) or _looks_like_archive(file_bytes): findings.append(_nested_archive_finding(rel_path, file_bytes[:8], lambda: file_bytes, [])) - if is_executable_binary_prefix(file_bytes[:8]): - findings.append(_finding("package-executable-binary", file=rel_path, evidence=_binary_magic_evidence(file_bytes[:8]))) + if is_executable_binary_prefix(file_bytes[:EXEC_SNIFF_BYTES]): + findings.append(_finding("package-executable-binary", file=rel_path, evidence=_binary_magic_evidence(file_bytes[:EXEC_SNIFF_BYTES]))) return findings @@ -1296,7 +1296,7 @@ def _nested_zip_contains_executable(data: bytes) -> bool: continue try: with nested.open(info) as member: - if is_executable_binary_prefix(member.read(8)): + if is_executable_binary_prefix(member.read(EXEC_SNIFF_BYTES)): return True except Exception: continue @@ -1392,9 +1392,10 @@ def _looks_like_archive(file_bytes: bytes) -> bool: def _binary_magic_evidence(prefix: bytes) -> str: - if prefix.startswith(b"\x7fELF"): + magic = executable_binary_magic(prefix) or b"" + if magic.startswith(b"\x7fELF"): return "ELF" - if prefix.startswith(b"MZ"): + if magic.startswith(b"MZ"): return "PE" return "Mach-O" diff --git a/backend/tests/test_lark_cli_integration.py b/backend/tests/test_lark_cli_integration.py index a2d29596fe..c3aace480b 100644 --- a/backend/tests/test_lark_cli_integration.py +++ b/backend/tests/test_lark_cli_integration.py @@ -160,6 +160,13 @@ class _FakeWindowsHandle: return False +def _force_windows_runtime_branch(monkeypatch) -> None: + """Expose an ``os.name == "nt"`` view only through lark_cli.""" + members = {name: getattr(os, name) for name in dir(os) if not name.startswith("__")} + members["name"] = "nt" + monkeypatch.setattr(lark_cli, "os", SimpleNamespace(**members)) + + def _windows_os_stub() -> SimpleNamespace: """Minimal ``os`` stub that forces the Windows code path in unit tests. @@ -289,6 +296,32 @@ def test_managed_sandbox_runtime_verifies_and_installs_linux_archives(monkeypatc assert "x86_64" in launcher and "aarch64" in launcher +@pytest.mark.parametrize( + ("filler", "magic"), + [ + (b"\n", b"\x7fELF"), + (b"\xef\xbb\xbf", b"\x7fELF"), + (b" " * 63, b"\xbf\xba\xfe\xca"), + ], + ids=["newline-elf", "bom-elf", "max-offset-macho-fat64-le"], +) +def test_managed_sandbox_runtime_download_accepts_filler_prefixed_binaries_on_windows(monkeypatch, tmp_path, filler, magic) -> None: + _patch_paths(monkeypatch, tmp_path / "home") + archives = { + "lark-cli-1.0.65-linux-amd64.tar.gz": _make_lark_cli_binary_tar(filler + magic + b"-amd64-payload"), + "lark-cli-1.0.65-linux-arm64.tar.gz": _make_lark_cli_binary_tar(filler + magic + b"-arm64-payload"), + } + checksums = "".join(f"{hashlib.sha256(payload).hexdigest()} {name}\n" for name, payload in archives.items()).encode() + assets = {"checksums.txt": checksums, **archives} + monkeypatch.setattr(lark_cli, "_download_lark_release_asset", lambda _version, name, **_kwargs: assets[name]) + _force_windows_runtime_branch(monkeypatch) + + runtime = lark_cli._ensure_managed_sandbox_lark_cli("v1.0.65") + + assert (runtime / "linux-amd64" / "lark-cli").read_bytes() == filler + magic + b"-amd64-payload" + assert (runtime / "linux-arm64" / "lark-cli").read_bytes() == filler + magic + b"-arm64-payload" + + def test_managed_sandbox_runtime_rejects_checksum_mismatch(monkeypatch, tmp_path) -> None: assert hasattr(lark_cli, "_ensure_managed_sandbox_lark_cli"), "managed sandbox runtime installer is missing" _patch_paths(monkeypatch, tmp_path / "home") @@ -374,6 +407,36 @@ def test_managed_sandbox_runtime_rejects_any_symlink_in_prestaged_tree(monkeypat assert not lark_cli.lark_cli_managed_sandbox_dir().exists() +@pytest.mark.parametrize( + ("filler", "magic"), + [ + (b"\n", b"\x7fELF"), + (b"\xef\xbb\xbf", b"\x7fELF"), + (b" " * 63, b"\xbf\xba\xfe\xca"), + ], + ids=["newline-elf", "bom-elf", "max-offset-macho-fat64-le"], +) +def test_managed_sandbox_runtime_accepts_filler_prefixed_binaries_on_windows(monkeypatch, tmp_path, filler, magic) -> None: + _patch_paths(monkeypatch, tmp_path / "home") + source = tmp_path / "pre-staged" + for arch in ("amd64", "arm64"): + binary = source / f"linux-{arch}" / "lark-cli" + binary.parent.mkdir(parents=True) + binary.write_bytes(filler + magic + f"-{arch}-binary".encode()) + binary.chmod(0o755) + launcher = source / "bin" / "lark-cli" + launcher.parent.mkdir(parents=True) + launcher.write_text("#!/bin/sh\n", encoding="utf-8") + launcher.chmod(0o755) + monkeypatch.setenv(lark_cli.LARK_CLI_SANDBOX_RUNTIME_SOURCE_ENV, str(source)) + _force_windows_runtime_branch(monkeypatch) + + runtime = lark_cli._ensure_managed_sandbox_lark_cli("v1.0.65") + + assert (runtime / "linux-amd64" / "lark-cli").read_bytes().startswith(filler + magic) + assert (runtime / "linux-arm64" / "lark-cli").read_bytes().startswith(filler + magic) + + def test_managed_sandbox_runtime_rejects_non_executable_prestaged_binary(monkeypatch, tmp_path) -> None: _patch_paths(monkeypatch, tmp_path / "home") source = tmp_path / "pre-staged" @@ -1389,7 +1452,7 @@ def test_install_lark_integration_rejects_executable_binary_member(monkeypatch, config = _config(tmp_path / "skills") archive = _make_lark_cli_source_zip(tmp_path) with zipfile.ZipFile(archive, "a") as zf: - zf.writestr("cli-1.0.65/skills/lark-doc/bin/tool", b"\x7fELFbinary") + zf.writestr("cli-1.0.65/skills/lark-doc/bin/tool", b"\n\x7fELFbinary") with pytest.raises(ValueError, match="executable binary member"): lark_cli.install_lark_integration("alice", config, source_archive=archive) diff --git a/backend/tests/test_skill_export.py b/backend/tests/test_skill_export.py index 2e852a8b8a..c3ae934ccf 100644 --- a/backend/tests/test_skill_export.py +++ b/backend/tests/test_skill_export.py @@ -68,6 +68,27 @@ def test_structural_blockers(package, kind): assert manifest["blockers"] +@pytest.mark.parametrize( + ("filler", "magic"), + [ + (b"\n", b"\x7fELF"), + (b"\xef\xbb\xbf", b"\x7fELF"), + (b" " * 63, b"\xbf\xba\xfe\xca"), + ], + ids=["newline-elf", "bom-elf", "max-offset-macho-fat64-le"], +) +@requires_safe_capture +def test_filler_prefixed_binary_is_blocked(package, filler, magic): + storage, root = package + (root / "payload").write_bytes(filler + magic + b"\x00" * 64) + + manifest = export.export_manifest(storage, "sample") + + assert not manifest["can_export"] + assert manifest["revision"] is None + assert manifest["blockers"][0]["code"] == "skill_export_executable_binary" + + @requires_safe_capture def test_limits_are_not_truncated(package, monkeypatch): storage, root = package diff --git a/backend/tests/test_skills_installer.py b/backend/tests/test_skills_installer.py index 25521087bf..8b62e4183f 100644 --- a/backend/tests/test_skills_installer.py +++ b/backend/tests/test_skills_installer.py @@ -283,6 +283,53 @@ class TestSafeExtract: with pytest.raises(ValueError, match="executable binary"): safe_extract_skill_archive(zf, dest) + @pytest.mark.parametrize( + ("filler", "magic"), + [ + pytest.param(b"\n", b"\x7fELF", id="newline-elf"), + pytest.param(b" ", b"MZ", id="space-pe"), + pytest.param(b"\x00\x00\x00\n", b"\x7fELF", id="nul-run-elf"), + pytest.param(b"\xef\xbb\xbf", b"\x7fELF", id="utf8-bom-elf"), + pytest.param(b"\xef\xbb\xbf", b"\xbf\xba\xfe\xca", id="utf8-bom-macho-fat64-le"), + pytest.param(b" " * 63, b"\x7fELF", id="max-filler-offset"), + ], + ) + def test_rejects_whitespace_prefixed_executable_binary(self, tmp_path, filler, magic): + """Leading filler must not smuggle a binary past the extraction guard.""" + zip_path = self._make_zip( + tmp_path, + { + "my-skill/SKILL.md": "---\nname: test\ndescription: x\n---\n# Test", + "my-skill/assets/payload": filler + magic + b"\x00" * 64, + }, + ) + dest = tmp_path / "out" + dest.mkdir() + with zipfile.ZipFile(zip_path) as zf: + with pytest.raises(ValueError, match="executable binary"): + safe_extract_skill_archive(zf, dest) + + @pytest.mark.parametrize( + ("payload", "identifier"), + [ + pytest.param(b" " * 64 + b"\x7fELF" + b"\x00" * 64, "filler-at-cap"), + pytest.param(b"\xef\xbb\xbf\xba\xfe\xca" + b"\x00" * 64, "bom-tail-is-not-macho"), + ], + ) + def test_allows_non_executable_payloads_with_prefixes_outside_the_sniff(self, tmp_path, payload, identifier): + zip_path = self._make_zip( + tmp_path, + { + "my-skill/SKILL.md": "---\nname: test\ndescription: x\n---\n# Test", + f"my-skill/assets/{identifier}": payload, + }, + ) + dest = tmp_path / "out" + dest.mkdir() + with zipfile.ZipFile(zip_path) as zf: + safe_extract_skill_archive(zf, dest) + assert (dest / "my-skill" / "assets" / identifier).read_bytes() == payload + def test_allows_non_executable_binary_assets(self, tmp_path): zip_path = self._make_zip( tmp_path, @@ -611,6 +658,27 @@ class TestInstallSkillFromArchive: assert (f"test-skill/{rel_path}", True) in calls assert not (skills_root / "custom" / "test-skill").exists() + @pytest.mark.parametrize( + ("filler", "magic"), + [ + pytest.param(b"\n", b"\x7fELF", id="newline-elf"), + pytest.param(b"\xef\xbb\xbf", b"\x7fELF", id="bom-elf"), + pytest.param(b" " * 63, b"\xbf\xba\xfe\xca", id="max-filler-offset-macho-fat64-le"), + ], + ) + def test_filler_prefixed_executable_binary_prevents_install(self, tmp_path, filler, magic): + zip_path = tmp_path / "test-skill.skill" + with zipfile.ZipFile(zip_path, "w") as zf: + zf.writestr("test-skill/SKILL.md", "---\nname: test-skill\ndescription: A test skill\n---\n\n# test-skill\n") + zf.writestr("test-skill/assets/payload", filler + magic + b"\x00" * 64) + skills_root = tmp_path / "skills" + skills_root.mkdir() + + with pytest.raises(ValueError, match="executable binary"): + get_or_new_skill_storage(skills_path=skills_root).install_skill_from_archive(zip_path) + + assert not (skills_root / "custom" / "test-skill").exists() + def test_executable_binary_prevents_install(self, tmp_path): zip_path = tmp_path / "test-skill.skill" with zipfile.ZipFile(zip_path, "w") as zf: diff --git a/backend/tests/test_skillscan_native.py b/backend/tests/test_skillscan_native.py index 008b6cf03d..2f5950cf27 100644 --- a/backend/tests/test_skillscan_native.py +++ b/backend/tests/test_skillscan_native.py @@ -10,7 +10,7 @@ from types import SimpleNamespace import pytest -from deerflow.skills.package_files import is_executable_binary_prefix +from deerflow.skills.package_files import EXEC_SNIFF_BYTES, is_executable_binary_prefix from deerflow.skills.security_scanner import scan_skill_content from deerflow.skills.skillscan import StaticScanBlockedError, enforce_static_scan, scan_archive_preflight, scan_skill_dir from deerflow.skills.skillscan.orchestrator import _PYTHON_CLIENT_SINK_METHODS, MAX_FILE_BYTES @@ -456,8 +456,8 @@ def test_archive_preflight_reports_package_findings(tmp_path: Path) -> None: @pytest.mark.parametrize( "magic", - [b"\xce\xfa\xed\xfe", b"\xbe\xba\xfe\xca", b"\xca\xfe\xba\xbf"], - ids=["mach-o-32-le", "mach-o-fat-le", "mach-o-fat64-be"], + [b"\xce\xfa\xed\xfe", b"\xbe\xba\xfe\xca", b"\xca\xfe\xba\xbf", b"\xbf\xba\xfe\xca"], + ids=["mach-o-32-le", "mach-o-fat-le", "mach-o-fat64-be", "mach-o-fat64-le"], ) def test_executable_magic_matches_the_installer_extraction_guard(tmp_path: Path, magic: bytes) -> None: skill_dir = tmp_path / "demo-skill" @@ -470,6 +470,73 @@ def test_executable_magic_matches_the_installer_extraction_guard(tmp_path: Path, assert is_executable_binary_prefix(magic) +@pytest.mark.parametrize( + ("filler", "magic", "evidence"), + [ + pytest.param(b"\n", b"\x7fELF", "ELF", id="newline-elf"), + pytest.param(b" ", b"\x7fELF", "ELF", id="spaces-elf"), + pytest.param(b" ", b"MZ", "PE", id="space-pe"), + pytest.param(b"\r\n", b"\xca\xfe\xba\xbe", "Mach-O", id="crlf-macho-fat"), + pytest.param(b"\xef\xbb\xbf", b"\x7fELF", "ELF", id="utf8-bom-elf"), + pytest.param(b"\xef\xbb\xbf", b"\xbf\xba\xfe\xca", "Mach-O", id="utf8-bom-macho-fat64-le"), + pytest.param(b"\n", b"\xbf\xba\xfe\xca", "Mach-O", id="newline-macho-fat64-le"), + ], +) +def test_whitespace_prefixed_executable_magic_is_critical(tmp_path: Path, filler: bytes, magic: bytes, evidence: str) -> None: + """A bounded filler run before a full executable magic must still yield a + CRITICAL finding that blocks the package.""" + skill_dir = tmp_path / "demo-skill" + _write_skill(skill_dir) + tool = skill_dir / "assets" / "tool" + tool.parent.mkdir(parents=True, exist_ok=True) + tool.write_bytes(filler + magic + b"\x00" * 64) + + result = scan_skill_dir(skill_dir) + + finding = _finding_by_rule(result["findings"], "package-executable-binary") + assert (finding["file"], finding["severity"], finding["evidence"]) == ("assets/tool", "CRITICAL", evidence) + assert result["blocked"] is True + + +def test_whitespace_prefixed_executable_blocks_enforce_static_scan(tmp_path: Path) -> None: + skill_dir = tmp_path / "demo-skill" + _write_skill(skill_dir) + helper = skill_dir / "bin" / "helper" + helper.parent.mkdir(parents=True, exist_ok=True) + helper.write_bytes(b" \t\n" + b"\x7fELF" + b"\x02\x01\x01\x00" + b"\x00" * 64) + + with pytest.raises(StaticScanBlockedError): + enforce_static_scan(skill_dir, skill_name="demo-skill", app_config=SimpleNamespace(skill_scan=SimpleNamespace(enabled=True))) + + +def test_archive_preflight_flags_whitespace_prefixed_executable(tmp_path: Path) -> None: + archive = tmp_path / "demo-skill.skill" + with zipfile.ZipFile(archive, "w") as zf: + zf.writestr("demo-skill/SKILL.md", "---\nname: demo-skill\ndescription: Demo skill\n---\n") + zf.writestr("demo-skill/assets/payload", b"\n" + b"\x7fELF" + b"\x00" * 64) + + result = scan_archive_preflight(archive) + + assert _finding_by_rule(result["findings"], "package-executable-binary")["severity"] == "CRITICAL" + assert result["blocked"] is True + + +def test_heavy_whitespace_beyond_the_cap_is_not_an_executable(tmp_path: Path) -> None: + """Indented prose must not become a false positive: a run of exactly the + 64-byte limit is outside the filler run the sniff tolerates.""" + skill_dir = tmp_path / "demo-skill" + _write_skill(skill_dir) + notes = skill_dir / "assets" / "notes" + notes.parent.mkdir(parents=True, exist_ok=True) + notes.write_bytes(b" " * 64 + b"MZ, the magic number\n") + boundary = skill_dir / "assets" / "boundary" + boundary.write_bytes(b" " * 63 + b"MZ, the magic number\n") + + findings = scan_skill_dir(skill_dir)["findings"] + assert not [finding for finding in findings if finding["rule_id"] == "package-executable-binary" and finding["file"] == "assets/notes"] + assert _finding_by_rule([finding for finding in findings if finding["file"] == "assets/boundary"], "package-executable-binary")["severity"] == "CRITICAL" + + def test_truncated_mach_o_magic_is_not_an_executable(tmp_path: Path) -> None: skill_dir = tmp_path / "demo-skill" _write_skill(skill_dir) @@ -478,6 +545,38 @@ def test_truncated_mach_o_magic_is_not_an_executable(tmp_path: Path) -> None: assert not [finding for finding in scan_skill_dir(skill_dir)["findings"] if finding["rule_id"] == "package-executable-binary"] +@pytest.mark.parametrize( + ("filler", "magic", "expected"), + [ + (b"\n", b"\x7fELF", True), + (b"\x00\t ", b"MZ", True), + (b"\xef\xbb\xbf", b"\xca\xfe\xba\xbf", True), + (b" " * 63, b"\x7fELF", True), + (b" " * 64, b"\x7fELF", False), + # A BOM is one sequence; its last byte must not start a Mach-O magic. + (b"\xef\xbb\xbf", b"\xba\xfe\xca", False), + ], + ids=["newline", "nul-whitespace", "bom-then-fat64", "max-offset", "over-max-offset", "bom-not-bytewise"], +) +def test_executable_magic_after_bounded_filler(tmp_path: Path, filler: bytes, magic: bytes, expected: bool) -> None: + payload = filler + magic + b"\x00" * 64 + assert EXEC_SNIFF_BYTES == 67 + assert is_executable_binary_prefix(payload[:EXEC_SNIFF_BYTES]) is expected + + skill_dir = tmp_path / "demo-skill" + _write_skill(skill_dir) + (skill_dir / "tool").write_bytes(payload) + findings = [finding for finding in scan_skill_dir(skill_dir)["findings"] if finding["rule_id"] == "package-executable-binary"] + assert bool(findings) is expected + + archive = tmp_path / "demo-skill.skill" + with zipfile.ZipFile(archive, "w") as zf: + zf.writestr("demo-skill/SKILL.md", "---\nname: demo-skill\ndescription: Demo skill\n---\n") + zf.writestr("demo-skill/tool", payload) + archive_findings = [finding for finding in scan_archive_preflight(archive)["findings"] if finding["rule_id"] == "package-executable-binary"] + assert bool(archive_findings) is expected + + def test_archive_preflight_rejects_ntfs_ads_colon_member(tmp_path: Path) -> None: """A member name like ``scripts/run.sh:hidden.txt`` addresses a Windows NTFS Alternate Data Stream on ``run.sh`` rather than a nested file. Such @@ -497,6 +596,30 @@ def test_archive_preflight_rejects_ntfs_ads_colon_member(tmp_path: Path) -> None assert result["blocked"] is True +@pytest.mark.parametrize( + ("filler", "magic"), + [ + (b"\n", b"\x7fELF"), + (b"\xef\xbb\xbf", b"\x7fELF"), + (b" " * 63, b"\xbf\xba\xfe\xca"), + ], + ids=["newline-elf", "bom-elf", "max-offset-macho-fat64-le"], +) +def test_nested_zip_with_filler_prefixed_executable_escalates_to_critical(tmp_path: Path, filler: bytes, magic: bytes) -> None: + payload = filler + magic + b"\x00" * 64 + archive = tmp_path / "demo-skill.skill" + with zipfile.ZipFile(archive, "w") as zf: + zf.writestr("demo-skill/SKILL.md", "---\nname: demo-skill\ndescription: Demo skill\n---\n") + zf.writestr("demo-skill/payload.zip", _nested_zip_bytes("tool", payload)) + + result = scan_archive_preflight(archive) + + finding = _finding_by_rule(result["findings"], "package-nested-archive") + assert finding["severity"] == "CRITICAL" + assert "contains an executable binary member" in (finding["evidence"] or "") + assert result["blocked"] is True + + def test_nested_zip_with_executable_member_escalates_to_critical(tmp_path: Path) -> None: archive = tmp_path / "demo-skill.skill" with zipfile.ZipFile(archive, "w") as zf: