Blog

Claude Code Security: 15 Best Practices

15 Claude Code security controls for devs, teams, and enterprise. .claudeignore, hooks, MCP governance, CI/CD, and executive policy checklist.

Phos Team ·
AI Strategy

Claude Code runs with your user’s permissions. It reads files, executes shell commands, writes to your codebase, and connects to external systems through MCP.

Every one of those capabilities is a potential attack surface when left unconfigured.

Securing Claude Code is not a one-time setup. It is a set of layered controls that compound across your team, your pipelines, and your operations over time.

Key Takeaways

  • Default configuration is not secure configuration: Claude Code’s built-in protections are a starting point, not a finished security posture.
  • Least privilege is the foundational principle: Launch from the smallest possible directory, restrict tools to what the task requires, and start with read-only where possible.
  • .claudeignore must exist before the first session: Create it before any developer runs Claude Code on a project, not after.
  • Hooks are the enforcement layer: CLAUDE.md guidance is advisory. PreToolUse hooks are mandatory.
  • MCP servers are executables: Treat every MCP server installation like adding a dependency to your production system.
  • Claude Code Security (the product) launched February 20, 2026: It reasons about code semantically, not just by pattern matching. It is a supplement to your existing SAST tooling, not a replacement.
  • CI/CD pipelines require specific controls: Automated pipelines that process external input must restrict tool access and never use bypass mode.

What Claude Code security actually means

Claude Code is not a passive suggestion tool. It is an agent with direct access to your development environment: reading your codebase, executing shell commands, writing files, and connecting to internal systems. Securing it requires controls at the environment, configuration, pipeline, and governance layers simultaneously.

The attack surface has three dimensions:

Input surface: Everything Claude reads, including your codebase, README files, config files, dependency documentation, and any content passed in context. Any of these can contain malicious instructions in a prompt injection attack.

Execution surface: Shell commands Claude runs, files it writes and deletes, external services it calls, and MCP servers it connects to. All execute with your user’s permissions by default.

Output surface: Code Claude generates (which may contain vulnerabilities), session logs, context transmitted to Anthropic’s API, and any data passed to MCP servers.


Foundational best practices: every developer

These apply to every developer running Claude Code, regardless of team size or use case. They are non-negotiable prerequisites, not optional enhancements.

1. Always launch from your project directory

Claude Code operates inside the directory where you launch it. Launching from ~/ or / gives Claude access to your entire home directory.

This includes SSH keys, browser credentials, cloud provider configurations, and dotfiles.

Always navigate to your project root before running claude:

cd /path/to/your/project
claude

Never run claude from ~, /, or any directory above your project root.

2. Create .claudeignore before the first session

.claudeignore controls which files Claude Code can read. It uses gitignore syntax. Create it at your project root and commit it to the repository before any developer runs Claude Code.

Minimum required entries:

# Credential files
.env
.env.*
.env.local
.env.staging
.env.production

# Private key material
*.pem
*.key
*.p12
*.pfx

# System credential stores
~/.ssh/
~/.aws/credentials
~/.aws/config
~/.config/

# Application secrets
config/secrets.*
secrets/
.secret

# Token files
*.token
auth.json
credentials.json

Commit this file to the repository. Every developer on the project shares the same file exclusions automatically.

3. Use Plan mode for unfamiliar repositories

Before running Claude Code on any repository you did not write yourself, use Plan mode.

Plan mode allows Claude to read, search, and reason but blocks all file edits, writes, and shell commands.

claude --permission-mode plan

CVE-2025-59536 demonstrated that malicious hooks in a repository’s .claude/settings.json could execute before the user had a chance to read the trust dialog. Plan mode prevents this by blocking all execution.

Use Plan mode by default on any repository from an external source, untrusted contributor, or unfamiliar codebase.

4. Treat bypass mode as a root-level privilege

--dangerously-skip-permissions disables all human review gates. Claude Code executes commands and writes files without asking for approval.

In development, this is a convenience feature. In any context involving untrusted input, it is a serious exposure.

Rules for bypass mode:

  • Never use it in CI/CD pipelines that process external input (pull requests from forks, issue comments, webhooks)
  • Document every use case where it is enabled
  • Restrict it to isolated containers or sandboxed environments
  • Treat authorization to use it like authorization for production database write access

