claude-code-project-boundary
Claude Code plugin: scope-aware protection — allows destructive ops (rm, mv, chmod) within project, blocks them outside. Built for dangerouslySkipPermissions mode.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/justi--claude-code-project-boundary)HTML
<a href="/listings/justi--claude-code-project-boundary"><img src="/api/listings/justi--claude-code-project-boundary/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Direct:
claude --plugin-dir /path/to/claude-code-project-boundary
From marketplace:
/plugin marketplace add davepoon/buildwithclaude /plugin install project-boundary@buildwithclaude
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 14 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- {
- "name": "claude-code-project-boundary",
- "owner": {
- "name": "Justyna Wojtczak",
- "url": "https://github.com/justi"
- },
- "plugins": [
- {
- "name": "project-boundary",
- "source": ".",
- "description": "Blocks destructive commands outside the project directory. Allows file operations within the project (refactoring, cleanup) but prevents accidental damage outside it."
- }
- ]
- }
README.md · README · 152 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- # Project Boundary — Claude Code Plugin
- Allows destructive operations **within your project** but blocks them **outside** the project directory. Built for `--dangerously-skip-permissions` mode where Claude doesn't ask — this plugin is your safety net.
- ## How it differs from existing plugins
- - **[claude-code-safety-net](https://github.com/kenryu42/claude-code-safety-net)** — blocks `rm` everywhere; Project Boundary allows it inside the project so refactoring works normally.
- - **[destructive-command-guard](https://github.com/Dicklesworthstone/destructive_command_guard)** — only distinguishes `/tmp` vs everything else; Project Boundary uses `$CLAUDE_PROJECT_DIR` as the actual boundary.
- - **[claude-code-damage-control](https://github.com/disler/claude-code-damage-control)** — requires manually listing protected paths; Project Boundary automatically protects everything outside the project.
- ## What it does
- ### Boundary-checked (allowed inside project, blocked outside)
- | Operation | Inside project | Outside project |
- |-----------|---------------|-----------------|
- | `rm`, `rm -rf` | Allowed | **Blocked** |
- | `mv` (source and destination) | Allowed | **Blocked** |
- | `cp` (source and destination) | Allowed | **Blocked** |
- | `ln` (source and target) | Allowed | **Blocked** |
- | `chmod` / `chown` | Allowed | **Blocked** |
- | `>` / `>>` redirect | Allowed | **Blocked** |
- | `tee` / `tee -a` | Allowed | **Blocked** |
- | `curl -o` / `curl --output` | Allowed | **Blocked** |
- | `wget -O` / `wget --output-document` | Allowed | **Blocked** |
- | `find -delete` / `find -exec rm` | Allowed | **Blocked** |
- | `dd of=` | Allowed | **Blocked** |
- | `install` (source, destination, `--target-directory=`) | Allowed | **Blocked** |
- | `rsync` (source, destination, `--log-file=`, `--partial-dir=`, `--backup-dir=`, `--temp-dir=`, `--write-batch=`, `--only-write-batch=`) | Allowed | **Blocked** |
- | `tar -C` / `--directory=` | Allowed | **Blocked** |
- | `unzip -d` / `cpio -D` | Allowed | **Blocked** |
- | `7z -o<dir>` / `7z -w<dir>` (extract verbs only) | Allowed | **Blocked** |
- | **Edit** tool (file edits) | Allowed | **Blocked** |
- | **MultiEdit** tool (multi-file edits) | Allowed | **Blocked** |
- | **Write** tool (file creation) | Allowed | **Blocked** |
- ### Always blocked (unsafe to inspect)
- | Command | Reason |
- |---------|--------|
- | `bash -c "..."` / `sh -c "..."` | Nested shell — cannot inspect inner command |
- | `eval '...'` | Cannot safely parse evaluated code |
- | Piping to `sh` / `bash` | Inner commands invisible to guard |
- | `xargs rm/mv/cp/...` | Arguments cannot be validated |
- | `python -c` / `ruby -e` / `perl -e` / `node --eval` / `php -r/-R/--run` / `Rscript -e` / `osascript -e` | Inline interpreter code is opaque to the Bash parser |
- | `awk '... system("...") ...'` (and similar `\| "sh"`) | Awk programs can shell out without the guard seeing the inner command |
- | `env -S` / `env --split-string` / `env -C` / `env --chdir` | These either smuggle a real command inside a string or change the working directory before the inner tool runs |
- | `$(...)` / backticks (outside single quotes) | Command substitution target is uninspectable. Single-quoted forms like `'$(cmd)'` and arithmetic expansion `$((2+2))` are allowed. |
- | `$VAR` / `${VAR}` and positional / special parameters (`$1` … `$9`, `$@`, `$*`, `$#`, `$?`, `$$`, `$!`, `$-`) outside single quotes | Variable expansion target is uninspectable for the same reason as `$(...)`. Only `$HOME` / `${HOME}` is allowed (canonical home path). Use literal values inline, or reach for the `Read` / `Grep` tools instead of piping shell vars. ANSI-C `$'…'`, i18n `$"…"`, backslash-escaped `\$VAR`, single-quoted `'$VAR'`, and quoted-heredoc bodies are unaffected. |
- ### Additional protections
- - **Chained commands** — splits on `;`, `&&`, `||`, `|`, and unquoted newlines, then checks each sub-command independently
- - **`cwd` awareness** — uses `cwd` from the hook event, so commands run outside the project (without an explicit `cd`) are also guarded
- - **`cd` tracking** — `cd /tmp && rm -rf something` is blocked because `cd` left the project; `cd ~/your-repo && rm file` is allowed even if the event `cwd` was outside (`$PROJECT` and other non-`$HOME` variables are uninspectable, so use `~`/`$HOME` or a literal path)
- - **Destructive subcommands outside project** — when running outside the project (via event `cwd` or `cd`), these are blocked: `git clean -f`, `git checkout .`, `git restore .`, `git reset --hard`, `git push --force`, `git stash drop/clear`, `git branch -D`, `git reflog expire`, `rails db:drop/reset`, `rake db:drop/reset`. Safe commands like `git status`, `git log`, `rails routes` remain allowed.
- - **`sudo` prefix** — stripped before checking, so `sudo rm /etc/passwd` is still blocked
- - **`find` options** — handles `-L`, `-H`, `-P` before the search path
- - **Path traversal** — `..` segments are resolved before boundary check
- - **`~` and `$HOME` expansion** — `rm ~/file` and `rm $HOME/file` are correctly detected as outside-project
- - **Symlink resolution** — handles macOS `/var` → `/private/var`, dereferences symlink chains in Edit/Write/MultiEdit (fail-closed after 20 hops)
- - **`/dev/null` bit-bucket** — `curl -o /dev/null`, `2>/dev/null`, `tee /dev/null`, `dd of=/dev/null`, and all redirect target forms are allowed so routine probe and silencing workflows don't hit the boundary. Narrow exemption: the discard-only walkers short-circuit *before* `is_write_permitted`; `sed -i /dev/null`, `truncate /dev/null`, and `cp|mv|ln ... /dev/null` remain blocked because each performs a real filesystem write under `/dev/`.
- - **POSIX `--` end-of-options** — `install`, `rsync`, `sed -i`, and `truncate` continue parsing operands after a literal `--`, so `rsync … -- -outside/file` and similar dash-prefixed targets are validated rather than silently skipped as flags.
- - **Windows-native path tokens in COMMAND** — `tee C:\Windows\System32\…`, `rm C:/Users/x/.ssh/id_rsa`, redirects to drive-letter paths and UNC `\\server\share\…` are rewritten per-token via `cygpath -u` (MSYS2) before walkers run, then the boundary check rejects them. On non-MSYS2 shells Windows-shape tokens fail closed because they don't match the POSIX absolute-path pattern.
- - **`jq` behaviour canary** — the hook entry challenges `jq` with a randomised key/value JSON object on every invocation. A hostile shim that returns canned output (`jq() { echo ""; }`) cannot reproduce a per-call random value and the hook blocks, so the parser used to extract `tool_input` is provably real `jq`.
- - **NTFS reparse-point traversal** — junctions (`mklink /J`) and symbolic links (`mklink /D`) inside the project are followed to their physical target by `cd -P` (MSYS2 implements it via Win32 `SetCurrentDirectory`), so `project/escape -> C:\Windows` resolves to `/c/Windows` and writes through it are blocked. Regression-anchored on the Windows-smoke job.
- ### Path allowlist (`hooks/allowlist.conf`)
- Some paths legitimately live outside every project — e.g. Claude Code's auto-memory under `~/.claude/projects/<slug>/memory/`, which needs to persist across projects by design. The allowlist file lets you permit writes to those paths without loosening the project boundary for everything else.
- **Scope:** the allowlist is a **WRITE exception only**. It applies to the gentle write paths — `Edit` / `Write` / `MultiEdit`, redirects (`>` / `>>`), `tee`, `curl -o`, `wget -O`, `dd of=`, and similar — and to `cd` into an allowlisted directory. It deliberately does **not** apply to destructive or move/copy operations (`rm`, `mv`, `cp`, `ln`, `chmod`, `chown`, `find -delete`, `find -exec rm`, `install`, `rsync`, `tar -C`, `unzip -d`, `cpio -D`) or to script execution and shell redirection from outside paths. An allowlist entry that grants WRITE to `~/.claude/projects/*/memory/**` will **not** let `rm` or `rsync` run against that path.
- **Format:** one glob pattern per line; `#` starts a comment; `~` expands to `$HOME`; `**` matches across path segments (bash globstar), `*` within a single segment.
- **Defaults shipped with the plugin:**
- - `~/.claude/projects/*/memory/**` — Claude Code auto-memory
- > [!WARNING]
- > **Do not mass-add entries to the allowlist.** Every entry is an escape hatch from the boundary, and Claude is creative enough to find non-obvious workarounds through allowed paths — for example: symlink-chasing from an allowlisted dir into sensitive files, writing executable content that some other tool later `source`s, or staging payloads in an allowed dir before moving them elsewhere. Widening the allowlist to something like `~/.claude/**` would let Claude overwrite `settings.json` or your shell rc files. Keep entries narrow, purpose-specific, and comment each one with the reason it exists. Prefer asking Claude for explicit per-write permission over adding entries.
- ### Known limitations
- - Paths with spaces work when properly quoted (single or double quotes). Unquoted paths with spaces are not supported.
- - Brace expansion (`{a,b,c}`) is not enumerated — literal match only
- - `~user/` (home of another user) is not expanded; only `~/` (current user) is handled
- ### Multiline git commits (`$(cat <<EOF)` is blocked)
- The common idiom `git commit -m "$(cat <<'EOF' … EOF)"` is **blocked on purpose** — command substitution `$(…)` is fail-closed because the inner command is not inspectable in the general case (`$(cat && rm /etc/passwd)` looks identical to the parser). Making an exception for one shape of `cat` would just open a new bypass category.
- The supported pattern is heredoc on stdin:
- ```bash
- git commit -F - <<'EOF'
- Subject line
- Body paragraph.
- EOF
- ```
- Repeated `-m` works for shorter messages where every paragraph fits on one line:
- ```bash
- git commit -m "Subject line" -m "Body paragraph."
- ```
- Avoid: writing the message to `.git/COMMIT_*` files (triggers a Write-tool prompt) or to `/tmp/*_msg.txt` (outside-project, blocked). The `SessionStart` hook ships a one-line hint that points Claude at the heredoc form on the first try, so no manual nudging is needed.
- ## Requirements
- `bash` and `jq` must be on the PATH of the hook shell. macOS and most Linux distros ship bash; `jq` is usually present but install it explicitly if missing — without `jq` the hook fails closed with a clear `BLOCKED: 'jq' is required ...` message.
- | Platform | Install |
- |---|---|
- | macOS | `brew install jq` |
- | Debian/Ubuntu | `apt install jq` |
- | Fedora/RHEL | `dnf install jq` |
- | Arch | `pacman -S jq` |
- | Windows (MSYS2) | `pacman -S jq` |
- | Windows (Scoop/Winget) | `scoop install jq` or `winget install jqlang.jq` |
- On Windows the plugin runs under MSYS2 bash; `cygpath` (shipped with MSYS2) is required for Windows-native paths (`C:\…`, `\\server\…`) to be normalized — without it those paths fail closed.
- ## Install
- Direct:
- ```
- claude --plugin-dir /path/to/claude-code-project-boundary
- ```
- From marketplace:
- ```
- /plugin marketplace add davepoon/buildwithclaude
- /plugin install project-boundary@buildwithclaude
- ```
- ## How it works
- Pure-bash PreToolUse hooks for Bash, Edit, MultiEdit, and Write tools. The Bash hook splits chained commands and resolves target paths (handling symlinks, `..`, `~`, `$HOME`); the Edit, MultiEdit, and Write hooks perform file path boundary checks against `$CLAUDE_PROJECT_DIR`. Dependencies: bash + jq.
- ## Testing
- ```
- bash tests/test_guard.sh
- ```
- Full test suite covering all guard scenarios. CI runs on Ubuntu, macOS, and Windows (MSYS2 smoke job — minimal end-to-end coverage of Windows-native path handling and the NTFS reparse-point regression anchor).
- ## License
- MIT
hooks/lib/remote_dispatch.sh · Bundled script · 316 lines · 2 findings marked
- #!/bin/bash
- # project-boundary guard — remote_dispatch module
- # ================================================
- # Generic neutralisation of "remote-dispatch" commands whose operands
- # target a remote host or a foreign (container/namespace) filesystem
- # rather than the local one this guard protects. Without this pass,
- # tokens that are part of a remote command string get walked by the
- # local-path detectors (cp, tee, rm, redirect, ...) and produce
- # false-positive boundary blocks.
- #
- # Three universal shapes are recognised, all rewritten so downstream
- # detectors only see the local-side surface (or nothing, when there
- # is no local surface):
- #
- # 1. Network-copy tools — operate on a remote target but may also
- # take local operands and -flag values. The point of this class
- # is that the remote `host:/path` / `host::module` / `rsync://`
- # operands must NOT be walked as local filesystem paths;
- # legitimate local operands (`scp ./key host:/dst` etc.) are
- # reads from the plugin's perspective and the boundary doesn't
- # police those.
- # scp / rcp / sftp
- # Rewrite: collapse CMD to the bare verb name.
- #
- # 2. Remote-command dispatch — `<verb> [opts] <target> <opaque-cmd>`,
- # where the target is a host / container / pod and the trailing
- # tokens form a command executed on a foreign filesystem (NOT
- # the local one this guard protects):
- # ssh
- # docker exec | podman exec
- # kubectl exec | oc exec | crictl exec | lxc exec
- # Rewrite: collapse CMD to the verb prefix only.
- #
- # `nsenter` and `chroot` are deliberately EXCLUDED — they
- # execute on the local host (just under a different namespace
- # or apparent root), so their command operands can still touch
- # host paths outside the project and must remain subject to the
- # destructive walkers (Copilot review on PR #22).
- #
- # `docker run` / `podman run` / `buildah run` are also EXCLUDED
- # because the `-v src:dst` / `--volume` / `--mount type=bind,…`
- # flags can bind-mount host paths into the container, turning a
- # container-side write into a host-fs write that bypasses the
- # boundary. Until host-mount-source parsing is added, leaving
- # them subject to the existing walkers errs on the safe side
- # (Copilot review on PR #22).
- #
- # 3. Remote file copy with mixed local / remote operands —
- # `<verb> <subverb> <a> <b>` where one operand has the form
- # `<id>:<path>` and the other is local.
- # docker cp | podman cp | kubectl cp | oc cp
- # Rewrite: keep only the LOCAL DESTINATION operand (last
- # positional, when not remote-shaped) so the cp walker still
- # validates download targets like `… c:/x /etc/owned`. Source
- # operands are dropped — local source = read (not policed),
- # remote source = foreign filesystem.
- #
- # Depends on tokenize_args / strip_quotes from hooks/lib/tokenize.sh.
- # Pure (no caller-scope dependencies); returns the rewritten command
- # string on stdout.
- # --- Generic remote-target detector ---
- # Returns 0 iff the argument looks like a "remote address" of the
- # universal `<id>:<path>` form used by ssh, scp, rsync, docker cp,
- # kubectl cp, etc. The `:` must live in the FIRST path segment
- # (before any `/`) — a local path may legitimately contain `:` after a
- # slash (e.g. `../tmp/a:b`), and a URL like `http://...` keeps the
- # scheme separator inside the first segment but is excluded by an
- # explicit URL check first.
- _rd_is_remote_target_operand() {
- local arg="$1"
- case "$arg" in
- *://*) return 1 ;; # URL scheme
- esac
- local first="${arg%%/*}"
- case "$first" in
- *:*) return 0 ;;
- esac
- return 1
- }
- # --- Find command-name token index, skipping wrappers/flags/VAR=val ---
- # Mirrors the wrapper-skip rules used by strip_command_name_prefix and
- # command_name_is. Reads from the module-local _RD_TOKS array (set by
- # rewrite_remote_dispatch before calling). Returns -1 if no command-name
- # found. Uses a global rather than `local -n` because macOS ships
- # bash 3.2 which lacks nameref support.
- #
- # Also skips a per-wrapper option-with-value pair (e.g. `-u USER` for
- # sudo/env, `-k DUR` for timeout) when the value would otherwise be
- # mis-identified as the verb. Without this, `env -u FOO docker exec
- # ctr rm -rf /` mis-identified `FOO` as the verb (verb_pair="FOO
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 92 on GitHub
- # docker"), `rewrite_remote_dispatch` returned the cmd unchanged, and
- # the bare rm walker over-blocked the foreign-fs `rm -rf /` (which
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 94 on GitHub
- # actually runs inside the container, not on host). Same root cause
- # as section 40 (subcmd_flags.sh) and section 41 (command_name.sh);
- # Codex round-4 follow-up on PR #23.
- _rd_find_verb_idx() {
- local i=0 n=${#_RD_TOKS[@]}
- local prev_was_timeout=0 last_wrapper=""
- while [ $i -lt $n ]; do
- local raw="${_RD_TOKS[$i]}" t
- t=$(strip_quotes "$raw")
- if [ -n "$last_wrapper" ]; then
- local opts; opts=$(_wrapper_opts_with_val "$last_wrapper")
- if [ -n "$opts" ]; then
- case " $opts " in
- *" $t "*) i=$((i + 2)); continue ;;
- esac
- fi
- fi
- if [ $prev_was_timeout -eq 1 ]; then
- prev_was_timeout=0
- case "$t" in
- [0-9]*|inf*) i=$((i + 1)); continue ;;
- esac
- fi
- case "$t" in
- timeout)
- prev_was_timeout=1; last_wrapper="timeout"; i=$((i + 1)); continue ;;
- sudo|env|/bin/env|/usr/bin/env|nice|nohup|time|stdbuf|ionice|chrt|taskset|command|builtin|exec)
- last_wrapper=$(_rd_strip_path_prefix "$t")
- i=$((i + 1)); continue ;;
- esac
- case "$t" in
- [A-Za-z_]*=*) i=$((i + 1)); continue ;;
- -*) i=$((i + 1)); continue ;;
- esac
- printf '%d' "$i"
- return
- done
- printf -- '-1'
- }
- # --- Strip /bin/, /sbin/, /usr/bin/, /usr/sbin/, /usr/local/bin/, ---
- # /opt/homebrew/bin/ prefix. Mirrors _cn_strip_path_prefix in
- # command_name.sh — kept in sync so a Homebrew-installed ssh /
- # kubectl / etc. is recognised by the remote-dispatch walkers.
- _rd_strip_path_prefix() {
- local n="$1"
- case "$n" in
- /bin/*|/sbin/*|/usr/bin/*|/usr/sbin/*|/usr/local/bin/*|/opt/homebrew/bin/*) printf '%s' "${n##*/}" ;;
- *) printf '%s' "$n" ;;
- esac
- }
- # --- Whitespace-list membership check ---
- # $1 = needle, $2 = space-separated haystack. Used to decide whether a
- # given short or long flag consumes the next token as its value.
- _rd_flag_takes_value() {
- local needle="$1"
- local short_list="$2"
- local long_list="$3"
- case " $short_list " in *" $needle "*) return 0 ;; esac
- case " $long_list " in *" $needle "*) return 0 ;; esac
- return 1
- }
- # --- Main entry: rewrite remote-dispatch commands ---
- # In: full CMD string
- # Out: CMD string with remote portions removed; unchanged for non-dispatch verbs.
- rewrite_remote_dispatch() {
- local cmd="$1"
- _RD_TOKS=()
- local t
- while IFS= read -r t; do
- [[ -z "$t" ]] && continue
- _RD_TOKS+=("$t")
- done < <(tokenize_args "$cmd")
- local verb_idx
- verb_idx=$(_rd_find_verb_idx)
- [ "$verb_idx" -lt 0 ] && { printf '%s' "$cmd"; return; }
- local verb subverb=""
- verb=$(strip_quotes "${_RD_TOKS[$verb_idx]}")
- verb=$(_rd_strip_path_prefix "$verb")
- if [ $((verb_idx + 1)) -lt ${#_RD_TOKS[@]} ]; then
- subverb=$(strip_quotes "${_RD_TOKS[$((verb_idx + 1))]}")
- fi
- # Class 1: pure remote-fs tools.
- case "$verb" in
- scp|rcp|sftp)
- printf '%s' "$verb"
- return ;;
- esac
- # Class 3: two-word remote copy verbs.
- case "$verb $subverb" in
- "docker cp"|"podman cp"|"kubectl cp"|"oc cp")
- _rd_rewrite_remote_copy "$verb_idx"
- return ;;
- esac
- # Class 2: two-word remote-command dispatch verbs. `docker run` /
- # `podman run` / `buildah run` are intentionally NOT in this list —
- # see the header comment for the bind-mount rationale.
- case "$verb $subverb" in
- "docker exec"|"podman exec"|"kubectl exec"|"oc exec"|"crictl exec"|"lxc exec")
- printf '%s %s' "$verb" "$subverb"
- return ;;
- esac
- # Class 2: one-word remote-command dispatch verbs. `nsenter` and
- # `chroot` are intentionally NOT in this list — see the header
- # comment for why they remain subject to the local walkers.
- case "$verb" in
- ssh)
- printf '%s' "$verb"
- return ;;
- esac
- printf '%s' "$cmd"
- }
- # --- Rewrite a `<verb> <subverb> <operand-a> <operand-b>` copy invocation ---
- # Keep the verb pair plus operands that are NOT remote `<id>:<path>` form.
- # Flags are dropped (they cannot be local file targets in any of the
- # supported `cp` subcommands; -L, --follow-link, --archive etc. are
- # value-less or take non-path values).
- _rd_rewrite_remote_copy() {
- local v_idx="$1"
- local verb_pair="${_RD_TOKS[$v_idx]} ${_RD_TOKS[$((v_idx + 1))]}"
- local k=$((v_idx + 2)) n=${#_RD_TOKS[@]}
- # Per-verb flags-that-consume-the-next-token list. Necessary because
- # Copilot review on PR #22 flagged a download-mode bypass shape:
- # `kubectl cp pod:/x /etc/owned --namespace default`
- # without this table, `default` (the value of `--namespace`) gets
- # added to the positionals list, becomes the LAST positional, and
- # the rewrite emits `cp default` — relative path resolved inside
- # the project → ALLOWED, missing the real download destination
- # `/etc/owned`. cobra/pflag (used by kubectl/oc) lets flags appear
- # before AND after positionals, so we can't just stop after the
- # first non-flag token.
- #
- # docker cp / podman cp share a small flag set with no value-taking
- # flags relevant to the path-walker bypass (`-a/--archive`,
- # `-L/--follow-link`, `--quiet`, `--pause`, `--extract` are all
- # value-less); their entries are deliberately empty. kubectl cp /
- # oc cp inherit the entire kubectl global flag set — only the ones
- # that take a value AND can credibly appear next to a path are
- # listed here (kubeconfig/cluster paths can be local files but the
- # plugin does not police reads, so we drop their values without
- # validation).
- local short_value_flags="" long_value_flags=""
- case "$verb_pair" in
- "kubectl cp"|"oc cp")
- short_value_flags="-c -n -s"
- long_value_flags="--container --namespace --kubeconfig --context --cluster --user --token --server --as --as-group --certificate-authority --client-certificate --client-key --cache-dir --request-timeout --tls-server-name --retries"
- ;;
- esac
- # Walk positional operands. cp-family semantics: the LAST positional
- # is the destination; every earlier positional is a source. The
- # plugin protects writes, not reads — so a local SOURCE is dropped
- # (uploading `docker cp /tmp/x container:/y` is read-only on /tmp/x
- # and must not false-positive). A local DESTINATION is preserved
- # below as the operand of a synthetic `cp <dst>` so the existing
- # cp walker validates it. This is a deliberate divergence from the
- # bare `cp` walker (which strict-checks both src and dst) — the
- # remote-dispatch case has a remote operand on the OTHER side, so
- # the boundary's "no copies from outside" semantics do not apply
- # symmetrically here. Operands of the universal `<id>:<path>` form
- # are dropped because they target a foreign filesystem.
- local -a positionals=()
- while [ $k -lt $n ]; do
- local raw="${_RD_TOKS[$k]}" tok
- tok=$(strip_quotes "$raw")
- case "$tok" in
- --)
- # POSIX end-of-options: every later token is a positional,
- # even if it begins with `-`. Used by kubectl exec but also
- # valid for cp invocations.
- k=$((k + 1))
- while [ $k -lt $n ]; do
- positionals+=("${_RD_TOKS[$k]}")
- k=$((k + 1))
- done
- continue ;;
- --*=*)
- k=$((k + 1)); continue ;;
- -*)
- if _rd_flag_takes_value "$tok" "$short_value_flags" "$long_value_flags"; then
- k=$((k + 2))
- else
- k=$((k + 1))
- fi
- continue ;;
- esac
- positionals+=("$raw")
- k=$((k + 1))
- done
- local last_idx=$(( ${#positionals[@]} - 1 ))
- if [ $last_idx -lt 0 ]; then
- printf '%s' "$verb_pair"
- return
- fi
- local last_raw="${positionals[$last_idx]}"
- local last_tok
- last_tok=$(strip_quotes "$last_raw")
- if _rd_is_remote_target_operand "$last_tok"; then
- # Destination is remote → no local write surface. Collapse to verb pair
- # so no walker fires on the local source(s).
- printf '%s %s' "${_RD_TOKS[$v_idx]}" "${_RD_TOKS[$((v_idx + 1))]}"
- return
- fi
- # Destination is local. Emit a synthetic `cp <dst>` so the cp walker
- # in destructive.sh validates that single path. Source operands are
- # dropped: remote ones are foreign, local ones are reads (not policed).
- printf 'cp %s' "$last_raw"
- }
hooks/lib/shell_exec_walkers.sh · Bundled script · 445 lines · 4 findings marked
- # shellcheck shell=bash
- # project-boundary guard — shell / interpreter execution walkers
- # ===============================================================
- # Extracted from hooks/guard.sh check_single_command. All five
- # walkers fail-closed on un-inspectable code execution surfaces:
- #
- # block_nested_shell_and_eval
- # `bash -c CMD`, `sh -c CMD`, `zsh -c CMD`, ..., `eval CMD`.
- #
- # block_interpreter_inline_code
- # `python -c`, `perl -e`, `ruby -e`, `node -e`, `php -r`,
- # `awk 'BEGIN{system(...)}'`, etc.
- #
- # block_pipe_to_shell
- # Bare `sh`/`bash`/... or shell with only flags (e.g. `bash -s`)
- # — typical `echo "rm -rf /" | sh` shape.
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 16 on GitHub
- #
- # block_shell_script_execution
- # Path-form: `bash /tmp/x.sh`, `source ~/x.sh`, `. /tmp/x.sh`.
- # STRICT project-root (allowlist must NOT grant execute).
- # Uses tokenize-with-redirects + heredoc-blanked parallel
- # stream + symlink dereference.
- #
- # All read CMD / CMD_BLANKED / EFFECTIVE_CWD / PROJECT_DIR from
- # caller's dynamic scope. Helpers (strip_quotes, expand_path,
- # resolve_path, tokenize_args, blank_quoted_heredoc_bodies,
- # is_shell_token, is_source_token) come from sibling modules.
- # Each calls `exit 2` on a boundary violation.
- block_nested_shell_and_eval() {
- # Match: bash -c, sh -c, bash -lc, bash -ec, /bin/bash -c, /bin/sh -c, /usr/bin/env bash -c
- # Also zsh / ksh / dash / fish / xonsh / tcsh / csh / nu / pwsh / osh
- # (macOS ships zsh by default; all accept -c CMD with un-inspectable semantics).
- #
- # VERB-GATE: substring matching alone false-positives on text-as-arg
- # cases (`echo "use bash -c here" > docs/fp.md`, `git commit -m
- # "explain eval risk"`). Gate every check on CMD_VERB so the
- # substring walker only fires when the verb itself is a shell
- # opener, an interpreter wrapper that resolves to one (env / sudo /
- # nice / ... already collapsed by _cn_find_verb_idx — CMD_VERB is
- # the post-wrapper name), or a remote-dispatch verb where the
- # asymmetry pin (294b64d / 7b65a45) intentionally over-blocks
- # inline-shell payloads.
- #
- # INTENTIONAL ORDERING: this walker still runs BEFORE
- # rewrite_remote_dispatch. That is what keeps `docker exec ctr sh
- # -c '...'`, `kubectl exec pod -- bash -c '...'`, `ssh host bash -c
- # '...'` blocked: CMD_VERB at this point is still `docker` /
- # `kubectl` / `ssh`, not yet rewritten away. Deferring the check to
- # AFTER remote-dispatch neutralisation would make the boundary
- # easier to abuse via payloads hidden in pseudo-remote arguments
- # (e.g. an alias that resolves `docker` to a local script but still
- # parses as `docker exec ...`). Path-operand forms (`docker exec
- # ctr rm /etc/x`) remain ALLOWED via rewrite_remote_dispatch —
- # CMD_VERB falls in the `*` branch and the walker returns. See the
- # asymmetry tests in test_true_negatives_b.sh near the docker exec
- # block.
- case "${CMD_VERB-}" in
- bash|sh|zsh|ksh|dash|fish|xonsh|tcsh|csh|nu|pwsh|osh)
- ;; # real shell opener — fall through to the substring check
- docker|podman|kubectl|oc|crictl|lxc|ssh)
- ;; # remote-dispatch verb — asymmetry pin: inline shell payload BLOCK
- eval)
- echo "BLOCKED: 'eval' cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2 ;;
- *)
- return ;; # text-as-arg / unrelated verb — substring is content, not exec
- esac
- if echo "$CMD" | grep -qE '(^|[[:space:]])(/usr/bin/env[[:space:]]+)?(/bin/)?(bash|sh|zsh|ksh|dash|fish|xonsh|tcsh|csh|nu|pwsh|osh)[[:space:]]+-[a-zA-Z]*c[[:space:]]'; then
- echo "BLOCKED: Nested shell execution ('bash -c' / 'sh -c' / 'zsh -c' / ...) cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi
- if echo "$CMD" | grep -qE '(^|[[:space:]])eval[[:space:]]'; then
- echo "BLOCKED: 'eval' cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi
- }
- # --- trap CMD SIG: deferred shell handler (round-4 pentest) ---
- # `trap CMD SIG` registers CMD as a shell handler that fires on the
- # named signal (EXIT, INT, TERM, ...). CMD is arbitrary shell code
- # stored on argv and executed later — same un-inspectable semantics
- # as `bash -c CMD` and `eval`. Read-only forms have no deferred CMD
- # and stay ALLOWED:
- # trap (list current traps)
- # trap -l (list signal names)
- # trap -p (print traps in re-input form)
- # trap - SIG (reset SIG to default — first positional `-`)
- # trap '' SIG (ignore SIG — first positional empty)
- # Lifted out of block_nested_shell_and_eval so the verb-gate on the
- # bash -c / eval substring checks does not also bypass this walker —
- # `trap` is its own verb and command_name_is gates correctly.
- block_trap_handler() {
- if ! command_name_is "trap"; then
- return
- fi
- local trap_i=1 trap_n=${#CMD_TOKENS_SCAN[@]}
- local trap_seen_dashdash=0
- local trap_readonly=0
- local trap_first_pos=""
- local trap_first_pos_set=0
- while [ $trap_i -lt $trap_n ]; do
- local trap_tok
- trap_tok=$(strip_quotes "${CMD_TOKENS_SCAN[$trap_i]}")
- if [ $trap_seen_dashdash -eq 0 ]; then
- case "$trap_tok" in
- --)
- trap_seen_dashdash=1; trap_i=$((trap_i + 1)); continue ;;
- -l|-p)
- # `-l` / `-p` make the entire call read-only regardless
- # of any signal-name args that may follow.
- trap_readonly=1; break ;;
- esac
- fi
- trap_first_pos="$trap_tok"
- trap_first_pos_set=1
- break
- done
- if [ "$trap_readonly" -eq 0 ] \
- && [ "$trap_first_pos_set" -eq 1 ] \
- && [ -n "$trap_first_pos" ] \
- && [ "$trap_first_pos" != "-" ]; then
- echo "BLOCKED: 'trap CMD SIG' deferred shell handler cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi
- }
- block_interpreter_inline_code() {
- # python/perl/ruby/node/php/osascript all accept code on argv. The inner
- # string cannot be inspected, so the same fail-closed rule as `bash -c`
- # applies. Flags covered: -c (python), -e (perl/ruby/node), --eval,
- # --execute, -E (perl alias). A dedicated rule catches `awk 'BEGIN{system(
- # "…")}'` and similar because awk programs are the first non-option arg,
- # not behind a flag — so we detect the `system(` marker in the CMD_BLANKED
- # view (heredoc bodies stripped) so a tee/cat heredoc whose body merely
- # mentions `python -c`, `awk … system(…)`, etc. is not false-positively
- # rejected.
- #
- # VERB-GATE: same reasoning as block_nested_shell_and_eval. Substring
- # walkers without a verb gate false-positive on text-as-arg cases
- # like `echo "avoid node -e examples" > docs/fp.md` and `git commit
- # -m "docs: avoid python -c examples"`. Each branch below now gates
- # on CMD_VERB so the substring check only fires when the verb itself
- # is the matching interpreter (post-wrapper, post-path-prefix). For
- # the awk family, `awk` / `gawk` / `mawk` / `nawk` all collapse to a
- # bare verb name via _cn_strip_path_prefix.
- case "${CMD_VERB-}" in
- python|python2|python3|perl|ruby|node|nodejs|deno|bun|osascript|Rscript)
- if echo "$CMD_BLANKED" | grep -qE '(^|[[:space:]])(python|python2|python3|perl|ruby|node|nodejs|deno|bun|osascript|Rscript)[[:space:]]+(-[a-zA-Z]*[ceE]|--eval|--execute)([[:space:]]|=|$)'; then
- echo "BLOCKED: Non-shell interpreter with inline code flag cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi ;;
- php)
- # Dedicated PHP rule — `-r`, `-R`, `--run` execute inline code.
- # Cannot be folded into the python/etc. regex because `-r` is a
- # module-preload flag in ruby/node (no code execution), so a
- # generic `r` letter would false-positive on `ruby -r json` /
- # `node -r dotenv`. The matcher accepts attached forms
- # (`-rcode`, `-Rcode`), quoted-attached (`-r'code'`), clustered-
- # ending (`-ar`, `-aR`), and the long alias `--run`.
- if echo "$CMD_BLANKED" | grep -qE '(^|[[:space:]])php[[:space:]]+(-[rR][^[:space:]=]*|-[a-zA-Z]*[rR]|--run)([[:space:]]|=|$|'\''|")'; then
- echo "BLOCKED: 'php -r/-R/--run' inline code cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi
- # php also accepts -c/--eval inline forms — same regex as the
- # python branch covers them.
- if echo "$CMD_BLANKED" | grep -qE '(^|[[:space:]])php[[:space:]]+(-[a-zA-Z]*[ceE]|--eval|--execute)([[:space:]]|=|$)'; then
- echo "BLOCKED: Non-shell interpreter with inline code flag cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi ;;
- awk|gawk|mawk|nawk)
- if echo "$CMD_BLANKED" | grep -qE 'system[[:space:]]*\(|\|[[:space:]]*&?[[:space:]]*"?(sh|bash)'; then
- echo "BLOCKED: awk program with 'system()' / shell pipe cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi ;;
- esac
- }
- block_pipe_to_shell() {
- # Match bare shell invocations: sh, bash, zsh, ksh, dash, fish,
- # /bin/sh, /bin/bash, ..., and with flags: sh -s, bash --login, etc.
- # But NOT: bash script.sh, bash -x script.sh (running a script file).
- if echo "$CMD" | grep -qE '^(/bin/)?(sh|bash|zsh|ksh|dash|fish)$'; then
- echo "BLOCKED: Piping to 'sh'/'bash'/'zsh'/'ksh'/'dash'/'fish' cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi
- # Match shell with only flags (no script file): sh -s, bash --login, sh -s -- args
- if echo "$CMD" | grep -qE '^(/bin/)?(sh|bash|zsh|ksh|dash|fish)[[:space:]]+-'; then
- local shell_args
- shell_args=$(echo "$CMD" | sed -E 's/^(\/bin\/)?(sh|bash|zsh|ksh|dash|fish)[[:space:]]+//')
- local has_script=0
- local shell_token
- for shell_token in $shell_args; do
- case "$shell_token" in
- --) break ;; # everything after -- is args to the script/stdin
- # Informational-only flags exit before reading stdin or
- # executing user code — `bash --version` / `sh --help` are
- # not pipe-to-shell targets even when they appear as a
- # standalone subcommand (issue #33).
- #
- # Codex sweep 4: `-V` is NOT safe across all shells —
- # zsh and dash treat `-V` as the version flag but still
- # read and execute stdin, so `curl URL | zsh -V` was a
- # real pipe-to-shell bypass. bash and ksh reject `-V`
- # as an unknown option (no stdin read), but the walker
- # can't distinguish per-shell here. Drop `-V` from the
- # whitelist entirely — only the long forms `--version`
- # and `--help` are safe across the guarded shell set.
- --version|--help)
- has_script=1; break ;;
- -*) continue ;;
- *) has_script=1; break ;;
- esac
- done
- if [[ $has_script -eq 0 ]]; then
- echo "BLOCKED: Piping to 'sh'/'bash' cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi
- fi
- }
- block_shell_script_execution() {
- # Catches: `bash /tmp/x.sh`, `sh ~/x.sh`, `zsh|ksh|dash|fish /tmp/x.sh`,
- # `source /tmp/x.sh`, `. /tmp/x.sh`. Inline-code forms (`bash -c ...`)
- # are caught by block_nested_shell_and_eval; this covers the
- # complementary case where the script is a path argument.
- #
- # STRICT project-root check (no allowlist). Allowlist grants WRITE to
- # specific paths (e.g. memory/); if execute inherited that, a write-
- # allowlisted dir would become an RCE escape hatch:
- # `echo 'rm -rf $HOME' > memory/x.sh && bash memory/x.sh`.
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 232 on GitHub
- # Walk CMD_TOKENS to locate the shell/source invocation, possibly buried
- # behind an `env [flags] [VAR=val]*` wrapper. Once found, scan for the
- # script-path operand — honoring flags that consume the next token
- # (-O / -o for bash set options). Finally, dereference symlinks on the
- # script path so a `project/link.sh -> /tmp/evil.sh` bait is caught.
- # Re-tokenize the command with redirect operators (< << <<< <<-) spaced
- # out so that attached forms like `bash</tmp/x.sh`, `bash<<EOF`, and
- # `bash<<<'rm -rf /'` don't slip past as single unsplit tokens.
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 240 on GitHub
- local _exec_cmd
- _exec_cmd=$(printf '%s' "$CMD" | sed -E 's/(<<-|<<<|<<|<)/ \1 /g')
- local -a CMD_TOKENS_EXEC=()
- local _etok
- while IFS= read -r _etok; do
- [[ -z "$_etok" ]] && continue
- CMD_TOKENS_EXEC+=("$_etok")
- done < <(tokenize_args "$_exec_cmd")
- # A parallel token stream built from a heredoc-blanked copy of CMD.
- # Used ONLY by the `_saw_redir`/`exec_kind` scans below, which otherwise
- # would treat a quoted-heredoc body byte like "bash" or "source" as a
- # shell token and false-positive with
- # "Stdin redirection feeding shell cannot be safely inspected"
- # on perfectly innocuous text like a git-commit body mentioning `bash`.
- # Real shell-stdin attacks (`bash << /tmp/x`, `< /tmp/x bash`,
- # `bash <<'EOF' ... EOF`, `bash <<<'rm -rf /'`, attached `bash</tmp/x>`)
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 257 on GitHub
- # still appear in this stream because their shell token sits OUTSIDE
- # any heredoc body, so the fail-closed detectors keep firing.
- local _exec_cmd_scan
- _exec_cmd_scan=$(blank_quoted_heredoc_bodies "$CMD" \
- | sed -E 's/(<<-|<<<|<<|<)/ \1 /g')
- local -a CMD_TOKENS_EXEC_SCAN=()
- while IFS= read -r _etok; do
- [[ -z "$_etok" ]] && continue
- CMD_TOKENS_EXEC_SCAN+=("$_etok")
- done < <(tokenize_args "$_exec_cmd_scan")
- local exec_kind="" exec_shell_idx=-1
- local _ti=0 _tn=${#CMD_TOKENS_EXEC[@]}
- # Fail-closed on ANY stdin redirect (< << <<< <<-) that appears before
- # a shell/source token — regardless of leading wrappers or VAR=val.
- # Bash allows redirections to sit anywhere in the command-prefix, so
- # `FOO=1 < /tmp/evil.sh bash`, `nice < /tmp/evil.sh bash`, and a bare
- # `< /tmp/evil.sh bash` all feed the shell from an uninspectable source.
- local _rk=0 _saw_redir=0
- local _tn_scan=${#CMD_TOKENS_EXEC_SCAN[@]}
- while [ $_rk -lt $_tn_scan ]; do
- local _rtok_chk
- _rtok_chk=$(strip_quotes "${CMD_TOKENS_EXEC_SCAN[$_rk]}")
- case "$_rtok_chk" in
- \<|\<\<|\<\<\<|\<\<-) _saw_redir=1 ;;
- *)
- if [ $_saw_redir -eq 1 ] && { is_shell_token "$_rtok_chk" || is_source_token "$_rtok_chk"; }; then
- echo "BLOCKED: Stdin redirection feeding shell cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2
- fi
- ;;
- esac
- _rk=$((_rk + 1))
- done
- # Fail-closed on `env -S <str>`, `env --split-string=<str>`, `env -C <dir>`,
- # `env --chdir=<dir>`: all of these either hide the real command inside a
- # split string or change the cwd so relative script paths no longer match
- # what Bash actually executes.
- if [ $_tn -gt 0 ]; then
- local _env_first
- _env_first=$(strip_quotes "${CMD_TOKENS_EXEC[0]}")
- if [[ "$_env_first" == "env" || "$_env_first" == "/usr/bin/env" ]]; then
- local _envk=1
- while [ $_envk -lt $_tn ]; do
- local _envtok
- _envtok=$(strip_quotes "${CMD_TOKENS_EXEC[$_envk]}")
- case "$_envtok" in
- -S|-S*|--split-string|--split-string=*|-C|-C*|--chdir|--chdir=*)
- echo "BLOCKED: 'env -S/--split-string/-C/--chdir' cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2 ;;
- esac
- _envk=$((_envk + 1))
- done
- fi
- fi
- # Walk past common runtime wrappers (env, command, nice, nohup, timeout,
- # time, stdbuf, ionice, chrt, taskset) and any leftover sudo flags
- # (sudo itself is already stripped at the top of check_single_command,
- # but its own short flags can remain in the token stream as `-E` etc.).
- # We only advance past token 0 when it is a recognized wrapper or looks
- # like a flag / VAR=val — this avoids false positives on invocations
- # like `echo bash`, where `bash` is an argument, not the command.
- # Greedy skip: walk past wrappers / flags / VAR=val / operands until
- # a shell or source token appears. Known tradeoff — this over-blocks
- # `time echo bash /tmp/x` (bash is an arg to echo, not a shell), but
- # precise per-wrapper operand grammars would miss real bypasses like
- # `timeout -s TERM 10 bash /tmp/x` and `stdbuf -o L bash /tmp/x` where
- # flag operands are non-numeric. Security over precision for this case.
- local _advance=0
- if [ $_tn -gt 0 ]; then
- local _t0
- _t0=$(strip_quotes "${CMD_TOKENS_EXEC[0]}")
- case "$_t0" in
- env|/usr/bin/env|command|builtin|exec|nice|nohup|timeout|time|stdbuf|ionice|chrt|taskset)
- _advance=1 ;;
- -*|+*) _advance=1 ;;
- *=*) _advance=1 ;;
- esac
- fi
- if [ $_advance -eq 1 ]; then
- _ti=1
- while [ $_ti -lt $_tn ]; do
- local _tok
- _tok=$(strip_quotes "${CMD_TOKENS_EXEC[$_ti]}")
- if is_shell_token "$_tok" || is_source_token "$_tok"; then
- break
- fi
- _ti=$((_ti + 1))
- done
- fi
- if [ $_ti -lt $_tn ]; then
- local _cmd_tok
- _cmd_tok=$(strip_quotes "${CMD_TOKENS_EXEC[$_ti]}")
- if is_shell_token "$_cmd_tok"; then
- exec_kind="shell"; exec_shell_idx=$_ti
- elif is_source_token "$_cmd_tok"; then
- exec_kind="source"; exec_shell_idx=$_ti
- fi
- fi
- [ -z "$exec_kind" ] && return 0
- local exec_target=""
- local ei=$((exec_shell_idx + 1)) en=${#CMD_TOKENS_EXEC[@]}
- local seen_ddash=0
- while [ $ei -lt $en ]; do
- local etok
- etok=$(strip_quotes "${CMD_TOKENS_EXEC[$ei]}")
- if [ $seen_ddash -eq 0 ]; then
- case "$etok" in
- --) seen_ddash=1; ei=$((ei + 1)); continue ;;
- # bash/sh -O/+O and -o/+o take the next token as operand
- -O|+O|-o|+o) ei=$((ei + 2)); continue ;;
- # Bash accepts both `-x` (enable) and `+x` (disable) forms
- -*|+*|'') ei=$((ei + 1)); continue ;;
- # fd prefix for a redirect operator (e.g. `bash 0<file`, `bash 2>&1`).
- # Skip — the operator itself is handled on the next iteration.
- [0-9]|[0-9][0-9])
- ei=$((ei + 1)); continue ;;
- # Stdin redirection variants: bash executes whatever is piped in.
- # `<< EOF` / `<<< "str"` content can't be inspected — fail closed.
- # `< file` — validate `file` as exec target (treat next token as script).
- \<\<|\<\<-|\<\<\<)
- echo "BLOCKED: Shell invoked with heredoc/here-string (<<, <<-, <<<) cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2 ;;
- \<)
- ei=$((ei + 1))
- if [ $ei -lt $en ]; then
- local _next_tok
- _next_tok=$(strip_quotes "${CMD_TOKENS_EXEC[$ei]}")
- # `bash < <(cmd)` — process substitution on stdin is a hidden
- # command source. Fail closed.
- case "$_next_tok" in
- \<|\<\(*|\(*|\&*)
- echo "BLOCKED: Shell stdin from process substitution / fd duplicate cannot be safely inspected. Ask user for explicit permission." >&2
- exit 2 ;;
- *)
- exec_target="$_next_tok" ;;
- esac
- fi
- break ;;
- esac
- fi
- exec_target="$etok"
- break
- done
- [ -z "$exec_target" ] && return 0
- exec_target=$(expand_path "$exec_target")
- if [[ "$exec_target" != /* ]]; then
- exec_target="$EFFECTIVE_CWD/$exec_target"
- fi
- local exec_resolved
- exec_resolved=$(resolve_path "$exec_target")
- # Dereference symlinks on the leaf — bash follows them at exec time,
- # so a project-local symlink pointing outside must be caught.
- local _exec_depth=20
- while [[ -L "$exec_resolved" && $_exec_depth -gt 0 ]]; do
- local _exec_link
- _exec_link=$(readlink "$exec_resolved")
- if [[ "$_exec_link" == /* ]]; then
- exec_resolved=$(resolve_path "$_exec_link")
- else
- exec_resolved=$(resolve_path "$(dirname "$exec_resolved")/$_exec_link")
- fi
- _exec_depth=$((_exec_depth - 1))
- done
- if [[ -L "$exec_resolved" ]]; then
- echo "BLOCKED: Script symlink chain too deep or circular at '$exec_resolved'. Ask user for explicit permission." >&2
- exit 2
- fi
- # Narrow, explicit exception: Claude Code skill helper scripts under
- # ~/.claude/skills/ are execute-only exempt (never create/write - the
- # Write/Edit/MultiEdit hooks below still block writes outside
- # PROJECT_DIR, so nothing new can land here through Claude's own tool
- # calls). User-requested to unblock trusted, already-installed skill
- # scripts (e.g. reader-knowledge-audit's render-report.py, the
- # rka-loop arm/disarm scripts) without opening execute for arbitrary
- # outside-project paths.
- if [[ "$exec_resolved" == "$_ALLOWLIST_HOME/.claude/skills/"* && ( "$exec_resolved" == *.py || "$exec_resolved" == *.sh ) ]]; then
- : # allowed - see comment above
- elif [[ "$exec_resolved/" != "$PROJECT_DIR/"* ]]; then
- echo "BLOCKED: Executing script '$exec_resolved' is OUTSIDE project directory '$PROJECT_DIR'. Allowlist does not cover execute. Ask user for explicit permission." >&2
- exit 2
- fi
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.