第七章:安全分析¶
安全分析概述¶
SonarQube 提供强大的安全分析能力,可以检测代码中的安全漏洞和安全热点。
安全问题类型¶
| 类型 | 说明 |
|---|---|
| Vulnerability | 已确认的安全漏洞 |
| Security Hotspot | 安全敏感代码,需人工审查 |
OWASP Top 10 覆盖¶
SonarQube 可以检测 OWASP Top 10 安全风险:
- 注入攻击(SQL、命令注入等)
- 失效的身份认证
- 敏感数据暴露
- XML 外部实体(XXE)
- 失效的访问控制
- 安全配置错误
- 跨站脚本(XSS)
- 不安全的反序列化
- 使用含有已知漏洞的组件
- 日志和监控不足
常见安全漏洞检测¶
1. SQL 注入¶
Python¶
# ❌ 不合规 - SQL 注入风险
def get_user(user_id):
query = f"SELECT * FROM users WHERE id = {user_id}"
cursor.execute(query)
# ✅ 合规 - 参数化查询
def get_user(user_id):
query = "SELECT * FROM users WHERE id = ?"
cursor.execute(query, (user_id,))
Java¶
// ❌ 不合规 - SQL 注入风险
String query = "SELECT * FROM users WHERE id = " + userId;
statement.executeQuery(query);
// ✅ 合规 - PreparedStatement
String query = "SELECT * FROM users WHERE id = ?";
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, userId);
2. 跨站脚本(XSS)¶
JavaScript¶
// ❌ 不合规 - XSS 风险
element.innerHTML = userInput;
// ✅ 合规 - 使用 textContent
element.textContent = userInput;
// ✅ 合规 - 使用框架自动转义
<div>{userInput}</div>
Python¶
# ❌ 不合规 - XSS 风险
return f"<div>{user_input}</div>"
# ✅ 合规 - HTML 转义
from html import escape
return f"<div>{escape(user_input)}</div>"
3. 命令注入¶
Python¶
# ❌ 不合规 - 命令注入风险
import os
os.system(f"ping {user_input}")
# ✅ 合规 - 使用 subprocess 并禁用 shell
import subprocess
subprocess.run(["ping", user_input], shell=False)
Java¶
// ❌ 不合规 - 命令注入风险
Runtime.getRuntime().exec("ping " + userInput);
// ✅ 合规 - 使用 ProcessBuilder
ProcessBuilder pb = new ProcessBuilder("ping", userInput);
pb.start();
4. 路径遍历¶
# ❌ 不合规 - 路径遍历风险
file_path = f"/uploads/{filename}"
with open(file_path, 'r') as f:
content = f.read()
# ✅ 合规 - 验证路径
import os
base_dir = "/uploads"
file_path = os.path.join(base_dir, filename)
real_path = os.path.realpath(file_path)
if not real_path.startswith(base_dir):
raise ValueError("Invalid path")
5. 敏感数据暴露¶
硬编码密码¶
# ❌ 不合规 - 硬编码密码
password = "admin123"
db.connect(password)
# ✅ 合规 - 使用环境变量
import os
password = os.environ.get("DB_PASSWORD")
db.connect(password)
日志敏感信息¶
# ❌ 不合规 - 日志记录敏感信息
logger.info(f"User login: {username}, password: {password}")
# ✅ 合规 - 避免记录敏感信息
logger.info(f"User login: {username}")
6. 不安全的加密¶
# ❌ 不合规 - 弱加密算法
from hashlib import md5
hashed = md5(password.encode()).hexdigest()
# ✅ 合规 - 使用安全的加密算法
import hashlib
import os
salt = os.urandom(32)
hashed = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, 100000)
7. XML 外部实体(XXE)¶
# ❌ 不合规 - XXE 风险
from xml.etree import ElementTree
tree = ElementTree.parse(xml_file)
# ✅ 合规 - 禁用外部实体
from defusedxml.ElementTree import parse
tree = parse(xml_file)
8. 不安全的反序列化¶
# ❌ 不合规 - 不安全的反序列化
import pickle
data = pickle.loads(user_input)
# ✅ 合规 - 使用安全的序列化格式
import json
data = json.loads(user_input)
安全热点(Security Hotspot)¶
安全热点是安全敏感的代码区域,需要人工审查确认是否存在风险。
常见安全热点¶
| 热点类型 | 说明 |
|---|---|
| 加密 | 加密算法使用是否安全 |
| 认证 | 认证机制是否安全 |
| 授权 | 权限检查是否完整 |
| 文件操作 | 文件访问是否安全 |
| 网络 | 网络通信是否安全 |
| SQL | SQL 查询是否安全 |
审查安全热点¶
- 进入项目 → Security Hotspots
- 查看热点列表
- 点击热点查看详情
- 标记为:
- To Review: 待审查
- Reviewed: 已审查
- Fixed: 已修复
- Safe: 安全
安全配置¶
安全规则配置¶
安全质量门禁¶
# 安全优先的质量门禁
conditions:
- metric: new_vulnerabilities
operator: EQUALS
error: 0
- metric: new_security_hotspots
operator: EQUALS
error: 0
- metric: security_rating
operator: GREATER_THAN
error: A
安全报告¶
生成安全报告¶
# API 获取安全问题
curl -u admin:admin \
"http://localhost:9000/api/issues/search?componentKeys=my-project&types=VULNERABILITY"
安全度量指标¶
项目概览 → Measures → Security
- Vulnerabilities: 漏洞数量
- Security Hotspots: 安全热点数量
- Security Rating: 安全评级
CWE 映射¶
SonarQube 规则映射到 CWE(Common Weakness Enumeration):
| CWE | 说明 | SonarQube 规则 |
|---|---|---|
| CWE-79 | XSS | javascript:S5131 |
| CWE-89 | SQL 注入 | python:S3649 |
| CWE-78 | 命令注入 | python:S4721 |
| CWE-22 | 路径遍历 | python:S7044 |
| CWE-200 | 信息暴露 | java:S1314 |
| CWE-327 | 弱加密 | python:S5547 |
安全最佳实践¶
1. 定期安全扫描¶
2. 安全代码审查¶
3. 安全培训¶
4. 安全问题跟踪¶
安全审计¶
审计报告¶
# 导出安全问题报告
curl -u admin:admin \
"http://localhost:9000/api/issues/export?componentKeys=my-project&types=VULNERABILITY" \
-o security-report.csv
合规检查¶
小结¶
本章介绍了 SonarQube 的安全分析功能:
- 常见安全漏洞检测
- 安全热点审查
- 安全配置和规则
- 安全报告和审计
下一章将介绍最佳实践。