Claude
Skills
Sign in
Back

enterprise-security

Included with Lifetime
$97 forever

Enterprise-grade security patterns for Claude Code — audit logging, compliance frameworks, secrets management, permission hardening, network security, and managed settings enforcement

AI Agents

What this skill does


# Enterprise Security Patterns for Claude Code

Production-grade security architecture for Claude Code deployments with compliance, audit, and policy enforcement.

## Permission Hardening by Role

### Developer (Restricted Privileges)

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Edit",
      "Bash(npm test)",
      "Bash(npm run dev)",
      "Bash(git status)",
      "Bash(git diff)",
      "Bash(git log)"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)",
      "Bash(chmod 777 *)",
      "Write",
      "WebFetch",
      "WebSearch"
    ]
  }
}
```

### Code Reviewer (Read-Heavy)

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Bash(git log *)",
      "Bash(git show *)",
      "Bash(git diff *)"
    ],
    "deny": [
      "Write",
      "Edit",
      "Bash(git commit *)",
      "Bash(git push *)",
      "Bash(git rebase *)"
    ]
  }
}
```

### Administrator (Full Access with Audit)

```json
{
  "permissions": {
    "allow": [
      "Read",
      "Write",
      "Edit",
      "Glob",
      "Grep",
      "Bash(*)",
      "Agent",
      "WebFetch"
    ]
  },
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "bash /opt/audit/admin-audit-log.sh"
          }
        ]
      }
    ]
  }
}
```

## Secrets Management

### Preventing Credential Exposure

PreToolUse hook to block access to credential files:

```bash
#!/bin/bash
# name: block-credential-files.sh
# Prevent Claude from reading .env, .pem, .key, .secret files

INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.tool_name' 2>/dev/null)
PATH_ARG=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""' 2>/dev/null)

# List of blocked patterns
BLOCKED_PATTERNS=(
  '\.env'
  '\.env\..*'
  '\.pem$'
  '\.key$'
  '\.secret$'
  '\.jks$'
  'credentials\.json'
  'service-account\.json'
  'firebase-key\.json'
  '/vault/'
  '/secrets/'
  '/private/'
)

# Check each pattern
for pattern in "${BLOCKED_PATTERNS[@]}"; do
  if echo "$PATH_ARG" | grep -qE "$pattern"; then
    echo '{
      "decision": "deny",
      "reason": "Access to credential files is blocked",
      "blocked_pattern": "'$pattern'"
    }'
    exit 0
  fi
done

echo '{"decision": "approve"}'
```

### Vault Integration Pattern

For HashiCorp Vault:

```bash
#!/bin/bash
# name: vault-credential-retrieval.sh
# Fetch credentials from Vault instead of storing locally

SECRET_NAME=$1
VAULT_ADDR=${VAULT_ADDR:-"https://vault.internal:8200"}
VAULT_TOKEN=${VAULT_TOKEN:-}

if [ -z "$VAULT_TOKEN" ]; then
  echo '{"error": "VAULT_TOKEN not set"}'
  exit 1
fi

curl -s \
  -H "X-Vault-Token: $VAULT_TOKEN" \
  "$VAULT_ADDR/v1/secret/data/$SECRET_NAME" | jq -r '.data.data'
```

### AWS Secrets Manager Pattern

```bash
#!/bin/bash
# name: aws-secrets-retrieval.sh

SECRET_NAME=$1
REGION=${AWS_REGION:-us-east-1}

aws secretsmanager get-secret-value \
  --secret-id "$SECRET_NAME" \
  --region "$REGION" \
  --query 'SecretString' \
  --output text 2>/dev/null
```

### Git Hook to Prevent Secret Commits

```bash
#!/bin/bash
# name: pre-commit-secret-scan.sh
# Placed in .git/hooks/pre-commit

# Patterns that suggest credentials
PATTERNS=(
  'PRIVATE.*KEY'
  'PASSWORD.*='
  'APIKEY'
  'api.key'
  'secret_access_key'
  'aws_secret'
  'postgresql://.*:.*@'
  'mongodb+srv://.*:.*@'
)

EXIT_CODE=0

for file in $(git diff --cached --name-only); do
  for pattern in "${PATTERNS[@]}"; do
    if git diff --cached "$file" | grep -qiE "$pattern"; then
      echo "ERROR: Potential secret detected in $file (pattern: $pattern)"
      EXIT_CODE=1
    fi
  done
done

exit $EXIT_CODE
```

## Audit Logging

### Comprehensive Audit Trail Hook