5. Review Claude Code-generated code before merging

Claude Code generates code quickly. Approximately 80 percent of AI-built applications contain at least one exploitable vulnerability at launch.

The patterns are predictable: missing input validation, SQL injection through string concatenation, missing authentication checks on internal endpoints.

Treat all Claude Code output as a first draft from a capable but untrusted contributor. Review every diff before merging. Never approve Claude Code-generated changes because they “look fine” without reading them.


Intermediate best practices: engineering teams

These practices apply when more than one developer uses Claude Code on shared projects. They prevent the most common team-level failures.

6. Commit permission rules to the repository

Security-critical permission rules belong in .claude/settings.json, committed to the repository. Every developer on the project gets the same protections without any individual configuration.

Deny rules every project should have:

{
  "permissions": {
    "deny": [
      "Bash(rm -rf /)",
      "Bash(rm -rf ~)",
      "Bash(rm -rf $HOME)",
      "Bash(git reset --hard origin*)",
      "Bash(git push --force*)",
      "Bash(curl | sh)",
      "Bash(wget | sh)",
      "Bash(cat ~/.ssh/*)",
      "Bash(cat ~/.aws/*)",
      "Bash(cat .env*)",
      "Bash(*prod* DROP TABLE*)",
      "Bash(*prod* TRUNCATE*)"
    ],
    "ask": [
      "Bash(git push*)",
      "Bash(npm publish*)",
      "Bash(*deploy*)",
      "Bash(*migration*)"
    ],
    "allow": [
      "Bash(npm run build)",
      "Bash(npm run test)",
      "Bash(npm run lint)",
      "Bash(git status)",
      "Bash(git diff)"
    ]
  }
}

Rule precedence: Deny overrides Ask, Ask overrides Allow. A command in both Allow and Ask will always trigger a prompt.

7. Configure PreToolUse hooks for shell command validation

Hooks are the enforcement layer. CLAUDE.md guidance is advisory and the model can overlook it.

A PreToolUse hook fires every time the matching tool is called and can block execution before it happens.

Every project running Claude Code in a team environment needs at minimum a danger guard hook.

Create .claude/hooks/danger-guard.sh:

#!/usr/bin/env bash
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

DANGER='(rm -rf /|rm -rf ~|rm -rf \$HOME|git reset --hard origin|git push --force.*main|git push --force.*master|DROP TABLE|TRUNCATE TABLE|curl.*\|.*sh|wget.*\|.*sh)'

if echo "$CMD" | grep -qE "$DANGER"; then
  echo "[danger-guard] BLOCKED: $CMD" >&2
  echo "Run this manually outside Claude Code if you are sure." >&2
  exit 1
fi

exit 0
chmod +x .claude/hooks/danger-guard.sh

Register in .claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": ".claude/hooks/danger-guard.sh" }]
      }
    ]
  }
}

8. Add a PostToolUse command logger

Without logging, you have no audit trail of what Claude Code did in a session. A PostToolUse hook creates a timestamped record of every shell command executed.

Create .claude/hooks/command-logger.sh:

#!/usr/bin/env bash
INPUT=$(cat)
CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
LOG="${CLAUDE_PROJECT_DIR:-.}/.claude/command_log.txt"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $CMD" >> "$LOG"
exit 0

Add .claude/command_log.txt to your .gitignore. Review these logs as part of your regular security review cadence.

9. Audit and govern MCP servers

Every MCP server connected to Claude Code is an executable running with your user’s permissions. Treat MCP server installation with the same scrutiny as adding a production dependency.

MCP governance checklist for teams:

  • Maintain a documented registry of approved MCP servers in CLAUDE.md
  • Require source code review, dependency audit, and network access review before adding any server to the approved list
  • Pin MCP server versions in your configuration
  • Use managed settings to block unapproved MCP servers at the permission level
  • Log all MCP tool calls using a PostToolUse hook with the matcher mcp__*

Specific permission rules for MCP servers in .claude/settings.json:

