Skip to main content

20 - Security and Privacy with Claude Code

Security and Privacy with Claude Code: AI adoption in software development raises fundamental questions about data security and privacy. Learn best practices for implementing secure AI workflows.

What do you think about this article?

At a Glance

Security and Privacy with Claude Code: AI adoption in software development raises fundamental questions about data security and privacy. Learn best practices for implementing secure AI workflows.

Security and Privacy with Claude Code

Adopting AI tools in software development raises fundamental questions about data security and privacy. When an AI agent has access to source code, configuration files, and potentially secrets like API keys and credentials, security becomes an absolute priority. In this article we will examine in depth the security architecture of Claude Code, Anthropic's certifications, the granular permission system, and the best practices for secure AI-assisted development.

Security is not optional or an afterthought: it is a design principle integrated into every aspect of Claude Code, from data transmission to permission management, from information retention to content exclusion policies.

What You'll Learn

  • Anthropic's security certifications (SOC 2 Type 2, ISO 27001)
  • Claude Code's permission system: read-only, allow, deny
  • How data transmission and retention work
  • Best practices for protecting secrets and credentials
  • Sensitive content exclusion patterns
  • Security configuration at enterprise, project, and user level
  • Audit logging and compliance for regulated environments
  • The OWASP Top 10 vulnerabilities to check in generated code

Series Overview

#ArticleFocus
1Claude as Technical PartnerSetup and first steps
2Context and Project SetupCLAUDE.md and configuration
3Ideation and RequirementsMVP and user personas
4Backend and Frontend ArchitectureSpring Boot and Angular
5Code StructureOrganization and conventions
6Advanced Prompt EngineeringAdvanced techniques
7Testing and QualityStrategies and test generation
8Professional DocumentationREADME, API, ADR
9Deploy and DevOpsDocker, CI/CD, monitoring
10Evolution and MaintenanceRefactoring and scalability
11Real Project IntegrationClaude Code in production
12Claude Code CLI Deep DiveAdvanced commands and workflows
13Agent SkillsAutomation with custom commands
14Specialized SubagentsDelegating tasks to sub-agents
15Hooks and AutomationEvent-driven automation
16The Ralph Wiggum MethodAdvanced prompt chaining
17The BMAD MethodStructured project management
18Multi-Agent OrchestrationParallel and coordinated agents
19Claude Cowork for Knowledge WorkersAI for non-developers
20Security and Privacy (you are here)Data protection and compliance
21Monitoring and ProductivityMetrics and optimization

1. Anthropic's Certifications and Compliance

The security of an AI tool starts with the security of the organization that develops it. Anthropic has invested significantly in certifications and independent security audits to assure its users that data is handled with the highest protection standards.

Anthropic Security Certifications

CertificationDescriptionWhat It Guarantees
SOC 2 Type 2 Independent audit of security controls Security, availability, processing integrity, confidentiality, and data privacy
ISO 27001 International standard for information security management Certified Information Security Management System (ISMS)
Third-party audits Regular reviews by independent security firms Continuous validation of security practices
Bug Bounty Program Reward program for reported vulnerabilities Proactive identification of security flaws

SOC 2 Type 2: What It Means

The SOC 2 Type 2 (Service Organization Control) certification is one of the most rigorous security standards for technology companies. Unlike Type 1, which evaluates controls at a single point in time, Type 2 evaluates the effectiveness of controls over an extended period (typically 6-12 months). This means an independent auditor has verified that Anthropic's security controls not only exist, but function effectively over time.

The 5 SOC 2 Trust Services Principles

  • Security: Systems are protected from unauthorized access, both physical and logical
  • Availability: Systems are available for use as agreed upon
  • Processing Integrity: Data processing is complete, accurate, timely, and authorized
  • Confidentiality: Information designated as confidential is protected as agreed
  • Privacy: Personal information is collected, used, stored, disclosed, and disposed of according to the privacy notice

ISO 27001: Information Security Framework

The ISO 27001 certification attests that Anthropic has implemented an Information Security Management System (ISMS) compliant with international standards. This framework includes policies, procedures, and controls for the systematic management of information security, covering aspects such as risk management, access control, encryption, physical security, and incident management.

2. Claude Code's Permission System

