security-review

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Security Review

安全审查

Overview

概述

Systematically review code for security vulnerabilities, apply secure coding patterns, and ensure applications follow defense-in-depth principles. This skill covers the OWASP Top 10, authentication pattern selection, input validation, secrets management, dependency auditing, security headers, and threat modeling.
Announce at start: "I'm using the security-review skill to assess security posture."

系统地审查代码中的安全漏洞,应用安全编码模式,确保应用遵循深度防御原则。本技能覆盖OWASP Top 10、认证模式选择、输入验证、密钥管理、依赖审计、安全头配置以及威胁建模。
启动时声明: "我正在使用security-review技能评估安全状态。"

Phase 1: Scope and Threat Assessment

第一阶段:范围与威胁评估

Goal: Identify the attack surface and prioritize review areas.
目标: 识别攻击面并确定审查区域优先级。

Actions

执行动作

  1. Identify all user-facing endpoints and input surfaces
  2. Map authentication and authorization boundaries
  3. List external dependencies and their trust levels
  4. Identify sensitive data flows (PII, credentials, payment)
  5. Determine compliance requirements (SOC 2, GDPR, HIPAA)
  1. 识别所有面向用户的端点和输入入口
  2. 梳理身份认证与授权边界
  3. 列出外部依赖项及其信任等级
  4. 识别敏感数据流(个人身份信息PII、凭证、支付信息)
  5. 明确合规要求(SOC 2、GDPR、HIPAA)

STOP — Do NOT proceed to Phase 2 until:

停止 — 请勿进入第二阶段,直到完成:

  • Attack surface is mapped
  • Sensitive data flows are identified
  • Compliance requirements are known

  • 完成攻击面梳理
  • 识别所有敏感数据流
  • 明确所有合规要求

Phase 2: OWASP Top 10 Audit

第二阶段:OWASP Top 10 审计

Goal: Systematically check against each OWASP category.
目标: 对照每个OWASP类别开展系统性检查。

OWASP Top 10 Checklist (2021)

OWASP Top 10 检查清单(2021版)

#CategoryKey CheckPass/Fail
1Broken Access ControlAuthorization verified on every endpoint, deny by default
2Cryptographic FailuresNo plaintext secrets, strong algorithms (AES-256, bcrypt)
3InjectionParameterized queries, no string concatenation for SQL/commands
4Insecure DesignThreat model exists, rate limiting, abuse cases considered
5Security MisconfigurationNo defaults in production, minimal permissions, error messages leak nothing
6Vulnerable ComponentsDependencies audited, no known CVEs, update policy in place
7Auth FailuresMFA available, passwords hashed, session management secure
8Data Integrity FailuresVerify signatures, validate CI/CD pipeline integrity
9Logging FailuresLog auth events, access control failures, input validation failures
10SSRFValidate/allowlist URLs, no internal network access from user input
#类别核心检查项通过/未通过
1访问控制失效所有端点均验证授权,默认拒绝访问
2加密机制失效无明文密钥,使用强加密算法(AES-256、bcrypt)
3注入使用参数化查询,SQL/命令执行无字符串拼接
4不安全设计存在威胁模型、配置限流、已考虑滥用场景
5安全配置错误生产环境无默认配置、权限最小化、错误信息无敏感泄露
6存在漏洞的组件依赖已审计、无已知CVE、已制定更新策略
7认证失效支持MFA、密码已哈希、会话管理安全
8数据完整性失效验证签名、校验CI/CD流水线完整性
9日志与监控失效记录认证事件、访问控制失败、输入验证失败日志
10SSRF(服务器端请求伪造)URL校验/白名单、用户输入无法访问内部网络

STOP — Do NOT proceed to Phase 3 until:

停止 — 请勿进入第三阶段,直到完成:

  • All 10 categories are checked
  • Findings are documented with severity

  • 全部10个类别检查完毕
  • 所有发现均已记录并标注严重等级

Phase 3: Deep Review by Category

第三阶段:分类深度审查

Goal: Apply detailed security patterns to identified issues.
目标: 为识别到的问题应用详细的安全修复模式。

Auth Pattern Selection Table

认证模式选择表