{
  "permissions": {
    "ask": ["mcp__github__create_pull_request", "mcp__github__push_files"],
    "deny": ["mcp__github__delete_repository"],
    "allow": ["mcp__github__get_file_contents", "mcp__github__list_pull_requests"]
  }
}

10. Scan for secrets before Claude Code accesses your codebase

Run a credential scan before enabling Claude Code access on any repository.

Secrets already present in the codebase flow into Claude’s context window and may appear in outputs or be transmitted to Anthropic’s API.

# Using truffleHog
trufflehog git file://. --only-verified

# Using git-secrets
git secrets --scan

Add a PostToolUse hook to scan newly written files for credential patterns:

#!/usr/bin/env bash
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

if [[ -f "$FILE" ]]; then
  PATTERNS='(AKIA[0-9A-Z]{16}|sk-[a-zA-Z0-9]{32,}|ghp_[a-zA-Z0-9]{36}|-----BEGIN.*PRIVATE KEY)'
  if grep -qE "$PATTERNS" "$FILE" 2>/dev/null; then
    echo "[secret-scan] WARNING: possible credential in $FILE" >&2
    exit 1
  fi
fi
exit 0

Advanced best practices: enterprise deployments

These practices apply to organizations deploying Claude Code across multiple teams, CI/CD pipelines, and regulated environments.

11. Eliminate shared API keys

Shared API keys prevent individual accountability, make cost attribution impossible, and complicate incident response.

When a shared key leaks, you cannot determine who last had access or which systems may also be compromised.

The right model at scale:

  • Route all Claude Code traffic through an AI gateway
  • Developers authenticate to the gateway with their corporate SSO credentials
  • The gateway holds the single API key and provides per-user audit trails
  • No individual developer holds a raw ANTHROPIC_API_KEY

This eliminates the primary API key theft vector: a developer’s key being stolen or accidentally exposed.

12. Use managed settings for team-wide enforcement

Managed settings distribute a centrally controlled settings.json that takes precedence over individual user settings. Security teams can enforce policies that developers cannot override.

Managed settings enable you to:

  • Block --dangerously-skip-permissions across all sessions
  • Enforce deny rules that individual user settings cannot override
  • Require specific hooks to run in every session
  • Route all traffic through an enterprise proxy

For enterprise teams, managed settings combined with OpenTelemetry export covers most SOC 2 and internal audit requirements.

13. Configure CI/CD pipelines with explicit tool restrictions

The June 2026 GitHub Actions CVE demonstrated that Claude Code in automated pipelines creates a specific attack surface.

Automated pipelines that process external input (pull requests from forks, issue comments, webhooks) must apply strict controls.

Required CI/CD configuration:

  • Never enable --dangerously-skip-permissions in any pipeline processing external input
  • Use --allowedTools to explicitly list only the tools the pipeline needs
  • Exclude CI/CD secrets from the context Claude Code can access
  • Sanitize or exclude external contributor input (PR descriptions, issue bodies, comments)
  • Log all tool calls with full parameters for audit review

Example CI/CD invocation:

claude --permission-mode plan \
  --allowedTools "Read,Bash(npm run test),Bash(npm run lint)" \
  --print "Review this PR for security issues"

14. Use sandboxed environments for untrusted code

Anthropic’s own security documentation recommends using virtual machines or containers when running Claude Code against external web services or repositories from untrusted sources.

Practical sandbox configurations:

  • Run Claude Code in Docker containers with no host filesystem mounts beyond the specific project directory
  • Use --network none for sessions that should not make outbound connections
  • Apply macOS Sandbox profiles (available in Claude Code settings) for terminal sessions
  • For CI/CD, run Claude Code in ephemeral environments that are destroyed after each job

15. Implement OpenTelemetry export for audit trails

Claude Code supports OpenTelemetry export for a complete audit trail of tool calls. Configure it to capture every action across developer machines and pipelines.

What to capture and route to your SIEM:

  • All tool calls with full parameters and results
  • Session identifiers linked to individual user accounts via SSO
  • Timing data for cost attribution
  • Error and exception events
  • MCP server interactions with full tool call parameters

For SOC 2-covered environments, tool call logs must be retained and reviewable for the audit period.

OpenTelemetry export plus a PostToolUse command logger together meet most auditor requirements in this control category.