Claude Code's permission system follows the Principle of Least Privilege. By default, Claude Code operates in read-only mode and requires explicit user authorization before any operation that modifies the filesystem or executes commands.

Permission Levels

Permission Hierarchy in Claude Code

LevelOperationsDefault Behavior
Read-Only Read files, analyze code, navigate directories Always allowed (no confirmation required)
Write Create files, modify existing files, delete files Requires explicit user confirmation
Execute Run shell commands, scripts, build tools Requires explicit user confirmation
Network HTTP calls, connections to external services Requires explicit user confirmation
MCP Invoke tools on configured MCP servers Requires confirmation, configurable trust per server

Permission Configuration

Permissions can be configured at three levels, with a well-defined precedence hierarchy. More restrictive configurations always take precedence over more permissive ones, ensuring that enterprise security policies cannot be bypassed by project or user configurations.

User-level permission configuration
// ~/.claude/settings.json - Global user settings
{
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "LS"
    ],
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)",
      "Bash(chmod 777 *)",
      "Bash(curl * | bash)",
      "Bash(wget * | sh)"
    ],
    "auto_approve": [
      "Write(src/**/*.ts)",
      "Write(src/**/*.html)",
      "Write(src/**/*.css)",
      "Bash(npm test)",
      "Bash(npm run lint)",
      "Bash(npm run build)"
    ]
  },
  "mcp": {
    "trusted_servers": [
      "filesystem",
      "github"
    ],
    "untrusted_behavior": "ask"
  }
}

The Deny List: Absolute Precedence

A fundamental principle of the permission system is that the deny list always has absolute precedence over any other configuration. If an operation is in the deny list, it can never be executed, regardless of the allow list, auto_approve, or user requests. This guarantees an inviolable level of security.

Recommended deny list for security
// Recommended deny list
{
  "permissions": {
    "deny": [
      // Destructive commands
      "Bash(rm -rf /)",
      "Bash(rm -rf ~)",
      "Bash(rm -rf .)",
      "Bash(:(){ :|:& };:)",

      // Privilege escalation
      "Bash(sudo *)",
      "Bash(su *)",
      "Bash(chmod 777 *)",
      "Bash(chown *)",

      // Unverified remote execution
      "Bash(curl * | bash)",
      "Bash(curl * | sh)",
      "Bash(wget * -O - | bash)",
      "Bash(eval $(curl *))",

      // Dangerous network operations
      "Bash(nc -l *)",
      "Bash(ncat *)",
      "Bash(socat *)",

      // System file modification
      "Write(/etc/**)",
      "Write(/usr/**)",
      "Write(/var/**)",
      "Write(~/.ssh/**)",
      "Write(~/.aws/**)",
      "Write(~/.config/gcloud/**)",

      // Access to secrets
      "Read(~/.ssh/id_rsa)",
      "Read(~/.ssh/id_ed25519)",
      "Read(~/.aws/credentials)",
      "Read(**/.env.production)",
      "Read(**/secrets.*)",

      // Git force push
      "Bash(git push --force *)",
      "Bash(git push -f *)",
      "Bash(git reset --hard *)"
    ]
  }
}

Golden Rule of Permissions

The fundamental principle is: when in doubt, deny. It is always better to require an extra confirmation than to allow a potentially dangerous operation. The deny list should contain all the commands that you never want executed, regardless of context.

3. Data Transmission and Retention

Understanding how Claude Code handles data is fundamental to assessing risks and implementing appropriate protection measures. Anthropic has adopted a transparent approach to user data management.

Data Encryption

Data Protection in Transit and at Rest

AspectProtectionDetail
Data in transit TLS 1.3 End-to-end encryption for all client-server communications
Data at rest AES-256 Encryption of data stored in Anthropic systems
Encryption keys Periodic rotation Keys are regularly rotated according to best practices
TLS certificates Certificate pinning Protection against man-in-the-middle attacks

Data Retention

Anthropic implements a well-defined data retention policy. Conversation data with Claude Code is automatically deleted after 90 days. This means that code, prompts, and responses are not retained indefinitely in Anthropic's systems.

