Skip to content

Chapter 10 of 2010 min readBy Deepak GuptaPublished

Claude Code for Security Engineers

Security engineers sit at the most consequential point in AI-assisted development. The same class of model that writes vulnerable code at scale can also find vulnerabilities that rule-based scanners missed for years. Which side of that your organization lands on is a policy decision, and you are the one who should make it.

The threat model has changed

Three shifts define it.

  • Volume. Engineers produce far more code per day. Review capacity did not grow with it.
  • Pattern risk. Models reproduce common patterns from their training data, including insecure ones: string-built queries, permissive CORS, disabled certificate checks "for local testing."
  • New identities. Agents, MCP servers, and CI bots are non-human identities with real privileges. Palo Alto Networks' 2026 Identity Security Landscape puts the average at 109 machine identities per human employee, as I covered in my analysis of the identity crisis, and most have weak lifecycle controls.

The defensive goal is not to slow developers down. It is to make the secure path the default path, enforced by the same automation that made them fast.

Layer 1: CLAUDE.md security rules

Claude follows written rules far more consistently than a tired human reviewer catches violations. Put your non-negotiables in every repository's CLAUDE.md:

## Security rules (IMPORTANT)
- Never hardcode secrets, keys, or tokens. Read them from the config module.
- Never log tokens, passwords, session IDs, card data, or full PII.
- All SQL through the ORM or parameterized queries. No string concatenation.
- Never pass user input to a shell, eval, or template engine unescaped.
- Every new route must declare its auth requirement explicitly.
- Authorization checks happen in the service layer, not only in the UI.
- Do not disable TLS verification, CSRF protection, or CORS restrictions.
- New dependencies require a stated reason; prefer existing ones.
- Changes under src/auth, src/billing, or src/admin: stop and flag for human review.

Layer 2: /security-review before every push

Claude Code includes a /security-review command that audits pending changes. It looks for injection risks, cross-site scripting, authentication and authorization flaws, insecure data handling, hardcoded secrets, and vulnerable dependencies (Claude Help Center). Make running it a habit before every push, and ask Claude to fix what it finds while the context is fresh.

You can customize the command for your environment by copying it into your project's commands or skills and adding your own focus areas, such as your auth library's known misuse patterns.

Layer 3: review on every pull request

The open-source claude-code-security-review GitHub Action runs on pull requests, analyzes only the changed files, and posts findings as inline comments.

name: Security Review
permissions:
  pull-requests: write
  contents: read
on:
  pull_request:
jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha || github.sha }}
          fetch-depth: 2
      - uses: anthropics/claude-code-security-review@main
        with:
          comment-pr: true
          claude-api-key: ${{ secrets.CLAUDE_API_KEY }}

Two cautions from the project itself. The Action is not hardened against prompt injection, so require maintainer approval before workflows run on pull requests from external contributors. And pin to a release or commit rather than @main once you have validated it.

Team and Enterprise plans also offer a managed Code Review feature that runs specialized agents over pull requests and posts severity-tagged findings without blocking merges by default (docs). If you want findings to gate merges, read the severity counts in your own CI and fail the build there.

Layer 4: whole-codebase scanning

For security teams, Anthropic offers Claude Security, which scans an entire codebase, traces data flows across files, runs an adversarial verification pass on each finding, and proposes patches for review (product page). At launch in February 2026, Anthropic reported that its team had used the underlying capability to find more than 500 previously unknown vulnerabilities in production open-source codebases (Anthropic). By November 2, 2026, its disclosure dashboard listed 5,087 vulnerabilities disclosed across 680 open-source projects (Anthropic CVD dashboard). Use it for periodic deep scans of code your company owns, including codebases you acquire. Its terms limit scanning to code you own or have rights to, so do not point it at a vendor's code.

Where AI review is strong

Rule-based SAST matches syntax. It can see that an authorization check exists; it cannot judge whether the check is correct, and its false positives train developers to ignore it (ReversingLabs covers both sides of this trade-off). AI review reasons about intent and data flow, which makes it strong on:

  • Broken access control and insecure direct object references
  • Authorization logic that exists but is wrong
  • Race conditions and time-of-check to time-of-use bugs
  • Trust boundary violations between services
  • Business logic flaws that fit no known signature
  • Missing validation on one path out of several

Where it is not enough

Claude's security review operates on source code. It does not replace:

Control Why you still need it
SCA and SBOM Complete, versioned dependency inventory and CVE matching
DAST Proves exploitability against the running application
Container and IaC scanning Base image CVEs, misconfigured cloud resources
Secret scanning Deterministic detection across full git history
Runtime protection Detects attacks that no static review predicted
Penetration testing Human creativity against your real deployment
Threat modeling Design flaws that no code review catches

The honest framing: AI review is a strong evolution of SAST and a fast first reviewer. It is not an AppSec program.

A security-reviewer subagent

Save this as .claude/agents/security-reviewer.md:

---
name: security-reviewer
description: Senior application security engineer. Use proactively after any
  change touching authentication, authorization, sessions, tokens, input
  handling, file uploads, payments, admin features, or third-party integrations.
tools: Read, Grep, Glob, Bash
model: opus
---

