Block Reads of Credential Files

Runs before the Read tool executes. If the target path matches a known credential-file shape — .env, id_rsa/id_ed25519, .pem, credentials.json, a service-account key, anything under .ssh/ — it blocks the read outright. Useful as a backstop against a prompt-injected instruction trying to get the agent to paste a secret into its own context or a tool call.

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

1. Save this as the hook script

#!/usr/bin/env python3
"""PreToolUse hook — blocks the agent from reading known credential files.
Wire this to the Read matcher. Edit BLOCKED_PATTERNS for your own project's secret locations."""
import json, re, sys

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

BLOCKED_PATTERNS = [
    r"\.env($|\.)", r"id_rsa$", r"id_ed25519$", r"\.pem$",
    r"credentials\.json$", r"service-account.*\.json$",
    r"\.aws/credentials$", r"\.ssh/", r"api[-_]?token.*\.json$",
]

for pattern in BLOCKED_PATTERNS:
    if re.search(pattern, path, re.IGNORECASE):
        print(f"BLOCKED: {path} matches a credential-file pattern ({pattern}).", file=sys.stderr)
        print("If this file genuinely needs to be read this session, remove it from BLOCKED_PATTERNS.", file=sys.stderr)
        sys.exit(2)

sys.exit(0)

Save to a path inside your project, e.g. .claude/hooks/block-credential-file-reads.sh, then chmod +x it.

2. Wire it into .claude/settings.json

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Read",
        "hooks": [
          {"type": "command", "command": "python3 .claude/hooks/block-credential-file-reads.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