security
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSecurity
安全
Security is not a feature — it is a property of every feature. Every endpoint, every form, every data flow, every integration point must be designed with security in mind from the start. Bolting security on after the fact is expensive, error-prone, and often incomplete.
This skill provides stack-agnostic guidance for building secure applications. It covers the OWASP Top 10, input validation, authentication and authorization patterns, data protection, secrets management, security headers, and common antipatterns.
安全并非一项功能——而是每一项功能都应具备的属性。从设计之初,每个端点、每个表单、每个数据流、每个集成点都必须考虑安全因素。事后再添加安全措施成本高昂、容易出错且往往不够全面。
本指南提供与技术栈无关的安全应用构建指导,涵盖OWASP Top 10、输入验证、身份认证与授权模式、数据保护、密钥管理、安全标头以及常见反模式。
When to Use
适用场景
Consult this skill when:
- Designing a new feature that handles user input, authentication, or sensitive data
- Reviewing code for security concerns
- Implementing authentication or authorization flows
- Handling secrets, API keys, or credentials
- Configuring HTTP security headers
- Assessing whether a dependency or design choice introduces risk
- Preparing for a security audit or penetration test
- Responding to a security incident or vulnerability report
在以下场景中参考本指南:
- 设计处理用户输入、身份认证或敏感数据的新功能
- 评审代码中的安全问题
- 实现身份认证或授权流程
- 处理密钥、API密钥或凭证
- 配置HTTP安全标头
- 评估依赖项或设计选择是否引入风险
- 准备安全审计或渗透测试
- 响应安全事件或漏洞报告
OWASP Top 10
OWASP Top 10
The OWASP Top 10 (2021 edition) represents the most critical security risks to web applications. Use this as a starting checklist — not an exhaustive list.
| # | Vulnerability | What It Is | Primary Defense |
|---|---|---|---|
| A01 | Broken Access Control | Users act outside intended permissions | Deny by default, enforce server-side |
| A02 | Cryptographic Failures | Sensitive data exposed due to weak/missing crypto | Use strong algorithms, encrypt in transit and at rest |
| A03 | Injection | Untrusted data sent to interpreter as part of a command/query | Parameterized queries, input validation |
| A04 | Insecure Design | Missing or ineffective security controls by design | Threat modeling, secure design patterns |
| A05 | Security Misconfiguration | Insecure default configs, incomplete setup | Hardened defaults, automated config validation |
| A06 | Vulnerable Components | Using components with known vulnerabilities | Dependency scanning, timely updates |
| A07 | Auth Failures | Broken authentication/identification | MFA, rate limiting, secure password storage |
| A08 | Integrity Failures | Code/data integrity not verified | Signed updates, CI/CD integrity checks |
| A09 | Logging Failures | Insufficient logging and monitoring | Log security events, set up alerting |
| A10 | SSRF | Server tricked into making unintended requests | Allowlist destinations, sanitize URLs |
OWASP Top 10(2021版)代表了Web应用面临的最关键安全风险。将其作为入门检查清单——而非详尽列表。
| # | 漏洞类型 | 定义 | 主要防御措施 |
|---|---|---|---|
| A01 | 访问控制失效 | 用户超出预期权限操作 | 默认拒绝,服务器端强制执行 |
| A02 | 加密机制失效 | 因加密薄弱或缺失导致敏感数据泄露 | 使用强算法,加密传输和存储数据 |
| A03 | 注入攻击 | 不可信数据作为命令/查询的一部分发送给解释器 | 参数化查询、输入验证 |
| A04 | 不安全设计 | 设计阶段缺失或无效的安全控制 | 威胁建模、安全设计模式 |
| A05 | 安全配置错误 | 不安全的默认配置、不完整的设置 | 强化默认配置、自动化配置验证 |
| A06 | 易受攻击的组件 | 使用存在已知漏洞的组件 | 依赖项扫描、及时更新 |
| A07 | 身份认证失效 | 身份认证/识别机制存在缺陷 | 多因素认证(MFA)、速率限制、安全密码存储 |
| A08 | 完整性失效 | 代码/数据完整性未验证 | 签名更新、CI/CD完整性检查 |
| A09 | 日志记录失效 | 日志记录与监控不足 | 记录安全事件、设置告警 |
| A10 | 服务器端请求伪造(SSRF) | 服务器被诱发出非预期请求 | 允许列表机制、URL清理 |
Input Validation
输入验证
Input validation is the first line of defense. Validate at every system boundary — not just at the UI.
Core principles:
- Validate on the server — client-side validation is a UX convenience, not a security control
- Allowlist over denylist — define what is acceptable rather than trying to block what is dangerous
- Validate type, length, format, and range — a "name" field should not accept 10MB of data or contain control characters
- Reject unexpected input — fail closed, do not attempt to "clean" malicious input and proceed
- Canonicalize before validation — normalize Unicode, decode URL encoding, resolve path traversals before checking
Type coercion dangers:
Loose type comparisons can bypass security checks. A string "0" might equal integer 0 or boolean false depending on the language. Always use strict comparison operators and explicit type casting.
Parameterized queries:
Never concatenate user input into SQL, LDAP, or OS commands. Always use parameterized queries or prepared statements. This applies to ORMs too — raw query methods bypass ORM protections. See secure coding reference for details.
输入验证是第一道防线。在每个系统边界进行验证——而非仅在UI层。
核心原则:
- 服务器端验证——客户端验证仅为用户体验优化,并非安全控制措施
- 优先使用允许列表而非拒绝列表——定义可接受的内容,而非尝试阻止危险内容
- 验证类型、长度、格式和范围——“姓名”字段不应接受10MB数据或包含控制字符
- 拒绝异常输入——采用关闭策略,不要尝试“清理”恶意输入后继续处理
- 验证前标准化——在检查前统一Unicode编码、解码URL编码、解析路径遍历
类型转换风险:
松散的类型比较可能绕过安全检查。字符串“0”在不同语言中可能等于整数0或布尔值false。始终使用严格比较运算符和显式类型转换。
参数化查询:
切勿将用户输入拼接进SQL、LDAP或操作系统命令。始终使用参数化查询或预编译语句。这同样适用于ORM——原生查询方法会绕过ORM的保护机制。详情请见安全编码参考文档。
Authentication Patterns
身份认证模式
Authentication verifies identity — "who are you?" See auth patterns reference for detailed guidance.
Password hashing:
- Use bcrypt, scrypt, or Argon2id — never MD5, SHA-1, or SHA-256 alone for passwords
- Salts must be unique per password and generated by the hashing library
- Never store plain-text passwords, never use reversible encryption for passwords
- Enforce minimum complexity but avoid overly restrictive rules that push users to weaker patterns
Multi-factor authentication (MFA):
- TOTP (time-based one-time passwords) is the baseline
- WebAuthn/passkeys provide the strongest phishing resistance
- SMS-based MFA is better than nothing but vulnerable to SIM swapping
- Always provide recovery codes
Session management:
- Generate cryptographically random session IDs with sufficient entropy (128+ bits)
- Set secure cookie attributes: ,
HttpOnly,Secure(orSameSite=Lax)Strict - Regenerate session ID after login to prevent session fixation
- Implement absolute and idle timeouts
- Invalidate sessions server-side on logout
Token-based auth (JWT caveats):
- JWTs are not sessions — they cannot be revoked without additional infrastructure
- Always validate the signature algorithm server-side; reject
alg: none - Keep tokens short-lived (minutes, not hours)
- Use refresh tokens for long-lived sessions; store them securely
- Never store sensitive data in JWT payloads — they are base64-encoded, not encrypted
OAuth2 flows:
- Authorization Code with PKCE — standard for web and mobile apps
- Client Credentials — for machine-to-machine communication
- Never use Implicit flow — it is deprecated for security reasons
身份认证用于验证身份——“你是谁?”详细指导请见身份认证模式参考文档。
密码哈希:
- 使用bcrypt、scrypt或Argon2id——切勿单独使用MD5、SHA-1或SHA-256存储密码
- 盐值必须每个密码唯一,且由哈希库生成
- 切勿存储明文密码,切勿对密码使用可逆加密
- 强制执行最低复杂度要求,但避免过于严格的规则导致用户采用更弱的密码模式
多因素认证(MFA):
- 基于时间的一次性密码(TOTP)是基准标准
- WebAuthn/通行密钥提供最强的防钓鱼能力
- 基于SMS的MFA聊胜于无,但易受SIM卡劫持攻击
- 始终提供恢复码
会话管理:
- 生成具有足够熵(128+位)的加密随机会话ID
- 设置安全Cookie属性:、
HttpOnly、Secure(或SameSite=Lax)Strict - 登录后重新生成会话ID以防止会话固定攻击
- 实现绝对超时和空闲超时
- 登出时在服务器端失效会话
基于令牌的认证(JWT注意事项):
- JWT并非会话——若无额外基础设施,无法撤销JWT
- 始终在服务器端验证签名算法;拒绝
alg: none - 保持令牌短生命周期(分钟级,而非小时级)
- 使用刷新令牌实现长会话;安全存储刷新令牌
- 切勿在JWT负载中存储敏感数据——它们仅经过base64编码,并未加密
OAuth2流程:
- 授权码流+PKCE——Web和移动应用的标准方案
- 客户端凭证流——适用于机器对机器通信
- 切勿使用隐式流——因安全原因已被弃用
Authorization Patterns
授权模式
Authorization determines permissions — "what are you allowed to do?" Authorization is not authentication. See auth patterns reference for details.
Principle of least privilege:
- Grant the minimum permissions needed for a task
- Default to deny — explicitly grant access rather than revoking it
- Time-bound elevated privileges when possible
Role-Based Access Control (RBAC):
- Assign permissions to roles, assign roles to users
- Keep roles coarse-grained; avoid role explosion
- Check permissions, not role names, in application code — this decouples authorization logic from role definitions
Attribute-Based Access Control (ABAC):
- Decisions based on attributes of user, resource, action, and environment
- More flexible than RBAC for complex policies (e.g., "managers can approve expenses under $10,000 during business hours")
- Higher complexity — use when RBAC is insufficient
Common authorization mistakes:
- Checking authorization only in the UI — always enforce server-side
- Relying on obscurity (unguessable URLs) instead of access controls
- Failing to check authorization on every request (including API calls, file downloads, and indirect references)
- IDOR (Insecure Direct Object Reference) — always verify the user has access to the specific resource they are requesting
授权用于确定权限——“你可以做什么?”授权不等同于身份认证。详情请见身份认证模式参考文档。
最小权限原则:
- 授予完成任务所需的最小权限
- 默认拒绝——明确授予访问权限,而非事后撤销
- 尽可能使用限时提升权限
基于角色的访问控制(RBAC):
- 将权限分配给角色,再将角色分配给用户
- 保持角色粗粒度;避免角色爆炸
- 在应用代码中检查权限而非角色名称——这将授权逻辑与角色定义解耦
基于属性的访问控制(ABAC):
- 基于用户、资源、操作和环境的属性决策
- 对于复杂策略比RBAC更灵活(例如:“经理可在工作时间批准10000美元以下的费用”)
- 复杂度更高——仅在RBAC不足时使用
常见授权错误:
- 仅在UI层检查授权——始终在服务器端强制执行
- 依赖模糊性(不可猜测的URL)替代访问控制
- 未在每个请求中检查授权(包括API调用、文件下载和间接引用)
- 不安全的直接对象引用(IDOR)——始终验证用户是否有权访问其请求的特定资源
Data Protection
数据保护
Encryption at rest:
- Encrypt sensitive data stored in databases, files, and backups
- Use AES-256 or equivalent for symmetric encryption
- Manage encryption keys separately from encrypted data
- Rotate encryption keys on a schedule and when compromise is suspected
Encryption in transit:
- Use TLS 1.2+ for all network communication
- Disable older protocols (SSL, TLS 1.0, TLS 1.1)
- Validate certificates properly — do not disable certificate verification
PII handling:
- Identify and classify all personally identifiable information
- Minimize collection — do not collect data you do not need
- Implement data retention policies — delete data when no longer needed
- Provide data export and deletion capabilities for compliance (GDPR, CCPA)
- Mask PII in logs — never log passwords, tokens, credit card numbers, or full SSNs
Secure deletion:
- Overwrite sensitive data before freeing memory (when the language allows)
- Ensure database deletions actually remove data (not just soft-delete for sensitive records)
- Consider backup retention — deleted data may persist in backups
静态加密:
- 加密存储在数据库、文件和备份中的敏感数据
- 使用AES-256或等效对称加密算法
- 单独管理加密密钥与加密数据
- 定期轮换加密密钥,疑似泄露时立即轮换
传输加密:
- 所有网络通信使用TLS 1.2+版本
- 禁用旧协议(SSL、TLS 1.0、TLS 1.1)
- 正确验证证书——切勿禁用证书验证
个人可识别信息(PII)处理:
- 识别并分类所有个人可识别信息
- 最小化收集——不要收集不需要的数据
- 实施数据保留策略——不再需要时删除数据
- 提供合规的数据导出和删除功能(GDPR、CCPA)
- 在日志中脱敏PII——切勿记录密码、令牌、信用卡号或完整社保号
安全删除:
- 释放内存前覆盖敏感数据(语言支持的情况下)
- 确保数据库删除操作实际移除数据(敏感记录不要仅软删除)
- 考虑备份保留期——已删除的数据可能仍存在于备份中
Secrets Management
密钥管理
Never in code or config files:
- No API keys, passwords, or tokens in source code, config files, or environment-specific files committed to version control
- Use for local config files, but do not rely on it as your only protection
.gitignore - Scan repositories for accidentally committed secrets (use tools like git-secrets, truffleHog, or Gitleaks)
Environment variables:
- Acceptable for simple deployments but have limitations
- They are visible to all processes in the same environment
- They appear in process listings and crash dumps
- Better than hardcoding, but not the strongest option
Secret managers:
- Use dedicated secret managers (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, GCP Secret Manager)
- Access secrets at runtime, not build time
- Audit access to secrets
Rotation strategy:
- Rotate secrets on a regular schedule
- Rotate immediately if compromise is suspected
- Design systems to support rotation without downtime (support two active versions during transition)
- Automate rotation where possible
切勿存储在代码或配置文件中:
- 不要在源代码、配置文件或提交到版本控制的环境特定文件中存储API密钥、密码或令牌
- 对本地配置文件使用,但不要将其作为唯一保护措施
.gitignore - 扫描仓库中意外提交的密钥(使用git-secrets、truffleHog或Gitleaks等工具)
环境变量:
- 适用于简单部署,但存在局限性
- 同一环境中的所有进程均可查看
- 会出现在进程列表和崩溃转储中
- 比硬编码好,但并非最安全的选项
密钥管理器:
- 使用专用密钥管理器(HashiCorp Vault、AWS Secrets Manager、Azure Key Vault、GCP Secret Manager)
- 在运行时而非构建时访问密钥
- 审计密钥访问记录
轮换策略:
- 定期轮换密钥
- 疑似泄露时立即轮换
- 设计支持无停机轮换的系统(过渡期间支持两个活跃版本)
- 尽可能自动化轮换
Security Headers
安全标头
Configure these HTTP response headers on every response. Each addresses a specific class of attack.
| Header | Purpose | Recommended Value |
|---|---|---|
| Prevents XSS by controlling which sources can load content | Start with a restrictive policy; avoid |
| Forces HTTPS for all future requests | |
| Prevents MIME-type sniffing | |
| Prevents clickjacking by controlling iframe embedding | |
| Controls how much referrer info is sent | |
| Controls browser features (camera, mic, geolocation) | Disable features you do not use |
CORS (Cross-Origin Resource Sharing):
- Do not use for authenticated endpoints
Access-Control-Allow-Origin: * - Allowlist specific origins
- Be restrictive with and
Access-Control-Allow-MethodsAccess-Control-Allow-Headers - Understand that CORS is enforced by browsers — it does not protect server-to-server calls
在每个响应中配置以下HTTP响应标头,每个标头针对特定类型的攻击。
| 标头 | 用途 | 推荐值 |
|---|---|---|
| 通过控制可加载内容的来源防止XSS攻击 | 从限制性策略开始;避免使用 |
| 强制后续所有请求使用HTTPS | |
| 防止MIME类型嗅探 | |
| 通过控制iframe嵌入防止点击劫持 | |
| 控制发送的引用信息数量 | |
| 控制浏览器功能(摄像头、麦克风、地理位置) | 禁用未使用的功能 |
跨源资源共享(CORS):
- 针对已认证端点,不要使用
Access-Control-Allow-Origin: * - 允许列表指定具体来源
- 严格限制和
Access-Control-Allow-MethodsAccess-Control-Allow-Headers - 注意CORS由浏览器强制执行——无法保护服务器到服务器的调用
Common Antipatterns
常见反模式
These are frequently encountered mistakes that create vulnerabilities:
- Security through obscurity — hiding URLs, using unpredictable IDs, or obfuscating code is not a security control. It supplements real controls; it never replaces them.
- Client-side validation only — any validation done in JavaScript or mobile code can be bypassed. Always validate server-side.
- Homegrown cryptography — never implement your own encryption, hashing, or random number generation. Use well-tested libraries.
- Overly permissive CORS — combined with credentials is a vulnerability. Be specific about allowed origins.
Access-Control-Allow-Origin: * - Storing secrets in repositories — even in "private" repos, secrets in code spread through forks, CI systems, and developer machines.
- Disabling security features for convenience — turning off CSRF protection, SSL verification, or authentication in "development" mode that leaks to production.
- Trusting internal networks — zero-trust means verifying identity and authorization even for internal service-to-service calls.
- Ignoring dependency vulnerabilities — known vulnerabilities in dependencies are among the easiest attack vectors. Scan and update regularly.
- Logging sensitive data — passwords, tokens, credit card numbers, and PII in logs create a secondary exposure surface.
- Catching and silencing exceptions — swallowing errors hides security failures. Log them (without sensitive details) and fail safely.
这些是经常遇到的会产生漏洞的错误:
- 通过模糊性实现安全——隐藏URL、使用不可预测ID或混淆代码并非安全控制措施。它仅能补充真正的控制措施,绝不能替代。
- 仅依赖客户端验证——任何在JavaScript或移动代码中完成的验证都可能被绕过。始终在服务器端验证。
- 自研加密算法——切勿自行实现加密、哈希或随机数生成。使用经过充分测试的库。
- 过于宽松的CORS配置——与凭证结合使用是漏洞。明确指定允许的来源。
Access-Control-Allow-Origin: * - 在仓库中存储密钥——即使在“私有”仓库中,代码中的密钥也会通过分支、CI系统和开发机器传播。
- 为了便利禁用安全功能——在“开发”模式下关闭CSRF保护、SSL验证或身份认证,却泄露到生产环境。
- 信任内部网络——零信任意味着即使是内部服务间调用,也需验证身份和授权。
- 忽略依赖项漏洞——依赖项中的已知漏洞是最容易被利用的攻击向量之一。定期扫描和更新。
- 记录敏感数据——日志中的密码、令牌、信用卡号和PII会形成二次暴露面。
- 捕获并静默异常——吞掉错误会隐藏安全故障。记录错误(不含敏感细节)并安全失败。
Security Review Checklist
安全评审清单
Use this checklist when reviewing code, designing features, or preparing for release:
Input/Output:
- All user input is validated server-side
- Parameterized queries used for all database operations
- Output is encoded/escaped for the appropriate context (HTML, URL, JavaScript, SQL)
- File uploads validate type, size, and content; stored outside web root
Authentication:
- Passwords hashed with bcrypt/Argon2id
- Session IDs regenerated after login
- Secure cookie attributes set (HttpOnly, Secure, SameSite)
- Rate limiting on login endpoints
- Account lockout or progressive delays after failed attempts
Authorization:
- Authorization enforced server-side on every request
- Principle of least privilege applied
- Direct object references validated against the current user
- Admin functions protected and not accessible through URL guessing
Data:
- Sensitive data encrypted at rest and in transit
- PII not logged
- Data retention policies implemented
- Backups encrypted
Configuration:
- No secrets in source code or config files
- Security headers configured
- Debug mode disabled in production
- Error messages do not leak internal details to clients
- Dependencies scanned for known vulnerabilities
- TLS 1.2+ enforced; older protocols disabled
Monitoring:
- Security events logged (login failures, authorization denials, input validation failures)
- Alerts configured for suspicious patterns
- Logs protected from tampering
- Incident response plan documented
评审代码、设计功能或准备发布时使用本清单:
输入/输出:
- 所有用户输入均在服务器端验证
- 所有数据库操作使用参数化查询
- 输出根据对应上下文(HTML、URL、JavaScript、SQL)进行编码/转义
- 文件上传验证类型、大小和内容;存储在网站根目录外
身份认证:
- 密码使用bcrypt/Argon2id哈希
- 登录后重新生成会话ID
- 设置安全Cookie属性(HttpOnly、Secure、SameSite)
- 登录端点配置速率限制
- 失败尝试后触发账户锁定或渐进式延迟
授权:
- 每个请求在服务器端强制执行授权
- 应用最小权限原则
- 直接对象引用针对当前用户验证
- 管理功能受保护,无法通过URL猜测访问
数据:
- 敏感数据在静态和传输时均加密
- PII未记录在日志中
- 实施数据保留策略
- 备份已加密
配置:
- 源代码或配置文件中无密钥
- 配置安全标头
- 生产环境禁用调试模式
- 错误消息未向客户端泄露内部细节
- 扫描依赖项的已知漏洞
- 强制使用TLS 1.2+;禁用旧协议
监控:
- 记录安全事件(登录失败、授权拒绝、输入验证失败)
- 针对可疑模式配置告警
- 日志防篡改
- 记录事件响应计划