Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 124 additions & 5 deletions core/harness/command_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,14 @@
from core.network.hostnames import is_domain_allowed

__all__ = [
"PYTHON_SHADOW_WAIVER_ENV_VAR",
"find_confusables",
"screen_all",
"screen_cwd_shadow",
"screen_command",
"screen_egress",
"screen_install",
"shadow_names_in",
"strict_screens_enabled",
]

Expand Down Expand Up @@ -803,24 +806,140 @@ def screen_install(
return None


# --------------------------------------------------------------------------
# Working-directory module shadowing
# --------------------------------------------------------------------------
# A Python interpreter puts its cwd on ``sys.path``, so a same-named file in
# that directory shadows the standard library. An archive shipping ``struct.py``
# executes arbitrary code as soon as the caller types ``import base64`` (base64
# imports struct transitively). Every step of that chain — download, unpack,
# run — stays *inside* the workspace, which is why a write fence does not stop
# it: the fence governs where bytes may land, not whether what just landed may
# run.
#
# That makes this the one class the sandbox structurally cannot see, so it gets
# its own screen. Scope is deliberately narrow: only names auto-imported at
# interpreter start (sitecustomize/usercustomize) or pulled in by very common
# stdlib modules (struct, via base64/json/pickle) are listed. A blanket "any
# .py beside the command" rule would fire on ordinary source trees and get
# switched off within a day, which is worse than not having it at all.

_CWD_SHADOW_MODULES = frozenset(
{"sitecustomize.py", "usercustomize.py", "struct.py", "_struct.py"}
)

#: Explicit waiver for the rare project that genuinely vendors one of these
#: names. Same shape as the other screens: opt out loudly, not silently.
PYTHON_SHADOW_WAIVER_ENV_VAR = "DEEPCODE_ALLOW_CWD_SHADOW"

_TRUE_VALUES = frozenset({"1", "true", "yes", "on"})


def _is_python_program(name: str) -> bool:
"""True for ``python`` / ``python3`` / ``python3.12`` / ``py`` / ``py3``."""
return name in {"python", "python3", "py"} or name.startswith(("python3.", "py3"))


def _simple_argvs(command: str) -> list[list[str]]:
"""Unwrapped simple commands in ``command`` (empty on unparseable input)."""
argvs: list[list[str]] = []
for tokens in _command_argvs(command):
unwrapped = _unwrap(tokens)
if unwrapped:
argvs.append(unwrapped)
return argvs


def shadow_names_in(directory: str) -> tuple[str, ...]:
"""Shadow-module names present in ``directory`` (sorted, empty on error)."""
try:
present = {
entry.name.lower() for entry in os.scandir(directory) if entry.is_file()
}
except OSError:
return ()
return tuple(sorted(present & _CWD_SHADOW_MODULES))


def _cd_targets(command: str) -> list[str]:
"""Directories the command line is likely to ``cd`` into (best effort).

An unpack-and-run chain typically looks like ``cd <archive-dir> && python3
-c ...``, so checking only the workspace root would miss it. Targets are
resolved against the workspace by the caller.
"""
targets: list[str] = []
for tokens in _simple_argvs(command):
if _program(tokens[0]) not in {"cd", "pushd"}:
continue
for arg in tokens[1:]:
if arg and not arg.startswith("-"):
targets.append(arg)
break
return targets


def screen_cwd_shadow(command: str, workspace: str | None = None) -> str | None:
"""Refuse a Python call that would import a shadow module from disk.

Returns a reason string, or ``None``. Never raises: an unreadable workspace
degrades to "nothing found", because a screening layer must not block on a
filesystem quirk.
"""
if not workspace:
return None
if os.environ.get(PYTHON_SHADOW_WAIVER_ENV_VAR, "").strip().lower() in _TRUE_VALUES:
return None

if not any(
_is_python_program(_program(tokens[0])) for tokens in _simple_argvs(command)
):
return None

candidates = [workspace]
for target in _cd_targets(command):
candidates.append(
target if os.path.isabs(target) else os.path.join(workspace, target)
)

for directory in candidates:
found = shadow_names_in(directory)
if found:
return (
f"python module shadowing in {directory} "
f"({', '.join(found)}) — a file there is imported instead of the "
f"standard library, so a downloaded archive could run code on "
f"import. Remove it, run from a clean directory, or set "
f"{PYTHON_SHADOW_WAIVER_ENV_VAR}=1 if the file is intentional."
)
return None


def screen_all(
command: str,
*,
workspace: str | None = None,
allowed_domains: tuple[str, ...] = (),
blocked_domains: tuple[str, ...] = (),
known_packages: frozenset[str] | tuple[str, ...] | set[str] = (),
allowed_indexes: frozenset[str] = _DEFAULT_TRUSTED_INDEXES,
) -> str | None:
"""Run every screen and return the first reason, or ``None``.

The destructive-command screen always runs. The egress and install screens
run only under ``DEEPCODE_COMMAND_SCREEN=strict`` (see
:func:`strict_screens_enabled`). Order matters only for the quality of the
message: the destructive check is the cheapest and the most certain, so it
speaks first.
The destructive-command screen always runs, followed by the working-directory
shadow screen — that one is cheap (a couple of ``scandir`` calls) and covers
the single class the sandbox cannot, so it does not wait for
``DEEPCODE_COMMAND_SCREEN=strict``. The egress and install screens run only
under strict (see :func:`strict_screens_enabled`).

``workspace`` is optional so existing callers keep working; without it the
shadow screen is inert (it needs a directory to inspect).
"""

reason = screen_command(command)
if reason:
return reason
reason = screen_cwd_shadow(command, workspace)
if reason or not strict_screens_enabled():
return reason
return screen_egress(
Expand Down
10 changes: 9 additions & 1 deletion core/harness/tools/shell.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,15 @@ async def execute(self, **kwargs: Any) -> Any:
# Destructive argv is always refused; under DEEPCODE_COMMAND_SCREEN=strict
# so are remote scripts piped into an interpreter, installs from unknown
# indexes and one-edit package names (see command_guard.screen_all).
screened = screen_all(command, known_packages=self._known_packages())
# ``workspace`` enables the working-directory shadow screen: a Python
# started here imports same-named files from its cwd before the stdlib,
# and that chain never leaves the workspace, so the write fence cannot
# see it (see command_guard.screen_cwd_shadow).
screened = screen_all(
command,
workspace=self._workspace,
known_packages=self._known_packages(),
)
if screened:
return (
f"Error: command blocked by policy screen ({screened}). "
Expand Down
147 changes: 147 additions & 0 deletions tests/test_command_guard_cwd_shadow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"""Regression tests for the working-directory module-shadow screen.

A Python interpreter puts its cwd on ``sys.path``, so a same-named file there
shadows the standard library. A downloaded archive shipping ``struct.py``
executes code as soon as the caller types ``import base64`` — base64 imports
struct transitively. Every step of that chain (download, unpack, run) stays
inside the workspace, so the sandbox write fence cannot see it: the fence
governs where bytes may land, not whether what just landed may run.
"""

from __future__ import annotations

import pytest

from core.harness.command_guard import (
PYTHON_SHADOW_WAIVER_ENV_VAR,
_is_python_program,
screen_all,
screen_cwd_shadow,
shadow_names_in,
)


# --------------------------------------------------------------------------- detection


def test_shadow_names_detects_the_published_payload(tmp_path):
(tmp_path / "struct.py").write_text("x = 1\n", encoding="utf-8")
assert shadow_names_in(str(tmp_path)) == ("struct.py",)


def test_shadow_names_is_case_insensitive(tmp_path):
(tmp_path / "STRUCT.PY").write_text("x = 1\n", encoding="utf-8")
assert shadow_names_in(str(tmp_path)) == ("struct.py",)


def test_shadow_names_ignores_unrelated_files(tmp_path):
(tmp_path / "main.py").write_text("x = 1\n", encoding="utf-8")
(tmp_path / "requirements.txt").write_text("", encoding="utf-8")
assert shadow_names_in(str(tmp_path)) == ()


def test_shadow_names_ignores_a_directory_with_the_same_name(tmp_path):
(tmp_path / "struct.py").mkdir()
assert shadow_names_in(str(tmp_path)) == ()


def test_shadow_names_degrades_on_missing_directory(tmp_path):
# Must never raise: a screening layer cannot block on a filesystem quirk.
assert shadow_names_in(str(tmp_path / "does-not-exist")) == ()


# --------------------------------------------------------------------------- screening


def test_python_call_is_refused_when_cwd_shadows(tmp_path):
(tmp_path / "struct.py").write_text("x = 1\n", encoding="utf-8")
reason = screen_cwd_shadow("python3 -c 'import base64'", str(tmp_path))
assert reason is not None
assert "shadow" in reason


def test_python_call_allowed_without_shadow_file(tmp_path):
assert screen_cwd_shadow("python3 -c 'import base64'", str(tmp_path)) is None


def test_non_python_command_is_not_screened(tmp_path):
(tmp_path / "struct.py").write_text("x = 1\n", encoding="utf-8")
assert screen_cwd_shadow("ls -la", str(tmp_path)) is None


def test_no_workspace_means_inert(tmp_path):
(tmp_path / "struct.py").write_text("x = 1\n", encoding="utf-8")
assert screen_cwd_shadow("python3 -c 'import base64'", None) is None


def test_cd_target_is_checked(tmp_path):
"""An unpack-and-run chain is ``cd <archive-dir> && python3 ...``.

Checking only the workspace root would miss it, so the cd target is
inspected too.
"""
unpacked = tmp_path / "catalogue"
unpacked.mkdir()
(unpacked / "struct.py").write_text("x = 1\n", encoding="utf-8")

reason = screen_cwd_shadow(
"cd catalogue && python3 -c 'import base64'", str(tmp_path)
)
assert reason is not None
assert "catalogue" in reason


def test_cd_into_clean_nested_dir_is_allowed(tmp_path):
(tmp_path / "clean").mkdir()
assert screen_cwd_shadow("cd clean && python3 -c 'print(1)'", str(tmp_path)) is None


def test_cd_into_missing_directory_does_not_raise(tmp_path):
reason = screen_cwd_shadow("cd nope && python3 -c 'print(1)'", str(tmp_path))
assert reason is None


def test_waiver_env_allows_deliberate_vendoring(tmp_path, monkeypatch):
(tmp_path / "struct.py").write_text("x = 1\n", encoding="utf-8")
monkeypatch.setenv(PYTHON_SHADOW_WAIVER_ENV_VAR, "1")
assert screen_cwd_shadow("python3 -c 'import base64'", str(tmp_path)) is None


def test_waiver_ignores_falsey_spellings(tmp_path, monkeypatch):
(tmp_path / "struct.py").write_text("x = 1\n", encoding="utf-8")
monkeypatch.setenv(PYTHON_SHADOW_WAIVER_ENV_VAR, "off")
assert screen_cwd_shadow("python3 -c 'import base64'", str(tmp_path)) is not None


@pytest.mark.parametrize("program", ["python", "python3", "python3.14", "py", "py3"])
def test_python_program_variants(program):
assert _is_python_program(program) is True


@pytest.mark.parametrize("program", ["pip", "python-config", "node", "bash"])
def test_non_python_programs_are_rejected(program):
assert _is_python_program(program) is False


# --------------------------------------------------------------------------- wiring


def test_screen_all_runs_shadow_before_strict_egress(tmp_path):
"""The shadow screen must not wait for DEEPCODE_COMMAND_SCREEN=strict."""
(tmp_path / "sitecustomize.py").write_text("x = 1\n", encoding="utf-8")
reason = screen_all("python -c 'print(1)'", workspace=str(tmp_path))
assert reason is not None
assert "shadow" in reason


def test_screen_all_keeps_destructive_screen_first(tmp_path):
(tmp_path / "struct.py").write_text("x = 1\n", encoding="utf-8")
reason = screen_all("rm -rf /", workspace=str(tmp_path))
assert reason is not None
assert "recursive force remove" in reason


def test_screen_all_without_workspace_is_unchanged(tmp_path):
"""Existing callers that pass no workspace keep the old behaviour."""
(tmp_path / "struct.py").write_text("x = 1\n", encoding="utf-8")
assert screen_all("python3 -c 'import base64'") is None
Loading