首页 › tutorials › Claude Code Security全实战:AI驱动漏洞扫描与修复

Claude Code Security全实战:AI驱动漏洞扫描与修复

概述

本教程系统讲解Claude Code Security——Anthropic于2025年8月推出的AI驱动安全扫描能力,以及2026年2月发布的Claude Security企业级产品。你将学会使用 /security-review 命令、GitHub Actions自动审查、安全Skill定制和CI/CD集成,构建从发现到修复的完整DevSecOps链路。适合有Claude Code基础的安全工程师、后端开发者和DevOps从业者。

学习目标:掌握三种安全扫描模式(终端命令/CI自动/企业面板)、自定义扫描策略、误报过滤、与现有SAST工具互补协作。


前置条件


一、Claude Code Security技术架构

Claude Code Security不是又一个正则匹配的静态分析器。它基于LLM的语义推理能力,像安全研究员一样阅读代码:追踪变量跨文件流动、理解组件交互方式、判断授权逻辑是否符合设计意图。

1.1 三层安全扫描体系

graph TB
    subgraph "Claude Code Security 三层架构"
        A["第一层:终端即时扫描<br/>/security-review 命令"] --> D["核心推理引擎<br/>Claude LLM语义分析"]
        B["第二层:CI/CD自动审查<br/>GitHub Action"] --> D
        C["第三层:企业级持续扫描<br/>Claude Security Dashboard"] --> D
        D --> E["数据流追踪<br/>跨文件变量分析"]
        D --> F["逻辑推理<br/>授权语义理解"]
        D --> G["误报验证<br/>多阶段确认"]
        E --> H["发现报告<br/>置信度+严重度"]
        F --> H
        G --> H
        H --> I["补丁生成<br/>分支+PR"]
        H --> J["人工审查<br/>Human-in-the-loop"]
    end

    style D fill:#f9f,stroke:#333,stroke-width:2px
    style H fill:#bbf,stroke:#333,stroke-width:2px

1.2 与传统SAST工具的本质差异

维度 传统SAST(SonarQube/Semgrep) Claude Code Security
检测机制 正则模式匹配 + 语法树规则 LLM语义推理 + 数据流追踪
SQL注入 匹配字符串拼接模式 分析数据流从入口到查询的完整路径
硬编码密钥 匹配credential字面量 识别日志泄露、上下文中的敏感数据
访问控制 检测缺失的装饰器 推理授权逻辑是否正确执行策略
业务逻辑缺陷 无法检测 识别竞态条件、TOCTOU、授权逻辑错误
跨服务漏洞 单仓库范围 单仓库语义分析(多仓库需配合其他工具)
误报率 高(规则宽泛) 低(多阶段验证 + 置信度评分)

二、第一层:终端即时扫描——/security-review命令

2.1 基本使用

在任意项目目录启动Claude Code后,直接输入:

> /security-review

Claude将自动扫描所有待提交的变更(unstaged和staged),并生成安全报告。报告包含:

2.2 范围控制

# 扫描指定目录
> /security-review --scope src/auth/

# 扫描指定文件
> /security-review --scope src/api/users.ts

# 结合自然语言定位
> run a security review on the payment processing module

2.3 实战:发现并修复一个SQL注入漏洞

假设你有一个Express.js项目,运行/security-review后:

Claude Code发现 3 个安全问题:

┌─────────────────────────────────────────────────────┐
│ CRITICAL │ SQL Injection in src/api/users.ts:47     │
│ Confidence: HIGH                                    │
│                                                     │
│ 用户输入 req.query.name 直接拼接到SQL查询字符串中,  │
│ 攻击者可通过构造恶意输入执行任意SQL命令。           │
│                                                     │
│ 当前代码:                                           │
│   const query = `SELECT * FROM users                │
│     WHERE name = '${req.query.name}'`;              │
│                                                     │
│ 建议修复:                                           │
│   const query = `SELECT * FROM users                │
│     WHERE name = $1`;                               │
│   const result = await pool.query(query,            │
│     [req.query.name]);                              │
│                                                     │
│ 参考: OWASP A03:2021 - Injection                    │
└─────────────────────────────────────────────────────┘

确认后,Claude直接应用修复并运行测试:

> yes, apply the fix and run tests

✓ Applied fix to src/api/users.ts
✓ Running test suite... 47/47 tests passed
✓ No regressions detected

2.4 常见问题

Q: 扫描整个项目时上下文窗口不足怎么办?