Claude Code Security: the product

On February 20, 2026, Anthropic launched Claude Code Security, a research-preview feature powered by Opus 4.6, rolling out to Team and Enterprise customers.

Claude Code Security is distinct from the /security-review command. /security-review matches code against known vulnerability patterns (SQL injection, XSS, common auth flaws) the way traditional SAST tools do. Claude Code Security reasons semantically: it traces how data moves through an application and how components interact, rather than checking for known-bad signatures.

Anthropic validated over 500 high-severity vulnerabilities across production open-source codebases using Claude Code Security, including logic-level flaws that survived years of expert review.

Each finding runs through a multi-stage check where Claude adversarially re-examines its own conclusion before surfacing a confidence rating to a human reviewer.

What Claude Code Security does:

  • Detects business logic flaws where code is syntactically correct but functionally insecure
  • Identifies authentication gaps by tracking multi-step execution flows
  • Catches hard-to-find insecure data handling patterns
  • Analyzes diffs contextually, evaluating changes in the context of surrounding code

What Claude Code Security does not do:

  • It is a static reasoning layer. It does not run your application.
  • It has no visibility into what an agent does once deployed at runtime.
  • It cannot detect prompt injection that occurs during live agent execution.
  • A function that passes Claude Code Security can still be manipulated at runtime.

Claude Code Security is a supplement to your existing SAST tooling and DAST pipeline, not a replacement for either.


The security best practices priority order

For teams starting from a default configuration, apply controls in this order:

PriorityControlImpact
1.claudeignore covering all credential pathsCritical: prevents secrets exposure
2Launch directory restriction (project root only)Critical: limits file system access
3Deny rules for irreversible commandsHigh: prevents catastrophic actions
4PreToolUse danger guard hookHigh: enforces policy every session
5Bypass mode restrictionHigh: eliminates unreviewed execution
6MCP server audit and governanceHigh: closes external attack surface
7PostToolUse command loggerMedium: creates audit trail
8Secret scanner on file writesMedium: catches credential leaks
9SAST in CI pipeline for generated codeMedium: catches output vulnerabilities
10Managed settings (enterprise)Medium: enforces team-wide policy
11AI gateway and SSO (enterprise)Medium: eliminates shared API key risk
12OpenTelemetry export (enterprise)Medium: enables full audit trail

Copy-paste security configuration

This configuration is the minimum viable security setup for a team project. Copy it into .claude/settings.json at your project root and commit it.

{
  "permissions": {
    "deny": [
      "Bash(rm -rf /)",
      "Bash(rm -rf ~)",
      "Bash(rm -rf $HOME)",
      "Bash(git reset --hard origin*)",
      "Bash(git push --force*)",
      "Bash(curl | sh)",
      "Bash(wget | sh)",
      "Bash(cat ~/.ssh/*)",
      "Bash(cat ~/.aws/*)",
      "Bash(cat .env*)"
    ],
    "ask": [
      "Bash(git push*)",
      "Bash(npm publish*)",
      "Bash(*deploy*)",
      "Bash(*migration*)",
      "Bash(psql*)",
      "Bash(kubectl*)"
    ],
    "allow": [
      "Bash(npm run build)",
      "Bash(npm run test)",
      "Bash(npm run lint)",
      "Bash(git status)",
      "Bash(git diff)",
      "Bash(git log*)"
    ]
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": ".claude/hooks/danger-guard.sh" }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{ "type": "command", "command": ".claude/hooks/command-logger.sh" }]
      }
    ]
  }
}

Best practices for non-technical users and executives

Most Claude Code security guidance is written for engineers. But the people who approve Claude Code adoption, set organizational policy, and manage the teams using it carry their own set of responsibilities.

Getting these decisions wrong at the leadership level creates security gaps that no amount of technical configuration can close.

What executives and leaders need to understand

Claude Code is not a productivity tool with an on/off switch. It is an autonomous agent that acts with the permissions of whoever runs it. Every developer on your team who uses Claude Code is, in effect, running an agent with their own access credentials. The security posture of that agent is your responsibility, not just your engineering team’s.

