secure-coding-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Secure 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

快速参考

TaskLoad reference
Input validation & sanitization
skills/secure-coding-practices/references/input-validation.md
Output encoding & XSS prevention
skills/secure-coding-practices/references/output-encoding.md
Authentication & sessions
skills/secure-coding-practices/references/authentication.md
Cryptography & key management
skills/secure-coding-practices/references/cryptography.md
Dependencies & supply chain
skills/secure-coding-practices/references/dependencies.md
Error handling & logging
skills/secure-coding-practices/references/error-handling.md
Secure defaults & configuration
skills/secure-coding-practices/references/secure-defaults.md
任务参考文档路径
输入验证与清理
skills/secure-coding-practices/references/input-validation.md
输出编码与XSS防护
skills/secure-coding-practices/references/output-encoding.md
身份验证与会话
skills/secure-coding-practices/references/authentication.md
加密与密钥管理
skills/secure-coding-practices/references/cryptography.md
依赖项与供应链
skills/secure-coding-practices/references/dependencies.md
错误处理与日志记录
skills/secure-coding-practices/references/error-handling.md
安全默认值与配置
skills/secure-coding-practices/references/secure-defaults.md

Workflow

工作流程

  1. Identify security requirements - Authentication, authorization, data protection, compliance
  2. Load relevant references - Use Quick Reference table to find specific guidance
  3. Implement security controls - Apply patterns from references with proper context
  4. Validate implementation - Test with security scanners, penetration testing, code review
  5. Monitor and maintain - Regular security audits, dependency updates, vulnerability scanning
  1. 确定安全需求 - 身份验证、授权、数据保护、合规性
  2. 加载相关参考文档 - 使用快速参考表查找特定指导
  3. 实施安全控制 - 根据具体上下文应用参考文档中的模式
  4. 验证实现效果 - 使用安全扫描器、渗透测试、代码审查进行测试
  5. 监控与维护 - 定期安全审计、依赖项更新、漏洞扫描

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:
  1. String concatenation in SQL queries (injection risk)
  2. Direct file path construction from user input (traversal risk)
  3. eval(), Function(), or exec() with user input (code injection)
  4. Deserialization of untrusted data (RCE risk)
  5. Hardcoded secrets or credentials (exposure risk)
  6. Missing authentication/authorization checks (access control)
  7. Weak cryptography (MD5, SHA1, ECB mode)
  8. Verbose error messages in production (information disclosure)
  9. Missing input validation (injection, DoS)
  10. Insecure session configuration (hijacking risk)
代码审查中需注意以下模式:
  1. SQL查询中的字符串拼接(注入风险)
  2. 根据用户输入直接构造文件路径(路径遍历风险)
  3. 使用eval()、Function()或exec()处理用户输入(代码注入)
  4. 反序列化不受信任的数据(RCE风险)
  5. 硬编码密钥或凭据(泄露风险)
  6. 缺失身份验证/授权检查(访问控制问题)
  7. 弱加密(MD5、SHA1、ECB模式)
  8. 生产环境中使用详细错误消息(信息泄露)
  9. 缺失输入验证(注入、DoS)
  10. 不安全的会话配置(劫持风险)

Resources

资源

OWASP Resources:
Standards & Guidelines:
Tools:
  • SAST: SonarQube, Semgrep, CodeQL
  • DAST: OWASP ZAP, Burp Suite
  • SCA: Snyk, npm audit, Dependabot
  • Secrets Detection: TruffleHog, git-secrets
OWASP资源:
标准与指南:
工具:
  • SAST: SonarQube、Semgrep、CodeQL
  • DAST: OWASP ZAP、Burp Suite
  • SCA: Snyk、npm audit、Dependabot
  • 密钥检测: TruffleHog、git-secrets