Data Retention Policy

  • Conversation data: Automatically deleted after 90 days
  • System logs: Retained for auditing and debugging, anonymized
  • Training data: User data is NOT used for model training (opt-out available)
  • Metadata: Aggregated information for usage metrics, not linkable to individual users

Opt-Out from Training

A crucial aspect for many organizations is the guarantee that their data will not be used to train the model. Anthropic allows users to disable data usage for training through privacy settings. This option is particularly important for those working with proprietary code or confidential data.

Disabling data usage for training
# In Anthropic account settings:
# 1. Go to Settings > Privacy
# 2. Disable "Help improve Claude"
# 3. This disables the use of your data for training

# Verify from the CLI:
claude settings --show privacy
# Output:
# {
#   "data_sharing": {
#     "help_improve_claude": false,
#     "usage_analytics": true,
#     "crash_reports": true
#   }
# }

# To disable everything:
claude settings --set privacy.help_improve_claude false
claude settings --set privacy.usage_analytics false

4. Best Practices for Secure Development with Claude Code

Beyond the security measures implemented by Anthropic, developers must adopt their own best practices to ensure that using Claude Code does not introduce vulnerabilities or expose sensitive data.

4.1 Protecting Secrets

Rule number one is: never include secrets in prompts. API keys, passwords, access tokens, certificates, and any other credentials must never be provided as context to Claude Code, nor included in files accessible to the agent.

Patterns for secret protection
# WRONG: secrets exposed in the prompt
claude "Configure the database with host: db.example.com,
user: admin, password: S3cr3tP@ss!, database: production"

# CORRECT: reference to environment variables
claude "Configure the database using the environment variables
DB_HOST, DB_USER, DB_PASSWORD, DB_NAME that are already set
in the .env file (do not read the .env file, just use the variable names)"

# WRONG: API key in the code
claude "Add the API call with the key sk-1234567890abcdef"

# CORRECT: use placeholders and external configuration
claude "Add the API call reading the key from the
environment variable API_KEY. Never hardcode the key in the source."

4.2 Trusted MCP Servers

MCP servers extend Claude Code's capabilities, but also introduce potential attack vectors. Each MCP server has access to the conversation context and can perform operations on the system. It is essential to enable only MCP servers you trust and verify the source code before installation.

MCP Server Security Checklist

  • Verify the source: Install only MCP servers from verified repositories with a high number of stars and active contributors
  • Read the code: Before installing an MCP server, examine the source code to verify it does not contain malicious operations
  • Principle of least privilege: Configure each MCP server with the minimum permissions necessary for its operation
  • Monitor activities: Enable logging for MCP servers to track executed operations
  • Update regularly: Keep MCP servers up to date to receive security patches
  • Isolate servers: Run MCP servers in isolated environments (containers, sandboxes) when possible
  • Revoke access: Remove MCP servers you no longer use

4.3 Treat AI Output as Unverified

Every line of code generated by Claude Code must be treated as unverified code until proven otherwise. This means applying the same level of scrutiny you would apply to code written by a new team member: code review, automated testing, static analysis, and vulnerability verification.

Verification pipeline for AI-generated code
# AI-generated code verification pipeline

# 1. Automated static analysis
npm run lint                          # ESLint for JavaScript/TypeScript
./mvnw checkstyle:check             # Checkstyle for Java
pylint src/                          # Pylint for Python

# 2. Security scanning
npm audit                            # npm dependency vulnerabilities
./mvnw dependency-check:check       # OWASP Dependency Check
snyk test                            # Snyk vulnerability scan
semgrep --config=auto src/           # Security patterns

# 3. Secrets detection
gitleaks detect                      # Search for secrets in code
trufflehog filesystem --directory=.  # Search for hardcoded credentials

# 4. Automated tests
npm test -- --coverage               # Unit tests with coverage
npm run test:integration             # Integration tests
npm run test:e2e                     # End-to-end tests

# 5. Human code review
# Manual review focusing on:
# - Input validation
# - SQL injection
# - XSS (Cross-Site Scripting)
# - CSRF (Cross-Site Request Forgery)
# - Authentication/Authorization
# - Error handling (no sensitive info in errors)
# - Logging (no secrets in logs)

4.4 Request Secure Defaults

When asking Claude Code to generate code that handles user input, authentication, authorization, or data access, it is important to explicitly request the adoption of secure practices such as input validation, parameterized queries, and output sanitization.

