python-security

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Python 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.
NeverInstead
eval()
/
exec()
with untrusted input
ast.literal_eval()
or a dedicated parser
pickle.load()
with untrusted data
json.loads()
or validated schema (e.g., Pydantic)
yaml.load()
yaml.safe_load()
shell=True
+ user input in subprocess
subprocess.run([cmd, arg1, arg2])
with list args
os.system()
subprocess.run()
String formatting / f-strings in SQLParameterized queries (
cursor.execute(sql, params)
)
random
module for security purposes
secrets
module
MD5 / SHA1 for password hashing
bcrypt
or
argon2-cffi
assert
for security checks
if not condition: raise SecurityError(...)
Bare
except:
or
except Exception:
except SpecificException:
with proper handling
Hardcoded secrets in source codeEnvironment variables or secret manager (Vault, AWS SM)
DEBUG=True
in production
Environment-specific configuration
绝不要使用以下模式。在任何审查中,违反这些规则均属于高严重性问题。
禁止使用替代方案
eval()
/
exec()
处理不可信输入
ast.literal_eval()
或专用解析器
pickle.load()
处理不可信数据
json.loads()
或经过验证的Schema(如Pydantic)
yaml.load()
yaml.safe_load()
shell=True
+ 子进程中传入用户输入
subprocess.run([cmd, arg1, arg2])
使用列表参数
os.system()
subprocess.run()
SQL中使用字符串格式化/f-string参数化查询(
cursor.execute(sql, params)
random
模块用于安全场景
secrets
模块
MD5 / SHA1 用于密码哈希
bcrypt
argon2-cffi
assert
用于安全检查
if not condition: raise SecurityError(...)
except:
except Exception:
except SpecificException:
并进行适当处理
源代码中硬编码密钥环境变量或密钥管理器(Vault、AWS SM)
生产环境中设置
DEBUG=True
环境专属配置

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:
  1. Static Analysis — Detect common vulnerability patterns automatically
    • bandit
      — Python-specific security linter (AST-based)
    • semgrep
      — Pattern-based analysis with OWASP and Python rulesets
    • pylint
      — General linting with some security-relevant checks
  2. Dependency Audit — Identify known vulnerabilities in third-party packages
    • pip-audit
      — Check installed packages against the OSV database
    • safety
      — Check against the Safety vulnerability database
  3. Secrets Detection — Find leaked credentials and API keys
    • detect-secrets
      — Baseline-aware secrets scanner
  4. Code Review — Apply the security review workflow and checklists
  5. Security Testing — Write negative tests that verify rejection of malicious inputs; fuzz-test parsers and validators
Quick tool commands:
bash
undefined
采用分层验证方法:
  1. 静态分析 —— 自动检测常见漏洞模式
    • bandit
      —— 基于AST的Python专用安全代码检查工具
    • semgrep
      —— 基于模式的分析工具,支持OWASP和Python规则集
    • pylint
      —— 通用代码检查工具,包含部分安全相关检查
  2. 依赖审计 —— 识别第三方包中的已知漏洞
    • pip-audit
      —— 对照OSV数据库检查已安装包
    • safety
      —— 对照Safety漏洞数据库检查
  3. 密钥检测 —— 查找泄露的凭证和API密钥
    • detect-secrets
      —— 支持基线对比的密钥扫描工具
  4. 代码审查 —— 遵循安全审查工作流并使用检查清单
  5. 安全测试 —— 编写负面测试验证恶意输入被拒绝;对解析器和验证器进行模糊测试
快速工具命令:
bash
undefined

Bandit — 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
    pip-audit
    in CI/CD pipeline on every build
  • 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
    trivy
    ; use minimal base images (distroless, alpine); run as non-root user
  • HTTPS/TLS — Enforce TLS 1.2+ for all connections; redirect HTTP to HTTPS; set
    Strict-Transport-Security
    header
  • Security headers — Configure
    Content-Security-Policy
    ,
    X-Content-Type-Options: nosniff
    ,
    X-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
  • 容器安全 —— 使用
    trivy
    扫描镜像;使用最小化基础镜像(distroless、alpine);以非root用户运行
  • HTTPS/TLS —— 强制所有连接使用TLS 1.2+;将HTTP重定向至HTTPS;设置
    Strict-Transport-Security
    头部
  • 安全头部 —— 配置
    Content-Security-Policy
    X-Content-Type-Options: nosniff
    X-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:
#CategoryPython-Specific RisksPrimary Mitigation
A01Broken Access ControlMissing
@login_required
/ auth decorators, IDOR via sequential IDs, path traversal, SSRF via
requests.get(user_url)
Centralized auth middleware, object-level permissions,
pathlib.resolve()
, URL allowlisting
A02Security Misconfiguration
DEBUG=True
in prod,
CORS(origins="*")
, Swagger/docs exposed, default
SECRET_KEY
, XXE via xml.etree
Environment-specific config, explicit CORS origins, disable docs in prod,
defusedxml
A03Software Supply Chain FailuresUnpinned deps, typosquatting, no SBOM, unvetted transitive deps, CI/CD secrets exposure
pip-audit
in CI, pinned versions with hashes, SBOM generation, CI/CD hardening
A04Cryptographic Failures
random
module for tokens, MD5/SHA1 password hashing, hardcoded API keys, no encryption at rest
secrets
module,
bcrypt
/
argon2
, env vars / secret manager,
cryptography
library
A05InjectionSQL via f-strings/
.format()
,
shell=True
, Jinja2 `
safe
/ SSTI,
eval()
/
exec()`
A06Insecure DesignNo rate limiting, missing input validation layer, no abuse case modelingThreat modeling, validation at boundaries (Pydantic), rate limiting middleware
A07Authentication FailuresWeak session config, JWT
algorithm="none"
or HS256 with public key, no brute-force protection
Secure session settings, explicit
algorithms=["RS256"]
, account lockout / rate limiting
A08Software or Data Integrity Failures
pickle.loads()
/
yaml.load()
deserialization, unsigned updates, CI/CD pipeline injection
json.loads()
/
yaml.safe_load()
, signed artifacts, pinned CI actions with SHA
A09Security Logging and Alerting FailuresLogging passwords/tokens, no auth event logging, missing alerting, no playbooksStructured logging with field filtering, audit trail, alerting thresholds, honeytokens
A10Mishandling of Exceptional ConditionsBare
except: pass
, failing open, transaction rollback failures, sensitive info in errors
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特有风险主要缓解措施
A01Broken Access Control(访问控制失效)缺失
@login_required
/权限装饰器、通过连续ID实现的IDOR、路径遍历、通过
requests.get(user_url)
引发的SSRF
集中式权限中间件、对象级权限控制、
pathlib.resolve()
、URL白名单
A02Security Misconfiguration(安全配置错误)生产环境中
DEBUG=True
CORS(origins="*")
、Swagger/文档暴露、默认
SECRET_KEY
、通过xml.etree引发的XXE
环境专属配置、显式CORS源、生产环境禁用文档、
defusedxml
A03Software Supply Chain Failures(软件供应链故障)未固定依赖版本、仿冒包、无SBOM、未审核的传递依赖、CI/CD密钥泄露CI中运行
pip-audit
、带哈希的固定版本、生成SBOM、CI/CD加固
A04Cryptographic Failures(加密失败)使用
random
模块生成令牌、MD5/SHA1密码哈希、硬编码API密钥、静态数据未加密
secrets
模块、
bcrypt
/
argon2
、环境变量/密钥管理器、
cryptography
A05Injection(注入)通过f-string/
.format()
实现的SQL注入、
shell=True
、Jinja2 `
safe
/SSTI、
eval()
/
exec()`
A06Insecure Design(不安全设计)无速率限制、缺失输入验证层、未进行滥用场景建模威胁建模、边界处验证(Pydantic)、速率限制中间件
A07Authentication Failures(身份验证失败)弱会话配置、JWT
algorithm="none"
或使用公钥的HS256、无暴力破解防护
安全会话设置、显式指定
algorithms=["RS256"]
、账户锁定/速率限制
A08Software or Data Integrity Failures(软件或数据完整性故障)
pickle.loads()
/
yaml.load()
反序列化、未签名更新、CI/CD流水线注入
json.loads()
/
yaml.safe_load()
、签名制品、带SHA的固定CI操作
A09Security Logging and Alerting Failures(安全日志与告警故障)记录密码/令牌、无身份验证事件日志、缺失告警、无应急预案带字段过滤的结构化日志、审计跟踪、告警阈值、蜜罐令牌
A10Mishandling of Exceptional Conditions(异常情况处理不当)
except: pass
、失败开放、事务回滚失败、错误中暴露敏感信息
特定异常类型、上下文管理器、集中式错误处理器、失败关闭模式
如需每个类别的详细漏洞代码→安全代码示例:请参阅references/owasp-top-10.md

Security Review Workflow

安全审查工作流

Follow this procedure when reviewing Python code for security:
  1. Scan for critical prohibitions — Check for any pattern in the "Critical Prohibitions" table above. Each match is an immediate high-severity finding.
  2. Check input validation — Verify every entry point (route handler, CLI argument, file parser, queue consumer) validates and sanitizes input before processing.
  3. Verify authentication and authorization — Confirm every endpoint requires authentication (unless explicitly public) and checks authorization for the specific resource being accessed.
  4. 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.
  5. Check error handling — Ensure errors do not leak stack traces, internal paths, database details, or configuration to users. Verify fail-secure behavior.
  6. Audit dependencies — Run
    pip-audit
    and
    safety check
    . Flag any unpinned dependencies or packages with known CVEs.
  7. Verify logging — Confirm no sensitive data (passwords, tokens, PII) appears in logs. Verify authentication events, authorization failures, and security-relevant actions are logged.
  8. Run static analysis — Execute
    bandit -r src/
    and review findings. Run
    semgrep
    with Python and OWASP rulesets for deeper analysis.
  9. 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代码安全性时遵循以下流程:
  1. 扫描严格禁止的模式 —— 检查是否存在上述“严格禁止的模式”表中的任何模式。每一项匹配均为立即标记的高严重性问题。
  2. 检查输入验证 —— 验证每个入口点(路由处理器、CLI参数、文件解析器、队列消费者)在处理前是否验证并清理输入。
  3. 验证身份验证与授权 —— 确认每个端点均要求身份验证(除非明确公开),并检查对所访问特定资源的授权情况。
  4. 审查数据处理 —— 追踪密钥、PII及敏感数据在系统中的流转。验证静态和传输中的加密、密钥管理及安全删除。
  5. 检查错误处理 —— 确保错误不会向用户泄露堆栈跟踪、内部路径、数据库细节或配置。验证安全失败默认行为。
  6. 审计依赖项 —— 运行
    pip-audit
    safety check
    。标记任何未固定版本的依赖或存在已知CVE的包。
  7. 验证日志 —— 确认日志中无敏感数据(密码、令牌、PII)。验证身份验证事件、授权失败及安全相关操作均已记录。
  8. 运行静态分析 —— 执行
    bandit -r src/
    并审查结果。使用Python和OWASP规则集运行
    semgrep
    进行深度分析。
  9. 报告问题 —— 针对每个问题,记录:严重性(Critical/High/Medium/Low)、位置(文件:行号)、漏洞代码片段、风险说明及包含代码示例的修复建议。

Security Hardening Quick Commands

安全加固快速命令

bash
undefined
bash
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>

undefined
undefined

Reference 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 —— 可执行的验证检查清单,涵盖代码审查、架构审查、依赖审计、部署加固、安全测试及事件响应