Claude Code Security & Best Practices Guide
Claude Code Security & Best Practices Guide
Security is paramount when working with AI tools that can execute commands and modify files. This comprehensive guide covers Claude Code's security features, best practices, and how to use it safely in various environments.
Understanding Claude Code's Security Model
Claude Code implements a multi-layered security approach:
- Permission System: Granular control over tool access
- Environment Isolation: Configurable workspace boundaries
- Audit Trails: Comprehensive logging and monitoring
- Secure Communication: Encrypted API communication
- Configuration Management: Secure credential handling
Permission System Deep Dive
Permission Levels
Claude Code operates on three main permission levels:
Level | Description | Risk | Use Case |
---|---|---|---|
Interactive | Prompt for each operation | Low | Development work |
Allowlist | Pre-approved tools only | Medium | Automation scripts |
Dangerous | Skip all permissions | CRITICAL | Containers only |
Interactive Mode (Recommended)
In interactive mode, Claude asks for permission before each potentially dangerous operation:
# Safe default - prompts for permissions
claude "Help me debug this application"
When Claude prompts: - Read the permission request carefully - Understand what tool will be used - Consider the potential impact - Grant only necessary permissions
Allowlist Mode
Pre-approve specific tools for automated workflows:
# Allow only safe tools
claude --allowedTools "Edit,View" "Review code for security issues"
# Allow specific command scopes
claude --allowedTools "Bash(git:*)" "Analyze git repository"
# Combined permissions
claude --allowedTools "Edit,View,mcp__git__status,mcp__git__log" "Code review session"
Dangerous Mode β οΈ
NEVER use dangerous mode on production systems or systems with important data!
# DANGEROUS - Use only in isolated containers
claude --dangerously-skip-permissions
Safe use cases for dangerous mode: - β Isolated Docker containers - β Disposable virtual machines - β Sandboxed environments - β Test systems with no important data
NEVER use dangerous mode on: - β Production systems - β Shared development machines - β Systems with sensitive data - β Your personal computer
Credential and Secret Management
API Key Security
Your Anthropic API key is the most critical credential to protect:
# β
Good: Environment variable
export ANTHROPIC_API_KEY="sk-your-key-here"
# β Bad: Hardcoded in commands
# claude --api-key "sk-your-key-here" "query"
# β
Good: Secure file permissions
chmod 600 ~/.bashrc # Make sure only you can read environment files
Configuration File Security
Protect your Claude Code configuration:
# Set proper file permissions
chmod 600 ~/.claude.json
# Check current permissions
ls -la ~/.claude.json
# Example output: -rw------- (only owner can read/write)
Environment Variable Best Practices
# β
Use environment variables for all secrets
export GITHUB_TOKEN="your-token"
export DATABASE_URL="postgresql://user:pass@host/db"
export API_SECRET="your-secret"
# β
Use separate environments for different contexts
# Development
export ANTHROPIC_API_KEY="sk-dev-key"
# Production
export ANTHROPIC_API_KEY="sk-prod-key"
# β Never hardcode secrets in configuration files
Secure Configuration Practices
Hierarchical Configuration
Use Claude Code's configuration hierarchy for security:
# 1. Global settings (least specific)
cat ~/.claude.json
{
"allowedTools": ["View"],
"disallowedTools": ["Bash"]
}
# 2. Project settings (more specific)
cat ./settings.json
{
"allowedTools": ["Edit", "View", "Bash(git:*)"],
"systemPrompt": "You are working on a secure application"
}
# 3. Command-line flags (most specific)
claude --allowedTools "View" "Analyze code for vulnerabilities"
Secure MCP Configuration
When configuring MCP servers, follow these security practices:
{
"mcpServers": {
"database": {
"command": "postgres-mcp-server",
"env": {
"POSTGRES_URL": "${DATABASE_URL}", // β
Environment variable
"POSTGRES_SSL": "require" // β
Force SSL
}
},
"github": {
"command": "github-mcp-server",
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}", // β
Environment variable
"GITHUB_ORG": "your-secure-org" // β
Limit scope
}
}
}
}
Network Security
Configure Claude Code for secure network access:
# Corporate proxy settings
export HTTP_PROXY="http://proxy.company.com:8080"
export HTTPS_PROXY="https://proxy.company.com:8443"
export NO_PROXY="localhost,127.0.0.1,*.company.com"
# Custom API endpoint (if using private deployment)
export ANTHROPIC_BASE_URL="https://your-private-endpoint.com"
# SSL verification (in corporate environments)
export NODE_TLS_REJECT_UNAUTHORIZED=1 # Keep SSL verification enabled
Workspace Security
Directory Isolation
Control which directories Claude Code can access:
# β
Limit to specific directories
claude --add-dir ./src ./tests "Review application code"
# β
Project-specific workspace
cd /path/to/project
claude "Work on this project only"
# β Avoid working from sensitive directories
# cd /etc && claude "help configure system" # DON'T DO THIS
File Permission Patterns
# β
Good: Specific tool permissions
claude --allowedTools "Edit(*.py),View(*.py)" "Work on Python files"
# β
Good: Scope-limited bash access
claude --allowedTools "Bash(git:*),Bash(npm:test)" "Development workflow"
# β Avoid: Broad bash access
# claude --allowedTools "Bash" "help with development"
Monitoring and Auditing
Logging Best Practices
Enable comprehensive logging for security monitoring:
# Enable verbose logging
claude --verbose "Start development session"
# Log to file for audit purposes
claude --verbose "Development session" 2>&1 | tee claude-session.log
# Monitor API calls
export ANTHROPIC_LOG_LEVEL=debug
claude "Analyze application security"
Session Tracking
Track and manage Claude Code sessions:
# List all sessions
claude sessions list
# Review session history
claude sessions export session-id > session-audit.json
# Clean up old sessions
claude sessions clear --before "30 days ago"
Cost Monitoring
Monitor API usage to detect unusual activity:
# Check current session costs
claude /cost
# Monitor token usage
claude /status
# Set up cost alerts (in production environments)
export MAX_SESSION_COST=10.00 # Example cost limit
Secure Development Workflows
Code Review Workflow
Secure approach to code review:
# β
Safe: Review only, no modifications
claude --allowedTools "View,mcp__git__*" "Review latest commits for security issues"
# β
Safe: Limited edit permissions
claude --allowedTools "Edit(*.md),View" "Update documentation"
# β οΈ Caution: Full edit access
claude --allowedTools "Edit,View" "Implement security fix"
Database Operations
Secure database interactions:
# β
Safe: Read-only database access
claude --allowedTools "mcp__postgres__query" "Analyze user data trends"
# β οΈ Caution: Limited write access
claude --allowedTools "mcp__postgres__query,mcp__postgres__insert" "Add test data"
# β Dangerous: Full database access
# claude --allowedTools "mcp__postgres__*" "Fix database issues"
Infrastructure Management
Secure infrastructure operations:
# β
Safe: Status checks only
claude --allowedTools "View,Bash(kubectl:get)" "Check cluster status"
# β οΈ Caution: Limited deployment access
claude --allowedTools "Bash(kubectl:apply),Bash(kubectl:rollout)" "Deploy application"
# β Never: Full infrastructure access
# claude --allowedTools "Bash" "Fix production issues"
Environment-Specific Security
Development Environment
# Relaxed permissions for development
claude --allowedTools "Edit,View,Bash(git:*),Bash(npm:*)" \
--add-dir ./src ./test ./docs \
"Development session"
# Project memory for context
claude /memory set "Development environment - be helpful but cautious"
Staging Environment
# More restrictive for staging
claude --allowedTools "View,Bash(git:status),Bash(git:log)" \
"Analyze staging deployment"
# Read-only database access
claude --allowedTools "mcp__postgres__query" \
"Check staging data integrity"
Production Environment
# Minimal permissions for production
claude --allowedTools "View" \
"Analyze production logs for errors"
# No file editing in production
claude --disallowedTools "Edit,Bash" \
"Production analysis session"
Security Incident Response
Compromised API Key
If your API key is compromised:
- Immediately revoke the key in Anthropic Console
- Generate a new API key
- Update environment variables
- Review recent API usage for unauthorized activity
- Audit Claude Code sessions for suspicious activity
# Check recent sessions
claude sessions list
# Export session for analysis
claude sessions export suspicious-session-id > incident-analysis.json
# Clear all sessions
claude sessions clear --all
Unauthorized File Access
If Claude Code accessed sensitive files:
- Stop the current session immediately
- Review session logs to understand what was accessed
- Change any exposed credentials
- Audit file permissions
- Implement stricter allowedTools policies
# Stop current session
claude /exit
# Review what happened
tail -100 claude-session.log
# Implement stricter permissions
claude config set allowedTools '["View"]'
MCP Server Compromise
If an MCP server is compromised:
- Disable the affected MCP server
- Review server logs
- Update server to latest version
- Rotate any credentials used by the server
- Re-enable with minimal permissions
# Disable MCP server
claude mcp remove compromised-server
# Check server status
claude mcp status
# Review configuration
claude config get mcpServers
Security Checklist
Daily Use Checklist
- Use specific, minimal permissions for each task
- Avoid dangerous mode on important systems
- Keep API keys secure in environment variables
- Review permission prompts before granting access
- Monitor session costs and usage
- Use project-specific configurations
Weekly Security Review
- Audit session history
- Review and clean up old sessions
- Check for Claude Code updates
- Review MCP server configurations
- Verify file permissions on configuration files
- Monitor API key usage patterns
Monthly Security Maintenance
- Rotate API keys
- Update MCP servers to latest versions
- Review and update allowedTools configurations
- Audit project memory files
- Clean up unused MCP servers
- Review corporate security policies compliance
Common Security Pitfalls
What NOT to Do
# β Never use dangerous mode on production
claude --dangerously-skip-permissions "fix production bug"
# β Never hardcode secrets
claude --env "API_KEY=secret123" "deploy application"
# β Never grant overly broad permissions
claude --allowedTools "Bash" "help with anything"
# β Never ignore permission prompts
# Always read and understand what Claude wants to do
# β Never use Claude Code with elevated privileges unnecessarily
sudo claude "fix system configuration" # Usually unnecessary and dangerous
Security Anti-Patterns
- Blanket permissions: Granting all tools access without consideration
- Credential exposure: Putting secrets in command line arguments
- Privilege escalation: Running Claude Code with unnecessary sudo
- Production experimentation: Testing in production environments
- Ignored warnings: Dismissing security prompts without reading
Advanced Security Configuration
Enterprise Security
For enterprise environments:
# Centralized configuration management
export CLAUDE_CONFIG_URL="https://internal.company.com/claude-config"
# Audit logging
export CLAUDE_AUDIT_LOG="/var/log/claude/audit.log"
# Network restrictions
export ANTHROPIC_BASE_URL="https://proxy.company.com/anthropic"
# Compliance mode
export CLAUDE_COMPLIANCE_MODE="SOC2"
Container Security
For containerized Claude Code:
# Dockerfile for secure Claude Code container
FROM node:18-alpine
# Create non-root user
RUN addgroup -g 1001 claude && adduser -D -u 1001 -G claude claude
# Install Claude Code
RUN npm install -g @anthropic-ai/claude-code
# Switch to non-root user
USER claude
# Set secure working directory
WORKDIR /workspace
# Default to safe mode
CMD ["claude", "--allowedTools", "View"]
Conclusion
Security in Claude Code is about balancing functionality with safety. Start with minimal permissions and gradually expand access as needed. Always consider the potential impact of granting permissions, and never use dangerous mode on systems with important data.
Remember: - Default to restrictive permissions - Use environment variables for secrets - Monitor and audit regularly - Keep configurations up to date - Follow the principle of least privilege
By following these security practices, you can safely harness the power of Claude Code while protecting your systems and data from potential risks.
Security Resources
- Anthropic Security Documentation
- Claude Code Security Best Practices
- MCP Security Guidelines
- API Key Management
Stay security-conscious, and Claude Code will be a powerful and safe addition to your development toolkit.