Prompt for secure-by-default code
# Prompt requesting secure defaults
claude "Implement the POST /api/users endpoint with the following
MANDATORY security requirements:

1. Input Validation:
   - Validate all fields with Bean Validation annotations
   - Sanitize input to prevent XSS
   - Limit field lengths (name max 100, email max 254)

2. SQL Injection Prevention:
   - Use ONLY parameterized queries (JPA/Hibernate)
   - NEVER concatenate strings for SQL queries

3. Authentication:
   - Endpoint protected by JWT
   - Verify ADMIN role for user creation

4. Password Security:
   - Hash with bcrypt (min 12 rounds)
   - NEVER log or return the password
   - Complexity validation (min 8 chars, upper, lower, digit, special)

5. Error Handling:
   - Return generic error messages to the user
   - Log technical details only in server logs
   - NEVER expose stack traces or internal details

6. Rate Limiting:
   - Max 10 requests per minute per IP
   - Max 3 creation attempts per account

7. Logging:
   - Log user creation (audit trail)
   - NEVER log sensitive data (passwords, tokens)"

5. OWASP Top 10: Verifying Generated Code

The OWASP Top 10 vulnerabilities represent the most critical security threats for web applications. Every line of code generated by Claude Code that handles user input, authentication, or data access must be verified against these vulnerabilities.

OWASP Top 10 - Verification Checklist

#VulnerabilityWhat to VerifyPrevention
A01 Broken Access Control Authorization checks on every endpoint RBAC, resource ownership verification, deny by default
A02 Cryptographic Failures Use of weak algorithms or sensitive data in clear text AES-256, bcrypt, TLS 1.3, no MD5/SHA1 for passwords
A03 Injection SQL injection, command injection, LDAP injection Parameterized queries, ORM, input validation
A04 Insecure Design Lack of controls at the design level Threat modeling, secure design patterns
A05 Security Misconfiguration Insecure defaults, missing headers, debug enabled Hardening, security headers, disable debug in prod
A06 Vulnerable Components Dependencies with known vulnerabilities npm audit, dependency-check, Snyk
A07 Authentication Failures Brute force, weak sessions, passwords in clear text MFA, rate limiting, secure session management
A08 Software and Data Integrity Insecure CI/CD, unverified updates Digital signatures, integrity verification, secure pipeline
A09 Security Logging Failures Insufficient or absent logging for critical events Audit trail, alerting, tamper-proof logs
A10 Server-Side Request Forgery The application makes requests to user-supplied URLs URL whitelist, input validation, network segmentation

6. Content Exclusion Patterns

Claude Code automatically reads files in the working directory to understand the project context. However, not all files should be accessible to the agent. Files containing secrets, personal data, or proprietary information must be explicitly excluded from Claude Code's context.

The .claudeignore File

Similar to .gitignore, you can create a .claudeignore file in the project root to specify files and directories that Claude Code should not read. The syntax is identical to that of .gitignore.

.claudeignore - Exclusion patterns
# .claudeignore - Files excluded from Claude Code context

# Secrets and credentials
.env
.env.*
*.pem
*.key
*.p12
*.pfx
secrets/
credentials/
**/secrets.*
**/credentials.*

# SSH keys and sensitive configurations
.ssh/
.aws/
.gcloud/
.azure/

# Configuration files with passwords
**/application-prod.yml
**/application-prod.properties
**/database.yml
docker-compose.prod.yml

# Personal data and GDPR
data/users/
data/personal/
exports/pii/
backups/

# Large files (not useful for context)
*.zip
*.tar.gz
*.sql.gz
node_modules/
dist/
build/
target/
.gradle/

# Vendor and dependencies
vendor/
bower_components/

# Logs that might contain sensitive data
logs/
*.log

# Temporary files
tmp/
temp/
.cache/

Enterprise-Level Exclusion

For organizations that want to apply exclusion rules to all projects and all developers, it is possible to configure exclusion patterns at the enterprise level, which cannot be overridden by project or user configurations.

