Skip to content
Back to search

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.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/justi--claude-code-project-boundary/badge.svg)](/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

i

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)

  1. {
  2. "name": "claude-code-project-boundary",
  3. "owner": {
  4. "name": "Justyna Wojtczak",
  5. "url": "https://github.com/justi"
  6. },
  7. "plugins": [
  8. {
  9. "name": "project-boundary",
  10. "source": ".",
  11. "description": "Blocks destructive commands outside the project directory. Allows file operations within the project (refactoring, cleanup) but prevents accidental damage outside it."
  12. }
  13. ]
  14. }
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)

  1. # Project Boundary — Claude Code Plugin
  2. 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.
  3. ## How it differs from existing plugins
  4. - **[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.
  5. - **[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.
  6. - **[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.
  7. ## What it does
  8. ### Boundary-checked (allowed inside project, blocked outside)
  9. | Operation | Inside project | Outside project |
  10. |-----------|---------------|-----------------|
  11. | `rm`, `rm -rf` | Allowed | **Blocked** |
  12. | `mv` (source and destination) | Allowed | **Blocked** |
  13. | `cp` (source and destination) | Allowed | **Blocked** |
  14. | `ln` (source and target) | Allowed | **Blocked** |
  15. | `chmod` / `chown` | Allowed | **Blocked** |
  16. | `>` / `>>` redirect | Allowed | **Blocked** |
  17. | `tee` / `tee -a` | Allowed | **Blocked** |
  18. | `curl -o` / `curl --output` | Allowed | **Blocked** |
  19. | `wget -O` / `wget --output-document` | Allowed | **Blocked** |
  20. | `find -delete` / `find -exec rm` | Allowed | **Blocked** |
  21. | `dd of=` | Allowed | **Blocked** |
  22. | `install` (source, destination, `--target-directory=`) | Allowed | **Blocked** |
  23. | `rsync` (source, destination, `--log-file=`, `--partial-dir=`, `--backup-dir=`, `--temp-dir=`, `--write-batch=`, `--only-write-batch=`) | Allowed | **Blocked** |
  24. | `tar -C` / `--directory=` | Allowed | **Blocked** |
  25. | `unzip -d` / `cpio -D` | Allowed | **Blocked** |
  26. | `7z -o<dir>` / `7z -w<dir>` (extract verbs only) | Allowed | **Blocked** |
  27. | **Edit** tool (file edits) | Allowed | **Blocked** |
  28. | **MultiEdit** tool (multi-file edits) | Allowed | **Blocked** |
  29. | **Write** tool (file creation) | Allowed | **Blocked** |
  30. ### Always blocked (unsafe to inspect)
  31. | Command | Reason |
  32. |---------|--------|
  33. | `bash -c "..."` / `sh -c "..."` | Nested shell — cannot inspect inner command |
  34. | `eval '...'` | Cannot safely parse evaluated code |
  35. | Piping to `sh` / `bash` | Inner commands invisible to guard |
  36. | `xargs rm/mv/cp/...` | Arguments cannot be validated |
  37. | `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 |
  38. | `awk '... system("...") ...'` (and similar `\| "sh"`) | Awk programs can shell out without the guard seeing the inner command |
  39. | `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 |
  40. | `$(...)` / backticks (outside single quotes) | Command substitution target is uninspectable. Single-quoted forms like `'$(cmd)'` and arithmetic expansion `$((2+2))` are allowed. |
  41. | `$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. |
  42. ### Additional protections
  43. - **Chained commands** — splits on `;`, `&&`, `||`, `|`, and unquoted newlines, then checks each sub-command independently
  44. - **`cwd` awareness** — uses `cwd` from the hook event, so commands run outside the project (without an explicit `cd`) are also guarded
  45. - **`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)
  46. - **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.
  47. - **`sudo` prefix** — stripped before checking, so `sudo rm /etc/passwd` is still blocked
  48. - **`find` options** — handles `-L`, `-H`, `-P` before the search path
  49. - **Path traversal** — `..` segments are resolved before boundary check
  50. - **`~` and `$HOME` expansion** — `rm ~/file` and `rm $HOME/file` are correctly detected as outside-project
  51. - **Symlink resolution** — handles macOS `/var` → `/private/var`, dereferences symlink chains in Edit/Write/MultiEdit (fail-closed after 20 hops)
  52. - **`/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/`.
  53. - **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.
  54. - **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.
  55. - **`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`.
  56. - **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.
  57. ### Path allowlist (`hooks/allowlist.conf`)
  58. 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.
  59. **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.
  60. **Format:** one glob pattern per line; `#` starts a comment; `~` expands to `$HOME`; `**` matches across path segments (bash globstar), `*` within a single segment.
  61. **Defaults shipped with the plugin:**
  62. - `~/.claude/projects/*/memory/**` — Claude Code auto-memory
  63. > [!WARNING]
  64. > **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.
  65. ### Known limitations
  66. - Paths with spaces work when properly quoted (single or double quotes). Unquoted paths with spaces are not supported.
  67. - Brace expansion (`{a,b,c}`) is not enumerated — literal match only
  68. - `~user/` (home of another user) is not expanded; only `~/` (current user) is handled
  69. ### Multiline git commits (`$(cat <<EOF)` is blocked)
  70. 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.
  71. The supported pattern is heredoc on stdin:
  72. ```bash
  73. git commit -F - <<'EOF'
  74. Subject line
  75. Body paragraph.
  76. EOF
  77. ```
  78. Repeated `-m` works for shorter messages where every paragraph fits on one line:
  79. ```bash
  80. git commit -m "Subject line" -m "Body paragraph."
  81. ```
  82. 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.
  83. ## Requirements
  84. `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.
  85. | Platform | Install |
  86. |---|---|
  87. | macOS | `brew install jq` |
  88. | Debian/Ubuntu | `apt install jq` |
  89. | Fedora/RHEL | `dnf install jq` |
  90. | Arch | `pacman -S jq` |
  91. | Windows (MSYS2) | `pacman -S jq` |
  92. | Windows (Scoop/Winget) | `scoop install jq` or `winget install jqlang.jq` |
  93. 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.
  94. ## Install
  95. Direct:
  96. ```
  97. claude --plugin-dir /path/to/claude-code-project-boundary
  98. ```
  99. From marketplace:
  100. ```
  101. /plugin marketplace add davepoon/buildwithclaude
  102. /plugin install project-boundary@buildwithclaude
  103. ```
  104. ## How it works
  105. 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.
  106. ## Testing
  107. ```
  108. bash tests/test_guard.sh
  109. ```
  110. 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).
  111. ## License
  112. MIT
hooks/lib/remote_dispatch.sh · Bundled script · 316 lines · 2 findings marked
  1. #!/bin/bash
  2. # project-boundary guard — remote_dispatch module
  3. # ================================================
  4. # Generic neutralisation of "remote-dispatch" commands whose operands
  5. # target a remote host or a foreign (container/namespace) filesystem
  6. # rather than the local one this guard protects. Without this pass,
  7. # tokens that are part of a remote command string get walked by the
  8. # local-path detectors (cp, tee, rm, redirect, ...) and produce
  9. # false-positive boundary blocks.
  10. #
  11. # Three universal shapes are recognised, all rewritten so downstream
  12. # detectors only see the local-side surface (or nothing, when there
  13. # is no local surface):
  14. #
  15. # 1. Network-copy tools — operate on a remote target but may also
  16. # take local operands and -flag values. The point of this class
  17. # is that the remote `host:/path` / `host::module` / `rsync://`
  18. # operands must NOT be walked as local filesystem paths;
  19. # legitimate local operands (`scp ./key host:/dst` etc.) are
  20. # reads from the plugin's perspective and the boundary doesn't
  21. # police those.
  22. # scp / rcp / sftp
  23. # Rewrite: collapse CMD to the bare verb name.
  24. #
  25. # 2. Remote-command dispatch — `<verb> [opts] <target> <opaque-cmd>`,
  26. # where the target is a host / container / pod and the trailing
  27. # tokens form a command executed on a foreign filesystem (NOT
  28. # the local one this guard protects):
  29. # ssh
  30. # docker exec | podman exec
  31. # kubectl exec | oc exec | crictl exec | lxc exec
  32. # Rewrite: collapse CMD to the verb prefix only.
  33. #
  34. # `nsenter` and `chroot` are deliberately EXCLUDED — they
  35. # execute on the local host (just under a different namespace
  36. # or apparent root), so their command operands can still touch
  37. # host paths outside the project and must remain subject to the
  38. # destructive walkers (Copilot review on PR #22).
  39. #
  40. # `docker run` / `podman run` / `buildah run` are also EXCLUDED
  41. # because the `-v src:dst` / `--volume` / `--mount type=bind,…`
  42. # flags can bind-mount host paths into the container, turning a
  43. # container-side write into a host-fs write that bypasses the
  44. # boundary. Until host-mount-source parsing is added, leaving
  45. # them subject to the existing walkers errs on the safe side
  46. # (Copilot review on PR #22).
  47. #
  48. # 3. Remote file copy with mixed local / remote operands —
  49. # `<verb> <subverb> <a> <b>` where one operand has the form
  50. # `<id>:<path>` and the other is local.
  51. # docker cp | podman cp | kubectl cp | oc cp
  52. # Rewrite: keep only the LOCAL DESTINATION operand (last
  53. # positional, when not remote-shaped) so the cp walker still
  54. # validates download targets like `… c:/x /etc/owned`. Source
  55. # operands are dropped — local source = read (not policed),
  56. # remote source = foreign filesystem.
  57. #
  58. # Depends on tokenize_args / strip_quotes from hooks/lib/tokenize.sh.
  59. # Pure (no caller-scope dependencies); returns the rewritten command
  60. # string on stdout.
  61. # --- Generic remote-target detector ---
  62. # Returns 0 iff the argument looks like a "remote address" of the
  63. # universal `<id>:<path>` form used by ssh, scp, rsync, docker cp,
  64. # kubectl cp, etc. The `:` must live in the FIRST path segment
  65. # (before any `/`) — a local path may legitimately contain `:` after a
  66. # slash (e.g. `../tmp/a:b`), and a URL like `http://...` keeps the
  67. # scheme separator inside the first segment but is excluded by an
  68. # explicit URL check first.
  69. _rd_is_remote_target_operand() {
  70. local arg="$1"
  71. case "$arg" in
  72. *://*) return 1 ;; # URL scheme
  73. esac
  74. local first="${arg%%/*}"
  75. case "$first" in
  76. *:*) return 0 ;;
  77. esac
  78. return 1
  79. }
  80. # --- Find command-name token index, skipping wrappers/flags/VAR=val ---
  81. # Mirrors the wrapper-skip rules used by strip_command_name_prefix and
  82. # command_name_is. Reads from the module-local _RD_TOKS array (set by
  83. # rewrite_remote_dispatch before calling). Returns -1 if no command-name
  84. # found. Uses a global rather than `local -n` because macOS ships
  85. # bash 3.2 which lacks nameref support.
  86. #
  87. # Also skips a per-wrapper option-with-value pair (e.g. `-u USER` for
  88. # sudo/env, `-k DUR` for timeout) when the value would otherwise be
  89. # mis-identified as the verb. Without this, `env -u FOO docker exec
  90. # 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
  91. # docker"), `rewrite_remote_dispatch` returned the cmd unchanged, and
  92. # 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
  93. # actually runs inside the container, not on host). Same root cause
  94. # as section 40 (subcmd_flags.sh) and section 41 (command_name.sh);
  95. # Codex round-4 follow-up on PR #23.
  96. _rd_find_verb_idx() {
  97. local i=0 n=${#_RD_TOKS[@]}
  98. local prev_was_timeout=0 last_wrapper=""
  99. while [ $i -lt $n ]; do
  100. local raw="${_RD_TOKS[$i]}" t
  101. t=$(strip_quotes "$raw")
  102. if [ -n "$last_wrapper" ]; then
  103. local opts; opts=$(_wrapper_opts_with_val "$last_wrapper")
  104. if [ -n "$opts" ]; then
  105. case " $opts " in
  106. *" $t "*) i=$((i + 2)); continue ;;
  107. esac
  108. fi
  109. fi
  110. if [ $prev_was_timeout -eq 1 ]; then
  111. prev_was_timeout=0
  112. case "$t" in
  113. [0-9]*|inf*) i=$((i + 1)); continue ;;
  114. esac
  115. fi
  116. case "$t" in
  117. timeout)
  118. prev_was_timeout=1; last_wrapper="timeout"; i=$((i + 1)); continue ;;
  119. sudo|env|/bin/env|/usr/bin/env|nice|nohup|time|stdbuf|ionice|chrt|taskset|command|builtin|exec)
  120. last_wrapper=$(_rd_strip_path_prefix "$t")
  121. i=$((i + 1)); continue ;;
  122. esac
  123. case "$t" in
  124. [A-Za-z_]*=*) i=$((i + 1)); continue ;;
  125. -*) i=$((i + 1)); continue ;;
  126. esac
  127. printf '%d' "$i"
  128. return
  129. done
  130. printf -- '-1'
  131. }
  132. # --- Strip /bin/, /sbin/, /usr/bin/, /usr/sbin/, /usr/local/bin/, ---
  133. # /opt/homebrew/bin/ prefix. Mirrors _cn_strip_path_prefix in
  134. # command_name.sh — kept in sync so a Homebrew-installed ssh /
  135. # kubectl / etc. is recognised by the remote-dispatch walkers.
  136. _rd_strip_path_prefix() {
  137. local n="$1"
  138. case "$n" in
  139. /bin/*|/sbin/*|/usr/bin/*|/usr/sbin/*|/usr/local/bin/*|/opt/homebrew/bin/*) printf '%s' "${n##*/}" ;;
  140. *) printf '%s' "$n" ;;
  141. esac
  142. }
  143. # --- Whitespace-list membership check ---
  144. # $1 = needle, $2 = space-separated haystack. Used to decide whether a
  145. # given short or long flag consumes the next token as its value.
  146. _rd_flag_takes_value() {
  147. local needle="$1"
  148. local short_list="$2"
  149. local long_list="$3"
  150. case " $short_list " in *" $needle "*) return 0 ;; esac
  151. case " $long_list " in *" $needle "*) return 0 ;; esac
  152. return 1
  153. }
  154. # --- Main entry: rewrite remote-dispatch commands ---
  155. # In: full CMD string
  156. # Out: CMD string with remote portions removed; unchanged for non-dispatch verbs.
  157. rewrite_remote_dispatch() {
  158. local cmd="$1"
  159. _RD_TOKS=()
  160. local t
  161. while IFS= read -r t; do
  162. [[ -z "$t" ]] && continue
  163. _RD_TOKS+=("$t")
  164. done < <(tokenize_args "$cmd")
  165. local verb_idx
  166. verb_idx=$(_rd_find_verb_idx)
  167. [ "$verb_idx" -lt 0 ] && { printf '%s' "$cmd"; return; }
  168. local verb subverb=""
  169. verb=$(strip_quotes "${_RD_TOKS[$verb_idx]}")
  170. verb=$(_rd_strip_path_prefix "$verb")
  171. if [ $((verb_idx + 1)) -lt ${#_RD_TOKS[@]} ]; then
  172. subverb=$(strip_quotes "${_RD_TOKS[$((verb_idx + 1))]}")
  173. fi
  174. # Class 1: pure remote-fs tools.
  175. case "$verb" in
  176. scp|rcp|sftp)
  177. printf '%s' "$verb"
  178. return ;;
  179. esac
  180. # Class 3: two-word remote copy verbs.
  181. case "$verb $subverb" in
  182. "docker cp"|"podman cp"|"kubectl cp"|"oc cp")
  183. _rd_rewrite_remote_copy "$verb_idx"
  184. return ;;
  185. esac
  186. # Class 2: two-word remote-command dispatch verbs. `docker run` /
  187. # `podman run` / `buildah run` are intentionally NOT in this list —
  188. # see the header comment for the bind-mount rationale.
  189. case "$verb $subverb" in
  190. "docker exec"|"podman exec"|"kubectl exec"|"oc exec"|"crictl exec"|"lxc exec")
  191. printf '%s %s' "$verb" "$subverb"
  192. return ;;
  193. esac
  194. # Class 2: one-word remote-command dispatch verbs. `nsenter` and
  195. # `chroot` are intentionally NOT in this list — see the header
  196. # comment for why they remain subject to the local walkers.
  197. case "$verb" in
  198. ssh)
  199. printf '%s' "$verb"
  200. return ;;
  201. esac
  202. printf '%s' "$cmd"
  203. }
  204. # --- Rewrite a `<verb> <subverb> <operand-a> <operand-b>` copy invocation ---
  205. # Keep the verb pair plus operands that are NOT remote `<id>:<path>` form.
  206. # Flags are dropped (they cannot be local file targets in any of the
  207. # supported `cp` subcommands; -L, --follow-link, --archive etc. are
  208. # value-less or take non-path values).
  209. _rd_rewrite_remote_copy() {
  210. local v_idx="$1"
  211. local verb_pair="${_RD_TOKS[$v_idx]} ${_RD_TOKS[$((v_idx + 1))]}"
  212. local k=$((v_idx + 2)) n=${#_RD_TOKS[@]}
  213. # Per-verb flags-that-consume-the-next-token list. Necessary because
  214. # Copilot review on PR #22 flagged a download-mode bypass shape:
  215. # `kubectl cp pod:/x /etc/owned --namespace default`
  216. # without this table, `default` (the value of `--namespace`) gets
  217. # added to the positionals list, becomes the LAST positional, and
  218. # the rewrite emits `cp default` — relative path resolved inside
  219. # the project → ALLOWED, missing the real download destination
  220. # `/etc/owned`. cobra/pflag (used by kubectl/oc) lets flags appear
  221. # before AND after positionals, so we can't just stop after the
  222. # first non-flag token.
  223. #
  224. # docker cp / podman cp share a small flag set with no value-taking
  225. # flags relevant to the path-walker bypass (`-a/--archive`,
  226. # `-L/--follow-link`, `--quiet`, `--pause`, `--extract` are all
  227. # value-less); their entries are deliberately empty. kubectl cp /
  228. # oc cp inherit the entire kubectl global flag set — only the ones
  229. # that take a value AND can credibly appear next to a path are
  230. # listed here (kubeconfig/cluster paths can be local files but the
  231. # plugin does not police reads, so we drop their values without
  232. # validation).
  233. local short_value_flags="" long_value_flags=""
  234. case "$verb_pair" in
  235. "kubectl cp"|"oc cp")
  236. short_value_flags="-c -n -s"
  237. 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"
  238. ;;
  239. esac
  240. # Walk positional operands. cp-family semantics: the LAST positional
  241. # is the destination; every earlier positional is a source. The
  242. # plugin protects writes, not reads — so a local SOURCE is dropped
  243. # (uploading `docker cp /tmp/x container:/y` is read-only on /tmp/x
  244. # and must not false-positive). A local DESTINATION is preserved
  245. # below as the operand of a synthetic `cp <dst>` so the existing
  246. # cp walker validates it. This is a deliberate divergence from the
  247. # bare `cp` walker (which strict-checks both src and dst) — the
  248. # remote-dispatch case has a remote operand on the OTHER side, so
  249. # the boundary's "no copies from outside" semantics do not apply
  250. # symmetrically here. Operands of the universal `<id>:<path>` form
  251. # are dropped because they target a foreign filesystem.
  252. local -a positionals=()
  253. while [ $k -lt $n ]; do
  254. local raw="${_RD_TOKS[$k]}" tok
  255. tok=$(strip_quotes "$raw")
  256. case "$tok" in
  257. --)
  258. # POSIX end-of-options: every later token is a positional,
  259. # even if it begins with `-`. Used by kubectl exec but also
  260. # valid for cp invocations.
  261. k=$((k + 1))
  262. while [ $k -lt $n ]; do
  263. positionals+=("${_RD_TOKS[$k]}")
  264. k=$((k + 1))
  265. done
  266. continue ;;
  267. --*=*)
  268. k=$((k + 1)); continue ;;
  269. -*)
  270. if _rd_flag_takes_value "$tok" "$short_value_flags" "$long_value_flags"; then
  271. k=$((k + 2))
  272. else
  273. k=$((k + 1))
  274. fi
  275. continue ;;
  276. esac
  277. positionals+=("$raw")
  278. k=$((k + 1))
  279. done
  280. local last_idx=$(( ${#positionals[@]} - 1 ))
  281. if [ $last_idx -lt 0 ]; then
  282. printf '%s' "$verb_pair"
  283. return
  284. fi
  285. local last_raw="${positionals[$last_idx]}"
  286. local last_tok
  287. last_tok=$(strip_quotes "$last_raw")
  288. if _rd_is_remote_target_operand "$last_tok"; then
  289. # Destination is remote → no local write surface. Collapse to verb pair
  290. # so no walker fires on the local source(s).
  291. printf '%s %s' "${_RD_TOKS[$v_idx]}" "${_RD_TOKS[$((v_idx + 1))]}"
  292. return
  293. fi
  294. # Destination is local. Emit a synthetic `cp <dst>` so the cp walker
  295. # in destructive.sh validates that single path. Source operands are
  296. # dropped: remote ones are foreign, local ones are reads (not policed).
  297. printf 'cp %s' "$last_raw"
  298. }
hooks/lib/shell_exec_walkers.sh · Bundled script · 445 lines · 4 findings marked
  1. # shellcheck shell=bash
  2. # project-boundary guard — shell / interpreter execution walkers
  3. # ===============================================================
  4. # Extracted from hooks/guard.sh check_single_command. All five
  5. # walkers fail-closed on un-inspectable code execution surfaces:
  6. #
  7. # block_nested_shell_and_eval
  8. # `bash -c CMD`, `sh -c CMD`, `zsh -c CMD`, ..., `eval CMD`.
  9. #
  10. # block_interpreter_inline_code
  11. # `python -c`, `perl -e`, `ruby -e`, `node -e`, `php -r`,
  12. # `awk 'BEGIN{system(...)}'`, etc.
  13. #
  14. # block_pipe_to_shell
  15. # Bare `sh`/`bash`/... or shell with only flags (e.g. `bash -s`)
  16. # — 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
  17. #
  18. # block_shell_script_execution
  19. # Path-form: `bash /tmp/x.sh`, `source ~/x.sh`, `. /tmp/x.sh`.
  20. # STRICT project-root (allowlist must NOT grant execute).
  21. # Uses tokenize-with-redirects + heredoc-blanked parallel
  22. # stream + symlink dereference.
  23. #
  24. # All read CMD / CMD_BLANKED / EFFECTIVE_CWD / PROJECT_DIR from
  25. # caller's dynamic scope. Helpers (strip_quotes, expand_path,
  26. # resolve_path, tokenize_args, blank_quoted_heredoc_bodies,
  27. # is_shell_token, is_source_token) come from sibling modules.
  28. # Each calls `exit 2` on a boundary violation.
  29. block_nested_shell_and_eval() {
  30. # Match: bash -c, sh -c, bash -lc, bash -ec, /bin/bash -c, /bin/sh -c, /usr/bin/env bash -c
  31. # Also zsh / ksh / dash / fish / xonsh / tcsh / csh / nu / pwsh / osh
  32. # (macOS ships zsh by default; all accept -c CMD with un-inspectable semantics).
  33. #
  34. # VERB-GATE: substring matching alone false-positives on text-as-arg
  35. # cases (`echo "use bash -c here" > docs/fp.md`, `git commit -m
  36. # "explain eval risk"`). Gate every check on CMD_VERB so the
  37. # substring walker only fires when the verb itself is a shell
  38. # opener, an interpreter wrapper that resolves to one (env / sudo /
  39. # nice / ... already collapsed by _cn_find_verb_idx — CMD_VERB is
  40. # the post-wrapper name), or a remote-dispatch verb where the
  41. # asymmetry pin (294b64d / 7b65a45) intentionally over-blocks
  42. # inline-shell payloads.
  43. #
  44. # INTENTIONAL ORDERING: this walker still runs BEFORE
  45. # rewrite_remote_dispatch. That is what keeps `docker exec ctr sh
  46. # -c '...'`, `kubectl exec pod -- bash -c '...'`, `ssh host bash -c
  47. # '...'` blocked: CMD_VERB at this point is still `docker` /
  48. # `kubectl` / `ssh`, not yet rewritten away. Deferring the check to
  49. # AFTER remote-dispatch neutralisation would make the boundary
  50. # easier to abuse via payloads hidden in pseudo-remote arguments
  51. # (e.g. an alias that resolves `docker` to a local script but still
  52. # parses as `docker exec ...`). Path-operand forms (`docker exec
  53. # ctr rm /etc/x`) remain ALLOWED via rewrite_remote_dispatch —
  54. # CMD_VERB falls in the `*` branch and the walker returns. See the
  55. # asymmetry tests in test_true_negatives_b.sh near the docker exec
  56. # block.
  57. case "${CMD_VERB-}" in
  58. bash|sh|zsh|ksh|dash|fish|xonsh|tcsh|csh|nu|pwsh|osh)
  59. ;; # real shell opener — fall through to the substring check
  60. docker|podman|kubectl|oc|crictl|lxc|ssh)
  61. ;; # remote-dispatch verb — asymmetry pin: inline shell payload BLOCK
  62. eval)
  63. echo "BLOCKED: 'eval' cannot be safely inspected. Ask user for explicit permission." >&2
  64. exit 2 ;;
  65. *)
  66. return ;; # text-as-arg / unrelated verb — substring is content, not exec
  67. esac
  68. 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
  69. echo "BLOCKED: Nested shell execution ('bash -c' / 'sh -c' / 'zsh -c' / ...) cannot be safely inspected. Ask user for explicit permission." >&2
  70. exit 2
  71. fi
  72. if echo "$CMD" | grep -qE '(^|[[:space:]])eval[[:space:]]'; then
  73. echo "BLOCKED: 'eval' cannot be safely inspected. Ask user for explicit permission." >&2
  74. exit 2
  75. fi
  76. }
  77. # --- trap CMD SIG: deferred shell handler (round-4 pentest) ---
  78. # `trap CMD SIG` registers CMD as a shell handler that fires on the
  79. # named signal (EXIT, INT, TERM, ...). CMD is arbitrary shell code
  80. # stored on argv and executed later — same un-inspectable semantics
  81. # as `bash -c CMD` and `eval`. Read-only forms have no deferred CMD
  82. # and stay ALLOWED:
  83. # trap (list current traps)
  84. # trap -l (list signal names)
  85. # trap -p (print traps in re-input form)
  86. # trap - SIG (reset SIG to default — first positional `-`)
  87. # trap '' SIG (ignore SIG — first positional empty)
  88. # Lifted out of block_nested_shell_and_eval so the verb-gate on the
  89. # bash -c / eval substring checks does not also bypass this walker —
  90. # `trap` is its own verb and command_name_is gates correctly.
  91. block_trap_handler() {
  92. if ! command_name_is "trap"; then
  93. return
  94. fi
  95. local trap_i=1 trap_n=${#CMD_TOKENS_SCAN[@]}
  96. local trap_seen_dashdash=0
  97. local trap_readonly=0
  98. local trap_first_pos=""
  99. local trap_first_pos_set=0
  100. while [ $trap_i -lt $trap_n ]; do
  101. local trap_tok
  102. trap_tok=$(strip_quotes "${CMD_TOKENS_SCAN[$trap_i]}")
  103. if [ $trap_seen_dashdash -eq 0 ]; then
  104. case "$trap_tok" in
  105. --)
  106. trap_seen_dashdash=1; trap_i=$((trap_i + 1)); continue ;;
  107. -l|-p)
  108. # `-l` / `-p` make the entire call read-only regardless
  109. # of any signal-name args that may follow.
  110. trap_readonly=1; break ;;
  111. esac
  112. fi
  113. trap_first_pos="$trap_tok"
  114. trap_first_pos_set=1
  115. break
  116. done
  117. if [ "$trap_readonly" -eq 0 ] \
  118. && [ "$trap_first_pos_set" -eq 1 ] \
  119. && [ -n "$trap_first_pos" ] \
  120. && [ "$trap_first_pos" != "-" ]; then
  121. echo "BLOCKED: 'trap CMD SIG' deferred shell handler cannot be safely inspected. Ask user for explicit permission." >&2
  122. exit 2
  123. fi
  124. }
  125. block_interpreter_inline_code() {
  126. # python/perl/ruby/node/php/osascript all accept code on argv. The inner
  127. # string cannot be inspected, so the same fail-closed rule as `bash -c`
  128. # applies. Flags covered: -c (python), -e (perl/ruby/node), --eval,
  129. # --execute, -E (perl alias). A dedicated rule catches `awk 'BEGIN{system(
  130. # "…")}'` and similar because awk programs are the first non-option arg,
  131. # not behind a flag — so we detect the `system(` marker in the CMD_BLANKED
  132. # view (heredoc bodies stripped) so a tee/cat heredoc whose body merely
  133. # mentions `python -c`, `awk … system(…)`, etc. is not false-positively
  134. # rejected.
  135. #
  136. # VERB-GATE: same reasoning as block_nested_shell_and_eval. Substring
  137. # walkers without a verb gate false-positive on text-as-arg cases
  138. # like `echo "avoid node -e examples" > docs/fp.md` and `git commit
  139. # -m "docs: avoid python -c examples"`. Each branch below now gates
  140. # on CMD_VERB so the substring check only fires when the verb itself
  141. # is the matching interpreter (post-wrapper, post-path-prefix). For
  142. # the awk family, `awk` / `gawk` / `mawk` / `nawk` all collapse to a
  143. # bare verb name via _cn_strip_path_prefix.
  144. case "${CMD_VERB-}" in
  145. python|python2|python3|perl|ruby|node|nodejs|deno|bun|osascript|Rscript)
  146. 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
  147. echo "BLOCKED: Non-shell interpreter with inline code flag cannot be safely inspected. Ask user for explicit permission." >&2
  148. exit 2
  149. fi ;;
  150. php)
  151. # Dedicated PHP rule — `-r`, `-R`, `--run` execute inline code.
  152. # Cannot be folded into the python/etc. regex because `-r` is a
  153. # module-preload flag in ruby/node (no code execution), so a
  154. # generic `r` letter would false-positive on `ruby -r json` /
  155. # `node -r dotenv`. The matcher accepts attached forms
  156. # (`-rcode`, `-Rcode`), quoted-attached (`-r'code'`), clustered-
  157. # ending (`-ar`, `-aR`), and the long alias `--run`.
  158. if echo "$CMD_BLANKED" | grep -qE '(^|[[:space:]])php[[:space:]]+(-[rR][^[:space:]=]*|-[a-zA-Z]*[rR]|--run)([[:space:]]|=|$|'\''|")'; then
  159. echo "BLOCKED: 'php -r/-R/--run' inline code cannot be safely inspected. Ask user for explicit permission." >&2
  160. exit 2
  161. fi
  162. # php also accepts -c/--eval inline forms — same regex as the
  163. # python branch covers them.
  164. if echo "$CMD_BLANKED" | grep -qE '(^|[[:space:]])php[[:space:]]+(-[a-zA-Z]*[ceE]|--eval|--execute)([[:space:]]|=|$)'; then
  165. echo "BLOCKED: Non-shell interpreter with inline code flag cannot be safely inspected. Ask user for explicit permission." >&2
  166. exit 2
  167. fi ;;
  168. awk|gawk|mawk|nawk)
  169. if echo "$CMD_BLANKED" | grep -qE 'system[[:space:]]*\(|\|[[:space:]]*&?[[:space:]]*"?(sh|bash)'; then
  170. echo "BLOCKED: awk program with 'system()' / shell pipe cannot be safely inspected. Ask user for explicit permission." >&2
  171. exit 2
  172. fi ;;
  173. esac
  174. }
  175. block_pipe_to_shell() {
  176. # Match bare shell invocations: sh, bash, zsh, ksh, dash, fish,
  177. # /bin/sh, /bin/bash, ..., and with flags: sh -s, bash --login, etc.
  178. # But NOT: bash script.sh, bash -x script.sh (running a script file).
  179. if echo "$CMD" | grep -qE '^(/bin/)?(sh|bash|zsh|ksh|dash|fish)$'; then
  180. echo "BLOCKED: Piping to 'sh'/'bash'/'zsh'/'ksh'/'dash'/'fish' cannot be safely inspected. Ask user for explicit permission." >&2
  181. exit 2
  182. fi
  183. # Match shell with only flags (no script file): sh -s, bash --login, sh -s -- args
  184. if echo "$CMD" | grep -qE '^(/bin/)?(sh|bash|zsh|ksh|dash|fish)[[:space:]]+-'; then
  185. local shell_args
  186. shell_args=$(echo "$CMD" | sed -E 's/^(\/bin\/)?(sh|bash|zsh|ksh|dash|fish)[[:space:]]+//')
  187. local has_script=0
  188. local shell_token
  189. for shell_token in $shell_args; do
  190. case "$shell_token" in
  191. --) break ;; # everything after -- is args to the script/stdin
  192. # Informational-only flags exit before reading stdin or
  193. # executing user code — `bash --version` / `sh --help` are
  194. # not pipe-to-shell targets even when they appear as a
  195. # standalone subcommand (issue #33).
  196. #
  197. # Codex sweep 4: `-V` is NOT safe across all shells —
  198. # zsh and dash treat `-V` as the version flag but still
  199. # read and execute stdin, so `curl URL | zsh -V` was a
  200. # real pipe-to-shell bypass. bash and ksh reject `-V`
  201. # as an unknown option (no stdin read), but the walker
  202. # can't distinguish per-shell here. Drop `-V` from the
  203. # whitelist entirely — only the long forms `--version`
  204. # and `--help` are safe across the guarded shell set.
  205. --version|--help)
  206. has_script=1; break ;;
  207. -*) continue ;;
  208. *) has_script=1; break ;;
  209. esac
  210. done
  211. if [[ $has_script -eq 0 ]]; then
  212. echo "BLOCKED: Piping to 'sh'/'bash' cannot be safely inspected. Ask user for explicit permission." >&2
  213. exit 2
  214. fi
  215. fi
  216. }
  217. block_shell_script_execution() {
  218. # Catches: `bash /tmp/x.sh`, `sh ~/x.sh`, `zsh|ksh|dash|fish /tmp/x.sh`,
  219. # `source /tmp/x.sh`, `. /tmp/x.sh`. Inline-code forms (`bash -c ...`)
  220. # are caught by block_nested_shell_and_eval; this covers the
  221. # complementary case where the script is a path argument.
  222. #
  223. # STRICT project-root check (no allowlist). Allowlist grants WRITE to
  224. # specific paths (e.g. memory/); if execute inherited that, a write-
  225. # allowlisted dir would become an RCE escape hatch:
  226. # `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
  227. # Walk CMD_TOKENS to locate the shell/source invocation, possibly buried
  228. # behind an `env [flags] [VAR=val]*` wrapper. Once found, scan for the
  229. # script-path operand — honoring flags that consume the next token
  230. # (-O / -o for bash set options). Finally, dereference symlinks on the
  231. # script path so a `project/link.sh -> /tmp/evil.sh` bait is caught.
  232. # Re-tokenize the command with redirect operators (< << <<< <<-) spaced
  233. # out so that attached forms like `bash</tmp/x.sh`, `bash<<EOF`, and
  234. # `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
  235. local _exec_cmd
  236. _exec_cmd=$(printf '%s' "$CMD" | sed -E 's/(<<-|<<<|<<|<)/ \1 /g')
  237. local -a CMD_TOKENS_EXEC=()
  238. local _etok
  239. while IFS= read -r _etok; do
  240. [[ -z "$_etok" ]] && continue
  241. CMD_TOKENS_EXEC+=("$_etok")
  242. done < <(tokenize_args "$_exec_cmd")
  243. # A parallel token stream built from a heredoc-blanked copy of CMD.
  244. # Used ONLY by the `_saw_redir`/`exec_kind` scans below, which otherwise
  245. # would treat a quoted-heredoc body byte like "bash" or "source" as a
  246. # shell token and false-positive with
  247. # "Stdin redirection feeding shell cannot be safely inspected"
  248. # on perfectly innocuous text like a git-commit body mentioning `bash`.
  249. # Real shell-stdin attacks (`bash << /tmp/x`, `< /tmp/x bash`,
  250. # `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
  251. # still appear in this stream because their shell token sits OUTSIDE
  252. # any heredoc body, so the fail-closed detectors keep firing.
  253. local _exec_cmd_scan
  254. _exec_cmd_scan=$(blank_quoted_heredoc_bodies "$CMD" \
  255. | sed -E 's/(<<-|<<<|<<|<)/ \1 /g')
  256. local -a CMD_TOKENS_EXEC_SCAN=()
  257. while IFS= read -r _etok; do
  258. [[ -z "$_etok" ]] && continue
  259. CMD_TOKENS_EXEC_SCAN+=("$_etok")
  260. done < <(tokenize_args "$_exec_cmd_scan")
  261. local exec_kind="" exec_shell_idx=-1
  262. local _ti=0 _tn=${#CMD_TOKENS_EXEC[@]}
  263. # Fail-closed on ANY stdin redirect (< << <<< <<-) that appears before
  264. # a shell/source token — regardless of leading wrappers or VAR=val.
  265. # Bash allows redirections to sit anywhere in the command-prefix, so
  266. # `FOO=1 < /tmp/evil.sh bash`, `nice < /tmp/evil.sh bash`, and a bare
  267. # `< /tmp/evil.sh bash` all feed the shell from an uninspectable source.
  268. local _rk=0 _saw_redir=0
  269. local _tn_scan=${#CMD_TOKENS_EXEC_SCAN[@]}
  270. while [ $_rk -lt $_tn_scan ]; do
  271. local _rtok_chk
  272. _rtok_chk=$(strip_quotes "${CMD_TOKENS_EXEC_SCAN[$_rk]}")
  273. case "$_rtok_chk" in
  274. \<|\<\<|\<\<\<|\<\<-) _saw_redir=1 ;;
  275. *)
  276. if [ $_saw_redir -eq 1 ] && { is_shell_token "$_rtok_chk" || is_source_token "$_rtok_chk"; }; then
  277. echo "BLOCKED: Stdin redirection feeding shell cannot be safely inspected. Ask user for explicit permission." >&2
  278. exit 2
  279. fi
  280. ;;
  281. esac
  282. _rk=$((_rk + 1))
  283. done
  284. # Fail-closed on `env -S <str>`, `env --split-string=<str>`, `env -C <dir>`,
  285. # `env --chdir=<dir>`: all of these either hide the real command inside a
  286. # split string or change the cwd so relative script paths no longer match
  287. # what Bash actually executes.
  288. if [ $_tn -gt 0 ]; then
  289. local _env_first
  290. _env_first=$(strip_quotes "${CMD_TOKENS_EXEC[0]}")
  291. if [[ "$_env_first" == "env" || "$_env_first" == "/usr/bin/env" ]]; then
  292. local _envk=1
  293. while [ $_envk -lt $_tn ]; do
  294. local _envtok
  295. _envtok=$(strip_quotes "${CMD_TOKENS_EXEC[$_envk]}")
  296. case "$_envtok" in
  297. -S|-S*|--split-string|--split-string=*|-C|-C*|--chdir|--chdir=*)
  298. echo "BLOCKED: 'env -S/--split-string/-C/--chdir' cannot be safely inspected. Ask user for explicit permission." >&2
  299. exit 2 ;;
  300. esac
  301. _envk=$((_envk + 1))
  302. done
  303. fi
  304. fi
  305. # Walk past common runtime wrappers (env, command, nice, nohup, timeout,
  306. # time, stdbuf, ionice, chrt, taskset) and any leftover sudo flags
  307. # (sudo itself is already stripped at the top of check_single_command,
  308. # but its own short flags can remain in the token stream as `-E` etc.).
  309. # We only advance past token 0 when it is a recognized wrapper or looks
  310. # like a flag / VAR=val — this avoids false positives on invocations
  311. # like `echo bash`, where `bash` is an argument, not the command.
  312. # Greedy skip: walk past wrappers / flags / VAR=val / operands until
  313. # a shell or source token appears. Known tradeoff — this over-blocks
  314. # `time echo bash /tmp/x` (bash is an arg to echo, not a shell), but
  315. # precise per-wrapper operand grammars would miss real bypasses like
  316. # `timeout -s TERM 10 bash /tmp/x` and `stdbuf -o L bash /tmp/x` where
  317. # flag operands are non-numeric. Security over precision for this case.
  318. local _advance=0
  319. if [ $_tn -gt 0 ]; then
  320. local _t0
  321. _t0=$(strip_quotes "${CMD_TOKENS_EXEC[0]}")
  322. case "$_t0" in
  323. env|/usr/bin/env|command|builtin|exec|nice|nohup|timeout|time|stdbuf|ionice|chrt|taskset)
  324. _advance=1 ;;
  325. -*|+*) _advance=1 ;;
  326. *=*) _advance=1 ;;
  327. esac
  328. fi
  329. if [ $_advance -eq 1 ]; then
  330. _ti=1
  331. while [ $_ti -lt $_tn ]; do
  332. local _tok
  333. _tok=$(strip_quotes "${CMD_TOKENS_EXEC[$_ti]}")
  334. if is_shell_token "$_tok" || is_source_token "$_tok"; then
  335. break
  336. fi
  337. _ti=$((_ti + 1))
  338. done
  339. fi
  340. if [ $_ti -lt $_tn ]; then
  341. local _cmd_tok
  342. _cmd_tok=$(strip_quotes "${CMD_TOKENS_EXEC[$_ti]}")
  343. if is_shell_token "$_cmd_tok"; then
  344. exec_kind="shell"; exec_shell_idx=$_ti
  345. elif is_source_token "$_cmd_tok"; then
  346. exec_kind="source"; exec_shell_idx=$_ti
  347. fi
  348. fi
  349. [ -z "$exec_kind" ] && return 0
  350. local exec_target=""
  351. local ei=$((exec_shell_idx + 1)) en=${#CMD_TOKENS_EXEC[@]}
  352. local seen_ddash=0
  353. while [ $ei -lt $en ]; do
  354. local etok
  355. etok=$(strip_quotes "${CMD_TOKENS_EXEC[$ei]}")
  356. if [ $seen_ddash -eq 0 ]; then
  357. case "$etok" in
  358. --) seen_ddash=1; ei=$((ei + 1)); continue ;;
  359. # bash/sh -O/+O and -o/+o take the next token as operand
  360. -O|+O|-o|+o) ei=$((ei + 2)); continue ;;
  361. # Bash accepts both `-x` (enable) and `+x` (disable) forms
  362. -*|+*|'') ei=$((ei + 1)); continue ;;
  363. # fd prefix for a redirect operator (e.g. `bash 0<file`, `bash 2>&1`).
  364. # Skip — the operator itself is handled on the next iteration.
  365. [0-9]|[0-9][0-9])
  366. ei=$((ei + 1)); continue ;;
  367. # Stdin redirection variants: bash executes whatever is piped in.
  368. # `<< EOF` / `<<< "str"` content can't be inspected — fail closed.
  369. # `< file` — validate `file` as exec target (treat next token as script).
  370. \<\<|\<\<-|\<\<\<)
  371. echo "BLOCKED: Shell invoked with heredoc/here-string (<<, <<-, <<<) cannot be safely inspected. Ask user for explicit permission." >&2
  372. exit 2 ;;
  373. \<)
  374. ei=$((ei + 1))
  375. if [ $ei -lt $en ]; then
  376. local _next_tok
  377. _next_tok=$(strip_quotes "${CMD_TOKENS_EXEC[$ei]}")
  378. # `bash < <(cmd)` — process substitution on stdin is a hidden
  379. # command source. Fail closed.
  380. case "$_next_tok" in
  381. \<|\<\(*|\(*|\&*)
  382. echo "BLOCKED: Shell stdin from process substitution / fd duplicate cannot be safely inspected. Ask user for explicit permission." >&2
  383. exit 2 ;;
  384. *)
  385. exec_target="$_next_tok" ;;
  386. esac
  387. fi
  388. break ;;
  389. esac
  390. fi
  391. exec_target="$etok"
  392. break
  393. done
  394. [ -z "$exec_target" ] && return 0
  395. exec_target=$(expand_path "$exec_target")
  396. if [[ "$exec_target" != /* ]]; then
  397. exec_target="$EFFECTIVE_CWD/$exec_target"
  398. fi
  399. local exec_resolved
  400. exec_resolved=$(resolve_path "$exec_target")
  401. # Dereference symlinks on the leaf — bash follows them at exec time,
  402. # so a project-local symlink pointing outside must be caught.
  403. local _exec_depth=20
  404. while [[ -L "$exec_resolved" && $_exec_depth -gt 0 ]]; do
  405. local _exec_link
  406. _exec_link=$(readlink "$exec_resolved")
  407. if [[ "$_exec_link" == /* ]]; then
  408. exec_resolved=$(resolve_path "$_exec_link")
  409. else
  410. exec_resolved=$(resolve_path "$(dirname "$exec_resolved")/$_exec_link")
  411. fi
  412. _exec_depth=$((_exec_depth - 1))
  413. done
  414. if [[ -L "$exec_resolved" ]]; then
  415. echo "BLOCKED: Script symlink chain too deep or circular at '$exec_resolved'. Ask user for explicit permission." >&2
  416. exit 2
  417. fi
  418. # Narrow, explicit exception: Claude Code skill helper scripts under
  419. # ~/.claude/skills/ are execute-only exempt (never create/write - the
  420. # Write/Edit/MultiEdit hooks below still block writes outside
  421. # PROJECT_DIR, so nothing new can land here through Claude's own tool
  422. # calls). User-requested to unblock trusted, already-installed skill
  423. # scripts (e.g. reader-knowledge-audit's render-report.py, the
  424. # rka-loop arm/disarm scripts) without opening execute for arbitrary
  425. # outside-project paths.
  426. if [[ "$exec_resolved" == "$_ALLOWLIST_HOME/.claude/skills/"* && ( "$exec_resolved" == *.py || "$exec_resolved" == *.sh ) ]]; then
  427. : # allowed - see comment above
  428. elif [[ "$exec_resolved/" != "$PROJECT_DIR/"* ]]; then
  429. echo "BLOCKED: Executing script '$exec_resolved' is OUTSIDE project directory '$PROJECT_DIR'. Allowlist does not cover execute. Ask user for explicit permission." >&2
  430. exit 2
  431. fi
  432. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.