python-security
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePython Security Development Guide
Python安全开发指南
Provide a structured approach to building secure Python applications, covering the OWASP Top 10, secure coding patterns, and verification checklists. Apply these guidelines throughout the secure development lifecycle — from threat modeling through deployment.
本文提供构建安全Python应用的结构化方法,涵盖OWASP Top 10、安全编码模式及验证清单。在安全开发生命周期的各个阶段——从威胁建模到部署——均需遵循这些指南。
Secure Development Lifecycle
安全开发生命周期
Phase 1: Threat Modeling and Secure Design
阶段1:威胁建模与安全设计
Before writing code, identify and mitigate threats at the design level:
- Identify trust boundaries — Map where untrusted data enters the system (HTTP requests, file uploads, database reads, environment variables, third-party APIs)
- Map data flows — Trace sensitive data (credentials, PII, tokens) through the system and verify protection at each stage
- Enumerate entry points — List all routes, endpoints, CLI arguments, message queue consumers, and cron jobs
- Map attack surfaces to OWASP Top 10 — Cross-reference each entry point against the OWASP categories in the quick reference table below
Design with security controls built-in:
- Centralized authentication and authorization middleware — never scatter auth checks across handlers
- Input validation at every trust boundary — validate early, reject invalid data before processing
- Least-privilege database access — use read-only connections where writes are not needed
- Defense in depth — layer multiple controls (input validation + parameterized queries + WAF)
- Fail securely — deny by default, require explicit grants
编写代码前,在设计层面识别并缓解威胁:
- 识别信任边界 —— 绘制不可信数据进入系统的路径(HTTP请求、文件上传、数据库读取、环境变量、第三方API)
- 梳理数据流 —— 追踪敏感数据(凭证、PII、令牌)在系统中的流转,并验证每个环节的保护措施
- 枚举入口点 —— 列出所有路由、端点、CLI参数、消息队列消费者及定时任务
- 将攻击面映射到OWASP Top 10 —— 将每个入口点与下方快速参考表中的OWASP类别交叉对照
设计时内置安全控制:
- 集中式身份验证与授权中间件 —— 切勿在多个处理器中分散权限检查
- 在每个信任边界处进行输入验证 —— 尽早验证,在处理前拒绝无效数据
- 数据库最小权限访问 —— 在无需写入的场景使用只读连接
- 纵深防御 —— 多层控制叠加(输入验证 + 参数化查询 + WAF)
- 安全失败默认 —— 默认拒绝,需显式授权
Phase 2: Secure Implementation
阶段2:安全实现
Critical Prohibitions
严格禁止的模式
Never use these patterns. Violations are high-severity findings in any review.
| Never | Instead |
|---|---|
| |
| |
| |
| |
| |
| String formatting / f-strings in SQL | Parameterized queries ( |
| |
| MD5 / SHA1 for password hashing | |
| |
Bare | |
| Hardcoded secrets in source code | Environment variables or secret manager (Vault, AWS SM) |
| Environment-specific configuration |
绝不要使用以下模式。在任何审查中,违反这些规则均属于高严重性问题。
| 禁止使用 | 替代方案 |
|---|---|
| |
| |
| |
| |
| |
| SQL中使用字符串格式化/f-string | 参数化查询( |
| |
| MD5 / SHA1 用于密码哈希 | |
| |
裸 | |
| 源代码中硬编码密钥 | 环境变量或密钥管理器(Vault、AWS SM) |
生产环境中设置 | 环境专属配置 |
Secure Implementation References
安全实现参考
- For OWASP Top 10 details with vulnerable → secure code examples: See references/owasp-top-10.md
- For secure coding patterns organized by domain (input validation, auth, crypto, serialization, subprocess, file I/O, web frameworks): See references/secure-coding.md
- 如需查看包含漏洞代码→安全代码示例的OWASP Top 10详细内容:请参阅references/owasp-top-10.md
- 如需按领域(输入验证、权限、加密、序列化、子进程、文件I/O、Web框架)分类的安全编码模式:请参阅references/secure-coding.md
Phase 3: Security Verification
阶段3:安全验证
Apply a layered verification approach:
- Static Analysis — Detect common vulnerability patterns automatically
- — Python-specific security linter (AST-based)
bandit - — Pattern-based analysis with OWASP and Python rulesets
semgrep - — General linting with some security-relevant checks
pylint
- Dependency Audit — Identify known vulnerabilities in third-party packages
- — Check installed packages against the OSV database
pip-audit - — Check against the Safety vulnerability database
safety
- Secrets Detection — Find leaked credentials and API keys
- — Baseline-aware secrets scanner
detect-secrets
- Code Review — Apply the security review workflow and checklists
- Security Testing — Write negative tests that verify rejection of malicious inputs; fuzz-test parsers and validators
Quick tool commands:
bash
undefined采用分层验证方法:
- 静态分析 —— 自动检测常见漏洞模式
- —— 基于AST的Python专用安全代码检查工具
bandit - —— 基于模式的分析工具,支持OWASP和Python规则集
semgrep - —— 通用代码检查工具,包含部分安全相关检查
pylint
- 依赖审计 —— 识别第三方包中的已知漏洞
- —— 对照OSV数据库检查已安装包
pip-audit - —— 对照Safety漏洞数据库检查
safety
- 密钥检测 —— 查找泄露的凭证和API密钥
- —— 支持基线对比的密钥扫描工具
detect-secrets
- 代码审查 —— 遵循安全审查工作流并使用检查清单
- 安全测试 —— 编写负面测试验证恶意输入被拒绝;对解析器和验证器进行模糊测试
快速工具命令:
bash
undefinedBandit — static analysis
Bandit — 静态分析
bandit -r src/ -f json -o bandit-report.json
bandit -r src/ -f json -o bandit-report.json
pip-audit — dependency vulnerabilities
pip-audit — 依赖漏洞检查
pip-audit
pip-audit
Safety — alternative dependency check
Safety — 替代依赖检查工具
safety check
safety check
detect-secrets — secrets scanning
detect-secrets — 密钥扫描
detect-secrets scan > .secrets.baseline
detect-secrets scan > .secrets.baseline
Semgrep — advanced pattern matching
Semgrep — 高级模式匹配
semgrep --config=p/python --config=p/owasp-top-ten src/
For complete verification checklists (code review, architecture review, dependency audit, deployment, testing, incident response): See [references/security-checklist.md](references/security-checklist.md)semgrep --config=p/python --config=p/owasp-top-ten src/
如需完整的验证检查清单(代码审查、架构审查、依赖审计、部署、测试、事件响应):请参阅[references/security-checklist.md](references/security-checklist.md)Phase 4: Dependency and Deployment Security
阶段4:依赖与部署安全
Dependency Management
依赖管理
- Pin all dependencies with exact versions in
requirements.txt - Use hash verification:
pip install --require-hashes -r requirements.txt - Run in CI/CD pipeline on every build
pip-audit - Monitor for typosquatting — verify package names carefully before installing
- Review new dependencies before adding — check maintainership, download counts, known issues
- 在中固定所有依赖的精确版本
requirements.txt - 使用哈希验证:
pip install --require-hashes -r requirements.txt - 在CI/CD流水线的每次构建中运行
pip-audit - 监控仿冒包——安装前仔细验证包名
- 添加新依赖前进行审查——检查维护情况、下载量、已知问题
Deployment Hardening
部署加固
- Container security — Scan images with ; use minimal base images (distroless, alpine); run as non-root user
trivy - HTTPS/TLS — Enforce TLS 1.2+ for all connections; redirect HTTP to HTTPS; set header
Strict-Transport-Security - Security headers — Configure ,
Content-Security-Policy,X-Content-Type-Options: nosniffX-Frame-Options: DENY - Secrets at runtime — Inject secrets via environment variables or mounted volumes; never bake into images
- Least privilege — Run processes as non-root; use read-only filesystems where possible; limit network access
- Logging — Use structured logging (JSON); never log passwords, tokens, PII, or full stack traces to users; log authentication events and access denials for audit
- 容器安全 —— 使用扫描镜像;使用最小化基础镜像(distroless、alpine);以非root用户运行
trivy - HTTPS/TLS —— 强制所有连接使用TLS 1.2+;将HTTP重定向至HTTPS;设置头部
Strict-Transport-Security - 安全头部 —— 配置、
Content-Security-Policy、X-Content-Type-Options: nosniffX-Frame-Options: DENY - 运行时密钥 —— 通过环境变量或挂载卷注入密钥;绝不要嵌入到镜像中
- 最小权限 —— 以非root用户运行进程;尽可能使用只读文件系统;限制网络访问
- 日志 —— 使用结构化日志(JSON);绝不向用户记录密码、令牌、PII或完整堆栈跟踪;记录身份验证事件和访问拒绝情况用于审计
OWASP Top 10:2025 Quick Reference
OWASP Top 10:2025快速参考
Map each OWASP 2025 category to Python-specific risks and primary mitigations:
| # | Category | Python-Specific Risks | Primary Mitigation |
|---|---|---|---|
| A01 | Broken Access Control | Missing | Centralized auth middleware, object-level permissions, |
| A02 | Security Misconfiguration | | Environment-specific config, explicit CORS origins, disable docs in prod, |
| A03 | Software Supply Chain Failures | Unpinned deps, typosquatting, no SBOM, unvetted transitive deps, CI/CD secrets exposure | |
| A04 | Cryptographic Failures | | |
| A05 | Injection | SQL via f-strings/ | safe |
| A06 | Insecure Design | No rate limiting, missing input validation layer, no abuse case modeling | Threat modeling, validation at boundaries (Pydantic), rate limiting middleware |
| A07 | Authentication Failures | Weak session config, JWT | Secure session settings, explicit |
| A08 | Software or Data Integrity Failures | | |
| A09 | Security Logging and Alerting Failures | Logging passwords/tokens, no auth event logging, missing alerting, no playbooks | Structured logging with field filtering, audit trail, alerting thresholds, honeytokens |
| A10 | Mishandling of Exceptional Conditions | Bare | Specific exception types, context managers, centralized error handlers, fail-closed patterns |
For detailed vulnerable → secure code examples for each category: See references/owasp-top-10.md
将每个OWASP 2025类别映射到Python特有风险及主要缓解措施:
| # | 类别 | Python特有风险 | 主要缓解措施 |
|---|---|---|---|
| A01 | Broken Access Control(访问控制失效) | 缺失 | 集中式权限中间件、对象级权限控制、 |
| A02 | Security Misconfiguration(安全配置错误) | 生产环境中 | 环境专属配置、显式CORS源、生产环境禁用文档、 |
| A03 | Software Supply Chain Failures(软件供应链故障) | 未固定依赖版本、仿冒包、无SBOM、未审核的传递依赖、CI/CD密钥泄露 | CI中运行 |
| A04 | Cryptographic Failures(加密失败) | 使用 | |
| A05 | Injection(注入) | 通过f-string/ | safe |
| A06 | Insecure Design(不安全设计) | 无速率限制、缺失输入验证层、未进行滥用场景建模 | 威胁建模、边界处验证(Pydantic)、速率限制中间件 |
| A07 | Authentication Failures(身份验证失败) | 弱会话配置、JWT | 安全会话设置、显式指定 |
| A08 | Software or Data Integrity Failures(软件或数据完整性故障) | | |
| A09 | Security Logging and Alerting Failures(安全日志与告警故障) | 记录密码/令牌、无身份验证事件日志、缺失告警、无应急预案 | 带字段过滤的结构化日志、审计跟踪、告警阈值、蜜罐令牌 |
| A10 | Mishandling of Exceptional Conditions(异常情况处理不当) | 裸 | 特定异常类型、上下文管理器、集中式错误处理器、失败关闭模式 |
如需每个类别的详细漏洞代码→安全代码示例:请参阅references/owasp-top-10.md
Security Review Workflow
安全审查工作流
Follow this procedure when reviewing Python code for security:
- Scan for critical prohibitions — Check for any pattern in the "Critical Prohibitions" table above. Each match is an immediate high-severity finding.
- Check input validation — Verify every entry point (route handler, CLI argument, file parser, queue consumer) validates and sanitizes input before processing.
- Verify authentication and authorization — Confirm every endpoint requires authentication (unless explicitly public) and checks authorization for the specific resource being accessed.
- Review data handling — Trace how secrets, PII, and sensitive data flow through the system. Verify encryption at rest and in transit, proper key management, and secure deletion.
- Check error handling — Ensure errors do not leak stack traces, internal paths, database details, or configuration to users. Verify fail-secure behavior.
- Audit dependencies — Run and
pip-audit. Flag any unpinned dependencies or packages with known CVEs.safety check - Verify logging — Confirm no sensitive data (passwords, tokens, PII) appears in logs. Verify authentication events, authorization failures, and security-relevant actions are logged.
- Run static analysis — Execute and review findings. Run
bandit -r src/with Python and OWASP rulesets for deeper analysis.semgrep - Report findings — For each finding, document: severity (Critical/High/Medium/Low), location (file:line), vulnerable code snippet, explanation of the risk, and recommended fix with code example.
审查Python代码安全性时遵循以下流程:
- 扫描严格禁止的模式 —— 检查是否存在上述“严格禁止的模式”表中的任何模式。每一项匹配均为立即标记的高严重性问题。
- 检查输入验证 —— 验证每个入口点(路由处理器、CLI参数、文件解析器、队列消费者)在处理前是否验证并清理输入。
- 验证身份验证与授权 —— 确认每个端点均要求身份验证(除非明确公开),并检查对所访问特定资源的授权情况。
- 审查数据处理 —— 追踪密钥、PII及敏感数据在系统中的流转。验证静态和传输中的加密、密钥管理及安全删除。
- 检查错误处理 —— 确保错误不会向用户泄露堆栈跟踪、内部路径、数据库细节或配置。验证安全失败默认行为。
- 审计依赖项 —— 运行和
pip-audit。标记任何未固定版本的依赖或存在已知CVE的包。safety check - 验证日志 —— 确认日志中无敏感数据(密码、令牌、PII)。验证身份验证事件、授权失败及安全相关操作均已记录。
- 运行静态分析 —— 执行并审查结果。使用Python和OWASP规则集运行
bandit -r src/进行深度分析。semgrep - 报告问题 —— 针对每个问题,记录:严重性(Critical/High/Medium/Low)、位置(文件:行号)、漏洞代码片段、风险说明及包含代码示例的修复建议。
Security Hardening Quick Commands
安全加固快速命令
bash
undefinedbash
undefined=== Static Analysis ===
=== 静态分析 ===
pip install bandit && bandit -r src/ -f json -o bandit-report.json
pip install semgrep && semgrep --config=p/python --config=p/owasp-top-ten src/
pip install bandit && bandit -r src/ -f json -o bandit-report.json
pip install semgrep && semgrep --config=p/python --config=p/owasp-top-ten src/
=== Dependency Audit ===
=== 依赖审计 ===
pip install pip-audit && pip-audit
pip install safety && safety check
pip install pip-audit && pip-audit
pip install safety && safety check
=== Secrets Detection ===
=== 密钥检测 ===
pip install detect-secrets && detect-secrets scan > .secrets.baseline
pip install detect-secrets && detect-secrets scan > .secrets.baseline
=== Pin Dependencies with Hashes ===
=== 带哈希的依赖版本固定 ===
pip install pip-tools && pip-compile --generate-hashes requirements.in
pip install pip-tools && pip-compile --generate-hashes requirements.in
=== Container Scanning ===
=== 容器扫描 ===
trivy image <image-name>
trivy image <image-name>
undefinedundefinedReference Files
参考文件
Consult these files for detailed guidance beyond this overview:
- references/owasp-top-10.md — Detailed OWASP Top 10 coverage with Python-specific vulnerable → secure code examples for each category, including Django, Flask, and FastAPI patterns
- references/secure-coding.md — Secure coding patterns organized by domain: input validation, authentication, cryptography, serialization, subprocess execution, file operations, and web framework configuration (Django, Flask, FastAPI)
- references/security-checklist.md — Actionable verification checklists for code review, architecture review, dependency audit, deployment hardening, security testing, and incident response
如需超出本文概述的详细指导,请查阅以下文件:
- references/owasp-top-10.md —— 详细的OWASP Top 10内容,包含每个类别的Python专用漏洞代码→安全代码示例,涵盖Django、Flask及FastAPI模式
- references/secure-coding.md —— 按领域分类的安全编码模式:输入验证、身份验证、加密、序列化、子进程执行、文件操作及Web框架配置(Django、Flask、FastAPI)
- references/security-checklist.md —— 可执行的验证检查清单,涵盖代码审查、架构审查、依赖审计、部署加固、安全测试及事件响应