PatternUse WhenKey Requirements
JWTStateless APIs, microservices, mobile backendsRS256 for multi-service; access token 15min max; HttpOnly cookies
Session-basedTraditional web apps, server-rendered pagesServer-side storage; HttpOnly + Secure + SameSite cookies; CSRF tokens
OAuth2/OIDCThird-party login, SSO, delegated authAuthorization Code + PKCE; validate ID token claims; server-side token storage
Passkeys/WebAuthnPasswordless, high-security appsPhishing-resistant; store public keys only; support multiple per account
模式适用场景核心要求
JWT无状态API、微服务、移动端后端多服务场景使用RS256;访问令牌有效期最长15分钟;使用HttpOnly Cookie
基于会话传统Web应用、服务端渲染页面服务端存储会话;配置HttpOnly + Secure + SameSite Cookie;使用CSRF令牌
OAuth2/OIDC第三方登录、SSO、委托认证使用授权码+PKCE流程;校验ID Token声明;服务端存储令牌
Passkeys/WebAuthn无密码、高安全级别的应用抗钓鱼;仅存储公钥;支持单个账号绑定多个凭证

JWT Security Checklist

JWT 安全检查清单

AspectGuidance
SigningRS256 (asymmetric) for multi-service, HS256 for single service
ExpiryAccess token: 15 minutes max. Refresh token: 7 days max
StorageHttpOnly cookie (web) or secure storage (mobile). Never localStorage
RefreshRotate refresh tokens on use, invalidate on logout
PayloadMinimal claims (sub, exp, iat, roles). No sensitive data
维度规范
签名多服务场景使用RS256(非对称),单服务场景可使用HS256
有效期访问令牌最长15分钟,刷新令牌最长7天
存储Web端存HttpOnly Cookie,移动端存安全存储,禁止使用localStorage
刷新刷新令牌使用即轮换,登出时立即失效
Payload仅保留最小必要声明(sub、exp、iat、roles),无敏感数据

Input Validation Patterns

输入验证模式

Allow-List Validation (always prefer over block-list):
python
undefined
白名单验证(优先级始终高于黑名单):
python
undefined

Good: allow-list

推荐:白名单验证

ALLOWED_SORT_FIELDS = {'name', 'created_at', 'price'} if sort_field not in ALLOWED_SORT_FIELDS: raise ValidationError("Invalid sort field")
ALLOWED_SORT_FIELDS = {'name', 'created_at', 'price'} if sort_field not in ALLOWED_SORT_FIELDS: raise ValidationError("Invalid sort field")

Bad: block-list (always incomplete)

不推荐:黑名单验证(永远存在遗漏)

BLOCKED_CHARS = ['<', '>', '"']

**Parameterized Queries** (never concatenate user input):
```python
BLOCKED_CHARS = ['<', '>', '"']

**参数化查询**(禁止拼接用户输入):
```python

Good: parameterized

推荐:参数化查询

cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))
cursor.execute("SELECT * FROM users WHERE id = %s", (user_id,))

Bad: SQL injection vulnerability

不推荐:存在SQL注入漏洞

cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
undefined
cursor.execute(f"SELECT * FROM users WHERE id = {user_id}")
undefined

File Upload Validation

文件上传验证

  • Validate MIME type server-side (not just extension)
  • Enforce file size limits
  • Generate random filenames (never use user-supplied names)
  • Store uploads outside the web root
  • Scan for malware if accepting from untrusted users
  • 服务端验证MIME类型(不能仅校验扩展名)
  • 强制文件大小限制
  • 生成随机文件名(禁止使用用户提供的文件名)
  • 存储在Web根目录之外
  • 接收不可信用户上传时需扫描恶意软件

STOP — Do NOT proceed to Phase 4 until:

停止 — 请勿进入第四阶段,直到完成:

  • All identified issues have remediation recommendations
  • Auth patterns are correctly applied
  • Input validation is comprehensive

  • 所有识别到的问题都有修复建议
  • 认证模式已正确应用
  • 输入验证覆盖全面

Phase 4: Infrastructure and Dependency Hardening

第四阶段:基础设施与依赖加固

Goal: Secure the deployment environment and supply chain.
目标: 保障部署环境和供应链安全。

Secrets Management Rules

密钥管理规则

EnvironmentMethod
Development
.env
files (git-ignored)
CI/CDPipeline secrets (GitHub Secrets, GitLab CI vars)
ProductionSecrets manager (AWS Secrets Manager, Vault, GCP Secret Manager)
环境管理方式
开发环境
.env
文件(加入git忽略列表)
CI/CD环境流水线密钥(GitHub Secrets、GitLab CI变量)
生产环境密钥管理服务(AWS Secrets Manager、Vault、GCP Secret Manager)

Secrets Never List

