mirror of
https://github.com/affaan-m/ECC.git
synced 2026-11-30 20:26:09 +09:00
fix(skill-comply): stop setup commands from planting git hooks
Greptile found three ways a generated setup could still place an executable hook in the sandbox repository, which a later accepted `git commit` then runs on the host: - git init --template=<dir> (any unvetted git option) - option values attached to the flag: cp --target-directory=.git, cp -t.git, tar --directory=.git - archive members: tar -xf / unzip of an archive holding .git/hooks/pre-commit Fixes: - allowlist options per git subcommand; --template, --separate-git-dir, -c, --exec-path and the rest are refused - treat every suffix of an option argument as a possible attached value and apply the in-sandbox / no-.git path check to it - before tar -x or unzip, open every existing file argument with tarfile/zipfile and refuse unknown formats, links, special files and members that are absolute, contain .., or have a .git component; refuse unzip wildcards and run setup with stdin=/dev/null - run setup git commands with -c core.hooksPath=/dev/null as defense in depth Each sequence has a real-execution test in tests/test_invariant_runner.py that fails on the previous head and passes now. Signed-off-by: Wen <jwcastillo@gmail.com>
This commit is contained in:
3 files changed
+215
-12
No files matched your search
@@ -9,7 +9,9 @@ import shlex
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
import zipfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
@@ -30,9 +32,20 @@ ALLOWED_SETUP_EXECUTABLES = frozenset({
|
||||
# Setup commands are model output generated from the skill under test, so each
|
||||
# allowed tool is limited to its file-creating uses. These lists are allowlists
|
||||
# on purpose: git, tar, npm and pip all have options that run other programs.
|
||||
SAFE_GIT_SUBCOMMANDS = frozenset({
|
||||
"init", "add", "commit", "checkout", "switch", "branch", "tag", "rm", "mv", "config",
|
||||
})
|
||||
# Options each git subcommand may take. Everything else is refused: options such
|
||||
# as --template, --separate-git-dir or --exec-path can install or run hooks.
|
||||
SAFE_GIT_OPTIONS = {
|
||||
"init": frozenset({"-q", "--quiet", "-b", "--initial-branch"}),
|
||||
"add": frozenset({"-A", "--all", "-u", "--update", "-f", "--force", "-v", "--verbose", "--"}),
|
||||
"commit": frozenset({"-m", "--message", "-a", "--all", "-am", "-q", "--quiet", "--allow-empty", "--no-verify"}),
|
||||
"checkout": frozenset({"-b", "-B", "-q", "--quiet", "--"}),
|
||||
"switch": frozenset({"-c", "-C", "--create", "-q", "--quiet"}),
|
||||
"branch": frozenset({"-m", "-M", "-d", "-D", "-q", "--quiet"}),
|
||||
"tag": frozenset({"-a", "-m", "--message", "-d"}),
|
||||
"rm": frozenset({"-r", "-f", "--cached", "-q", "--quiet", "--"}),
|
||||
"mv": frozenset({"-f", "-k", "-v", "--"}),
|
||||
"config": frozenset(),
|
||||
}
|
||||
SAFE_GIT_CONFIG_KEYS = frozenset({"user.name", "user.email", "init.defaultbranch", "commit.gpgsign"})
|
||||
SAFE_TAR_SHORT_FLAGS = frozenset("cxtvfzjJC")
|
||||
SAFE_TAR_LONG_OPTIONS = frozenset({
|
||||
@@ -174,19 +187,32 @@ def _setup_sandbox(sandbox_dir: Path, scenario: Scenario) -> None:
|
||||
# reach outside the sandbox.
|
||||
continue
|
||||
try:
|
||||
subprocess.run(argv, cwd=sandbox_dir, capture_output=True)
|
||||
subprocess.run(argv, cwd=sandbox_dir, capture_output=True, stdin=subprocess.DEVNULL)
|
||||
except FileNotFoundError:
|
||||
# Setup tool not installed in this environment; skip rather than
|
||||
# crash the whole scenario. The compliance run continues.
|
||||
continue
|
||||
|
||||
|
||||
def _attached_values(arg: str) -> list[str]:
|
||||
"""Every possible value attached to an option: -t.git, -rt.git, --directory=.git."""
|
||||
body = arg.lstrip("-")
|
||||
return [body[index:] for index in range(len(body))]
|
||||
|
||||
|
||||
def _arg_stays_in_sandbox(arg: str, sandbox_dir: Path) -> bool:
|
||||
"""True if a path-like argument resolves inside the sandbox, outside its .git."""
|
||||
if arg.startswith("-"):
|
||||
# Option values attached to the flag (--file=/x, -t.., -C/) are not
|
||||
# resolved here, so refuse any that could name another directory.
|
||||
return not any(token in arg for token in ("/", "\\", "~", ".."))
|
||||
# parsed per tool, so refuse any that could name another directory
|
||||
# and check every suffix as if it were the value.
|
||||
if any(token in arg for token in ("/", "\\", "~", "..")):
|
||||
return False
|
||||
return all(_path_stays_in_sandbox(value, sandbox_dir) for value in _attached_values(arg))
|
||||
return _path_stays_in_sandbox(arg, sandbox_dir)
|
||||
|
||||
|
||||
def _path_stays_in_sandbox(arg: str, sandbox_dir: Path) -> bool:
|
||||
if arg.startswith("~"):
|
||||
return False
|
||||
root = sandbox_dir.resolve()
|
||||
@@ -197,6 +223,62 @@ def _arg_stays_in_sandbox(arg: str, sandbox_dir: Path) -> bool:
|
||||
return ".git" not in {part.lower() for part in relative.parts}
|
||||
|
||||
|
||||
def _archive_member_safe(name: str) -> bool:
|
||||
parts = re.split(r"[\\/]+", name)
|
||||
return (
|
||||
not name.startswith(("/", "\\"))
|
||||
and not re.match(r"[A-Za-z]:", name)
|
||||
and ".." not in parts
|
||||
and ".git" not in {part.lower() for part in parts}
|
||||
)
|
||||
|
||||
|
||||
def _archive_safe(path: Path) -> bool:
|
||||
"""True if path is a tar or zip archive of plain files and directories, none under .git."""
|
||||
names: list[str] = []
|
||||
recognized = False
|
||||
try:
|
||||
if tarfile.is_tarfile(path):
|
||||
recognized = True
|
||||
with tarfile.open(path) as archive:
|
||||
for member in archive.getmembers():
|
||||
if not (member.isfile() or member.isdir()):
|
||||
return False # links, devices and fifos
|
||||
names.append(member.name)
|
||||
if zipfile.is_zipfile(path):
|
||||
recognized = True
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
for info in archive.infolist():
|
||||
if stat.S_ISLNK(info.external_attr >> 16):
|
||||
return False
|
||||
names.append(info.filename)
|
||||
except (tarfile.TarError, zipfile.BadZipFile, OSError):
|
||||
return False
|
||||
return recognized and all(_archive_member_safe(name) for name in names)
|
||||
|
||||
|
||||
def _extracted_archives_safe(tool: str, args: list[str], sandbox_dir: Path) -> bool:
|
||||
"""Before tar -x or unzip runs, check the members of every archive it could read.
|
||||
|
||||
Any existing file named by an argument (or attached to an option) must be a
|
||||
tar/zip archive that _archive_safe() accepts, so an unreadable format fails
|
||||
closed instead of being extracted unchecked.
|
||||
"""
|
||||
if tool == "tar":
|
||||
flags = [arg for index, arg in enumerate(args) if arg[:2] != "--" and (arg[:1] == "-" or index == 0)]
|
||||
if "--extract" not in args and not any("x" in flag for flag in flags):
|
||||
return True
|
||||
elif any(char in arg for arg in args for char in "*?["):
|
||||
return False # unzip expands wildcards in the archive name itself
|
||||
root = sandbox_dir.resolve()
|
||||
for arg in args:
|
||||
for value in _attached_values(arg) if arg.startswith("-") else [arg]:
|
||||
path = (root / value).resolve()
|
||||
if path.is_file() and not _archive_safe(path):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _packages_allowed(args: list[str], options: frozenset[str]) -> bool:
|
||||
return all(
|
||||
arg in options or (not arg.startswith("-") and PACKAGE_SPEC.fullmatch(arg))
|
||||
@@ -233,11 +315,17 @@ def _sandboxed_setup_command(parts: list[str], sandbox_dir: Path) -> list[str] |
|
||||
if tool == "git":
|
||||
# The subcommand must come first, which also rules out global
|
||||
# options such as -c, -C, --config-env and --exec-path.
|
||||
if not args or args[0] not in SAFE_GIT_SUBCOMMANDS:
|
||||
if not args or args[0] not in SAFE_GIT_OPTIONS:
|
||||
return None
|
||||
allowed = SAFE_GIT_OPTIONS[args[0]]
|
||||
if any(arg.startswith("-") and arg.split("=", 1)[0] not in allowed for arg in args[1:]):
|
||||
return None
|
||||
if args[0] == "config" and (len(args) != 3 or args[1].lower() not in SAFE_GIT_CONFIG_KEYS):
|
||||
return None
|
||||
return parts
|
||||
# Defense in depth: no hook runs during setup even if one slipped in.
|
||||
return ["git", "-c", f"core.hooksPath={os.devnull}", *args]
|
||||
if tool in {"tar", "unzip"} and not _extracted_archives_safe(tool, args, sandbox_dir):
|
||||
return None
|
||||
if tool == "tar":
|
||||
return parts if _tar_args_allowed(args) else None
|
||||
if tool == "npm":
|
||||
|
||||
@@ -7,7 +7,9 @@ import os
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import zipfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
@@ -18,6 +20,7 @@ from scripts.runner import (
|
||||
SANDBOX_BASE,
|
||||
_parse_stream_json,
|
||||
_safe_sandbox_dir,
|
||||
_sandboxed_setup_command,
|
||||
_setup_sandbox,
|
||||
run_scenario,
|
||||
)
|
||||
@@ -324,6 +327,9 @@ class TestSetupSandboxSkipsShellBuiltins:
|
||||
assert ["cd", "ignored"] not in called_args
|
||||
|
||||
|
||||
_GIT = ["git", "-c", f"core.hooksPath={os.devnull}"]
|
||||
|
||||
|
||||
def _run_setup(sandbox: Path, *commands: str) -> list[list[str]]:
|
||||
"""Run _setup_sandbox with a fake subprocess and return the argv it executed."""
|
||||
called: list[list[str]] = []
|
||||
@@ -392,6 +398,17 @@ class TestSetupCommandConfinement:
|
||||
"touch -r /etc/shadow x",
|
||||
"mkdir -p /tmp/skill-comply-sandbox/x",
|
||||
"unzip a.zip -d /tmp/out",
|
||||
# git options that install hooks or move the repository
|
||||
"git init --template=templates",
|
||||
"git init --separate-git-dir=gitdir",
|
||||
"git commit --template=msg -m x",
|
||||
"git add --chmod=+x hook",
|
||||
# option values attached to the flag
|
||||
"cp -r --target-directory=.git hooks",
|
||||
"cp -r -t.git hooks",
|
||||
"cp -rt.GIT hooks",
|
||||
"tar -xf hooks.tar --directory=.git",
|
||||
"unzip 'payload*'",
|
||||
])
|
||||
def test_bypass_is_not_executed(self, tmp_path: Path, command: str) -> None:
|
||||
assert _run_setup(tmp_path / "sandbox", command) == []
|
||||
@@ -400,10 +417,10 @@ class TestSetupCommandConfinement:
|
||||
("mkdir -p src tests", ["mkdir", "-p", "src", "tests"]),
|
||||
("touch src/__init__.py", ["touch", "src/__init__.py"]),
|
||||
("echo hello", ["echo", "hello"]),
|
||||
("git add .", ["git", "add", "."]),
|
||||
("git commit -m 'initial commit'", ["git", "commit", "-m", "initial commit"]),
|
||||
("git config user.email test@example.com", ["git", "config", "user.email", "test@example.com"]),
|
||||
("git checkout -b feature/x", ["git", "checkout", "-b", "feature/x"]),
|
||||
("git add .", [*_GIT, "add", "."]),
|
||||
("git commit -m 'initial commit'", [*_GIT, "commit", "-m", "initial commit"]),
|
||||
("git config user.email test@example.com", [*_GIT, "config", "user.email", "test@example.com"]),
|
||||
("git checkout -b feature/x", [*_GIT, "checkout", "-b", "feature/x"]),
|
||||
("cp src/a.py src/b.py", ["cp", "src/a.py", "src/b.py"]),
|
||||
("mv src/a.py lib.py", ["mv", "src/a.py", "lib.py"]),
|
||||
("chmod +x run.sh", ["chmod", "+x", "run.sh"]),
|
||||
@@ -431,6 +448,41 @@ class TestSetupCommandConfinement:
|
||||
assert _run_setup(sandbox, f"mkdir -p {sandbox}/src") == [["mkdir", "-p", f"{sandbox}/src"]]
|
||||
|
||||
|
||||
class TestArchiveMembers:
|
||||
"""tar -x / unzip only run when every member is a plain file outside .git."""
|
||||
|
||||
@pytest.mark.parametrize("name,ok", [
|
||||
("src/a.py", True),
|
||||
(".gitignore", True),
|
||||
(".git/hooks/pre-commit", False),
|
||||
("sub/.GIT/config", False),
|
||||
("../escape", False),
|
||||
("/abs", False),
|
||||
("a\\..\\..\\x", False),
|
||||
])
|
||||
def test_member_names(self, tmp_path: Path, name: str, ok: bool) -> None:
|
||||
sandbox = tmp_path / "sandbox"
|
||||
sandbox.mkdir()
|
||||
with tarfile.open(sandbox / "a.tar", "w") as archive:
|
||||
archive.addfile(tarfile.TarInfo(name))
|
||||
with zipfile.ZipFile(sandbox / "a.zip", "w") as archive:
|
||||
archive.writestr(name, "")
|
||||
for command in ("tar -xf a.tar", "unzip a.zip"):
|
||||
assert (_sandboxed_setup_command(command.split(), sandbox) is not None) is ok, command
|
||||
|
||||
def test_links_and_unknown_formats_are_refused(self, tmp_path: Path) -> None:
|
||||
sandbox = tmp_path / "sandbox"
|
||||
sandbox.mkdir()
|
||||
link = tarfile.TarInfo("inside")
|
||||
link.type, link.linkname = tarfile.SYMTYPE, "elsewhere"
|
||||
with tarfile.open(sandbox / "link.tar", "w") as archive:
|
||||
archive.addfile(link)
|
||||
(sandbox / "a.tar.zst").write_bytes(b"\x28\xb5\x2f\xfd")
|
||||
assert _sandboxed_setup_command(["tar", "-xf", "link.tar"], sandbox) is None
|
||||
assert _sandboxed_setup_command(["tar", "-xf", "a.tar.zst"], sandbox) is None
|
||||
assert _sandboxed_setup_command(["tar", "-cf", "out.tar", "a.tar.zst"], sandbox) is not None
|
||||
|
||||
|
||||
class TestSandboxBaseOwnership:
|
||||
def test_default_base_is_per_user(self) -> None:
|
||||
if hasattr(os, "getuid"):
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import io
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -74,3 +79,61 @@ def test_setup_sandbox_blocks_dangerous_commands(setup_commands, test_id, tmp_pa
|
||||
f"Arbitrary command execution detected for '{test_id}': "
|
||||
f"marker file created at {_GLOBAL_MARKER}"
|
||||
)
|
||||
|
||||
|
||||
def _plant_registry_package(sandbox_dir):
|
||||
"""Stand in for `npm install attacker-pkg`: a registry package that ships hook files."""
|
||||
pkg = sandbox_dir / "node_modules" / "attacker-pkg"
|
||||
hook = f"#!/bin/sh\ntouch {_GLOBAL_MARKER}\n"
|
||||
(pkg / "hooks").mkdir(parents=True)
|
||||
(pkg / "hooks" / "post-commit").write_text(hook)
|
||||
(pkg / "hooks" / "post-commit").chmod(0o755)
|
||||
info = tarfile.TarInfo("hooks/post-commit")
|
||||
info.size, info.mode = len(hook), 0o755
|
||||
with tarfile.open(pkg / "hooks.tar", "w") as archive:
|
||||
archive.addfile(info, io.BytesIO(hook.encode()))
|
||||
info.name = ".git/hooks/post-commit"
|
||||
with tarfile.open(pkg / "payload.tar", "w") as archive:
|
||||
archive.addfile(info, io.BytesIO(hook.encode()))
|
||||
member = zipfile.ZipInfo(".git/hooks/post-commit")
|
||||
member.external_attr = 0o100755 << 16
|
||||
with zipfile.ZipFile(pkg / "payload.zip", "w") as archive:
|
||||
archive.writestr(member, hook)
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell hooks")
|
||||
@pytest.mark.parametrize(
|
||||
"plant",
|
||||
[
|
||||
("mkdir templates", "cp -r node_modules/attacker-pkg/hooks templates/hooks", "git init --template=templates"),
|
||||
("cp -r --target-directory=.git node_modules/attacker-pkg/hooks",),
|
||||
("cp -r -t.git node_modules/attacker-pkg/hooks",),
|
||||
("tar -xf node_modules/attacker-pkg/hooks.tar --directory=.git",),
|
||||
("tar -xf node_modules/attacker-pkg/payload.tar",),
|
||||
("unzip -o node_modules/attacker-pkg/payload.zip",),
|
||||
],
|
||||
ids=["git_template", "cp_target_directory", "cp_attached_t", "tar_directory", "tar_member", "unzip_member"],
|
||||
)
|
||||
def test_setup_cannot_plant_git_hooks(plant, tmp_path):
|
||||
"""Invariant: setup must not leave a hook that a later accepted `git commit` runs on the host."""
|
||||
real_run = subprocess.run
|
||||
sandbox_dir = tmp_path / "sandbox"
|
||||
|
||||
def run(argv, **kwargs):
|
||||
if argv[0] == "npm":
|
||||
_plant_registry_package(sandbox_dir)
|
||||
return subprocess.CompletedProcess(argv, 0)
|
||||
return real_run(argv, **kwargs)
|
||||
|
||||
identity = ("git config user.name t", "git config user.email t@example.com", "git config commit.gpgsign false")
|
||||
scenario = Scenario(
|
||||
id="hook-plant", level=1, level_name="basic", description="security test scenario", prompt="",
|
||||
setup_commands=("npm install attacker-pkg", *plant, *identity, "git commit --allow-empty -m setup"),
|
||||
)
|
||||
with patch("scripts.runner.subprocess.run", side_effect=run):
|
||||
_setup_sandbox(sandbox_dir, scenario)
|
||||
# The agent (or the user) commits later, without the runner's protections.
|
||||
real_run(["git", "commit", "--allow-empty", "-m", "later"], cwd=sandbox_dir, capture_output=True)
|
||||
|
||||
assert not os.path.exists(_GLOBAL_MARKER), "a planted git hook ran on the host"
|
||||
assert not (sandbox_dir / ".git" / "hooks" / "post-commit").exists()
|
||||
Reference in new issue
Block a user