Three things every non-technical leader should know before approving Claude Code deployment:

  1. Claude Code acts, it does not just suggest. Unlike a writing assistant, Claude Code executes changes in your codebase and runs commands on your systems. Unsecured, it can delete files, exfiltrate credentials, and modify production configurations.

  2. Default configuration is not secure configuration. Anthropic ships Claude Code with reasonable individual-developer defaults. Those defaults are not appropriate for a team environment without additional configuration. Approving Claude Code deployment without also approving a security configuration process is approving an unsecured deployment.

  3. Shadow adoption is the biggest risk. If developers are already using Claude Code unofficially without security controls or IT visibility, that is more urgent than the question of whether to formally adopt it. The answer is not to ban it. It is to govern it.


The four decisions executives need to make

Decision 1: Approve or define a Claude Code usage policy

A Claude Code usage policy does not need to be long. It needs to answer four questions:

  • Which systems and repositories can developers use Claude Code on?
  • What data is prohibited from entering Claude Code’s context (customer PII, regulated data, credentials)?
  • Who approves new MCP server integrations before they are connected?
  • What is the process when a suspected security incident involves Claude Code?

Without a policy, every developer makes these decisions individually. That is not a security posture; it is a collection of individual choices with no shared accountability.

Decision 2: Require IT or security team sign-off before production deployment

Claude Code on a developer’s local machine is a different risk profile from Claude Code in CI/CD pipelines, accessing production databases through MCP, or deployed across a team of 50 engineers.

The decision to move from informal individual use to team-wide deployment should involve your security team.

The configuration changes required (managed settings, SSO integration, audit logging, MCP governance) require engineering work that cannot happen retroactively without disruption.

Decision 3: Establish a Claude Code budget and monitor it

Claude Code API usage is billed per token. An unmanaged deployment with no spending limits can accumulate significant costs before anyone notices.

Unexpected spikes in API spending are a potential signal of misuse or a compromised API key.

Set per-developer or per-team spending limits in the Anthropic Console. Assign someone to review the billing dashboard monthly.

Treat a significant unexpected spike the same way you would treat an unexpected cloud infrastructure bill: investigate before assuming it is normal.

Decision 4: Include Claude Code in your vendor security review process

Claude Code is a third-party tool with access to your codebase and potentially your internal systems through MCP. It should go through your standard vendor security review, including:

  • Data handling and retention policy review (zero data retention options exist; verify against your requirements)
  • Compliance certification review (SOC 2 Type II, ISO 27001:2022, ISO/IEC 42001:2023 are verified; FedRAMP is not currently certified)
  • BAA requirements for healthcare organizations (Enterprise plan required; BAA must be explicitly activated)
  • GDPR and data residency requirements for EU-facing operations

Red flags executives should watch for

These patterns indicate a Claude Code deployment that needs immediate security attention.

  • Developers using Claude Code on production systems without a usage policy in place: Production access requires explicit authorization and audit logging, not informal adoption.
  • No one in IT or security knows which MCP servers are connected to Claude Code: Each MCP server is an integration with external systems. Unreviewed integrations are unreviewed access.
  • Claude Code API keys are shared across the team: Shared credentials eliminate individual accountability and make incident response nearly impossible.
  • No one is reviewing what Claude Code is doing: Without audit logs or PostToolUse command logging, you have no visibility into what the agent is executing on your systems.
  • Developers running Claude Code against repositories containing customer data or PII without data controls: Claude Code transmits content to Anthropic’s API. Unprotected customer data in the context window is a potential regulatory and contractual exposure.

Questions to ask your engineering team

If you are an executive or non-technical leader with Claude Code deployed on your team, these questions surface the security posture without requiring technical depth to interpret the answers.

  1. “Do we have a .claudeignore file in every repository where Claude Code is used?” If the answer is no or “I’m not sure,” credentials and sensitive files in those repositories are potentially accessible to Claude Code.

  2. “Does anyone on the team use Claude Code with bypass mode enabled regularly?” Bypass mode disables all review gates. Regular use is a red flag outside of isolated testing environments.

  3. “Who approves new MCP server installations?” If there is no approval process, your team is connecting Claude Code to external systems without a security review.

  4. “Where are the Claude Code session logs stored and who reviews them?” If there are no logs, you have no audit trail of what the agent has executed on your systems.

  5. “Do individual developers have their own API keys, or is there a shared key?” Shared keys are an accountability gap. Individual keys or an AI gateway are the right model.


