owasp-top-10
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseOWASP Top 10
OWASP Top 10
Protect against the most critical web security risks.
防范最关键的Web安全风险。
1. Broken Access Control
1. 访问控制失效
python
undefinedpython
undefined❌ Bad: No authorization check
❌ 错误示例:未做权限校验
@app.route('/api/users/<user_id>')
def get_user(user_id):
return db.query(f"SELECT * FROM users WHERE id = {user_id}")
@app.route('/api/users/<user_id>')
def get_user(user_id):
return db.query(f"SELECT * FROM users WHERE id = {user_id}")
✅ Good: Verify user can access resource
✅ 正确示例:验证用户是否有权限访问资源
@app.route('/api/users/<user_id>')
@login_required
def get_user(user_id):
if current_user.id != user_id and not current_user.is_admin:
abort(403)
return db.query("SELECT * FROM users WHERE id = ?", [user_id])
undefined@app.route('/api/users/<user_id>')
@login_required
def get_user(user_id):
if current_user.id != user_id and not current_user.is_admin:
abort(403)
return db.query("SELECT * FROM users WHERE id = ?", [user_id])
undefined2. Cryptographic Failures
2. 加密机制失效
python
undefinedpython
undefined❌ Bad: Weak hashing
❌ 错误示例:弱哈希算法
import hashlib
password_hash = hashlib.md5(password.encode()).hexdigest()
import hashlib
password_hash = hashlib.md5(password.encode()).hexdigest()
✅ Good: Strong hashing
✅ 正确示例:强哈希算法
from argon2 import PasswordHasher
ph = PasswordHasher()
password_hash = ph.hash(password)
undefinedfrom argon2 import PasswordHasher
ph = PasswordHasher()
password_hash = ph.hash(password)
undefined3. Injection
3. 注入攻击
python
undefinedpython
undefined❌ Bad: SQL injection vulnerable
❌ 错误示例:易受SQL注入攻击
query = f"SELECT * FROM users WHERE email = '{email}'"
query = f"SELECT * FROM users WHERE email = '{email}'"
✅ Good: Parameterized query
✅ 正确示例:参数化查询
query = "SELECT * FROM users WHERE email = ?"
db.execute(query, [email])
undefinedquery = "SELECT * FROM users WHERE email = ?"
db.execute(query, [email])
undefined4. Insecure Design
4. 不安全设计
- No rate limiting on login
- Sequential/guessable IDs
- No CAPTCHA on sensitive operations
Fix: Use UUIDs, implement rate limiting, threat model early.
- 登录接口未做速率限制
- 使用可被猜测的连续ID
- 敏感操作未添加验证码
修复方案: 使用UUID,实现速率限制,尽早进行威胁建模。
5. Security Misconfiguration
5. 安全配置错误
python
undefinedpython
undefined❌ Bad: Debug mode in production
❌ 错误示例:生产环境开启调试模式
app.debug = True
app.debug = True
✅ Good: Environment-based config
✅ 正确示例:基于环境配置
app.debug = os.getenv('FLASK_ENV') == 'development'
undefinedapp.debug = os.getenv('FLASK_ENV') == 'development'
undefined6. Vulnerable Components
6. 易受攻击的组件
bash
undefinedbash
undefinedScan for vulnerabilities
扫描漏洞
npm audit
pip-audit
npm audit
pip-audit
Fix vulnerabilities
修复漏洞
npm audit fix
undefinednpm audit fix
undefined7. Authentication Failures
7. 身份认证失效
python
undefinedpython
undefined✅ Strong password requirements
✅ 强密码要求
def validate_password(password):
if len(password) < 12:
return "Password must be 12+ characters"
if not re.search(r"[A-Z]", password):
return "Must contain uppercase"
if not re.search(r"[0-9]", password):
return "Must contain number"
return None
undefineddef validate_password(password):
if len(password) < 12:
return "密码长度必须至少12位"
if not re.search(r"[A-Z]", password):
return "必须包含大写字母"
if not re.search(r"[0-9]", password):
return "必须包含数字"
return None
undefinedJWT Security (OWASP Best Practices)
JWT安全(OWASP最佳实践)
python
import jwt
import hashlib
import secrets
from datetime import datetime, timezone, timedeltapython
import jwt
import hashlib
import secrets
from datetime import datetime, timezone, timedelta❌ Bad: Trust algorithm from header
❌ 错误示例:信任请求头中的算法
payload = jwt.decode(token, SECRET, algorithms=jwt.get_unverified_header(token)['alg'])
payload = jwt.decode(token, SECRET, algorithms=jwt.get_unverified_header(token)['alg'])
✅ Good: Hardcode expected algorithm (prevents algorithm confusion attacks)
✅ 正确示例:硬编码预期算法(防止算法混淆攻击)
def verify_jwt(token: str) -> dict:
try:
payload = jwt.decode(
token,
SECRET_KEY,
algorithms=['HS256'], # NEVER read from header
options={
'require': ['exp', 'iat', 'iss', 'aud'], # Required claims
}
)
# Validate issuer and audience
if payload['iss'] != EXPECTED_ISSUER:
raise jwt.InvalidIssuerError()
if payload['aud'] != EXPECTED_AUDIENCE:
raise jwt.InvalidAudienceError()
return payload
except jwt.ExpiredSignatureError:
raise AuthError("Token expired")
except jwt.InvalidTokenError as e:
raise AuthError(f"Invalid token: {e}")def verify_jwt(token: str) -> dict:
try:
payload = jwt.decode(
token,
SECRET_KEY,
algorithms=['HS256'], # 绝不要从请求头读取
options={
'require': ['exp', 'iat', 'iss', 'aud'], # 必填声明
}
)
# 验证签发者和受众
if payload['iss'] != EXPECTED_ISSUER:
raise jwt.InvalidIssuerError()
if payload['aud'] != EXPECTED_AUDIENCE:
raise jwt.InvalidAudienceError()
return payload
except jwt.ExpiredSignatureError:
raise AuthError("令牌已过期")
except jwt.InvalidTokenError as e:
raise AuthError(f"无效令牌: {e}")Token sidejacking protection (OWASP recommended)
令牌劫持防护(OWASP推荐)
def create_protected_token(user_id: str, response) -> str:
"""Create token with user context to prevent sidejacking."""
# Generate random fingerprint
fingerprint = secrets.token_urlsafe(32)
# Store fingerprint hash in token (not raw value)
payload = {
'user_id': user_id,
'fingerprint': hashlib.sha256(fingerprint.encode()).hexdigest(),
'exp': datetime.now(timezone.utc) + timedelta(minutes=15),
'iat': datetime.now(timezone.utc),
'iss': ISSUER,
'aud': AUDIENCE,
}
# Send raw fingerprint as hardened cookie
response.set_cookie(
'__Secure-Fgp', # Cookie prefix for extra security
fingerprint,
httponly=True,
secure=True,
samesite='Strict',
max_age=900 # 15 min
)
return jwt.encode(payload, SECRET_KEY, algorithm='HS256')
**JWT Security Checklist:**
- [ ] Hardcode algorithm (never read from header)
- [ ] Validate: exp, iat, iss, aud claims
- [ ] Short expiry (15 min - 1 hour)
- [ ] Use refresh token rotation for longer sessions
- [ ] Implement token denylist for logout/revocationdef create_protected_token(user_id: str, response) -> str:
"""创建带有用户上下文的令牌以防止劫持。"""
# 生成随机指纹
fingerprint = secrets.token_urlsafe(32)
# 在令牌中存储指纹哈希值(而非原始值)
payload = {
'user_id': user_id,
'fingerprint': hashlib.sha256(fingerprint.encode()).hexdigest(),
'exp': datetime.now(timezone.utc) + timedelta(minutes=15),
'iat': datetime.now(timezone.utc),
'iss': ISSUER,
'aud': AUDIENCE,
}
# 将原始指纹作为增强型Cookie发送
response.set_cookie(
'__Secure-Fgp', # Cookie前缀提升安全性
fingerprint,
httponly=True,
secure=True,
samesite='Strict',
max_age=900 # 15分钟
)
return jwt.encode(payload, SECRET_KEY, algorithm='HS256')
**JWT安全检查清单:**
- [ ] 硬编码算法(绝不要从请求头读取)
- [ ] 验证:exp、iat、iss、aud声明
- [ ] 短有效期(15分钟-1小时)
- [ ] 为长会话使用刷新令牌轮换机制
- [ ] 实现令牌拒绝列表以支持登出/吊销8. Data Integrity Failures
8. 数据完整性失效
html
<!-- Use SRI for CDN scripts -->
<script src="https://cdn.example.com/lib.js"
integrity="sha384-..."
crossorigin="anonymous"></script>html
<!-- 为CDN脚本使用SRI -->
<script src="https://cdn.example.com/lib.js"
integrity="sha384-..."
crossorigin="anonymous"></script>9. Logging Failures
9. 日志记录失效
python
undefinedpython
undefined✅ Log security events
✅ 记录安全事件
@app.route('/login', methods=['POST'])
def login():
user = authenticate(email, password)
if user:
logger.info(f"Successful login: {email}")
else:
logger.warning(f"Failed login: {email}")
undefined@app.route('/login', methods=['POST'])
def login():
user = authenticate(email, password)
if user:
logger.info(f"登录成功: {email}")
else:
logger.warning(f"登录失败: {email}")
undefined10. SSRF (Server-Side Request Forgery)
10. SSRF(服务器端请求伪造)
python
undefinedpython
undefined❌ Bad: Fetch any URL
❌ 错误示例:允许请求任意URL
response = requests.get(user_provided_url)
response = requests.get(user_provided_url)
✅ Good: Allowlist domains
✅ 正确示例:使用域名白名单
ALLOWED = ['api.example.com']
if urlparse(url).hostname not in ALLOWED:
abort(400)
undefinedALLOWED = ['api.example.com']
if urlparse(url).hostname not in ALLOWED:
abort(400)
undefinedQuick Checklist
快速检查清单
- Authorization on all endpoints
- Passwords hashed with bcrypt/argon2
- Parameterized queries only
- Rate limiting enabled
- Debug mode off in production
- Dependencies scanned regularly
- Security events logged
- 所有端点都已配置权限验证
- 密码使用bcrypt/argon2哈希
- 仅使用参数化查询
- 启用速率限制
- 生产环境关闭调试模式
- 定期扫描依赖项
- 记录安全事件
Related Skills
相关技能
- - Authentication implementation
auth-patterns - - Sanitization patterns
input-validation - - Automated scanning
security-scanning
- - 身份认证实现
auth-patterns - - 数据清理模式
input-validation - - 自动化扫描
security-scanning
Capability Details
能力详情
injection
injection
Keywords: sql injection, command injection, injection, parameterized
Solves:
- Prevent SQL injection
- Fix command injection
- Use parameterized queries
关键词: sql injection, command injection, injection, parameterized
解决问题:
- 防止SQL注入
- 修复命令注入
- 使用参数化查询
access-control
access-control
Keywords: access control, authorization, idor, privilege
Solves:
- Fix broken access control
- Prevent IDOR vulnerabilities
- Implement authorization checks
关键词: access control, authorization, idor, privilege
解决问题:
- 修复访问控制失效问题
- 防止IDOR漏洞
- 实现权限校验
owasp-fixes
owasp-fixes
Keywords: fix, mitigation, example, vulnerability
Solves:
- OWASP vulnerability fixes
- Mitigation examples
- Code fix patterns
关键词: fix, mitigation, example, vulnerability
解决问题:
- OWASP漏洞修复
- 缓解方案示例
- 代码修复模式