Enterprise configuration for content exclusion
// /etc/claude-code/managed-settings.json
// Enterprise configuration (requires admin privileges)
{
  "content_exclusion": {
    "global_patterns": [
      "**/.env*",
      "**/secrets/**",
      "**/credentials/**",
      "**/*.pem",
      "**/*.key",
      "**/application-prod.*"
    ],
    "enforce": true,
    "override_allowed": false
  },
  "permissions": {
    "deny": [
      "Bash(rm -rf *)",
      "Bash(sudo *)",
      "Bash(git push --force *)",
      "Write(/etc/**)",
      "Write(~/.ssh/**)"
    ],
    "max_auto_approve_scope": "project_only"
  },
  "data_handling": {
    "help_improve_claude": false,
    "log_retention_days": 30,
    "audit_all_operations": true
  }
}

7. Multi-Level Security Configuration

Claude Code supports a three-level hierarchical security configuration: enterprise, project, and user. Each level can add restrictions but cannot relax those imposed by the higher level.

Security Configuration Hierarchy

LevelFileScopePriority
Enterprise /etc/claude-code/managed-settings.json All users on the machine Highest (cannot be overridden)
Project (shared) .claude/settings.json All project developers Medium (committed to the repo)
Project (local) .claude/settings.local.json Only the local developer Medium (not committed)
User ~/.claude/settings.json All user's projects Lowest (overridden by higher levels)
Shared project configuration (.claude/settings.json)
// .claude/settings.json - Committed to the repository
// Shared among all team developers
{
  "project": {
    "name": "MyApp",
    "description": "Enterprise web application"
  },
  "permissions": {
    "allow": [
      "Read",
      "Glob",
      "Grep",
      "Write(src/**)",
      "Write(tests/**)",
      "Write(docs/**)",
      "Bash(npm *)",
      "Bash(npx *)",
      "Bash(git *)"
    ],
    "deny": [
      "Write(.env*)",
      "Write(**/secrets/**)",
      "Read(.env.production)",
      "Bash(rm -rf *)",
      "Bash(sudo *)",
      "Bash(git push --force *)",
      "Bash(docker run --privileged *)",
      "Bash(npm publish)"
    ],
    "auto_approve": [
      "Read",
      "Glob",
      "Grep",
      "Bash(npm test)",
      "Bash(npm run lint)",
      "Bash(npm run build)"
    ]
  },
  "content_exclusion": [
    ".env*",
    "secrets/",
    "*.key",
    "*.pem",
    "docker-compose.prod.yml"
  ]
}

8. Audit Logging and Compliance

For organizations subject to compliance requirements (SOX, HIPAA, GDPR, PCI DSS), it is essential to maintain a complete audit trail of all operations performed by Claude Code. Audit logging allows tracking who did what, when, and on which files.

Enabling audit logging
// Audit logging configuration
// ~/.claude/settings.json
{
  "audit": {
    "enabled": true,
    "log_directory": "~/.claude/audit-logs/",
    "log_level": "detailed",
    "events": [
      "file_read",
      "file_write",
      "file_delete",
      "command_execute",
      "mcp_tool_invoke",
      "permission_request",
      "permission_granted",
      "permission_denied",
      "session_start",
      "session_end"
    ],
    "retention_days": 365,
    "format": "json"
  }
}

# Example audit log entry:
# {
#   "timestamp": "2026-02-14T10:23:45.123Z",
#   "session_id": "sess_abc123",
#   "user": "developer@company.com",
#   "event": "file_write",
#   "details": {
#     "file": "src/app/services/user.service.ts",
#     "operation": "modify",
#     "lines_changed": 15,
#     "permission": "auto_approved"
#   }
# }

Compliance Requirements for Regulatory Frameworks

FrameworkRequirementHow Claude Code Meets It
GDPR Right to data deletion 90-day retention, training opt-out, data deletion on request
SOX Audit trail for changes to financial systems Complete audit logging with timestamp and user
HIPAA Health data protection Content exclusion for files with PHI, TLS 1.3 encryption
PCI DSS Credit card data protection Deny list for files with PAN, audit logging, access control
ISO 27001 Documented ISMS Hierarchical configuration, enforceable policies, audit trail

9. Considerations for Enterprise Environments

Adopting Claude Code in enterprise contexts requires additional considerations compared to individual use. Organizations must balance productivity benefits with security, governance, and compliance requirements.

