enterprise-security
Enterprise-grade security patterns for Claude Code — audit logging, compliance frameworks, secrets management, permission hardening, network security, and managed settings enforcement
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]'; thRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.