You are a senior application security engineer reviewing a change you did
not write. Assume it is vulnerable until you have evidence it is not.

Process:
1. Run `git diff` and identify every new or changed entry point.
2. For each entry point, trace untrusted input to every sensitive sink:
   database, shell, file system, template, redirect, outbound request, log.
3. Verify authentication and authorization on every privileged path.
   Check object-level authorization, not just route-level.
4. Check token and session handling: storage, expiry, rotation, revocation.
5. Look for secrets, weak crypto, unsafe defaults, and disabled protections.
6. Check new dependencies for necessity and reputation.

Report each finding as:
- Severity: Critical, High, Medium, Low, Info
- Location: file and line
- Issue and realistic attack scenario
- Fix, with a code suggestion
- Confidence: High, Medium, Low

Do not report style issues. If you find nothing, say what you checked.

Review prompt templates

Use these directly or as the body of skills.

OWASP Top 10 pass:

Review the changes on this branch against the OWASP Top 10. For each category, state whether the change is relevant, what you checked, and any finding with file, line, severity, and fix. Pay particular attention to broken access control and injection.

API pass:

Review every new or modified API endpoint against the OWASP API Security Top 10. For each endpoint list: authentication requirement, object-level authorization check, input validation, rate limiting, and data returned. Flag any field in the response that the caller should not see.

Auth flow pass:

Trace the full login, token refresh, logout, and password reset flows. Check PKCE on OAuth flows, state and nonce validation, token storage location, refresh token rotation, session invalidation on password change, and account enumeration through error messages or timing.

For the protocol details behind that last prompt, see my guide to authentication implementation.

Supply chain pass:

List every dependency added or upgraded on this branch. For each: why it is needed, whether an existing dependency covers the need, maintainer and release history signals, install scripts, and known advisories. Flag any name that resembles a popular package.

That last check matters more with AI coding. Models sometimes suggest packages that do not exist, and attackers register those names.

Layer 5: deterministic gates

AI review is probabilistic. Back it with deterministic tools in hooks and CI.

#!/usr/bin/env bash
# .claude/hooks/secret-scan.sh  (PreToolUse on Bash commands containing "git commit")
if ! gitleaks git --pre-commit --staged --redact --no-banner >/tmp/gitleaks.out 2>&1; then
  echo "Secret detected in staged changes. Remove it before committing." >&2
  head -20 /tmp/gitleaks.out >&2
  exit 2
fi
exit 0

Pair it with a standard pre-commit framework running the same scanner, so commits made outside Claude Code are covered too.

Mandatory human review paths

Some code requires a qualified human reviewer regardless of who or what wrote it. Enforce this with CODEOWNERS and branch protection, not goodwill.

  • Authentication, session, and token handling
  • Authorization and permission models
  • Cryptography and key management
  • Payments and billing
  • Admin and support tooling
  • Data export, deletion, and PII processing
  • Infrastructure and network policy

Where possible, keep these concerns behind proven libraries or platforms rather than letting any author, human or AI, implement them inline. My CIAM landscape analysis covers the identity options.

Securing the agent itself

Claude Code is now part of your attack surface.

  • Least privilege. Deny reads of secret files. Allowlist commands instead of skipping permissions.
  • Isolation. Run autonomous or headless sessions in containers without production credentials.
  • Untrusted input. Repository content, issues, web pages, and tool output can carry prompt injection. Never let an agent act on instructions found in data.
  • Plugin and MCP hygiene. Review source, pin versions, and keep an inventory, as with any dependency.
  • Credentials. Give MCP servers and CI bots short-lived, narrowly scoped tokens with owners and rotation.

Detection engineering and blue team work

Claude Code is a strong assistant for defensive work. Useful patterns:

  • Draft Sigma, YARA, or Suricata rules from a threat report, then test them against sample logs or files you provide.
  • Convert rules between formats and explain coverage gaps.
  • Summarize large log extracts into a timeline for an incident.
  • Map observed behavior to MITRE ATT&CK techniques.
  • Draft postmortems from incident channels and timelines.

The Trail of Bits skills repository is the best starting point for security skills, including CodeQL and SARIF workflows. Snyk maintains a useful roundup of security skills.

Offensive testing guardrails

Authorized penetration testers use Claude Code to enumerate attack surface, review code for exploitable paths, and write reports. Keep three rules: written authorization and scope before any active testing, test environments rather than production unless the engagement explicitly covers it, and human review of every finding before it reaches a client.

Warning

Pitfall: Treating a clean AI review as proof of security. It means the reviewer found nothing in the code it saw. Absence of findings is not evidence of absence.

Tip

What to do this week

  • Add the security rules block to CLAUDE.md in your highest-risk repository.
  • Install the security-reviewer subagent and run it on the last five merged PRs.
  • Pilot the GitHub Action on one repository with external-contributor approval enabled.

Key takeaways

  • Put security non-negotiables in every repository's CLAUDE.md.
  • Run /security-review before pushes and an automated review on every pull request.
  • AI review is strong on logic and access control but does not replace SCA, DAST, secret scanning, or pen tests.
  • Treat the agent as part of your attack surface: least privilege, isolation, and scoped credentials.