```bash
#!/bin/bash
# name: audit-trail.sh
# PostToolUse hook: log all tool usage with context

INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.tool_name' 2>/dev/null)
RESULT=$(echo "$INPUT" | jq -r '.tool_result' 2>/dev/null)
USER=${CLAUDE_USER:-"unknown"}
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
AUDIT_LOG="/var/log/claude-code/audit.log"

# Truncate output for logging (first 200 chars)
RESULT_SUMMARY=$(echo "$RESULT" | head -c 200)
INPUT_SUMMARY=$(echo "$INPUT" | jq -r '.tool_input | @json' 2>/dev/null | head -c 200)

# Append to audit log with atomic write
{
  flock -x 200
  echo "{
    \"timestamp\": \"$TIMESTAMP\",
    \"user\": \"$USER\",
    \"tool\": \"$TOOL\",
    \"input_summary\": \"$INPUT_SUMMARY\",
    \"output_length\": $(echo "$RESULT" | wc -c),
    \"status\": \"success\"
  }" >> "$AUDIT_LOG"
} 200>"/var/log/claude-code/audit.log.lock"

# Also log file modifications
if [[ "$TOOL" == "Write" ]] || [[ "$TOOL" == "Edit" ]]; then
  FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""')
  echo "{
    \"timestamp\": \"$TIMESTAMP\",
    \"user\": \"$USER\",
    \"action\": \"file_modified\",
    \"file\": \"$FILE_PATH\",
    \"tool\": \"$TOOL\"
  }" >> "/var/log/claude-code/file-changes.log"
fi
```

### Log Rotation Configuration

```bash
#!/bin/bash
# name: setup-audit-log-rotation.sh
# Configure logrotate for Claude Code audit trails

cat > /etc/logrotate.d/claude-code << 'EOF'
/var/log/claude-code/*.log {
  daily
  rotate 90
  compress
  delaycompress
  missingok
  notifempty
  create 0600 root root
  sharedscripts
  postrotate
    # Notify SIEM or archival system
    /opt/claude-code/archive-audit-logs.sh
  endscript
}
EOF

chmod 644 /etc/logrotate.d/claude-code
```

## SOC2 Compliance Mapping

### CC-6.1 Logical Access Control

**Control:** Restrict access to systems and data.

**Implementation:**
- Permission modes (plan, default, acceptEdits) limit tool access
- Allow/deny lists in settings.json prevent unauthorized tool use
- Managed settings prevent user override
- Pre-commit hooks block credential commits

**Evidence Collection:**
```bash
# Audit: Current permissions configuration
grep -r "permissions" ~/.claude/settings.json

# Audit: Session permission changes
grep "permission_mode" /var/log/claude-code/audit.log

# Audit: Denied tool uses
grep '"decision": "deny"' /var/log/claude-code/audit.log | wc -l
```

### CC-7.1 System Monitoring and Anomaly Detection

**Control:** Monitor activity for anomalies.

**Implementation:**
- PostToolUse hooks capture all tool calls with timestamps
- File change tracking logs modifications with user
- Login events tracked via forceLoginMethod
- Cost tracking detects unusual API usage patterns

**Evidence Collection:**
```bash
# Daily activity summary
awk '$tool == "Bash(rm*)" {rm_count++} END {
  print "Dangerous Bash uses: " rm_count
}' /var/log/claude-code/audit.log

# User activity timeline
grep '"user":' /var/log/claude-code/audit.log | \
  jq -s 'group_by(.user) |
         map({user: .[0].user, count: length})'
```

### CC-8.1 Change Management

**Control:** Authorize and document changes.

**Implementation:**
- Git hooks require pre-commit message format
- File modification audit trail (tool, user, timestamp)
- Pre-push hooks verify branch protection
- PostToolUse hooks log all code changes

**Evidence Collection:**
```bash
# Git change log with user and timestamp
git log --pretty=format:"%h %an %ad %s" --date=short

# Files modified in past 30 days
find . -mtime -30 -type f | xargs ls -lt | head -20
```

## HIPAA Compliance Template

Protected Health Information (PHI) prevention hooks:

```bash
#!/bin/bash
# name: hipaa-phi-guard.sh
# PreToolUse: Block tools that could expose PHI

INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.tool_name' 2>/dev/null)

# Reject tools that could output to insecure locations
case "$TOOL" in
  WebFetch|WebSearch)
    echo '{"decision": "deny", "reason": "WebFetch/WebSearch blocked in HIPAA environment"}'
    exit 0
    ;;
  Bash)
    CMD=$(echo "$INPUT" | jq -r '.tool_input.command' 2>/dev/null)
    # Block commands that might exfiltrate data
    if echo "$CMD" | grep -qE '(curl|wget|scp|rsync|nc).*[^127\.0\.0\.1]'; th

Related in AI Agents