密钥禁止行为清单

  • Never hard-code secrets in source code
  • Never commit
    .env
    files to git
  • Never log secrets (even at debug level)
  • Never pass secrets as command-line arguments
  • Never use the same secrets across environments
  • 禁止在源代码中硬编码密钥
  • 禁止将
    .env
    文件提交到git
  • 禁止打印密钥日志(即使是debug级别)
  • 禁止将密钥作为命令行参数传递
  • 禁止跨环境复用相同密钥

Dependency Auditing Commands

依赖审计命令

bash
undefined
bash
undefined

Node.js

Node.js

npm audit npx socket-security audit
npm audit npx socket-security audit

Python

Python

pip-audit safety check
pip-audit safety check

Go

Go

govulncheck ./...
govulncheck ./...

Rust

Rust

cargo audit
undefined
cargo audit
undefined

Security Headers

安全头配置

HeaderValuePurpose
Content-Security-Policy
default-src 'self'
(customize per app)
Prevents XSS, data injection
Strict-Transport-Security
max-age=63072000; includeSubDomains
Forces HTTPS
X-Content-Type-Options
nosniff
Prevents MIME sniffing
X-Frame-Options
DENY
or
SAMEORIGIN
Prevents clickjacking
Referrer-Policy
strict-origin-when-cross-origin
Controls referer leakage
Permissions-Policy
Disable unused APIsLimits browser feature access
响应头取值作用
Content-Security-Policy
default-src 'self'
(可根据应用自定义)
防范XSS、数据注入
Strict-Transport-Security
max-age=63072000; includeSubDomains
强制使用HTTPS
X-Content-Type-Options
nosniff
防范MIME类型嗅探
X-Frame-Options
DENY
SAMEORIGIN
防范点击劫持
Referrer-Policy
strict-origin-when-cross-origin
控制Referrer信息泄露
Permissions-Policy
禁用未使用的API限制浏览器功能访问权限

CORS Rules

CORS 规则

  • Never use
    Access-Control-Allow-Origin: *
    with credentials
  • Allowlist specific origins
  • Restrict allowed methods and headers to what is needed

  • 禁止搭配凭证使用
    Access-Control-Allow-Origin: *
  • 配置白名单域名
  • 仅允许必要的请求方法和请求头

Phase 5: Threat Modeling (STRIDE)

第五阶段:威胁建模(STRIDE)

Goal: For new features or significant changes, walk through each threat category.
ThreatQuestionMitigation
SpoofingCan an attacker pretend to be someone else?Strong authentication, MFA
TamperingCan data be modified without detection?Integrity checks, signatures
RepudiationCan a user deny performing an action?Audit logging
Information DisclosureCan sensitive data leak through errors, logs, or side channels?Error sanitization, encryption
Denial of ServiceCan the system be overwhelmed?Rate limits, resource quotas
Elevation of PrivilegeCan a user gain permissions they should not have?Least privilege, RBAC
For each identified threat:
  1. Document the threat and attack vector
  2. Assess likelihood and impact
  3. Define mitigations
  4. Verify mitigations are implemented and tested

目标: 针对新功能或重大变更,逐一排查每个威胁类别。
威胁排查问题缓解方案
欺骗(Spoofing)攻击者能否冒充其他身份?强身份认证、MFA
篡改(Tampering)数据能否被未察觉地修改?完整性校验、签名
抵赖(Repudiation)用户能否否认自己的操作?审计日志
信息泄露(Information Disclosure)敏感数据能否通过错误、日志或侧信道泄露?错误信息脱敏、加密
拒绝服务(Denial of Service)系统能否被打垮?限流、资源配额
权限提升(Elevation of Privilege)用户能否获取超出自身范围的权限?最小权限原则、RBAC
对每个识别到的威胁:
  1. 记录威胁和攻击路径
  2. 评估发生概率和影响范围
  3. 定义缓解措施
  4. 验证缓解措施已实现并经过测试

Decision Table: Security Review Depth

决策表:安全审查深度

Change TypeReview DepthFocus Areas
Auth/session changesFull STRIDE + OWASPAll categories
User input handlingInjection + validation focusOWASP 1, 3, 10
Dependency updateCVE scan + changelog reviewOWASP 6
API endpoint additionAccess control + input validationOWASP 1, 3, 5
Config/infrastructureSecrets + headers + misconfigOWASP 2, 5
File upload featureInjection + SSRF + malwareOWASP 3, 10