Claude Code自动采用分批策略——先扫描入口文件和路由定义,再逐步深入各个模块。对于大型项目(100+文件),建议缩小范围:

> /security-review src/auth/ and src/api/

Q: 如何处理误报?

在CLAUDE.md中添加安全规则白名单:

# Security conventions
- Admin bypass routes in /src/admin/* intentionally skip auth checks
- Test utilities in /tests/helpers/ intentionally use hardcoded credentials
- The /api/internal/* endpoints are only accessible from internal network

三、第二层:CI/CD自动审查——GitHub Action

3.1 快速配置

在仓库中创建.github/workflows/security.yml:

name: Security Review

permissions:
  pull-requests: write   # 用于在PR上评论
  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 }}

关键步骤: 1. 在GitHub仓库Settings → Secrets中添加CLAUDE_API_KEY 2. API Key需要在Anthropic控制台启用Claude API和Claude Code使用权限 3. fetch-depth: 2确保能获取diff上下文

3.2 高级配置选项

- uses: anthropics/claude-code-security-review@main
  with:
    claude-api-key: ${{ secrets.CLAUDE_API_KEY }}
    comment-pr: true
    upload-results: true

    # 排除目录(vendor、测试fixture等)
    exclude-directories: "vendor/,tests/fixtures/,node_modules/"

    # 模型选择(平衡速度与深度)
    claude-model: "claude-opus-4-1-20250805"

    # 超时(大型monorepo可能需要更长)
    claudecode-timeout: 30

    # 每次提交都扫描(默认只扫描最新commit)
    run-every-commit: false

    # 自定义误报过滤指令
    false-positive-filtering-instructions: ".security/filter-rules.txt"

    # 自定义扫描指令
    custom-security-scan-instructions: ".security/custom-rules.txt"

3.3 自定义扫描策略

创建.security/custom-rules.txt:

Additional security checks for this project:

1. All API endpoints under /api/v2/ must validate Bearer tokens
2. Database queries must use parameterized statements (no string interpolation)
3. File uploads must validate MIME type AND file content, not just extension
4. Rate limiting is required on all public endpoints
5. PII fields (email, phone, SSN) must be encrypted at rest
6. Third-party OAuth tokens must never be logged

创建.security/filter-rules.txt减少误报:

Known false positive patterns to exclude:

- Warnings about missing auth on /health and /metrics endpoints (intentional)
- Flags about hardcoded values in config/test.env (test environment only)
- Reports about CORS on localhost (development-only configuration)
- Missing CSRF warnings on API-only endpoints (using Bearer tokens instead)

3.4 工作流效果

sequenceDiagram
    participant Dev as 开发者
    participant PR as Pull Request
    participant CI as GitHub Actions
    participant CC as Claude Code Security
    participant Rev as 安全审查员

    Dev->>PR: 创建PR
    PR->>CI: 触发 security.yml
    CI->>CC: checkout + diff分析
    CC->>CC: 语义推理 + 数据流追踪
    CC->>CC: 多阶段验证 + 误报过滤
    CC->>PR: 内联评论:发现 + 严重度
    CC->>CI: JSON结果文件
    Note over PR: Critical问题阻止合并<br/>Medium/Low作为建议
    PR->>Rev: 人工审查确认
    Rev->>PR: Approve
    PR->>Dev: 合并

3.5 分支保护策略

在GitHub仓库设置中配置:

  1. Settings → Branches → Branch protection rules
  2. 勾选"Require status checks to pass before merging"
  3. 添加Security Review为必需检查
  4. 配置"Require approval for all external contributors"——防止外部Fork中的恶意代码触发扫描

安全警告:CVE-2025-59536披露了一个通过PR内容注入恶意指令的漏洞。务必要求外部贡献者的PR经过维护者审批后才触发安全扫描,不要在不受信任的代码上自动运行。


四、第三层:企业级持续扫描——Claude Security Dashboard

4.1 功能概览

Claude Security(2026年2月发布,面向Enterprise和Team客户)提供了Web面板:

4.2 从发现到修复的完整流程

01 Finding → 02 Validation → 03 Patching → 04 Review → 05 Ship

01 发现阶段:Claude像安全研究员一样阅读代码,理解组件交互,追踪数据如何穿过应用。

02 验证阶段:每个发现经历多阶段验证——Claude重新审视每个结果以证明或反驳,过滤误报,分配严重度和置信度。

03 补丁阶段:为每个验证通过的问题生成定向补丁,创建分支准备PR审查。

04 审查阶段:团队在Dashboard中查看diff。任何修改都不会未经人工批准而发布。

05 发布阶段:审查通过后合并修复。

4.3 访问方式


五、实战案例:为Express.js项目构建完整安全工作流

5.1 项目结构

express-payments/
├── src/
│   ├── api/
│   │   ├── auth.ts          # 认证路由
│   │   ├── payments.ts      # 支付处理
│   │   └── users.ts         # 用户管理
│   ├── middleware/
│   │   └── auth.ts          # JWT验证
│   ├── db/
│   │   └── queries.ts       # 数据库查询
│   └── utils/
│       └── validators.ts    # 输入校验
├── tests/
├── .security/
│   ├── custom-rules.txt
│   └── filter-rules.txt
├── .github/
│   └── workflows/
│       └── security.yml
├── CLAUDE.md
└── package.json

5.2 配置CLAUDE.md安全指令

# Security Policy

## Authentication
- All /api/* endpoints except /api/auth/login and /api/auth/register require Bearer token
- JWT tokens expire after 1 hour, refresh tokens after 7 days
- Admin endpoints under /api/admin/* require role=admin in token payload

## Data Handling
- PII (email, phone, address) must be encrypted with AES-256 at rest
- Payment card data MUST NEVER touch our servers — use Stripe tokenization
- Log files must not contain user IDs, tokens, or request bodies

## Database
- All queries MUST use parameterized statements ($1, $2 placeholders)
- Connection pooling via pg-pool, max 20 connections
- Migration files are immutable once merged

## Input Validation
- All user input validated with joi schemas before processing
- File uploads limited to 5MB, allowed types: jpg, png, pdf
- Rate limiting: 100 req/min per IP, 1000 req/min per API key

5.3 配置安全审查Skill

创建.claude/commands/security-review.md(覆盖默认命令):

---
description: "Comprehensive security review with OWASP compliance"
---

Perform a thorough security review of the changed files with focus on:

1. **Injection vectors**: SQL, NoSQL, command injection, XSS
2. **Authentication bypass**: Token validation, session management
3. **Authorization flaws**: Missing role checks, IDOR
4. **Data exposure**: Secrets in logs, PII leakage, debug endpoints
5. **Payment security**: Ensure no card data touches our servers

For each finding:
- Rate severity: Critical/High/Medium/Low
- Provide confidence rating: High/Medium/Low
- Generate a fix that addresses the root cause
- Explain why this matters in our payment processing context

Known safe patterns to exclude:
- /api/health endpoint intentionally has no auth
- Test files use mock credentials
- CORS allows localhost in development

5.4 运行完整安全扫描

# 进入项目目录
cd express-payments

# 启动Claude Code
claude

# 运行安全审查
> /security-review

# 查看结果后,让Claude修复所有Critical和High问题
> fix all critical and high severity issues, run the test suite after each fix

# 提交修复
> commit the security fixes with descriptive messages referencing each CVE category

5.5 CI/CD安全流水线配置

name: Security Pipeline

on:
  pull_request:
    paths:
      - 'src/**'
      - 'package.json'
      - 'package-lock.json'

jobs:
  security-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}
          fetch-depth: 2

      # 第一步:Claude Code语义安全审查
      - uses: anthropics/claude-code-security-review@main
        id: claude-security
        with:
          claude-api-key: ${{ secrets.CLAUDE_API_KEY }}
          comment-pr: true
          upload-results: true
          exclude-directories: "node_modules/,tests/fixtures/"
          claude-model: "claude-opus-4-1-20250805"
          false-positive-filtering-instructions: ".security/filter-rules.txt"
          custom-security-scan-instructions: ".security/custom-rules.txt"

      # 第二步:传统依赖扫描(与Claude互补)
      - name: npm audit
        run: npm audit --audit-level=high

      # 第三步:输出扫描结果摘要
      - name: Security Summary
        if: always()
        run: |
          echo "### Security Scan Results" >> $GITHUB_STEP_SUMMARY
          echo "Claude findings: ${{ steps.claude-security.outputs.findings-count }}" >> $GITHUB_STEP_SUMMARY
          echo "Results file: ${{ steps.claude-security.outputs.results-file }}" >> $GITHUB_STEP_SUMMARY

5.6 完整DevSecOps工作流

flowchart TD
    A["开发者编写代码"] --> B["本地 /security-review"]
    B --> B1{发现漏洞?}
    B1 -->|是| B2["Claude生成修复补丁"]
    B2 --> B3["运行测试验证"]
    B3 --> B4["修复通过?"]
    B4 -->|是| C["Git commit + push"]
    B4 -->|否| B2
    B1 -->|否| C

    C --> D["创建Pull Request"]
    D --> E["GitHub Action触发"]

    E --> F["Claude Code Security Review"]
    E --> G["npm audit依赖扫描"]
    E --> H["Semgrep模式匹配"]

    F --> I["语义安全报告"]
    G --> J["依赖漏洞报告"]
    H --> K["模式匹配报告"]

    I --> L{"合并检查"}
    J --> L
    K --> L

    L -->|Critical: 阻止| M["要求修复"]
    L -->|High: 警告| N["建议修复"]
    L -->|Low: 记录| O["允许合并"]

    M --> A
    N --> P["人工审查"]
    P --> Q{批准?}
    Q -->|是| R["合并到main"]
    Q -->|否| A
    O --> R

    R --> S["Claude Security定时扫描"]
    S --> T["持续安全态势监控"]

    style F fill:#f96,stroke:#333,stroke-width:2px
    style L fill:#bbf,stroke:#333,stroke-width:2px
    style R fill:#bfb,stroke:#333,stroke-width:2px

六、安全Skill定制进阶

6.1 创建专属安全审查Skill

在.claude/skills/security-audit/SKILL.md中:

---
name: security-audit
description: OWASP Top 10 compliance audit for payment applications
---

# Security Audit Skill

Perform a comprehensive OWASP Top 10 (2025) audit:

## Checklist
1. **A01 - Broken Access Control**: Check all API routes for proper authorization
2. **A02 - Cryptographic Failures**: Verify TLS, encryption at rest, key rotation
3. **A03 - Injection**: Trace all user inputs to database queries and shell commands
4. **A04 - Insecure Design**: Review business logic for abuse scenarios
5. **A05 - Security Misconfiguration**: Check CORS, headers, debug modes
6. **A06 - Vulnerable Components**: Review package.json for known CVEs
7. **A07 - Auth Failures**: Test session management, brute force protection
8. **A08 - Data Integrity**: Verify input validation and deserialization safety
9. **A09 - Logging Failures**: Ensure security events are logged without PII
10. **A10 - SSRF**: Check all outbound HTTP requests for user-controlled URLs

For each category, read the relevant files, trace data flows, and report findings.
Generate a compliance score (0-100) for each category.

使用方式:

> /security-audit

6.2 创建安全审查Subagent

在.claude/agents/security-reviewer.md中:

---
name: security-reviewer
description: Dedicated security code reviewer
tools: Read, Grep, Glob, Bash
model: opus
---

You are a senior application security engineer with 15 years of experience
in penetration testing and secure code review.

Review code for these specific concerns:
- Injection vulnerabilities (SQL, XSS, command injection)
- Authentication and authorization flaws
- Secrets or credentials in code
- Insecure data handling and PII exposure
- Race conditions and TOCTOU issues
- Insecure deserialization
- SSRF and CSRF vulnerabilities

Provide specific line references with file paths.
For each finding, rate severity (Critical/High/Medium/Low)
and provide a concrete fix.

使用方式:

> use the security-reviewer subagent to review all changes in this PR

6.3 安全审查Hook

在.claude/settings.json中配置安全Hook:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "python3 .claude/hooks/check-secrets.py \"$TOOL_INPUT\""
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "command": "python3 .claude/hooks/check-security.py \"$TOOL_INPUT\""
      }
    ]
  }
}

check-secrets.py示例:

#!/usr/bin/env python3
"""Hook: Block writes containing hardcoded secrets"""
import sys, json, re

input_data = json.loads(sys.argv[1])
content = input_data.get('content', '')
file_path = input_data.get('file_path', '')

# Skip test files
if '/test' in file_path or '/tests/' in file_path:
    sys.exit(0)

patterns = [
    (r'(?:password|passwd|pwd)\s*[=:]\s*["\'][^"\']{4,}', 'Hardcoded password'),
    (r'(?:api[_-]?key|apikey)\s*[=:]\s*["\'][^"\']{8,}', 'Hardcoded API key'),
    (r'(?:secret|token)\s*[=:]\s*["\']sk-[a-zA-Z0-9]{20,}', 'Hardcoded secret/token'),
    (r'-----BEGIN (?:RSA |EC )?PRIVATE KEY-----', 'Private key in code'),
]

for pattern, description in patterns:
    if re.search(pattern, content, re.IGNORECASE):
        print(f"SECURITY BLOCK: {description} detected in {file_path}")
        sys.exit(2)  # Block the tool call

sys.exit(0)  # Allow the tool call

七、与传统安全工具协作策略

7.1 三层互补防御架构

防御层 工具 职责
模式匹配层 Semgrep / SonarQube 快速扫描已知模式(SQL拼接、XSS向量、硬编码凭证)
语义推理层 Claude Code Security 理解业务逻辑、授权语义、数据流正确性
依赖扫描层 npm audit / Snyk / Dependabot 已知CVE漏洞、供应链安全

7.2 GitHub Actions集成示例

jobs:
  security-layers:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      # 层1:快速模式匹配
      - name: Semgrep Scan
        uses: semgrep/semgrep-action@v1
        with:
          config: p/owasp-top-ten

      # 层2:语义安全推理
      - uses: anthropics/claude-code-security-review@main
        with:
          claude-api-key: ${{ secrets.CLAUDE_API_KEY }}
          comment-pr: true

      # 层3:依赖漏洞扫描
      - name: Dependency Review
        uses: actions/dependency-review-action@v4

八、已知限制与安全注意事项

8.1 CVE漏洞

CVE编号 影响 缓解措施
CVE-2025-59536 通过PR内容注入恶意指令导致远程代码执行 仅扫描受信任的PR,要求外部贡献者审批
CVE-2026-21852 通过类似向量泄露API Key 配置GitHub Actions secret管理,不在不受信任代码上运行

8.2 使用原则

  1. 仅扫描受信任仓库——不对外部Fork自动运行
  2. 不自动应用补丁——所有修复必须人工审查
  3. 不替代人工审查——AI是辅助工具,不是替代品
  4. API Key隔离——使用最小权限的API Key,定期轮换
  5. 结果验证——对Critical发现进行手动渗透测试确认

8.3 成本控制

Claude Code Security的扫描会消耗API调用额度。控制策略:


九、命令速查表

命令/操作 用途
/security-review 终端内扫描待提交变更
/security-review src/auth/ 扫描指定目录
claude mcp add 连接外部安全工具
/permissions 管理安全审查权限
.claude/commands/security-review.md 自定义扫描策略
.claude/skills/security-audit/ 创建安全审查Skill
.claude/agents/security-reviewer.md 安全审查Subagent
.claude/hooks/check-secrets.py 自动密钥检测Hook

训练营适用性评估

训练营类型 适用性 预计时长
DevSecOps入门营 高 4小时(含CI/CD配置实践)
安全工程师进阶营 高 6小时(含自定义Skill和Hook开发)
全栈开发训练营 中 3小时(重点在/security-review + GitHub Action)
企业安全合规培训 中 5小时(重点在Dashboard + 合规报告)
AI安全研究 高 8小时(含CVE分析 + 对抗测试)

延伸阅读


参考来源

  1. Automate Security Reviews with Claude Code - Anthropic Blog — 官方产品发布公告,/security-review命令和GitHub Action介绍
  2. anthropics/claude-code-security-review - GitHub — 官方开源GitHub Action,包含完整配置选项和工作原理
  3. Anthropic Launches Claude Code Security - The Hacker News — 企业级产品发布报道,多阶段验证和Human-in-the-loop机制
  4. Claude Code Security Review: Complete Guide - Gecko Security — 第三方深度评测,包含与SAST工具对比和CVE分析
  5. Claude Security - Anthropic — 企业级持续扫描产品,从发现到修复的完整流程

[!tip] 51学通信知识星球 星主:爱卫生(微信:gprshome201101)——公众号「51学通信」创办者,19 年通信行业运维与讲师经验,著有《GPRS网络信令实例详解》《EPC原理与实践》《5G核心网原理与实践》三本纸质书(各大电商平台有售)。 星球定位:深耕 5G 核心网、IMS、NFV/AI、云原生等 ICT 领域,主打运维岗位与信令分析。 当前规模:5200 篇主题 / 990 个回答,198 元/年。 加入福利:加入星球后请加爱卫生微信,拉您进知识星球年度陪伴与答疑群——不限量回复您的各种问题,另有群内分享。 AI 加持:51学通信知识星球已作为 skill 接入 WorkBuddy,使用 deepseek-4-flash 在海量星球帖子中精准找贴、找视频、找 FAQ 和案例,做总结、找文档和 PPT 等场景全覆盖。

51学通信知识星球海报-扫码加入