secure-coding-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSecure Coding Practices
安全编码实践
Comprehensive guidance for implementing security-first development patterns with defensive programming techniques and proactive threat mitigation strategies.
为采用防御性编程技术和主动威胁缓解策略的安全优先开发模式提供全面指导。
When to Use This Skill
适用场景
- Implementing authentication and authorization systems
- Processing user input or external data
- Handling sensitive data (PII, credentials, financial information)
- Building APIs and web services
- Managing cryptographic operations (hashing, encryption)
- Conducting security-focused code reviews
- Establishing secure development standards for teams
- Evaluating third-party dependencies and libraries
- Designing error handling and logging strategies
- Implementing session management and token handling
- 实现身份验证与授权系统
- 处理用户输入或外部数据
- 管理敏感数据(PII、凭据、财务信息)
- 构建API与Web服务
- 管理加密操作(哈希、加密)
- 开展以安全为重点的代码审查
- 为团队制定安全开发标准
- 评估第三方依赖项与库
- 设计错误处理与日志记录策略
- 实现会话管理与令牌处理
Core Security Principles
核心安全原则
Defense in Depth
纵深防御
Apply multiple layers of security controls - never rely on a single protection mechanism.
应用多层安全控制——绝不依赖单一保护机制。
Fail Securely
安全失败
When errors occur, default to the secure state (deny access, reject input, log event).
发生错误时,默认进入安全状态(拒绝访问、拒绝输入、记录事件)。
Least Privilege
最小权限
Grant minimum necessary permissions - users, services, and databases should have only required access.
授予必要的最小权限——用户、服务和数据库应仅拥有所需的访问权限。
Trust Nothing
不信任任何事物
Validate all input, encode all output, verify all sources, authenticate all requests.
验证所有输入,编码所有输出,验证所有来源,认证所有请求。
Quick Reference
快速参考
| Task | Load reference |
|---|---|
| Input validation & sanitization | |
| Output encoding & XSS prevention | |
| Authentication & sessions | |
| Cryptography & key management | |
| Dependencies & supply chain | |
| Error handling & logging | |
| Secure defaults & configuration | |
| 任务 | 参考文档路径 |
|---|---|
| 输入验证与清理 | |
| 输出编码与XSS防护 | |
| 身份验证与会话 | |
| 加密与密钥管理 | |
| 依赖项与供应链 | |
| 错误处理与日志记录 | |
| 安全默认值与配置 | |
Workflow
工作流程
- Identify security requirements - Authentication, authorization, data protection, compliance
- Load relevant references - Use Quick Reference table to find specific guidance
- Implement security controls - Apply patterns from references with proper context
- Validate implementation - Test with security scanners, penetration testing, code review
- Monitor and maintain - Regular security audits, dependency updates, vulnerability scanning
- 确定安全需求 - 身份验证、授权、数据保护、合规性
- 加载相关参考文档 - 使用快速参考表查找特定指导
- 实施安全控制 - 根据具体上下文应用参考文档中的模式
- 验证实现效果 - 使用安全扫描器、渗透测试、代码审查进行测试
- 监控与维护 - 定期安全审计、依赖项更新、漏洞扫描
Security Checklist
安全检查清单
Input Validation:
- Validate all user input server-side with allowlists
- Use schema validation libraries (Joi, Yup, Zod)
- Implement strict type checking
- Sanitize file paths and prevent traversal
Output Encoding:
- Apply context-aware encoding (HTML, JS, URL, SQL)
- Use templating engines with auto-escaping
- Implement Content Security Policy (CSP)
- Set secure HTTP headers (Helmet.js)
Authentication & Authorization:
- Hash passwords with bcrypt/Argon2 (salt rounds ≥12)
- Implement secure session management
- Use HTTPS-only cookies with HttpOnly and SameSite
- Apply rate limiting on authentication endpoints
- Verify authorization on every request
Cryptography:
- Use AES-256-GCM for encryption
- Generate keys with crypto.randomBytes()
- Store secrets in environment variables or KMS
- Never roll your own crypto
Dependencies:
- Run npm audit regularly
- Lock dependency versions in package.json
- Use Snyk/Dependabot for monitoring
- Verify package integrity (SRI for CDN)
Error Handling & Logging:
- Return generic error messages to users
- Log errors with correlation IDs
- Never log passwords, tokens, or PII
- Monitor security events and alerts
输入验证:
- 在服务器端使用允许列表验证所有用户输入
- 使用模式验证库(Joi、Yup、Zod)
- 实施严格的类型检查
- 清理文件路径并防止路径遍历
输出编码:
- 应用上下文感知编码(HTML、JS、URL、SQL)
- 使用具备自动转义功能的模板引擎
- 实施内容安全策略(CSP)
- 设置安全HTTP头(Helmet.js)
身份验证与授权:
- 使用bcrypt/Argon2哈希密码(盐轮数≥12)
- 实现安全会话管理
- 使用仅HTTPS的HttpOnly和SameSite Cookie
- 在身份验证端点应用速率限制
- 对每个请求验证授权
加密技术:
- 使用AES-256-GCM进行加密
- 使用crypto.randomBytes()生成密钥
- 将密钥存储在环境变量或KMS中
- 绝不自行实现加密逻辑
依赖项:
- 定期运行npm audit
- 在package.json中锁定依赖项版本
- 使用Snyk/Dependabot进行监控
- 验证包完整性(CDN使用SRI)
错误处理与日志记录:
- 向用户返回通用错误消息
- 使用关联ID记录错误
- 绝不记录密码、令牌或PII
- 监控安全事件与警报
Common Mistakes
常见错误
- Using client-side validation as sole defense (always validate server-side)
- Blocklisting instead of allowlisting (define what's allowed, not forbidden)
- Exposing stack traces or internal errors to users
- Hardcoding secrets in source code
- Using Math.random() for security-critical operations
- Not implementing rate limiting on authentication endpoints
- Loose equality comparisons allowing type coercion attacks
- Trusting user input in database queries (SQL injection)
- Missing output encoding based on context (XSS vulnerabilities)
- Insufficient password hashing (weak algorithms or low work factor)
- 将客户端验证作为唯一防御手段(始终在服务器端验证)
- 使用拒绝列表而非允许列表(定义允许的内容,而非禁止的内容)
- 向用户暴露堆栈跟踪或内部错误
- 在源代码中硬编码密钥
- 使用Math.random()处理安全关键操作
- 未在身份验证端点实施速率限制
- 宽松的相等比较允许类型强制转换攻击
- 在数据库查询中信任用户输入(SQL注入)
- 未根据上下文进行输出编码(XSS漏洞)
- 密码哈希不足(弱算法或低工作因子)
High-Risk Code Patterns
高风险代码模式
Watch for these patterns in code reviews:
- String concatenation in SQL queries (injection risk)
- Direct file path construction from user input (traversal risk)
- eval(), Function(), or exec() with user input (code injection)
- Deserialization of untrusted data (RCE risk)
- Hardcoded secrets or credentials (exposure risk)
- Missing authentication/authorization checks (access control)
- Weak cryptography (MD5, SHA1, ECB mode)
- Verbose error messages in production (information disclosure)
- Missing input validation (injection, DoS)
- Insecure session configuration (hijacking risk)
代码审查中需注意以下模式:
- SQL查询中的字符串拼接(注入风险)
- 根据用户输入直接构造文件路径(路径遍历风险)
- 使用eval()、Function()或exec()处理用户输入(代码注入)
- 反序列化不受信任的数据(RCE风险)
- 硬编码密钥或凭据(泄露风险)
- 缺失身份验证/授权检查(访问控制问题)
- 弱加密(MD5、SHA1、ECB模式)
- 生产环境中使用详细错误消息(信息泄露)
- 缺失输入验证(注入、DoS)
- 不安全的会话配置(劫持风险)
Resources
资源
OWASP Resources:
- OWASP Top 10: https://owasp.org/Top10/
- OWASP Cheat Sheet Series: https://cheatsheetseries.owasp.org/
- OWASP ASVS: Application Security Verification Standard
- OWASP Dependency-Check: https://owasp.org/www-project-dependency-check/
Standards & Guidelines:
- NIST Cybersecurity Framework: https://www.nist.gov/cyberframework
- NIST SP 800-63B: Digital Identity Guidelines (Authentication)
- CWE Top 25: https://cwe.mitre.org/top25/
Tools:
- SAST: SonarQube, Semgrep, CodeQL
- DAST: OWASP ZAP, Burp Suite
- SCA: Snyk, npm audit, Dependabot
- Secrets Detection: TruffleHog, git-secrets
OWASP资源:
- OWASP Top 10: https://owasp.org/Top10/
- OWASP Cheat Sheet Series: https://cheatsheetseries.owasp.org/
- OWASP ASVS: 应用安全验证标准
- OWASP Dependency-Check: https://owasp.org/www-project-dependency-check/
标准与指南:
- NIST网络安全框架: https://www.nist.gov/cyberframework
- NIST SP 800-63B: 数字身份指南(身份验证)
- CWE Top 25: https://cwe.mitre.org/top25/
工具:
- SAST: SonarQube、Semgrep、CodeQL
- DAST: OWASP ZAP、Burp Suite
- SCA: Snyk、npm audit、Dependabot
- 密钥检测: TruffleHog、git-secrets