变更类型审查深度重点关注领域
认证/会话变更完整STRIDE+OWASP审查所有类别
用户输入处理变更重点排查注入+验证OWASP 1、3、10
依赖更新CVE扫描+变更日志审查OWASP 6
新增API端点访问控制+输入验证OWASP 1、3、5
配置/基础设施变更密钥+安全头+配置错误OWASP 2、5
新增文件上传功能注入+SSRF+恶意软件OWASP 3、10

Anti-Patterns / Common Mistakes

反模式/常见错误

Anti-PatternWhy It Is WrongCorrect Approach
Client-side only validationEasily bypassedAlways validate server-side
Storing tokens in localStorageXSS can steal themUse HttpOnly cookies
Block-list input validationAlways incompleteUse allow-list validation
Generic error messages in productionMay leak internal detailsSanitize errors, log details server-side
Same secrets across environmentsBreach of one compromises allUnique secrets per environment
Ignoring dependency CVEsKnown vulnerabilities are actively exploitedAudit and update regularly
CORS wildcard with credentialsDefeats CORS protection entirelyAllowlist specific origins
Logging sensitive dataLog exposure creates data breachNever log secrets, PII, or tokens

反模式风险正确做法
仅做客户端验证极易被绕过始终在服务端做验证
将令牌存在localStorageXSS攻击可窃取令牌使用HttpOnly Cookie
黑名单输入验证永远存在遗漏使用白名单验证
生产环境返回通用错误信息可能泄露内部细节错误信息脱敏,服务端记录完整日志
跨环境复用密钥一个环境泄露会波及所有环境每个环境使用独立密钥
忽略依赖CVE已知漏洞会被主动利用定期审计并更新依赖
搭配凭证使用CORS通配符完全失效CORS保护配置白名单域名
打印敏感数据日志日志泄露会导致数据泄露禁止打印密钥、PII、令牌日志

Secrets Rotation Schedule

密钥轮换计划

Secret TypeRotation FrequencyAfter Suspected Compromise
API keysEvery 90 daysImmediately
Database passwordsEvery 90 daysImmediately
Encryption keysAnnually (support key versioning)Immediately
JWT signing keysEvery 6 monthsImmediately
OAuth client secretsEvery 90 daysImmediately

密钥类型轮换频率疑似泄露后处理
API密钥每90天立即轮换
数据库密码每90天立即轮换
加密密钥每年(支持密钥版本化)立即轮换
JWT签名密钥每6个月立即轮换
OAuth客户端密钥每90天立即轮换

Subagent Dispatch Opportunities

子Agent调度场景

Task PatternDispatch ToWhen
Scanning different OWASP categories in parallel
Agent
tool with
subagent_type="Explore"
(one per category)
When reviewing a large codebase across multiple vulnerability types
Authentication flow analysis
Agent
tool with
subagent_type="general-purpose"
When auth implementation spans multiple files/services
Dependency vulnerability scanning
Bash
tool with
run_in_background=true
When running
npm audit
or similar tools concurrently
Follow the
dispatching-parallel-agents
skill protocol when dispatching.

任务模式调度对象触发时机
并行扫描不同OWASP类别配置
subagent_type="Explore"
Agent
工具(每个类别对应一个)
跨多种漏洞类型审查大型代码库时
认证流程分析配置
subagent_type="general-purpose"
Agent
工具
认证实现跨多个文件/服务时
依赖漏洞扫描配置
run_in_background=true
Bash
工具
并行运行
npm audit
等同类工具时
调度时遵循
dispatching-parallel-agents
技能协议。

Integration Points

集成点

SkillRelationship
code-review
Security findings are Critical category issues
senior-backend
Backend hardening follows security review findings
senior-fullstack
Auth implementation follows security patterns
acceptance-testing
Security requirements become acceptance criteria
performance-optimization
Rate limiting serves both security and performance
systematic-debugging
Security incidents trigger debugging workflow

技能关联关系
code-review
安全发现属于严重等级问题
senior-backend
后端加固基于安全审查发现执行
senior-fullstack
认证实现遵循安全模式
acceptance-testing
安全要求转化为验收标准
performance-optimization
限流同时满足安全和性能需求
systematic-debugging
安全事件触发调试工作流

Skill Type

技能类型

FLEXIBLE — Adapt the depth of review to the change type using the decision table. The OWASP checklist and STRIDE analysis are strongly recommended for any auth or input-handling changes. Secrets management rules are non-negotiable.
灵活型 — 根据决策表适配变更类型对应的审查深度。对于任何认证或输入处理变更,强烈建议执行OWASP检查清单和STRIDE分析。密钥管理规则为强制要求。