From fe4cb51872437a398fd109983c64b9acf4541af5 Mon Sep 17 00:00:00 2001 From: raymondginger Date: Sun, 15 Nov 2026 06:04:36 +0800 Subject: [PATCH] fix(security): name the hidden target when a shell word links to a secret A shell command's operands sit inside the command string, under a key no path rule names, so a word like `video.mp4` never reached the sensitive-path check. When that word was a symlink to `.env`, the approval prompt showed the harmless end and the write landed on the secret. The first attempt screened every word against the denylist, which turned ten ordinary commands (`cp .env.example .env`, `source .env`, `git add .env.example`, ...) from "ask" into denials no rule could override. That conflicts with a deliberate choice on main and only ever affected Ask mode. This narrows the probe to the shape that actually deceives the prompt: an existing symlink whose own name is not protected, whose resolved target is. Both conditions matter -- `is_sensitive_path` resolves links, so asking it whether the alias's own name is sensitive would answer for the target instead. The result is a confirmation that names both ends, not a deny: 'video.mp4' links to '/path/to/.env', a protected path; confirm before this runs It is raised wherever the call would otherwise be allowed, so an allow rule cannot quietly wave it through: the explicit-allow branch, the full-auto branch, and the mode-default path all upgrade to ask (and still downgrade to deny under an "approval policy: never"). Decision table, same commands, both trees, Ask mode (main -> branch): cp .env.example .env ask -> ask source .env ask -> ask docker compose --env-file .env up ask -> ask echo PORT=3000 >> .env ask -> ask git add .env.example ask -> ask jq -r .key package.json ask -> ask curl -O .../cacert.pem ask -> ask openssl -keyout key.pem ask -> ask uvicorn --ssl-keyfile key.pem ask -> ask grep -n id_rsa README.md ask -> ask cp video.mp4 out/ (-> .env) ask -> ask, now naming the target Tests: tests/test_harness_permissions.py, 47 passed. They pin the alias shape, the named confirmation in both full-auto and ask mode, the allow-rule case, the ten commands above staying ask, and that a non-shell tool's `command` argument is not scanned. ruff 0.15.21 check and format clean. --- core/harness/permissions.py | 137 ++++++++++++++++++++++++++++++ tests/test_harness_permissions.py | 107 +++++++++++++++++++++++ 2 files changed, 244 insertions(+) diff --git a/core/harness/permissions.py b/core/harness/permissions.py index 110433d4..fd25986d 100644 --- a/core/harness/permissions.py +++ b/core/harness/permissions.py @@ -37,6 +37,7 @@ import fnmatch import os import re +import shlex from collections.abc import Iterable, Mapping from dataclasses import dataclass, field from enum import Enum @@ -333,6 +334,68 @@ def _is_shell_tool(tool_name: str) -> bool: ) +def _shell_symlink_alias( + command: str, cwd: str | None = None +) -> tuple[str, str] | None: + """Return ``(alias, target)`` when a command word is a link to a secret. + + A shell tool carries its operands inside the command string, under a key no + path rule names, so ``_path_values`` never sees them. Screening every word + would make ordinary commands impossible to approve, though: ``cp + .env.example .env``, ``source .env`` and ``git add .env.example`` would all + become denials that no rule can override, and builds legitimately read + files with those names. + + The shape that actually hides a target from the approval prompt is narrower: + an existing symlink whose own name says nothing, but whose resolved target + is protected. The prompt then shows ``video.mp4`` while the write lands on + ``.env``. Only that shape is returned here. + + ``argv[0]`` is skipped because it is the program name. A word that is not + an existing symlink is left alone: a plain ``.env`` is already governed by + the sandbox, which keeps shell commands away from the home credential + stores. A link whose own name is already sensitive is also left to the + ordinary path check, so this helper never weakens it. + """ + try: + tokens = shlex.split(command, posix=True) + except ValueError: # unbalanced quotes -> fall back to whitespace splitting + tokens = command.split() + for index, token in enumerate(tokens): + if not token or token.startswith("-"): + continue + # Strip shell punctuation that wraps a path (``a.mp4;``, ``(x)``). + cleaned = token.strip("'\"").rstrip(";,&|)") + if not cleaned: + continue + # argv[0] is the program name, not an operand. + if index == 0 and "/" not in cleaned and "\\" not in cleaned: + continue + path = _normalize_path(cleaned, cwd) + try: + if not os.path.islink(path): + continue + except OSError: + continue + # "Own name" is judged without resolving the link. is_sensitive_path() + # resolves realpath first, so asking it here would answer for the + # TARGET and skip the one shape this helper exists to report. + own = path.replace(os.sep, "/").casefold() + own_name = own.rsplit("/", 1)[-1] + if any( + fnmatch.fnmatchcase(own, pattern) or fnmatch.fnmatchcase(own_name, pattern) + for pattern in SENSITIVE_PATH_PATTERNS + ): + continue + try: + target = os.path.realpath(path) + except (OSError, ValueError): + continue + if is_sensitive_path(target, cwd): + return cleaned, target + return None + + def is_shell_tool(tool_name: str) -> bool: """Whether ``tool_name`` runs a shell command.""" @@ -461,6 +524,34 @@ def hits_sensitive_path(self, arguments: Mapping[str, object]) -> str | None: return raw return None + def shell_symlink_alias( + self, tool_name: str, arguments: Mapping[str, object] + ) -> tuple[str, str] | None: + """Return ``(alias, target)`` for a shell word that links to a secret. + + Shell operands live inside the command string, so no path-keyed rule + sees them; the aliasing shape is described on + :func:`_shell_symlink_alias`. Kept separate from + :meth:`hits_sensitive_path` because the two answer different questions: + that one is a non-overridable deny, this one is a named confirmation. + """ + if not tool_name or not _is_shell_tool(tool_name): + return None + for key in ("command", "cmd", "commands", "script"): + value = arguments.get(key) + if isinstance(value, str): + found = _shell_symlink_alias(value, self.cwd) + if found is not None: + return found + elif isinstance(value, (list, tuple)): + for item in value: + if not isinstance(item, str): + continue + found = _shell_symlink_alias(item, self.cwd) + if found is not None: + return found + return None + def hits_hook_config_path(self, arguments: Mapping[str, object]) -> str | None: """Return the raw path if any argument targets a hook-discovery file.""" for raw in self._candidate_paths(arguments): @@ -565,6 +656,16 @@ def _evaluate( ), ) + # A shell word that is a link to a secret hides its target from the + # approval prompt: the operator reads ``video.mp4`` and the write lands + # on ``.env``. This is a named confirmation, not a deny -- the denylist + # above stays reserved for paths that are secret by their own name. + symlink_alias = ( + self.shell_symlink_alias(tool_name, arguments) + if self.protect_sensitive_paths + else None + ) + read_only = ( self.is_read_only(tool_name) if read_only_override is None @@ -595,6 +696,11 @@ def _evaluate( if rule.matches(tool_name, argument): matched = rule if matched is not None: + if matched.action is PermissionDecision.ALLOW and symlink_alias is not None: + return self._apply_approval_policy( + PermissionDecision.ASK, + self._alias_reason(symlink_alias), + ) if matched.action is PermissionDecision.ALLOW and hook_config is not None: return self._apply_approval_policy( PermissionDecision.ASK, @@ -625,6 +731,11 @@ def _evaluate( "exploration is permitted until the plan is approved.", ) if self.mode is PermissionMode.FULL_AUTO: + if symlink_alias is not None: + return self._apply_approval_policy( + PermissionDecision.ASK, + self._alias_reason(symlink_alias), + ) if hook_config is not None: return self._apply_approval_policy( PermissionDecision.ASK, @@ -641,6 +752,14 @@ def _evaluate( return self._mode_default_allow( tool_name, arguments, "default mode: read-only tool allowed" ) + # Ask mode is where the prompt is shown, so it is where a hidden + # target must be named: otherwise the operator approves "cp video.mp4" + # without ever seeing that the write lands on .env. + if symlink_alias is not None: + return self._apply_approval_policy( + PermissionDecision.ASK, + self._alias_reason(symlink_alias), + ) return self._apply_approval_policy( PermissionDecision.ASK, confirmation_reason(tool_name), @@ -667,6 +786,16 @@ def _mode_default_allow( feature. """ + if symlink_alias := ( + self.shell_symlink_alias(tool_name, arguments) + if self.protect_sensitive_paths + else None + ): + return self._apply_approval_policy( + PermissionDecision.ASK, + self._alias_reason(symlink_alias), + ) + if self.risk_evaluator is None: return PermissionDecision.ALLOW, reason @@ -678,6 +807,14 @@ def _mode_default_allow( f"risk evaluator flagged this call: {risk_reason}", ) + @staticmethod + def _alias_reason(symlink_alias: tuple[str, str]) -> str: + """Name both ends of the link: the visible word and the real target.""" + alias, target = symlink_alias + return ( + f"'{alias}' links to '{target}', a protected path; confirm before this runs" + ) + def _risk_opinion( self, tool_name: str, arguments: Mapping[str, object] ) -> str | None: diff --git a/tests/test_harness_permissions.py b/tests/test_harness_permissions.py index 06507e67..9f7365ba 100644 --- a/tests/test_harness_permissions.py +++ b/tests/test_harness_permissions.py @@ -509,3 +509,110 @@ def test_rule_reasons_name_the_users_rule(): PermissionDecision.DENY, "Blocked by your permission rule `bash rm *`.", ) + + +# ---- shell command paths must reach the sensitive-path check ---------------- +# +# An approval prompt shows the command text, so an innocent-looking symlink can +# hide the real target: the command touches the link, the kernel writes through +# it to a protected file. Key-based path extraction never looked inside a shell +# command string, so that shape was auto-allowed. + + +def _symlink_fixture(tmp_path): + """Create a protected credential file (victim) + ``video.mp4`` link (bait).""" + import os + + victim = tmp_path / ".env" + victim.write_text("SECRET=x", encoding="utf-8") + bait = tmp_path / "video.mp4" + try: + os.symlink(victim, bait) + except (OSError, NotImplementedError) as exc: # Windows without privilege + import pytest + + pytest.skip(f"cannot create symlink here: {exc}") + return victim, bait + + +def test_shell_symlink_alias_reports_the_hidden_target(tmp_path): + """Only an existing link with an innocent name counts as an alias.""" + import os + + from core.harness.permissions import _shell_symlink_alias + + victim, bait = _symlink_fixture(tmp_path) + found = _shell_symlink_alias(f"cp {bait.name} out/", str(tmp_path)) + assert found is not None, "a link to a protected file was not reported" + alias, target = found + assert alias == bait.name + assert os.path.realpath(target) == os.path.realpath(victim) + + +def test_key_only_extraction_never_saw_shell_paths(): + """Baseline of the hole: key-based extraction yields nothing.""" + from core.harness.permissions import _path_values + + assert list(_path_values({"command": "cp video.mp4 docs/"})) == [] + + +def test_copy_through_symlink_asks_and_names_the_target(tmp_path): + """The payload becomes a confirmation naming both ends, never a silent allow.""" + import os + + victim, bait = _symlink_fixture(tmp_path) + engine = PermissionEngine(mode=PermissionMode.FULL_AUTO, cwd=str(tmp_path)) + decision, reason = engine.evaluate("bash", {"command": f"cp {bait.name} out/"}) + assert decision is PermissionDecision.ASK, reason + assert bait.name in reason + assert os.path.basename(str(victim)) in reason + + # Ask mode is where the prompt is shown: the same command must name the + # target there too, not fall back to the generic "needs your approval". + ask_mode = PermissionEngine(mode=PermissionMode.DEFAULT, cwd=str(tmp_path)) + decision, reason = ask_mode.evaluate("bash", {"command": f"cp {bait.name} out/"}) + assert decision is PermissionDecision.ASK, reason + assert bait.name in reason + assert os.path.basename(str(victim)) in reason + + +def test_a_symlink_alias_asks_even_when_an_allow_rule_matches(tmp_path): + """An allow rule may not quietly wave the hidden target through.""" + _victim, bait = _symlink_fixture(tmp_path) + engine = PermissionEngine( + mode=PermissionMode.DEFAULT, + cwd=str(tmp_path), + rules=[PermissionRule("*", "*", PermissionDecision.ALLOW)], + ) + decision, reason = engine.evaluate("bash", {"command": f"cp {bait.name} out/"}) + assert decision is PermissionDecision.ASK, reason + assert "links to" in reason + + +def test_ordinary_shell_commands_still_ask(tmp_path): + """Everyday commands stay ask; naming a secret is not itself a denial.""" + engine = PermissionEngine(mode=PermissionMode.DEFAULT, cwd=str(tmp_path)) + for command in ( + "cp .env.example .env", + "source .env", + "docker compose --env-file .env up", + "echo PORT=3000 >> .env", + "git add .env.example", + "jq -r .key package.json", + "curl -O https://curl.se/ca/cacert.pem", + "openssl req -keyout key.pem -out cert.pem", + "uvicorn --ssl-keyfile key.pem", + "grep -n id_rsa README.md", + ): + decision, reason = engine.evaluate("bash", {"command": command}) + assert decision is PermissionDecision.ASK, f"{command!r}: {reason}" + + +def test_non_shell_tool_command_arg_is_not_scanned(tmp_path): + """Only shell tools get argv probing; an MCP ``command`` arg is untouched.""" + _victim, bait = _symlink_fixture(tmp_path) + engine = PermissionEngine(mode=PermissionMode.FULL_AUTO, cwd=str(tmp_path)) + arguments = {"command": f"cp {bait.name} out/"} + assert engine.shell_symlink_alias("mcp_custom", arguments) is None + # ...while the same argument on a shell tool is reported. + assert engine.shell_symlink_alias("bash", arguments) is not None