Complete Claude Code Guide: From Installation to Advanced Usage

Complete Claude Code Guide: From Installation to Advanced Usage

A comprehensive tutorial covering everything you need to know about Claude Code - from basic installation and setup to advanced features like MCP integration, automation, and security best practices.

Lesson 4 2025-07-03 08:03

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:

  1. Permission System: Granular control over tool access
  2. Environment Isolation: Configurable workspace boundaries
  3. Audit Trails: Comprehensive logging and monitoring
  4. Secure Communication: Encrypted API communication
  5. 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

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:

  1. Immediately revoke the key in Anthropic Console
  2. Generate a new API key
  3. Update environment variables
  4. Review recent API usage for unauthorized activity
  5. 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:

  1. Stop the current session immediately
  2. Review session logs to understand what was accessed
  3. Change any exposed credentials
  4. Audit file permissions
  5. 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:

  1. Disable the affected MCP server
  2. Review server logs
  3. Update server to latest version
  4. Rotate any credentials used by the server
  5. 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

  1. Blanket permissions: Granting all tools access without consideration
  2. Credential exposure: Putting secrets in command line arguments
  3. Privilege escalation: Running Claude Code with unnecessary sudo
  4. Production experimentation: Testing in production environments
  5. 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

Stay security-conscious, and Claude Code will be a powerful and safe addition to your development toolkit.