Block Bash Commands That Echo Environment Variables

A surprising number of secret leaks happen because an agent runs `env` or `printenv` while debugging a config issue — not maliciously, just reflexively — and every loaded credential ends up verbatim in the transcript. This blocks the handful of commands that dump the full environment.

Secrets & Credentials Event: PreToolUse Claude Code Open source · Free

1. Save this as the hook script

#!/usr/bin/env python3
"""PreToolUse hook — blocks commands that dump the full environment.
Wire this to the Bash matcher."""
import json, re, sys

data = json.load(sys.stdin)
command = (data.get("tool_input") or {}).get("command", "")

DUMP_PATTERNS = [r"^\s*env\s*$", r"^\s*printenv\s*$", r"export\s*$", r"set\s+-o\s+posix"]

if any(re.search(p, command) for p in DUMP_PATTERNS):
    print("BLOCKED: this command dumps the full environment to stdout, which "
          "would echo every loaded secret into the transcript.", file=sys.stderr)
    print("Use `env | grep <specific var>` instead.", file=sys.stderr)
    sys.exit(2)

sys.exit(0)

Save to a path inside your project, e.g. .claude/hooks/block-env-var-echo.sh, then chmod +x it.

2. Wire it into .claude/settings.json

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {"type": "command", "command": "python3 .claude/hooks/block-env-var-echo.py"}
        ]
      }
    ]
  }
}

Before you use this

A hook runs with your local shell's permissions — review the script above before adding it, the same way you'd review any script you didn't write yourself. See our guide on hook security risks for the specific CVEs this category of feature has already produced.

Related hooks

← All hooks
FEEDBACK