The minimum viable governance posture for non-technical leaders

You do not need to understand the technical details of hooks or MCP server configurations to ensure Claude Code is deployed safely.

You need to ensure four things are in place:

Governance controlWhat it means in plain languageWho implements it
Written usage policyDevelopers know what they can and cannot do with Claude CodeLeadership approves; security team drafts
Security team review before team deploymentA qualified person has reviewed the configuration before it goes liveEngineering and security team
Individual credentials (no shared API keys)Every developer is accountable for their own Claude Code usageEngineering team
Audit loggingSomeone can answer “what did Claude Code do?” for any sessionEngineering team; leadership requires it

These four controls do not require technical expertise to require. They require leadership to ask for them.



Need help implementing production-grade Claude Code security?

Individual configuration is manageable. Team-wide security policy with managed settings, hook enforcement, MCP governance, and audit logging across dozens of developers is a different scope of work.

Phos AI Labs is an embedded AI consulting firm for small and mid-market businesses.

We identify the right AI problems, build the strategy, handle implementation, and train your team until AI is how the business actually runs.

  • Strategy before systems: We establish which Claude Code workflows need which security controls before any configuration begins.
  • AI Foundations that hold: We install the operating context, decision rules, and configuration standards your team runs on for years.
  • Real team training: We build security fluency inside your actual workflows, not in generic compliance sessions.
  • Private AI Workspace: We design a company-wide AI environment with security and governance built around your existing stack.
  • AI Implementation: We rebuild the workflows that matter most with security built in from the start.
  • Honest judgment, every time: We tell you which controls matter for your specific environment and which are unnecessary overhead.
  • We stay until it compounds: We are not done when the configuration is delivered. We are done when the team runs it reliably.

400+ engagements. Clients include Zapier, Coca-Cola, Medtronic, Dataiku, and American Express.

For certified Claude Code development with security-first configuration from day one, LOW/CODE Agency is one of the first Anthropic partners worldwide with 10+ CCA-F certified developers on staff.

If you want your Claude Code security posture to hold under scrutiny, talk to the team at Phos AI Labs.


Frequently Asked Questions

What are the most important Claude Code security best practices?

Create .claudeignore covering all credential paths. Always launch from your project directory (never ~/). Configure deny rules for irreversible commands. Add a PreToolUse hook for shell command validation.

These four controls address the highest-severity risks.

What is Claude Code Security (the product)?

Claude Code Security launched February 20, 2026, powered by Opus 4.6. It reasons semantically about code, tracing how data flows rather than matching known-bad patterns.

It is rolling out to Team and Enterprise customers.

What is the difference between /security-review and Claude Code Security?

/security-review matches code against known vulnerability signatures the way SAST tools do.

Claude Code Security reasons semantically and can detect logic-level flaws and authentication gaps that pattern matching misses.

Is bypass mode (--dangerously-skip-permissions) ever safe to use?

Only in isolated containers or sandboxed environments where you fully control all input. Never in CI/CD pipelines that process external input.

Treat authorization to use it like authorization for production database write access.

How do I secure Claude Code in CI/CD pipelines?

Never enable bypass mode in pipelines processing external input. Use --allowedTools to restrict tools to what the pipeline requires. Exclude CI/CD secrets from context.

Log all tool calls. Run Claude Code in ephemeral environments.

What is the difference between CLAUDE.md security guidance and hooks?

CLAUDE.md guidance is advisory: Claude can overlook it. Hooks are deterministic and fire every time the matching tool is called.

For any rule where ignoring it would cause a production incident, use a hook.

Should I use Claude Code Security instead of my existing SAST tools?

No. Claude Code Security is a supplement, not a replacement. It finds logic-level vulnerabilities that pattern-matching SAST misses.

But it has no runtime visibility and cannot detect prompt injection during live execution. Run both.

Related articles

The fastest way to know whether we're the right fit, is a conversation.

STEP 1/2 · ABOUT YOU