security-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSecurity Patterns Skill
Security Patterns Skill
Security best practices and patterns for secure development.
See: code-examples.md for Python implementations
See: templates.md for checklists and config templates
安全开发的安全最佳实践与模式。
参考: code-examples.md 中的Python实现代码
参考: templates.md 中的检查清单与配置模板
When This Activates
触发场景
- API key handling
- User input validation
- File operations
- Security-sensitive code
- Keywords: "security", "api key", "secret", "validate", "input"
- API密钥处理
- 用户输入验证
- 文件操作
- 安全敏感代码
- 关键词:"security"、"api key"、"secret"、"validate"、"input"
API Keys & Secrets
API密钥与敏感信息
Environment Variables (REQUIRED)
环境变量(必填)
Rule: Never hardcode secrets. Always use environment variables via files.
.envpython
undefined规则: 切勿硬编码敏感信息。始终通过文件使用环境变量。
.envpython
undefined✅ CORRECT
✅ 正确写法
api_key = os.getenv("ANTHROPIC_API_KEY")
api_key = os.getenv("ANTHROPIC_API_KEY")
❌ WRONG
❌ 错误写法
api_key = "sk-ant-1234567890abcdef" # NEVER!
**See:** [code-examples.md#api-keys--secrets](code-examples.md#api-keys--secrets) for full validation code
---api_key = "sk-ant-1234567890abcdef" # 绝对不要这样做!
**参考:** [code-examples.md#api-keys--secrets](code-examples.md#api-keys--secrets) 中的完整验证代码
---Input Validation
输入验证
Path Traversal Prevention
路径遍历防护
Rule: Always validate paths are within allowed directories.
python
undefined规则: 始终验证路径是否在允许的目录范围内。
python
undefinedUse is_relative_to() to prevent ../ attacks
使用is_relative_to()防止../攻击
if not file_path.is_relative_to(base_dir):
raise ValueError("Path traversal detected")
undefinedif not file_path.is_relative_to(base_dir):
raise ValueError("Path traversal detected")
undefinedCommand Injection Prevention
命令注入防护
Rule: Never use . Pass arguments as lists.
shell=Truepython
undefined规则: 切勿使用。以列表形式传递参数。
shell=Truepython
undefined✅ CORRECT
✅ 正确写法
subprocess.run([command] + args, shell=False)
subprocess.run([command] + args, shell=False)
❌ WRONG
❌ 错误写法
subprocess.run(f"ls {user_input}", shell=True) # Injection risk!
undefinedsubprocess.run(f"ls {user_input}", shell=True) # 存在注入风险!
undefinedSQL Injection Prevention
SQL注入防护
Rule: Always use parameterized queries.
python
undefined规则: 始终使用参数化查询。
python
undefined✅ CORRECT
✅ 正确写法
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
❌ WRONG
❌ 错误写法
cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")
**See:** [code-examples.md#input-validation](code-examples.md#input-validation) for complete examples
---cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")
**参考:** [code-examples.md#input-validation](code-examples.md#input-validation) 中的完整示例
---File Operations Security
文件操作安全
Secure Permissions
安全权限设置
| Use Case | Permission | Octal |
|---|---|---|
| Sensitive files | | 0o600 |
| Sensitive dirs | | 0o700 |
| Public files | | 0o644 |
| 使用场景 | 权限 | 八进制值 |
|---|---|---|
| 敏感文件 | | 0o600 |
| 敏感目录 | | 0o700 |
| 公共文件 | | 0o644 |
File Upload Validation
文件上传验证
- Validate extensions (whitelist only)
- Check file size limits
- Reject executable files
See: code-examples.md#file-operations-security
- 验证文件扩展名(仅允许白名单内的类型)
- 检查文件大小限制
- 拒绝可执行文件
参考: code-examples.md#file-operations-security
Cryptographic Operations
加密操作
Secure Random
安全随机数生成
Rule: Use module for security-sensitive random values.
secretspython
undefined规则: 对于安全敏感的随机值,使用模块。
secretspython
undefined✅ CORRECT
✅ 正确写法
token = secrets.token_hex(32)
token = secrets.token_hex(32)
❌ WRONG
❌ 错误写法
token = str(random.randint(0, 999999)) # Not cryptographically secure!
**See:** [code-examples.md#cryptographic-operations](code-examples.md#cryptographic-operations) for password hashing
---token = str(random.randint(0, 999999)) # 不具备密码学安全性!
**参考:** [code-examples.md#cryptographic-operations](code-examples.md#cryptographic-operations) 中的密码哈希示例
---Logging Security
日志安全
Rule: Never log full secrets. Mask sensitive values.
python
undefined规则: 切勿记录完整的敏感信息。对敏感值进行掩码处理。
python
undefined✅ CORRECT
✅ 正确写法
masked_key = api_key[:7] + "***" + api_key[-4:]
logging.info(f"Using key {masked_key}")
masked_key = api_key[:7] + "***" + api_key[-4:]
logging.info(f"Using key {masked_key}")
❌ WRONG
❌ 错误写法
logging.info(f"Using key {api_key}") # Exposes full key!
---logging.info(f"Using key {api_key}") # 暴露完整密钥!
---Dependencies Security
依赖项安全
bash
undefinedbash
undefinedCheck for vulnerabilities
检查漏洞
pip install safety && safety check
pip install safety && safety check
OR
或者
pip install pip-audit && pip-audit
---pip install pip-audit && pip-audit
---Key Takeaways
核心要点
- Never hardcode secrets - Use environment variables
- Validate all inputs - User data, file paths, commands
- Prevent path traversal - Use
is_relative_to() - No shell=True - Use list arguments with subprocess
- Parameterized queries - Never string interpolation
- Secure random - Use module
secrets - Restrict permissions - Files 0o600, dirs 0o700
- Mask secrets in logs - Show only first/last few chars
- Scan dependencies - Use safety/pip-audit
- .gitignore secrets - .env, *.key, *.pem
- 切勿硬编码敏感信息 - 使用环境变量
- 验证所有输入 - 用户数据、文件路径、命令
- 防止路径遍历 - 使用
is_relative_to() - 禁用shell=True - 与subprocess配合使用列表参数
- 使用参数化查询 - 切勿使用字符串插值
- 安全随机数 - 使用模块
secrets - 限制权限 - 文件设为0o600,目录设为0o700
- 日志中掩码敏感信息 - 仅显示首尾部分字符
- 扫描依赖项 - 使用safety或pip-audit
- 通过.gitignore忽略敏感信息 - .env、.key、.pem
Related Files
相关文件
- code-examples.md - Complete Python code examples
- templates.md - .env, .gitignore, and security checklists
- code-examples.md - 完整的Python代码示例
- templates.md - .env、.gitignore及安全检查清单
OWASP Top 10 Quick Reference
OWASP Top 10快速参考
See: templates.md#owasp-top-10-quick-reference
参考: templates.md#owasp-top-10-quick-reference