Enterprise Security Checklist

  • AI governance policy: Define a corporate policy on the use of AI tools in development, including guidelines on which data can be shared and which cannot
  • Data classification: Implement a classification system (public, internal, confidential, secret) and define exclusion rules for each level
  • Network segmentation: Isolate development environments using Claude Code from the production network with sensitive data
  • Developer training: Train developers on security best practices specific to AI-assisted development
  • Review process: Implement a mandatory code review process for all AI-generated code before merging
  • Incident response: Integrate Claude Code events into the corporate incident response plan
  • Vendor risk assessment: Conduct a risk assessment specific to adopting Anthropic as a vendor
  • Contracts and SLAs: Verify Anthropic's contractual terms regarding data management and liability

Secure Team Deployment

Recommended configuration for enterprise teams
# Setup script for a new developer on the team
#!/bin/bash
# setup-claude-security.sh

echo "Configuring Claude Code security for the team..."

# 1. Create configuration directory
mkdir -p ~/.claude

# 2. Copy the team's base configuration
cp /shared/team-config/claude-settings.json ~/.claude/settings.json

# 3. Verify that the deny list is active
echo "Verifying deny list..."
claude settings --show permissions.deny
echo ""

# 4. Verify sensitive content exclusion
echo "Verifying content exclusion..."
claude settings --show content_exclusion
echo ""

# 5. Disable data sharing for training
claude settings --set privacy.help_improve_claude false
echo "Data sharing for training: DISABLED"

# 6. Enable audit logging
claude settings --set audit.enabled true
claude settings --set audit.log_level detailed
echo "Audit logging: ENABLED"

# 7. Configure team-approved MCP servers
echo "Configuring approved MCP servers..."
claude mcp trust github
claude mcp trust filesystem
echo "Only team-approved MCP servers are enabled"

# 8. Verify final configuration
echo ""
echo "=== Configuration Complete ==="
claude settings --show | head -30
echo ""
echo "Remember:"
echo "- NEVER include secrets in prompts"
echo "- Code review ALL generated code"
echo "- Report any anomalous behavior to the security team"

10. Threat Model for AI-Assisted Development

A structured approach to security requires a threat model that identifies the specific threats of using AI in software development. Understanding these threats is the first step to mitigating them effectively.

Threats and Mitigations in AI-Assisted Development

ThreatDescriptionLikelihoodMitigation
Data Leakage Secrets or sensitive data included in prompts High Content exclusion, deny list, team training
Vulnerable Code Generated code with security vulnerabilities Medium Code review, SAST, DAST, security testing
Prompt Injection Malicious input that manipulates AI behavior Low Input validation, output verification, sandbox
Supply Chain Compromised MCP servers or dependencies Low MCP server vetting, dependency scanning, lockfile
Unauthorized Access Compromised Claude account with codebase access Low MFA, session management, audit logging
Over-Reliance Excessive trust in generated code without verification High Mandatory code review, verification culture

Conclusion

Security in AI-assisted development is not a tradeoff with productivity: it is a prerequisite. Claude Code integrates security at every level, from Anthropic's SOC 2 Type 2 and ISO 27001 certifications to the granular permission system with an absolute-precedence deny list.

However, technology alone is not enough. Security is a shared responsibility between Anthropic (which protects the infrastructure and data in transit), the organization (which defines policies and controls), and the individual developer (who adopts best practices daily).

Key Takeaways

  • Certifications: Anthropic is SOC 2 Type 2 and ISO 27001 certified with regular third-party audits
  • Granular permissions: Read-only by default, absolute-precedence deny list, 3-level configuration
  • Protected data: TLS 1.3 in transit, AES-256 at rest, 90-day retention, training opt-out
  • NEVER include secrets in prompts: Use environment variables and references, not direct values
  • Trusted MCP servers: Enable only verified MCP servers with inspected source code
  • Unverified output: Treat all generated code as unverified, apply code review and testing
  • OWASP Top 10: Systematically verify generated code against the 10 most critical vulnerabilities
  • Audit logging: Enable comprehensive logging for compliance and incident response

In the last article of this series, we will explore monitoring and productivity with Claude Code: tools for measuring usage, optimizing costs, and maximizing return on investment.

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects