summaryrefslogtreecommitdiff
path: root/plugins
diff options
context:
space:
mode:
authorMohamed Hegazy <mhegazy@anthropic.com>2026-10-12 18:43:05 +0000
committerClaude <noreply@anthropic.com>2026-10-15 22:39:38 +0000
commit5ac3c91066c7ec7f36e84348316742f7dd12de6a (patch)
tree118a951ddf548f08dfb48568ac950a0b7ad54cc4 /plugins
parentf359d43b406057f1a8cdbc4ea93b827642c162e6 (diff)
security-guidance: never run a hook with a Python that cannot read it
On Windows, python/python3/py can be packaged launcher aliases (Microsoft Store Python, Python Install Manager). Started through the alias, the interpreter answers `-c` but has a different view of %APPDATA% and cannot see a plugin staged there. sg-python.sh picked it, CPython failed with "can't open file ... [Errno 2]" and exit code 2, and exit 2 from the asyncRewake Stop hook was delivered to the model as review findings. The model's reply ran the Stop hook again, so the session looped without ever reviewing anything (#6251, #5781). The launcher's probe now also checks that the interpreter can read the hook script. When no name on PATH qualifies, it tries the other python3/python entries on PATH by full path and the real executable each alias reports. If nothing can read the script it says so and exits 1, so a launch failure is never reported as findings.
Diffstat (limited to 'plugins')
-rwxr-xr-xplugins/security-guidance/hooks/sg-python.sh93
-rw-r--r--plugins/security-guidance/tests/test_launcher_unreadable_script.py162
2 files changed, 251 insertions, 4 deletions
diff --git a/plugins/security-guidance/hooks/sg-python.sh b/plugins/security-guidance/hooks/sg-python.sh
index 9cf8cc07..4dee3106 100755
--- a/plugins/security-guidance/hooks/sg-python.sh
+++ b/plugins/security-guidance/hooks/sg-python.sh
@@ -56,10 +56,36 @@ if command -v cygpath >/dev/null 2>&1; then
set -- "${converted[@]}"
fi
+# The hook script the chosen interpreter has to run (already in native form).
+SG_TARGET=""
+case "${1:-}" in
+ ""|-*) ;;
+ *) SG_TARGET="$1" ;;
+esac
+
+# Names whose interpreter runs but cannot see the hook script ("|"-separated).
+sg_unreadable=""
+
probe() {
# $1..N: the interpreter command (may be multi-word like `py -3`)
- # Writes "<major>.<minor>" to stdout and exits 0 iff at least Python 3.
- "$@" -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")' 2>/dev/null
+ # Writes "<major>.<minor>" to stdout and exits 0 iff it is at least
+ # Python 3 AND it can read the hook script; exits 3 if it cannot.
+ #
+ # The second half matters on Windows: an interpreter started through a
+ # packaged launcher alias (Microsoft Store Python, Python Install Manager;
+ # the python/python3/py entries under ...\Microsoft\WindowsApps) runs with
+ # a different view of %APPDATA% than the process that started it. It
+ # answers `-c` fine, then fails on the script with "can't open file ...
+ # [Errno 2]" and exit code 2 -- and exit 2 from an asyncRewake hook wakes
+ # the model, whose reply runs the Stop hook again: an endless loop that
+ # never reviewed anything. See #6251, #5781.
+ "$@" -c 'import os, sys; t = (sys.argv[1:] or [""])[0]; sys.exit(3) if t and not (os.path.isfile(t) and os.access(t, os.R_OK)) else print(f"{sys.version_info[0]}.{sys.version_info[1]}")' "$SG_TARGET" 2>/dev/null
+}
+
+# Use as `v=$(probe ...) || { note_unreadable "<name>"; continue; }`.
+note_unreadable() {
+ [ $? -eq 3 ] && sg_unreadable="$sg_unreadable|$1|"
+ return 0
}
# True iff arg is a "M.m" version string >= 3.10. claude_agent_sdk requires
@@ -80,7 +106,7 @@ is_sdk_compatible() {
# so picking one here always upgrades over the system `python3`. Highest
# available wins; the user doesn't have to PATH-prefer it.
for cmd in "python3.13" "python3.12" "python3.11" "python3.10"; do
- v=$(probe "$cmd") || continue
+ v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
if is_sdk_compatible "$v"; then
exec "$cmd" "$@"
fi
@@ -91,7 +117,7 @@ done
# `py -3` resolves to the user's python.org install.
for cmd in "python3" "python" "py -3"; do
# shellcheck disable=SC2086
- v=$(probe $cmd) || continue
+ v=$(probe $cmd) || { note_unreadable "$cmd"; continue; }
if is_sdk_compatible "$v"; then
# shellcheck disable=SC2086
exec $cmd "$@"
@@ -104,6 +130,7 @@ done
# inside the Python code. Without this fallback, the entire plugin would
# stop working on default macOS, which is a regression vs today.
for cmd in "python3" "python" "py -3"; do
+ case "$sg_unreadable" in *"|$cmd|"*) continue ;; esac
# shellcheck disable=SC2086
v=$(probe $cmd) || continue
# Accept anything that successfully reported a "M.m" string.
@@ -115,6 +142,64 @@ for cmd in "python3" "python" "py -3"; do
esac
done
+# Pass 4 — nothing above could run the hook script. If that is because the
+# names on PATH resolve to packaged launcher aliases that cannot see the
+# plugin directory (see probe), the same interpreter usually works when it is
+# started by its real path instead of through the alias. Candidates:
+# - every further python3/python on PATH, by full path (a regular install
+# often sits behind the alias in PATH order; the first match is the one
+# the bare name resolved to above),
+# - the real executable each alias reports as sys.executable.
+# The list is built before the loop that execs, and from a here-document: a
+# redirect around that loop would become the hook's stdin.
+sg_candidates=()
+for name in "python3" "python"; do
+ first=1
+ while IFS= read -r c; do
+ if [ -n "$first" ]; then first=""; continue; fi
+ [ -n "$c" ] && sg_candidates+=("$c")
+ done <<EOF
+$(type -ap "$name" 2>/dev/null)
+EOF
+done
+for cmd in "python3" "python" "py -3"; do
+ case "$sg_unreadable" in *"|$cmd|"*) ;; *) continue ;; esac
+ # shellcheck disable=SC2086
+ c=$($cmd -c 'import sys; print(sys.executable)' 2>/dev/null) || continue
+ c=${c%$'\r'} # native Windows Python prints CRLF
+ [ -n "$c" ] || continue
+ if command -v cygpath >/dev/null 2>&1; then
+ c=$(cygpath -u "$c" 2>/dev/null) || continue
+ fi
+ sg_candidates+=("$c")
+done
+sg_fallback=""
+sg_tried="|"
+for cmd in "${sg_candidates[@]}"; do
+ case "$sg_tried" in *"|$cmd|"*) continue ;; esac
+ sg_tried="$sg_tried$cmd|"
+ v=$(probe "$cmd") || { note_unreadable "$cmd"; continue; }
+ v=${v%$'\r'}
+ if is_sdk_compatible "$v"; then
+ exec "$cmd" "$@"
+ fi
+ case "$v" in
+ [0-9]*.[0-9]*) [ -n "$sg_fallback" ] || sg_fallback="$cmd" ;;
+ esac
+done
+if [ -n "$sg_fallback" ]; then
+ exec "$sg_fallback" "$@"
+fi
+
+# Exit 1, never 2: on an asyncRewake hook exit 2 means "the review has
+# findings, wake the model", and a launcher failure is not a finding.
+if [ -n "$sg_unreadable" ]; then
+ echo "security-guidance: found Python, but it cannot read the hook script (missing, or not visible to Python), so no security checks ran." >&2
+ echo " hook script: $SG_TARGET" >&2
+ echo " on Windows this happens when python, python3 and py are Microsoft Store or Python Install Manager aliases;" >&2
+ echo " install Python from https://python.org and put it ahead of ...\\Microsoft\\WindowsApps in PATH" >&2
+ exit 1
+fi
echo "security-guidance: no working Python 3 interpreter found." >&2
echo " tried: python3.13, python3.12, python3.11, python3.10, python3, python, py -3" >&2
echo " on Windows, install Python from https://python.org (NOT the Microsoft Store)" >&2
diff --git a/plugins/security-guidance/tests/test_launcher_unreadable_script.py b/plugins/security-guidance/tests/test_launcher_unreadable_script.py
new file mode 100644
index 00000000..e3780404
--- /dev/null
+++ b/plugins/security-guidance/tests/test_launcher_unreadable_script.py
@@ -0,0 +1,162 @@
+"""sg-python.sh never hands the hook script to an interpreter that cannot see it.
+
+On Windows, python/python3/py can be packaged launcher aliases whose
+interpreter answers `-c` but has no view of the plugin directory. Running the
+hook with one fails with CPython's "can't open file" and exit code 2, which an
+asyncRewake hook reports to the model as review findings, on every Stop.
+
+The aliases are emulated with shell wrappers around the real interpreter, so
+these tests need a POSIX shell.
+"""
+import json
+import os
+import shutil
+import subprocess
+import sys
+
+import pytest
+
+from conftest import HOOKS_DIR
+
+pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="POSIX shell wrappers")
+
+SHIM = HOOKS_DIR / "sg-python.sh"
+BASH = shutil.which("bash") or "/bin/bash"
+REAL = os.path.realpath(sys.executable)
+
+# Echoes its stdin and exits 2, like a hook that has findings to report.
+HOOK = "import sys\nsys.stderr.write('ran:' + sys.stdin.read())\nsys.exit(2)\n"
+
+ALIAS = """#!{bash}
+# A packaged alias: `-c` works, files under HIDE are invisible.
+HIDE='{hide}'; REAL='{real}'
+if [ "${{1:-}}" = "-c" ]; then
+ code="$2"; shift 2
+ out=$("$REAL" -c "import os as _o, sys as _s
+_f = _o.path.isfile
+_o.path.isfile = lambda p, _f=_f: False if str(p).startswith('$HIDE') else _f(p)
+if '{sealed}': _s.executable = '$0'
+$code" "$@"); rc=$?
+ [ -n "$out" ] && printf '%s{eol}' "$out"
+ exit $rc
+fi
+case "${{1:-}}" in
+ "$HIDE"/*) echo "python: can't open file '$1': [Errno 2] No such file or directory" >&2; exit 2 ;;
+esac
+exec "$REAL" "$@"
+"""
+
+
+def _alias(bindir, name, hide, sealed=False, crlf=False):
+ bindir.mkdir(parents=True, exist_ok=True)
+ p = bindir / name
+ p.write_text(ALIAS.format(bash=BASH, hide=hide, real=REAL, sealed="1" if sealed else "",
+ eol="\\r\\n" if crlf else "\\n"))
+ p.chmod(0o755)
+
+
+def _run(path_dirs, script, payload='{"k": 1}'):
+ return subprocess.run(
+ [BASH, str(SHIM), str(script)], input=payload, capture_output=True, text=True, timeout=60,
+ env={"PATH": os.pathsep.join(str(d) for d in path_dirs), "HOME": os.environ.get("HOME", "/")},
+ )
+
+
+@pytest.fixture
+def plugin(tmp_path):
+ d = tmp_path / "plugin" / "hooks"
+ d.mkdir(parents=True)
+ (d / "hook.py").write_text(HOOK)
+ return d
+
+
+def test_alias_is_replaced_by_the_interpreter_it_reports(plugin, tmp_path):
+ for name in ("python3", "python"):
+ _alias(tmp_path / "alias", name, plugin)
+ r = _run([tmp_path / "alias"], plugin / "hook.py")
+ assert "can't open file" not in r.stderr
+ # The hook ran, read its payload, and its own exit code came through.
+ assert r.stderr == 'ran:{"k": 1}'
+ assert r.returncode == 2
+
+
+def test_regular_install_later_on_path_is_used(plugin, tmp_path):
+ _alias(tmp_path / "alias", "python3", plugin, sealed=True)
+ (tmp_path / "real").mkdir()
+ os.symlink(REAL, tmp_path / "real" / "python3")
+ r = _run([tmp_path / "alias", tmp_path / "real"], plugin / "hook.py")
+ assert r.stderr == 'ran:{"k": 1}'
+ assert r.returncode == 2
+
+
+def test_regular_install_under_another_name_is_used(plugin, tmp_path):
+ _alias(tmp_path / "alias", "python3", plugin, sealed=True)
+ (tmp_path / "real").mkdir()
+ os.symlink(REAL, tmp_path / "real" / "python")
+ r = _run([tmp_path / "alias", tmp_path / "real"], plugin / "hook.py")
+ assert r.stderr == 'ran:{"k": 1}'
+ assert r.returncode == 2
+
+
+def test_no_interpreter_can_see_the_script_is_not_reported_as_findings(plugin, tmp_path):
+ for name in ("python3", "python"):
+ _alias(tmp_path / "alias", name, plugin, sealed=True)
+ r = _run([tmp_path / "alias"], plugin / "hook.py")
+ assert r.returncode == 1
+ assert "can't open file" not in r.stderr
+ assert "cannot read the hook script" in r.stderr
+ assert str(plugin / "hook.py") in r.stderr
+
+
+def test_missing_script_is_not_reported_as_findings(plugin, tmp_path):
+ (tmp_path / "real").mkdir()
+ os.symlink(REAL, tmp_path / "real" / "python3")
+ r = _run([tmp_path / "real"], plugin / "gone.py")
+ assert r.returncode == 1
+ assert "can't open file" not in r.stderr
+
+
+def test_no_python_keeps_its_own_message(plugin, tmp_path):
+ (tmp_path / "empty").mkdir()
+ r = _run([tmp_path / "empty"], plugin / "hook.py")
+ assert r.returncode == 1
+ assert "no working Python 3 interpreter found" in r.stderr
+
+
+def test_unusable_python_keeps_the_no_interpreter_message(plugin, tmp_path):
+ # Runs, but is not Python 3: nothing says the script is unreadable.
+ d = tmp_path / "old"
+ d.mkdir()
+ (d / "python").write_text("#!%s\nexit 1\n" % BASH)
+ (d / "python").chmod(0o755)
+ r = _run([d], plugin / "hook.py")
+ assert r.returncode == 1
+ assert "no working Python 3 interpreter found" in r.stderr
+
+
+def test_alias_with_crlf_output_is_still_resolved(plugin, tmp_path):
+ # Native Windows Python prints CRLF; the reported path must survive that.
+ _alias(tmp_path / "alias", "python3", plugin, crlf=True)
+ r = _run([tmp_path / "alias"], plugin / "hook.py")
+ assert r.stderr == 'ran:{"k": 1}'
+ assert r.returncode == 2
+
+
+@pytest.mark.skipif(shutil.which("git") is None, reason="needs git")
+def test_real_hook_runs_through_an_alias_only_path(tmp_path):
+ for name in ("python3", "python"):
+ _alias(tmp_path / "alias", name, HOOKS_DIR)
+ payload = json.dumps({"hook_event_name": "UserPromptSubmit", "session_id": "launcher-test",
+ "cwd": str(tmp_path), "prompt": "hello"})
+ # git only: its directory usually holds a regular python3 as well.
+ git_dir = tmp_path / "git"
+ git_dir.mkdir()
+ os.symlink(shutil.which("git"), git_dir / "git")
+ r = subprocess.run(
+ [BASH, str(SHIM), str(HOOKS_DIR / "security_reminder_hook.py")],
+ input=payload, capture_output=True, text=True, timeout=120,
+ env={"PATH": os.pathsep.join([str(tmp_path / "alias"), str(git_dir)]), "HOME": str(tmp_path),
+ "SECURITY_GUIDANCE_DEBUG_LOG": str(tmp_path / "debug.log")},
+ )
+ assert r.returncode == 0, r.stderr
+ assert "hook_event=UserPromptSubmit" in (tmp_path / "debug.log").read_text()