gstack icon indicating copy to clipboard operation
gstack copied to clipboard

/careful fails open on chained rm: 'rm -rf /; rm -rf node_modules' is silently allowed

Open jbetala7 opened this issue 5 months ago • 3 comments

Summary

The /careful PreToolUse hook (careful/bin/check-careful.sh) fails open on chained rm -r commands: a destructive recursive delete is silently allowed when the command is chained with a second rm that targets a build-artifact directory.

Observed problem

The "safe exception" block (lines 28-48) whitelists rm -rf of build artifacts (node_modules, dist, .next, etc.). It extracts the rm targets with a single greedy expression:

RM_ARGS=$(printf '%s' "$CMD" | sed -E 's/.*rm[[:space:]]+(-[a-zA-Z]+[[:space:]]+)*//;s/--recursive[[:space:]]*//')

.*rm matches greedily, so for a chained command it only ever inspects the targets of the last rm in the string. If that final rm targets a safe directory, the whole command is whitelisted and the hook returns {} (allow) without warning, even though an earlier rm in the chain is destructive.

Current behavior on upstream main (c7ae6320)

$ printf '{"tool_input":{"command":"rm -rf /; rm -rf node_modules"}}' | bash careful/bin/check-careful.sh
{}

No warning. The rm -rf / is waved through because the greedy extraction only sees the trailing node_modules.

Reversing the order (safe rm first, dangerous rm last) correctly warns, which confirms the asymmetry is caused by the last-rm-only extraction:

$ printf '{"tool_input":{"command":"rm -rf node_modules; rm -rf /home/user/data"}}' | bash careful/bin/check-careful.sh
{"permissionDecision":"ask","message":"[careful] Destructive: recursive delete (rm -r). This permanently removes files."}

Expected behavior

Any chained command containing a destructive recursive rm should warn (permissionDecision: "ask"), regardless of where the safe rm sits in the chain. Single-command artifact cleanups (rm -rf node_modules, rm -rf .next dist) should still be allowed.

Candidate fix shape

The target-extraction shortcut is only reliable for a single rm invocation. Gate the safe-exception so it applies only when the command has no shell separator (;, |, &, newline). When a separator is present, fall through to the existing destructive-pattern check, which already warns on any rm -r. This is the fail-safe direction for a guard and preserves the single-command artifact-cleanup convenience.

Duplicate searches performed

  • Open PRs touching careful/bin/check-careful.sh: #1110 (text-output false positives — over-warning, the opposite direction; it splits on &&/|| but turns ; into a space and re-feeds the same greedy safe-exception, so it does not fix this) and #1509 (hook activation gate + hookSpecificOutput shape — does not touch the detection logic).
  • Open issues: #1060 (false positives in commit messages — over-warning), #1091 (broad proposal to add structured execution judgment). Neither covers this fail-open.
  • Verified the bug reproduces on current main (c7ae6320).

jbetala7 avatar Jun 18 '26 09:06 jbetala7

This is a safety parser contract issue.

/careful should not decide safety from a single command fragment if the shell line contains multiple chained commands.

The risky shape is:

rm -rf /; rm -rf node_modules

The guard may see one allowed cleanup pattern and miss another destructive command in the same shell line.

A standard AISP-style contract could express the safety invariant:

[
  {
    "role": "system",
    "content": {
      "protocol": "AISP V1.0.0",
      "axiom_0": "Human_Sovereignty_and_Wellbeing",
      "id": "gstack_careful_shell_command_gate_aisp",
      "name": "gstack /careful Shell Command Gate",
      "version": "1.0.0",
      "license": "MIT",
      "summary": "Machine-checkable contract for parsing and gating chained shell commands before execution.",
      "flow_format": "mermaid",
      "loading_mode": "node",
      "tools": ["shell"],
      "params": {
        "shell_command": "string"
      },
      "system_prompt": ""
    }
  },
  {
    "role": "user",
    "content": {
      "instruction": "STRICTLY OBEY aisp_contract; its non_negotiable rules are inviolable; then RUN aisop.main",
      "user_input": "{user_input}",
      "aisp_contract": {
        "profile": "aisp.skill.v1",
        "invocation": {
          "mode": "pre_tool_safety_gate",
          "when_to_use": [
            "before executing Bash or shell commands under /careful",
            "when command contains ;, &&, ||, pipes, subshells, or command substitutions"
          ],
          "when_not_to_use": [
            "read-only command already classified as safe",
            "commands executed outside /careful policy"
          ]
        },
        "non_negotiable": [
          {
            "rule": "Every command segment in a chained shell line must be parsed and classified.",
            "enforced_by": "parse.step2:sys.assert"
          },
          {
            "rule": "If any segment is destructive, the whole shell line must require confirmation or be blocked.",
            "enforced_by": "gate.step2:sys.assert"
          },
          {
            "rule": "An allowlisted cleanup segment must not mask a separate destructive segment.",
            "enforced_by": "gate.step3:sys.assert"
          }
        ],
        "discovery": {
          "category": "safety_gate",
          "tags": ["gstack", "careful", "shell", "rm-rf", "safety", "aisp"]
        },
        "risk_level": "critical",
        "resources": []
      },
      "aisop": {
        "main": "graph TD\n    parse[Parse shell command into segments] --> classify[Classify every segment]\n    classify --> gate[Apply aggregate safety gate]\n    gate --> decision[Return allow confirm or block]\n    decision --> end_node((End))"
      },
      "functions": {
        "parse": {
          "step1": "Parse shell_command into command segments respecting separators, pipes, subshells, and command substitutions.",
          "step2": "sys.assert('all command segments parsed', 'Chained shell line must be fully parsed')",
          "output_mapping": "command_segments"
        },
        "classify": {
          "step1": "Classify each segment as read_only, routine_cleanup, destructive, credential, network, or unknown.",
          "output_mapping": "segment_classifications"
        },
        "gate": {
          "step1": "Aggregate segment classifications.",
          "step2": "sys.assert('no destructive segment is silently allowed', 'Destructive segment requires confirmation or block')",
          "step3": "sys.assert('allowlisted segment does not hide separate destructive segment', 'Allowlist cannot mask chained destructive command')",
          "output_mapping": "safety_gate_result"
        },
        "decision": {
          "step1": "Return allow, confirm, or block with segment-level explanation.",
          "output_mapping": "careful_decision"
        },
        "end_node": {
          "step1": "Return careful_decision."
        }
      }
    }
  }
]

The minimal fix:

1. Split shell lines into segments before allowlist matching.
2. Classify every segment.
3. If any segment is destructive, require confirmation or block.
4. Add regression tests for:
   - rm -rf node_modules
   - rm -rf /; rm -rf node_modules
   - safe && dangerous
   - dangerous || safe
   - subshell destructive command

The invariant:

/careful must fail closed on chained destructive commands.

optimization2026 avatar Jun 30 '26 06:06 optimization2026

The safe-cleanup exception should be evaluated per parsed command node, not against the whole shell string. Every node in a chain must independently satisfy the allowed cleanup shape; one matching rm must never whitelist sibling commands. Rejecting separators is a useful short-term guard, but parsing failure or unsupported shell syntax should resolve to ask/deny. Regression cases should include logical chains, semicolons, newlines, subshells, substitutions, and redirections.

BGMLAI avatar Jul 14 '26 00:07 BGMLAI

@16francej Please close this issue as resolved. #2264 removed the greedy chained-command parsing that allowed a later destructive rm to be missed. The reported semicolon example is now caught.

time-attack avatar Jul 15 '26 10:07 time-attack