Add files via upload
This commit is contained in:
1 parent
b3dd5348e9
commit
23bc8f1351
17 files changed
+3469
No files matched your search
Binary file not shown.
|
After Width: | Height: | Size: 157 KiB |
@@ -0,0 +1,160 @@
|
||||
# Mirror Flowers (镜花)
|
||||
|
||||

|
||||
|
||||
MirrorFlower(镜花)是一款基于 AI 的代码安全审计工具,支持多种编程语言的代码分析,可以帮助开发者快速发现代码中的潜在安全漏洞。支持DeepSeek-R1,ChatGPT-4o等多种大模型。
|
||||
|
||||
## 支持的API接口
|
||||
|
||||
FREEGPTAPI:https://github.com/popjane/free_chatgpt_api
|
||||
SiliconFlow(硅基流动):https://cloud.siliconflow.cn/i/JzMCyiJ3
|
||||
|
||||
如需要使用GPT大模型则使用FREEGPTAPI,使用DeepSeek-R1大模型则使用SiliconFlow API。
|
||||
|
||||
SiliconFlow(硅基流动)注册可免费领取14元使用额度,可通过SMS接码平台注册账号,理论可无限免费使用API KEY。
|
||||
|
||||
## 核心功能
|
||||
|
||||
### 多语言支持
|
||||
- PHP
|
||||
- Java
|
||||
- Python
|
||||
- JavaScript
|
||||
|
||||
### 依赖分析
|
||||
- Maven (pom.xml)
|
||||
- NPM (package.json)
|
||||
- Python (requirements.txt)
|
||||
- Composer (composer.json)
|
||||
|
||||
### 框架安全分析
|
||||
- Spring Framework
|
||||
- Spring Security配置审计
|
||||
- 权限控制检查
|
||||
- CSRF/XSS防护
|
||||
- 跨域配置检查
|
||||
|
||||
- Django
|
||||
- 中间件配置检查
|
||||
- CSRF Token验证
|
||||
- XSS防护配置
|
||||
- 调试模式检查
|
||||
|
||||
- Express.js
|
||||
- 安全中间件配置
|
||||
- 认证机制检查
|
||||
- CORS配置审计
|
||||
- 输入验证检查
|
||||
|
||||
- Hibernate
|
||||
- HQL注入检测
|
||||
- 缓存配置审计
|
||||
- 实体验证检查
|
||||
- 会话管理检查
|
||||
|
||||
### 安全检查特性
|
||||
|
||||
#### PHP安全检查
|
||||
- 文件包含漏洞(include/require)
|
||||
- SQL注入(mysql_*函数)
|
||||
- 命令注入(system, exec, shell_exec)
|
||||
- 文件上传漏洞
|
||||
- 反序列化漏洞(unserialize)
|
||||
- XSS(echo, print)
|
||||
- SSRF漏洞
|
||||
- 目录遍历
|
||||
- 会话管理问题
|
||||
- 配置文件泄露
|
||||
|
||||
#### Java安全检查
|
||||
- SQL注入(PreparedStatement相关)
|
||||
- 命令注入(Runtime.exec, ProcessBuilder)
|
||||
- XXE漏洞(XML解析器配置)
|
||||
- 反序列化漏洞(readObject)
|
||||
- 不安全的文件操作
|
||||
- CSRF/XSS防护
|
||||
- 权限控制缺陷
|
||||
- 线程安全问题
|
||||
- 密码学实现缺陷
|
||||
- 日志信息泄露
|
||||
|
||||
#### Python安全检查
|
||||
- 不安全的反序列化(pickle.loads, yaml.load)
|
||||
- 命令注入(os.system, eval, exec, subprocess)
|
||||
- 不安全的模块导入(__import__)
|
||||
- SQL注入(字符串格式化, execute)
|
||||
- 路径遍历(open, os.path)
|
||||
- 模板注入(render_template_string)
|
||||
- 密码学实现问题(weak random)
|
||||
- 环境变量泄露
|
||||
- 调试配置泄露
|
||||
- 不安全的依赖加载
|
||||
|
||||
#### JavaScript安全检查
|
||||
- XSS(DOM型和反射型)
|
||||
- 原型污染
|
||||
- 不安全的第三方依赖
|
||||
- 客户端存储安全
|
||||
- 不安全的随机数生成
|
||||
- CSRF防护缺失
|
||||
- 跨域配置问题
|
||||
- 敏感信息泄露
|
||||
- 不安全的正则表达式
|
||||
- 事件监听器泄露
|
||||
|
||||
### 分析器组件
|
||||
- TaintAnalyzer: 污点分析和数据流追踪
|
||||
- SecurityAnalyzer: 通用安全问题检测
|
||||
- DependencyAnalyzer: 依赖组件安全分析
|
||||
- FrameworkAnalyzer: 框架特定安全检查
|
||||
- ConfigAnalyzer: 配置文件安全分析
|
||||
- ContextAnalyzer: 上下文感知分析
|
||||
|
||||
## 安装和配置
|
||||
|
||||
### 环境要求
|
||||
- Python 3.8+
|
||||
- FastAPI
|
||||
- Node.js (前端开发)
|
||||
|
||||
### 快速开始
|
||||
|
||||
1. 克隆项目
|
||||
```bash
|
||||
git clone https://github.com/Ky0toFu/Mirror-Flowers.git
|
||||
cd Mirror-Flowers
|
||||
```
|
||||
|
||||
2. 安装依赖
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
3. 配置环境变量
|
||||
```env
|
||||
OPENAI_API_KEY=your_api_key_here
|
||||
OPENAI_API_BASE=your_api_base_url
|
||||
OPENAI_MODEL=your_preferred_model
|
||||
```
|
||||
|
||||
4. 启动服务
|
||||
```bash
|
||||
uvicorn backend.app:app --reload
|
||||
```
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. 文件大小限制:10MB
|
||||
2. 支持的文件类型:.php, .java, .py, .js
|
||||
3. API密钥安全:请妥善保管API密钥
|
||||
4. 分析时间:大型项目可能需要较长时间
|
||||
5. 结果验证:建议结合人工审查
|
||||
6. API配置问题:如果提示"API配置更新错误"或"不存在某个模型",请检查API Base URL格式,尝试在URL后添加/v1或删除/v1(例如:https://api.example.com 或 https://api.example.com/v1)
|
||||
|
||||
## 许可证
|
||||
|
||||
MIT License
|
||||
|
||||
## 联系方式
|
||||
|
||||
如有问题或建议,请通过 Issue 与我联系。
|
||||
Binary file not shown.
+1119
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,924 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Mirror Flowers</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<link href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css" rel="stylesheet">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Cinzel+Decorative:wght@700&display=swap" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
|
||||
<style>
|
||||
:root {
|
||||
--bg-color: #ffffff;
|
||||
--text-color: #212529;
|
||||
--card-bg: #ffffff;
|
||||
--border-color: #dee2e6;
|
||||
--custom-file-bg: #f8f9fa;
|
||||
--custom-file-border: #ddd;
|
||||
--custom-file-hover-bg: #f1f8ff;
|
||||
--custom-file-hover-border: #0d6efd;
|
||||
--pre-bg: #f8f9fa;
|
||||
--pre-color: #212529;
|
||||
}
|
||||
|
||||
[data-theme="dark"] {
|
||||
--bg-color: #212529;
|
||||
--text-color: #f8f9fa;
|
||||
--card-bg: #343a40;
|
||||
--border-color: #495057;
|
||||
--custom-file-bg: #2b3035;
|
||||
--custom-file-border: #495057;
|
||||
--custom-file-hover-bg: #3d4247;
|
||||
--custom-file-hover-border: #0d6efd;
|
||||
--pre-bg: #2b3035;
|
||||
--pre-color: #f8f9fa;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: var(--bg-color);
|
||||
color: var(--text-color);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.card {
|
||||
background-color: var(--card-bg);
|
||||
border-color: var(--border-color);
|
||||
}
|
||||
|
||||
.card-header {
|
||||
background-color: var(--card-bg);
|
||||
border-bottom-color: var(--border-color);
|
||||
}
|
||||
|
||||
.container { max-width: 1200px; margin-top: 2rem; }
|
||||
.result-card {
|
||||
margin: 1rem 0;
|
||||
padding: 1rem;
|
||||
border-radius: 8px;
|
||||
background-color: var(--card-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
.loading { text-align: center; margin: 2rem 0; }
|
||||
.file-list { margin-top: 1rem; }
|
||||
.file-list-item { padding: 0.5rem; border-bottom: 1px solid #eee; }
|
||||
.file-list-item:last-child { border-bottom: none; }
|
||||
pre {
|
||||
white-space: pre-wrap;
|
||||
word-wrap: break-word;
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
background-color: var(--pre-bg) !important;
|
||||
color: var(--pre-color) !important;
|
||||
border: 1px solid var(--border-color);
|
||||
padding: 1rem;
|
||||
}
|
||||
.btn-link { text-decoration: none; }
|
||||
.collapse { transition: all 0.3s ease; }
|
||||
.upload-container {
|
||||
position: relative;
|
||||
min-height: 100px;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.upload-section {
|
||||
width: 100%;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
.upload-section input[type="file"] {
|
||||
display: block !important;
|
||||
opacity: 1 !important;
|
||||
position: relative !important;
|
||||
width: 100%;
|
||||
}
|
||||
.custom-file-upload {
|
||||
border: 2px dashed var(--custom-file-border);
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
background: var(--custom-file-bg);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
.custom-file-upload:hover {
|
||||
border-color: var(--custom-file-hover-border);
|
||||
background: var(--custom-file-hover-bg);
|
||||
}
|
||||
.form-label {
|
||||
margin-bottom: 10px;
|
||||
color: #666;
|
||||
}
|
||||
.file-list {
|
||||
margin-top: 1rem;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.file-list-item {
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid #eee;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.file-list-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.progress {
|
||||
background-color: #e9ecef;
|
||||
border-radius: 0.25rem;
|
||||
box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
|
||||
}
|
||||
|
||||
.progress-bar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
background-color: #007bff;
|
||||
transition: width .6s ease;
|
||||
}
|
||||
|
||||
.progress-bar-striped {
|
||||
background-image: linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);
|
||||
background-size: 1rem 1rem;
|
||||
}
|
||||
|
||||
.progress-bar-animated {
|
||||
animation: progress-bar-stripes 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes progress-bar-stripes {
|
||||
from { background-position: 1rem 0; }
|
||||
to { background-position: 0 0; }
|
||||
}
|
||||
|
||||
/* 主题切换按钮样式 */
|
||||
.theme-toggle {
|
||||
position: fixed;
|
||||
top: 1rem;
|
||||
right: 1rem;
|
||||
padding: 0.5rem;
|
||||
border-radius: 50%;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
background-color: var(--card-bg);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--text-color);
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
.theme-toggle:hover {
|
||||
background-color: var(--custom-file-hover-bg);
|
||||
}
|
||||
|
||||
.vulnerability-item {
|
||||
background-color: var(--card-bg);
|
||||
border-color: var(--border-color) !important;
|
||||
}
|
||||
|
||||
.list-group-item {
|
||||
background-color: var(--card-bg);
|
||||
border-color: var(--border-color);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.text-muted {
|
||||
color: #6c757d !important;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .text-muted {
|
||||
color: #adb5bd !important;
|
||||
}
|
||||
|
||||
.title-container {
|
||||
text-align: center;
|
||||
margin-bottom: 2rem;
|
||||
padding: 2rem 0;
|
||||
}
|
||||
|
||||
.main-title {
|
||||
font-family: 'Cinzel Decorative', cursive;
|
||||
font-size: 3rem;
|
||||
background: linear-gradient(45deg, #1a1a1a, #4a4a4a);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
margin-bottom: 0.5rem;
|
||||
text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .main-title {
|
||||
background: linear-gradient(45deg, #ffffff, #cccccc);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-family: "Microsoft YaHei", sans-serif;
|
||||
color: var(--text-color);
|
||||
font-size: 1.2rem;
|
||||
opacity: 0.8;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<button class="theme-toggle" onclick="toggleTheme()" title="切换主题">
|
||||
<i class="bi bi-moon-fill" id="themeIcon"></i>
|
||||
</button>
|
||||
<div class="container">
|
||||
<div class="title-container">
|
||||
<h1 class="main-title">Mirror Flowers</h1>
|
||||
<div class="subtitle">镜花 · 代码安全审计工具</div>
|
||||
</div>
|
||||
|
||||
<!-- API配置部分 -->
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0">API配置</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-4">
|
||||
<input type="text" id="apiKey" class="form-control" placeholder="OpenAI API Key">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<input type="text" id="apiBase" class="form-control" placeholder="API Base URL(可选)">
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<select id="modelSelect" class="form-select">
|
||||
<option value="">选择模型</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-2">
|
||||
<button onclick="updateConfig()" class="btn btn-primary w-100">更新配置</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 文件上传部分 -->
|
||||
<div class="card mb-4">
|
||||
<div class="card-header">
|
||||
<h5 class="mb-0">代码审计</h5>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="mb-3">
|
||||
<select id="uploadType" class="form-select mb-3">
|
||||
<option value="single">单文件审计</option>
|
||||
<option value="folder">项目文件夹审计</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="upload-container">
|
||||
<!-- 单文件上传 -->
|
||||
<div id="singleFileUpload" class="upload-section">
|
||||
<div class="custom-file-upload">
|
||||
<label for="codeFile" class="form-label">选择文件 (.php, .java, .js, .py)</label>
|
||||
<input type="file" id="codeFile" class="form-control" accept=".php,.java,.js,.py">
|
||||
</div>
|
||||
<div id="singleFileList" class="file-list mt-2"></div>
|
||||
</div>
|
||||
|
||||
<!-- 文件夹上传 -->
|
||||
<div id="folderUpload" class="upload-section" style="display: none;">
|
||||
<div class="custom-file-upload">
|
||||
<label for="codeFolder" class="form-label">选择项目文件夹</label>
|
||||
<input type="file" id="codeFolder" class="form-control" webkitdirectory directory>
|
||||
</div>
|
||||
<div id="folderFileList" class="file-list mt-2"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button onclick="startAudit()" id="auditBtn" class="btn btn-success mt-3" disabled>
|
||||
开始审计
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 结果显示部分 -->
|
||||
<div id="results" style="display: none;">
|
||||
<h2>审计结果</h2>
|
||||
<div class="accordion" id="auditResults">
|
||||
<!-- 结果将动态添加到这里 -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 加载提示 -->
|
||||
<div id="loading" class="loading" style="display: none;">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">分析中...</span>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<p id="loadingText" class="mb-2">代码分析中,请稍候...</p>
|
||||
<div class="progress" style="height: 20px; width: 300px; margin: 0 auto;">
|
||||
<div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated"
|
||||
role="progressbar" style="width: 0%;"
|
||||
aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
|
||||
</div>
|
||||
<p id="currentFile" class="mt-2 text-muted small"></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const apiUrl = 'http://127.0.0.1:8000';
|
||||
|
||||
// 获取可用模型列表
|
||||
async function fetchAvailableModels() {
|
||||
try {
|
||||
const response = await fetch(`${apiUrl}/api/models`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
console.log('获取到的模型数据:', data);
|
||||
|
||||
const modelSelect = document.getElementById('modelSelect');
|
||||
modelSelect.innerHTML = '<option value="">选择模型</option>';
|
||||
|
||||
if (data.models && typeof data.models === 'object') {
|
||||
// 遍历每个模型类别
|
||||
Object.entries(data.models).forEach(([category, models]) => {
|
||||
if (models.length > 0) {
|
||||
const optgroup = document.createElement('optgroup');
|
||||
optgroup.label = category;
|
||||
|
||||
// 对模型进行排序
|
||||
const sortedModels = [...models].sort((a, b) => {
|
||||
// 将Pro模型排在后面
|
||||
const aIsPro = a.startsWith('Pro/');
|
||||
const bIsPro = b.startsWith('Pro/');
|
||||
if (aIsPro && !bIsPro) return 1;
|
||||
if (!aIsPro && bIsPro) return -1;
|
||||
return a.localeCompare(b);
|
||||
});
|
||||
|
||||
sortedModels.forEach(model => {
|
||||
const option = document.createElement('option');
|
||||
option.value = model;
|
||||
// 美化显示名称
|
||||
option.textContent = model.split('/').pop() || model;
|
||||
if (model === data.current_model) {
|
||||
option.selected = true;
|
||||
}
|
||||
optgroup.appendChild(option);
|
||||
});
|
||||
|
||||
modelSelect.appendChild(optgroup);
|
||||
}
|
||||
});
|
||||
|
||||
// 如果没有选中的模型,默认选择第一个GPT模型
|
||||
if (!modelSelect.value && data.models.GPT?.length > 0) {
|
||||
modelSelect.value = data.models.GPT[0];
|
||||
}
|
||||
} else {
|
||||
console.error('模型数据格式错误:', data);
|
||||
}
|
||||
} else {
|
||||
const error = await response.json();
|
||||
console.error('获取模型列表失败:', error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取模型列表失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// 更新配置函数
|
||||
async function updateConfig() {
|
||||
const apiKey = document.getElementById('apiKey').value;
|
||||
let apiBase = document.getElementById('apiBase').value;
|
||||
const modelSelect = document.getElementById('modelSelect');
|
||||
const model = modelSelect.value || modelSelect.options[1]?.value; // 如果没有选择,使用第一个有效选项
|
||||
|
||||
if (!apiKey) {
|
||||
alert('请输入 API Key');
|
||||
return;
|
||||
}
|
||||
|
||||
// 规范化 API 基础 URL
|
||||
if (apiBase) {
|
||||
apiBase = apiBase.trim();
|
||||
if (!apiBase.startsWith('http')) {
|
||||
apiBase = 'https://' + apiBase;
|
||||
}
|
||||
if (!apiBase.endsWith('/v1')) {
|
||||
apiBase = apiBase.replace(/\/+$/, '') + '/v1';
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
console.log('发送配置:', { api_key: apiKey, api_base: apiBase, model }); // 添加调试日志
|
||||
|
||||
const response = await fetch(`${apiUrl}/api/configure`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_key: apiKey,
|
||||
api_base: apiBase || null,
|
||||
model: model || null
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
console.log('配置更新结果:', result); // 添加调试日志
|
||||
alert(result.message);
|
||||
await fetchAvailableModels();
|
||||
} else {
|
||||
const error = await response.json();
|
||||
throw new Error(error.detail || '配置更新失败');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('配置更新失败:', error);
|
||||
alert('配置更新失败: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化上传类型切换
|
||||
function initializeUploadTypes() {
|
||||
const uploadType = document.getElementById('uploadType');
|
||||
const sections = {
|
||||
single: document.getElementById('singleFileUpload'),
|
||||
folder: document.getElementById('folderUpload')
|
||||
};
|
||||
|
||||
// 确保初始状态正确
|
||||
sections.single.style.display = 'block';
|
||||
sections.folder.style.display = 'none';
|
||||
|
||||
uploadType.addEventListener('change', function() {
|
||||
// 使用简单的显示/隐藏切换
|
||||
Object.entries(sections).forEach(([type, section]) => {
|
||||
section.style.display = type === this.value ? 'block' : 'none';
|
||||
|
||||
// 如果是隐藏的部分,清除其文件选择
|
||||
if (type !== this.value) {
|
||||
const input = section.querySelector('input[type="file"]');
|
||||
if (input) {
|
||||
input.value = '';
|
||||
}
|
||||
const fileList = section.querySelector('.file-list');
|
||||
if (fileList) {
|
||||
fileList.innerHTML = '';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 更新按钮状态
|
||||
updateAuditButtonState();
|
||||
});
|
||||
}
|
||||
|
||||
// 修改文件输入监听器
|
||||
function initializeFileInputs() {
|
||||
const fileInputs = {
|
||||
'codeFile': 'singleFileList',
|
||||
'codeFolder': 'folderFileList'
|
||||
};
|
||||
|
||||
Object.entries(fileInputs).forEach(([inputId, listId]) => {
|
||||
const input = document.getElementById(inputId);
|
||||
if (input) {
|
||||
input.addEventListener('change', function() {
|
||||
if (this.files && this.files.length > 0) {
|
||||
updateFileList(this.files, listId);
|
||||
document.getElementById('auditBtn').disabled = false;
|
||||
} else {
|
||||
document.getElementById(listId).innerHTML = '';
|
||||
document.getElementById('auditBtn').disabled = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 页面加载时初始化
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
initTheme();
|
||||
initializeUploadTypes();
|
||||
initializeFileInputs();
|
||||
fetchAvailableModels();
|
||||
});
|
||||
|
||||
// API Base URL 改变时更新模型列表
|
||||
document.getElementById('apiBase').addEventListener('change', async (event) => {
|
||||
console.log('API Base URL changed:', event.target.value);
|
||||
await fetchAvailableModels();
|
||||
});
|
||||
|
||||
// 更新文件列表显示
|
||||
function updateFileList(files, containerId) {
|
||||
const container = document.getElementById(containerId);
|
||||
container.innerHTML = '';
|
||||
|
||||
if (containerId === 'folderFileList') {
|
||||
// 对于文件夹上传,使用新的处理逻辑
|
||||
const supportedExtensions = ['.php', '.java', '.js', '.py'];
|
||||
const validFiles = Array.from(files).filter(file => {
|
||||
const ext = '.' + file.name.split('.').pop().toLowerCase();
|
||||
return supportedExtensions.includes(ext);
|
||||
});
|
||||
|
||||
showProcessingInfo(validFiles, files.length - validFiles.length);
|
||||
|
||||
// 只有存在有效文件时才启用审计按钮
|
||||
document.getElementById('auditBtn').disabled = validFiles.length === 0;
|
||||
} else {
|
||||
// 对于单文件上传,保持原有逻辑
|
||||
Array.from(files).forEach(file => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'file-list-item';
|
||||
item.innerHTML = `
|
||||
<i class="bi bi-file-earmark-text"></i>
|
||||
${file.webkitRelativePath || file.name}
|
||||
<small class="text-muted">(${formatFileSize(file.size)})</small>
|
||||
`;
|
||||
container.appendChild(item);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 修改审计按钮状态更新函数
|
||||
function updateAuditButtonState() {
|
||||
const uploadType = document.getElementById('uploadType').value;
|
||||
const inputId = uploadType === 'single' ? 'codeFile' : 'codeFolder';
|
||||
const input = document.getElementById(inputId);
|
||||
|
||||
document.getElementById('auditBtn').disabled = !input || !input.files.length;
|
||||
}
|
||||
|
||||
// 格式化文件大小
|
||||
function formatFileSize(bytes) {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
const k = 1024;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
}
|
||||
|
||||
// 修改审计函数
|
||||
async function startAudit() {
|
||||
const uploadType = document.getElementById('uploadType').value;
|
||||
let files;
|
||||
|
||||
try {
|
||||
showLoading();
|
||||
|
||||
switch(uploadType) {
|
||||
case 'single':
|
||||
files = document.getElementById('codeFile').files;
|
||||
if (files.length > 0) {
|
||||
await auditSingleFile(files[0]);
|
||||
} else {
|
||||
throw new Error('请选择要审计的文件');
|
||||
}
|
||||
break;
|
||||
case 'folder':
|
||||
files = document.getElementById('codeFolder').files;
|
||||
if (files.length > 0) {
|
||||
await auditFolder(files);
|
||||
} else {
|
||||
throw new Error('请选择要审计的文件夹');
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
alert(error.message);
|
||||
} finally {
|
||||
hideLoading();
|
||||
}
|
||||
}
|
||||
|
||||
async function auditSingleFile(file) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const apiKey = document.getElementById('apiKey').value;
|
||||
const apiBase = document.getElementById('apiBase').value;
|
||||
|
||||
if (apiKey) formData.append('api_key', apiKey);
|
||||
if (apiBase) formData.append('api_base', apiBase);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiUrl}/api/audit`, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('审计请求失败');
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
displayResults([{ file: file.name, result }]);
|
||||
} catch (error) {
|
||||
alert('审计失败: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 修改 auditFolder 函数
|
||||
async function auditFolder(files) {
|
||||
try {
|
||||
// 过滤支持的文件类型
|
||||
const supportedExtensions = ['.php', '.java', '.js', '.py'];
|
||||
const validFiles = Array.from(files).filter(file => {
|
||||
const ext = '.' + file.name.split('.').pop().toLowerCase();
|
||||
return supportedExtensions.includes(ext);
|
||||
});
|
||||
|
||||
if (validFiles.length === 0) {
|
||||
throw new Error('未找到支持的源代码文件(支持 .php, .java, .js, .py)');
|
||||
}
|
||||
|
||||
// 显示初始进度 - 压缩阶段
|
||||
updateProgress(0, validFiles.length, '准备文件...');
|
||||
|
||||
// 创建ZIP文件,只包含支持的文件
|
||||
const zip = new JSZip();
|
||||
let totalSize = 0;
|
||||
const maxSize = 10 * 1024 * 1024; // 10MB 限制
|
||||
|
||||
for (let i = 0; i < validFiles.length; i++) {
|
||||
const file = validFiles[i];
|
||||
totalSize += file.size;
|
||||
if (totalSize > maxSize) {
|
||||
throw new Error('项目文件总大小超过限制(10MB)');
|
||||
}
|
||||
const relativePath = file.webkitRelativePath || file.name;
|
||||
zip.file(relativePath, file);
|
||||
|
||||
// 更新压缩进度
|
||||
updateProgress(i + 1, validFiles.length, `正在处理: ${relativePath}`);
|
||||
}
|
||||
|
||||
// 显示处理信息
|
||||
showProcessingInfo(validFiles, files.length - validFiles.length);
|
||||
|
||||
// 更新进度显示为压缩阶段
|
||||
updateProgress(validFiles.length, validFiles.length, '正在压缩文件...');
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// 准备上传
|
||||
const formData = new FormData();
|
||||
formData.append('project', new File([zipBlob], 'project.zip'));
|
||||
|
||||
const apiKey = document.getElementById('apiKey').value;
|
||||
const apiBase = document.getElementById('apiBase').value;
|
||||
|
||||
if (apiKey) formData.append('api_key', apiKey);
|
||||
if (apiBase) formData.append('api_base', apiBase);
|
||||
|
||||
// 更新进度显示为分析阶段
|
||||
resetProgress();
|
||||
document.getElementById('loadingText').textContent = '正在进行代码分析...';
|
||||
document.getElementById('currentFile').textContent = '正在初始化分析...';
|
||||
|
||||
const response = await fetch(`${apiUrl}/api/audit/project`, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('项目审计失败');
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
// 分析完成
|
||||
document.getElementById('loadingText').textContent = '分析完成';
|
||||
document.getElementById('currentFile').textContent = '';
|
||||
document.getElementById('progressBar').style.width = '100%';
|
||||
|
||||
displayProjectResults(result.results);
|
||||
} catch (error) {
|
||||
alert('审计失败: ' + error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// 添加重置进度条函数
|
||||
function resetProgress() {
|
||||
const progressBar = document.getElementById('progressBar');
|
||||
const currentFileText = document.getElementById('currentFile');
|
||||
|
||||
progressBar.style.width = '0%';
|
||||
progressBar.setAttribute('aria-valuenow', 0);
|
||||
progressBar.textContent = '0%';
|
||||
currentFileText.textContent = '';
|
||||
}
|
||||
|
||||
// 修改更新进度条函数
|
||||
function updateProgress(processed, total, message = '') {
|
||||
const percentage = Math.round((processed / total) * 100);
|
||||
const progressBar = document.getElementById('progressBar');
|
||||
const loadingText = document.getElementById('loadingText');
|
||||
const currentFileText = document.getElementById('currentFile');
|
||||
|
||||
progressBar.style.width = `${percentage}%`;
|
||||
progressBar.setAttribute('aria-valuenow', percentage);
|
||||
progressBar.textContent = `${percentage}%`;
|
||||
|
||||
if (message) {
|
||||
currentFileText.textContent = message;
|
||||
}
|
||||
|
||||
loadingText.textContent = `处理进度:${processed}/${total}`;
|
||||
}
|
||||
|
||||
// 添加显示处理信息的函数
|
||||
function showProcessingInfo(validFiles, skippedCount) {
|
||||
const container = document.getElementById('folderFileList');
|
||||
container.innerHTML = `
|
||||
<div class="alert alert-info">
|
||||
<h6 class="mb-2">文件处理信息:</h6>
|
||||
<p class="mb-1">待审计文件数:${validFiles.length}</p>
|
||||
<p class="mb-1">已跳过文件数:${skippedCount}</p>
|
||||
<p class="mb-0">支持的文件类型:.php, .java, .js, .py</p>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<h6>待审计文件列表:</h6>
|
||||
${validFiles.map(file => `
|
||||
<div class="file-list-item">
|
||||
<i class="bi bi-file-earmark-code"></i>
|
||||
${file.webkitRelativePath || file.name}
|
||||
<small class="text-muted">(${formatFileSize(file.size)})</small>
|
||||
</div>
|
||||
`).join('')}
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function displayResults(results) {
|
||||
const resultsDiv = document.getElementById('results');
|
||||
const accordion = document.getElementById('auditResults');
|
||||
accordion.innerHTML = '';
|
||||
|
||||
results.forEach((item, index) => {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card mb-3';
|
||||
const headerId = `heading${index}`;
|
||||
const collapseId = `collapse${index}`;
|
||||
|
||||
card.innerHTML = `
|
||||
<div class="card-header" id="${headerId}">
|
||||
<h5 class="mb-0">
|
||||
<button class="btn btn-link w-100 text-start" type="button"
|
||||
data-bs-toggle="collapse" data-bs-target="#${collapseId}"
|
||||
aria-expanded="false" aria-controls="${collapseId}">
|
||||
${item.file}
|
||||
</button>
|
||||
</h5>
|
||||
</div>
|
||||
<div id="${collapseId}" class="collapse"
|
||||
aria-labelledby="${headerId}" data-bs-parent="#auditResults">
|
||||
<div class="card-body">
|
||||
<div class="mb-4">
|
||||
<h6 class="mb-3">第一轮分析</h6>
|
||||
<pre class="bg-light p-3 rounded">${item.result.first_analysis}</pre>
|
||||
</div>
|
||||
<div>
|
||||
<h6 class="mb-3">第二轮验证</h6>
|
||||
<pre class="bg-light p-3 rounded">${item.result.second_analysis}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
accordion.appendChild(card);
|
||||
});
|
||||
|
||||
resultsDiv.style.display = 'block';
|
||||
|
||||
// 自动展开第一个结果
|
||||
const firstCollapse = accordion.querySelector('.collapse');
|
||||
if (firstCollapse) {
|
||||
new bootstrap.Collapse(firstCollapse, { show: true });
|
||||
}
|
||||
}
|
||||
|
||||
function displayProjectResults(results) {
|
||||
const resultsDiv = document.getElementById('results');
|
||||
const accordion = document.getElementById('auditResults');
|
||||
accordion.innerHTML = '';
|
||||
|
||||
Object.entries(results).forEach(([filePath, result], index) => {
|
||||
const card = document.createElement('div');
|
||||
card.className = 'card mb-3';
|
||||
const headerId = `heading${index}`;
|
||||
const collapseId = `collapse${index}`;
|
||||
|
||||
// 格式化漏洞信息
|
||||
const vulnerabilitiesHtml = result.vulnerabilities.length > 0
|
||||
? result.vulnerabilities.map(vuln => `
|
||||
<div class="vulnerability-item mb-3 p-3 border rounded">
|
||||
<h6 class="text-danger">${vuln.type}</h6>
|
||||
<p><strong>位置:</strong>${vuln.location}</p>
|
||||
<p><strong>严重程度:</strong>${vuln.severity}</p>
|
||||
<p><strong>描述:</strong>${vuln.description}</p>
|
||||
<p><strong>影响:</strong>${vuln.impact}</p>
|
||||
<p><strong>修复建议:</strong>${vuln.fix}</p>
|
||||
<p><strong>相关上下文:</strong>${vuln.related_context}</p>
|
||||
</div>
|
||||
`).join('')
|
||||
: '<p class="text-muted">未发现漏洞</p>';
|
||||
|
||||
// 格式化相关文件
|
||||
const relatedFilesHtml = result.related_files.length > 0
|
||||
? `<ul class="list-group">
|
||||
${result.related_files.map(file =>
|
||||
`<li class="list-group-item">${file}</li>`
|
||||
).join('')}
|
||||
</ul>`
|
||||
: '<p class="text-muted">无相关文件</p>';
|
||||
|
||||
card.innerHTML = `
|
||||
<div class="card-header" id="${headerId}">
|
||||
<h5 class="mb-0">
|
||||
<button class="btn btn-link w-100 text-start" type="button"
|
||||
data-bs-toggle="collapse" data-bs-target="#${collapseId}"
|
||||
aria-expanded="false" aria-controls="${collapseId}">
|
||||
${filePath}
|
||||
</button>
|
||||
</h5>
|
||||
</div>
|
||||
<div id="${collapseId}" class="collapse"
|
||||
aria-labelledby="${headerId}" data-bs-parent="#auditResults">
|
||||
<div class="card-body">
|
||||
<div class="mb-4">
|
||||
<h6 class="mb-3">漏洞分析</h6>
|
||||
<div class="vulnerabilities-container">
|
||||
${vulnerabilitiesHtml}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<h6 class="mb-3">上下文分析</h6>
|
||||
<pre class="rounded">${result.context_analysis}</pre>
|
||||
</div>
|
||||
<div>
|
||||
<h6 class="mb-3">相关文件</h6>
|
||||
<div class="related-files-container">
|
||||
${relatedFilesHtml}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
accordion.appendChild(card);
|
||||
});
|
||||
|
||||
resultsDiv.style.display = 'block';
|
||||
|
||||
// 自动展开第一个结果
|
||||
const firstCollapse = accordion.querySelector('.collapse');
|
||||
if (firstCollapse) {
|
||||
new bootstrap.Collapse(firstCollapse, { show: true });
|
||||
}
|
||||
}
|
||||
|
||||
function showLoading() {
|
||||
document.getElementById('loading').style.display = 'block';
|
||||
document.getElementById('results').style.display = 'none';
|
||||
}
|
||||
|
||||
function hideLoading() {
|
||||
document.getElementById('loading').style.display = 'none';
|
||||
}
|
||||
|
||||
// 添加主题切换功能
|
||||
function toggleTheme() {
|
||||
const body = document.body;
|
||||
const themeIcon = document.getElementById('themeIcon');
|
||||
const currentTheme = body.getAttribute('data-theme');
|
||||
|
||||
if (currentTheme === 'dark') {
|
||||
body.removeAttribute('data-theme');
|
||||
themeIcon.className = 'bi bi-moon-fill';
|
||||
localStorage.setItem('theme', 'light');
|
||||
} else {
|
||||
body.setAttribute('data-theme', 'dark');
|
||||
themeIcon.className = 'bi bi-sun-fill';
|
||||
localStorage.setItem('theme', 'dark');
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化主题
|
||||
function initTheme() {
|
||||
const savedTheme = localStorage.getItem('theme') || 'light';
|
||||
const themeIcon = document.getElementById('themeIcon');
|
||||
|
||||
if (savedTheme === 'dark') {
|
||||
document.body.setAttribute('data-theme', 'dark');
|
||||
themeIcon.className = 'bi bi-sun-fill';
|
||||
} else {
|
||||
document.body.removeAttribute('data-theme');
|
||||
themeIcon.className = 'bi bi-moon-fill';
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- 添加JSZip库 -->
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,55 @@
|
||||
class ConfigAnalyzer:
|
||||
def __init__(self):
|
||||
self.dangerous_configs = {
|
||||
'php': {
|
||||
'allow_url_fopen': 'On',
|
||||
'allow_url_include': 'On',
|
||||
'display_errors': 'On',
|
||||
'expose_php': 'On'
|
||||
},
|
||||
'java': {
|
||||
'debug': 'true',
|
||||
'trace': 'true',
|
||||
'security.basic.enabled': 'false'
|
||||
}
|
||||
}
|
||||
|
||||
# 添加更多配置检查规则
|
||||
self.security_rules = {
|
||||
'authentication': {
|
||||
'required_settings': ['session.cookie_secure', 'session.cookie_httponly'],
|
||||
'forbidden_settings': ['session.use_only_cookies=0']
|
||||
},
|
||||
'file_upload': {
|
||||
'check_settings': ['upload_max_filesize', 'max_file_uploads'],
|
||||
'risk_values': ['unlimited', '-1']
|
||||
},
|
||||
'error_reporting': {
|
||||
'production_settings': {
|
||||
'display_errors': 'Off',
|
||||
'log_errors': 'On',
|
||||
'error_reporting': 'E_ALL & ~E_DEPRECATED & ~E_STRICT'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def analyze(self, config_files):
|
||||
"""增强的配置分析"""
|
||||
issues = []
|
||||
|
||||
for file_path in config_files:
|
||||
config_type = self._detect_config_type(file_path)
|
||||
|
||||
# 基本配置检查
|
||||
basic_issues = self._check_dangerous_settings(file_path, config_type)
|
||||
issues.extend(basic_issues)
|
||||
|
||||
# 环境特定检查
|
||||
env_issues = self._check_environment_specific(file_path, config_type)
|
||||
issues.extend(env_issues)
|
||||
|
||||
# 安全规则检查
|
||||
security_issues = self._check_security_rules(file_path, config_type)
|
||||
issues.extend(security_issues)
|
||||
|
||||
return self._prioritize_issues(issues)
|
||||
@@ -0,0 +1,47 @@
|
||||
class ContextAnalyzer:
|
||||
def __init__(self):
|
||||
self.file_dependencies = {}
|
||||
self.global_variables = {}
|
||||
self.function_calls = {}
|
||||
self.class_hierarchy = {}
|
||||
|
||||
def analyze_project_context(self, files):
|
||||
"""分析项目整体上下文"""
|
||||
for file_path in files:
|
||||
self._analyze_file_context(file_path)
|
||||
|
||||
def _analyze_file_context(self, file_path):
|
||||
"""分析单个文件的上下文"""
|
||||
with open(file_path, 'r') as f:
|
||||
content = f.read()
|
||||
|
||||
# 分析文件依赖
|
||||
self._analyze_dependencies(content, file_path)
|
||||
|
||||
# 分析全局变量
|
||||
self._analyze_globals(content, file_path)
|
||||
|
||||
# 分析函数调用关系
|
||||
self._analyze_function_calls(content, file_path)
|
||||
|
||||
# 分析类继承关系
|
||||
self._analyze_class_hierarchy(content, file_path)
|
||||
|
||||
def get_call_graph(self, function_name):
|
||||
"""获取函数调用图"""
|
||||
call_graph = {
|
||||
'name': function_name,
|
||||
'calls': self.function_calls.get(function_name, []),
|
||||
'called_by': self._find_callers(function_name)
|
||||
}
|
||||
return call_graph
|
||||
|
||||
def get_variable_scope(self, variable_name):
|
||||
"""获取变量作用域"""
|
||||
if variable_name in self.global_variables:
|
||||
return {
|
||||
'type': 'global',
|
||||
'defined_in': self.global_variables[variable_name],
|
||||
'used_in': self._find_variable_usage(variable_name)
|
||||
}
|
||||
return None
|
||||
@@ -0,0 +1,98 @@
|
||||
import json
|
||||
|
||||
class DependencyAnalyzer:
|
||||
def __init__(self):
|
||||
self.vulnerability_database = self._load_vulnerability_database()
|
||||
self.dependency_graph = {}
|
||||
|
||||
def analyze_dependencies(self, project_files):
|
||||
"""完整的项目依赖分析"""
|
||||
issues = []
|
||||
for file in project_files:
|
||||
if file.endswith('pom.xml'):
|
||||
issues.extend(self._analyze_maven_dependencies(file))
|
||||
elif file.endswith('package.json'):
|
||||
issues.extend(self._analyze_npm_dependencies(file))
|
||||
elif file.endswith('requirements.txt'):
|
||||
issues.extend(self._analyze_python_dependencies(file))
|
||||
elif file.endswith('composer.json'):
|
||||
issues.extend(self._analyze_composer_dependencies(file))
|
||||
return issues
|
||||
|
||||
def _analyze_maven_dependencies(self, pom_file):
|
||||
"""分析Maven依赖"""
|
||||
try:
|
||||
with open(pom_file, 'r') as f:
|
||||
content = f.read()
|
||||
dependencies = self._parse_pom_xml(content)
|
||||
return self._check_dependencies(dependencies, 'maven')
|
||||
except Exception as e:
|
||||
return [{'error': f'Maven依赖分析失败: {str(e)}'}]
|
||||
|
||||
def _analyze_npm_dependencies(self, package_file):
|
||||
"""分析NPM依赖"""
|
||||
try:
|
||||
with open(package_file, 'r') as f:
|
||||
data = json.load(f)
|
||||
dependencies = {**data.get('dependencies', {}), **data.get('devDependencies', {})}
|
||||
return self._check_dependencies(dependencies, 'npm')
|
||||
except Exception as e:
|
||||
return [{'error': f'NPM依赖分析失败: {str(e)}'}]
|
||||
|
||||
def _analyze_python_dependencies(self, requirements_file):
|
||||
"""分析Python依赖"""
|
||||
try:
|
||||
with open(requirements_file, 'r') as f:
|
||||
dependencies = {}
|
||||
for line in f:
|
||||
if '==' in line:
|
||||
name, version = line.strip().split('==')
|
||||
dependencies[name] = version
|
||||
return self._check_dependencies(dependencies, 'python')
|
||||
except Exception as e:
|
||||
return [{'error': f'Python依赖分析失败: {str(e)}'}]
|
||||
|
||||
def _check_dependencies(self, dependencies, ecosystem):
|
||||
"""检查依赖的安全问题"""
|
||||
issues = []
|
||||
for name, version in dependencies.items():
|
||||
# 检查已知漏洞
|
||||
vulns = self._check_known_vulnerabilities(name, version, ecosystem)
|
||||
if vulns:
|
||||
issues.extend(vulns)
|
||||
|
||||
# 检查版本过时
|
||||
if self._is_outdated_version(name, version, ecosystem):
|
||||
issues.append({
|
||||
'type': 'outdated_dependency',
|
||||
'name': name,
|
||||
'current_version': version,
|
||||
'latest_version': self._get_latest_version(name, ecosystem),
|
||||
'ecosystem': ecosystem,
|
||||
'severity': 'medium',
|
||||
'recommendation': '建议更新到最新的稳定版本'
|
||||
})
|
||||
|
||||
# 检查许可证
|
||||
license_issue = self._check_license_compatibility(name, ecosystem)
|
||||
if license_issue:
|
||||
issues.append(license_issue)
|
||||
|
||||
return issues
|
||||
|
||||
def analyze(self, dependencies):
|
||||
"""分析项目依赖中的安全问题"""
|
||||
vulnerabilities = []
|
||||
|
||||
for dep in dependencies:
|
||||
if dep in self.vulnerability_database:
|
||||
vulnerabilities.append({
|
||||
'type': 'vulnerable_dependency',
|
||||
'name': dep,
|
||||
'version': dependencies[dep],
|
||||
'known_vulnerabilities': self.vulnerability_database[dep],
|
||||
'severity': 'high',
|
||||
'recommendation': '更新到最新的安全版本'
|
||||
})
|
||||
|
||||
return vulnerabilities
|
||||
@@ -0,0 +1,189 @@
|
||||
class FrameworkAnalyzer:
|
||||
def __init__(self):
|
||||
self.framework_rules = {
|
||||
'spring': {
|
||||
'security_checks': {
|
||||
'csrf': [
|
||||
r'@EnableWebSecurity(?!.*csrf\(\)\.disable\(\))',
|
||||
r'csrf\(\)\.disable\(\)'
|
||||
],
|
||||
'auth': [
|
||||
r'@PreAuthorize',
|
||||
r'@Secured',
|
||||
r'SecurityContextHolder'
|
||||
],
|
||||
'cors': [
|
||||
r'@CrossOrigin\(.*allowCredentials\s*=\s*true.*\)',
|
||||
r'addCorsMappings\('
|
||||
]
|
||||
},
|
||||
'dangerous_configs': [
|
||||
r'security\.basic\.enabled\s*=\s*false',
|
||||
r'management\.security\.enabled\s*=\s*false'
|
||||
]
|
||||
},
|
||||
'django': {
|
||||
'security_checks': {
|
||||
'csrf': [
|
||||
r'@csrf_exempt',
|
||||
r'CSRF_COOKIE_SECURE\s*=\s*False'
|
||||
],
|
||||
'auth': [
|
||||
r'@login_required',
|
||||
r'@permission_required'
|
||||
],
|
||||
'xss': [
|
||||
r'mark_safe\(',
|
||||
r'safe\s+filter'
|
||||
]
|
||||
},
|
||||
'dangerous_configs': [
|
||||
r'DEBUG\s*=\s*True',
|
||||
r'ALLOWED_HOSTS\s*=\s*\[\s*\'\*\'\s*\]'
|
||||
]
|
||||
},
|
||||
'express': {
|
||||
'security_checks': {
|
||||
'helmet': [
|
||||
r'app\.use\(helmet\(\)\)',
|
||||
r'app\.use\(cors\(\)\)'
|
||||
],
|
||||
'auth': [
|
||||
r'passport\.authenticate',
|
||||
r'jwt\.verify'
|
||||
],
|
||||
'input': [
|
||||
r'body-parser',
|
||||
r'express-validator'
|
||||
]
|
||||
},
|
||||
'dangerous_configs': [
|
||||
r'app\.disable\(.*trust\s*proxy.*\)',
|
||||
r'app\.use\(bodyParser\.raw\(\)\)'
|
||||
]
|
||||
},
|
||||
'hibernate': {
|
||||
'security_checks': {
|
||||
'sql': [
|
||||
r'createQuery\(.*\+.*\)',
|
||||
r'createSQLQuery\(.*\+.*\)'
|
||||
],
|
||||
'cache': [
|
||||
r'@Cache\(',
|
||||
r'setCacheable\('
|
||||
],
|
||||
'validation': [
|
||||
r'@Valid',
|
||||
r'@Validated'
|
||||
]
|
||||
},
|
||||
'dangerous_configs': [
|
||||
r'show_sql\s*=\s*true',
|
||||
r'hibernate\.format_sql\s*=\s*true'
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
def analyze_framework(self, code: str, framework: str) -> dict:
|
||||
"""分析框架特定的安全问题"""
|
||||
if framework not in self.framework_rules:
|
||||
return {"error": f"不支持的框架: {framework}"}
|
||||
|
||||
issues = []
|
||||
rules = self.framework_rules[framework]
|
||||
|
||||
# 检查安全配置
|
||||
for check_type, patterns in rules['security_checks'].items():
|
||||
for pattern in patterns:
|
||||
matches = re.finditer(pattern, code)
|
||||
for match in matches:
|
||||
issues.append({
|
||||
'type': f'{framework}_{check_type}_issue',
|
||||
'pattern': pattern,
|
||||
'location': self._get_location(code, match.start()),
|
||||
'description': self._get_issue_description(framework, check_type, pattern),
|
||||
'severity': self._calculate_severity(framework, check_type)
|
||||
})
|
||||
|
||||
# 检查危险配置
|
||||
for pattern in rules['dangerous_configs']:
|
||||
matches = re.finditer(pattern, code)
|
||||
for match in matches:
|
||||
issues.append({
|
||||
'type': f'{framework}_dangerous_config',
|
||||
'pattern': pattern,
|
||||
'location': self._get_location(code, match.start()),
|
||||
'description': f'发现危险的{framework}配置',
|
||||
'severity': 'high'
|
||||
})
|
||||
|
||||
return {
|
||||
'framework': framework,
|
||||
'issues': issues,
|
||||
'analysis_summary': self._generate_summary(issues)
|
||||
}
|
||||
|
||||
def _get_location(self, code: str, pos: int) -> dict:
|
||||
"""获取代码位置信息"""
|
||||
lines = code[:pos].splitlines()
|
||||
return {
|
||||
'line': len(lines),
|
||||
'column': len(lines[-1]) if lines else 0
|
||||
}
|
||||
|
||||
def _calculate_severity(self, framework: str, check_type: str) -> str:
|
||||
"""计算问题严重程度"""
|
||||
high_severity = {
|
||||
'spring': ['csrf', 'auth'],
|
||||
'django': ['csrf', 'auth'],
|
||||
'express': ['helmet', 'auth'],
|
||||
'hibernate': ['sql']
|
||||
}
|
||||
|
||||
if framework in high_severity and check_type in high_severity[framework]:
|
||||
return 'high'
|
||||
return 'medium'
|
||||
|
||||
def _get_issue_description(self, framework: str, check_type: str, pattern: str) -> str:
|
||||
"""获取问题描述"""
|
||||
descriptions = {
|
||||
'spring': {
|
||||
'csrf': 'Spring Security CSRF 保护配置问题',
|
||||
'auth': 'Spring Security 认证授权配置问题',
|
||||
'cors': 'Spring CORS 配置可能存在安全风险'
|
||||
},
|
||||
'django': {
|
||||
'csrf': 'Django CSRF 保护被禁用',
|
||||
'auth': 'Django 认证装饰器使用不当',
|
||||
'xss': 'Django XSS 防护被绕过'
|
||||
},
|
||||
'express': {
|
||||
'helmet': 'Express 安全中间件配置问题',
|
||||
'auth': 'Express 认证机制实现问题',
|
||||
'input': 'Express 输入验证配置问题'
|
||||
},
|
||||
'hibernate': {
|
||||
'sql': 'Hibernate SQL 注入风险',
|
||||
'cache': 'Hibernate 缓存配置问题',
|
||||
'validation': 'Hibernate 验证配置问题'
|
||||
}
|
||||
}
|
||||
|
||||
return descriptions.get(framework, {}).get(check_type, '未知问题')
|
||||
|
||||
def _generate_summary(self, issues: list) -> str:
|
||||
"""生成分析总结"""
|
||||
if not issues:
|
||||
return "未发现框架相关的安全问题"
|
||||
|
||||
summary = "框架安全分析总结:\n"
|
||||
severity_count = {'high': 0, 'medium': 0, 'low': 0}
|
||||
|
||||
for issue in issues:
|
||||
severity_count[issue['severity']] += 1
|
||||
|
||||
summary += f"- 高危问题: {severity_count['high']} 个\n"
|
||||
summary += f"- 中危问题: {severity_count['medium']} 个\n"
|
||||
summary += f"- 低危问题: {severity_count['low']} 个\n"
|
||||
|
||||
return summary
|
||||
@@ -0,0 +1,36 @@
|
||||
class SecurityAnalyzer:
|
||||
def __init__(self):
|
||||
self.patterns = {
|
||||
'weak_crypto': [
|
||||
r'md5\(',
|
||||
r'sha1\(',
|
||||
r'crypt\(',
|
||||
r'des_encrypt\('
|
||||
],
|
||||
'hardcoded_secrets': [
|
||||
r'password\s*=\s*[\'"][^\'"]+[\'"]',
|
||||
r'secret\s*=\s*[\'"][^\'"]+[\'"]',
|
||||
r'api_key\s*=\s*[\'"][^\'"]+[\'"]'
|
||||
],
|
||||
'insecure_config': [
|
||||
r'display_errors\s*=\s*On',
|
||||
r'allow_url_include\s*=\s*On',
|
||||
r'register_globals\s*=\s*On'
|
||||
],
|
||||
'csrf_vulnerability': [
|
||||
r'form.*method=[\'"]post[\'"].*(?!.*csrf)',
|
||||
r'ajax\.post\(.*(?!.*token)'
|
||||
]
|
||||
}
|
||||
|
||||
def analyze(self, code, file_type):
|
||||
"""执行安全分析"""
|
||||
vulnerabilities = []
|
||||
|
||||
# 根据文件类型选择不同的分析策略
|
||||
if file_type == 'php':
|
||||
vulnerabilities.extend(self._analyze_php(code))
|
||||
elif file_type == 'java':
|
||||
vulnerabilities.extend(self._analyze_java(code))
|
||||
|
||||
return vulnerabilities
|
||||
@@ -0,0 +1,573 @@
|
||||
import re
|
||||
|
||||
class TaintAnalyzer:
|
||||
def __init__(self):
|
||||
self.sources = set([
|
||||
'GET', 'POST', 'REQUEST', 'FILES', 'COOKIE',
|
||||
'file_get_contents', 'fgets', 'fread',
|
||||
'stdin', '$_SERVER', '$_ENV', 'getenv',
|
||||
'mysqli_query', 'mysql_query', 'PDO->query',
|
||||
'curl_exec', 'file', 'readfile', 'unserialize'
|
||||
])
|
||||
self.sinks = set([
|
||||
'eval', 'exec', 'system', 'shell_exec',
|
||||
'passthru', 'popen', 'proc_open',
|
||||
'include', 'include_once', 'require', 'require_once',
|
||||
'mysqli_query', 'mysql_query', 'PDO->query',
|
||||
'echo', 'print', 'printf',
|
||||
'header',
|
||||
'file_put_contents', 'fwrite',
|
||||
'unserialize',
|
||||
'mail'
|
||||
])
|
||||
self.sanitizers = set([
|
||||
'htmlspecialchars', 'htmlentities', 'strip_tags',
|
||||
'addslashes', 'escapeshellarg', 'escapeshellcmd'
|
||||
])
|
||||
self.vulnerability_types = {
|
||||
'rce': ['eval', 'exec', 'system', 'shell_exec'],
|
||||
'sqli': ['mysqli_query', 'mysql_query', 'PDO->query'],
|
||||
'xss': ['echo', 'print', 'printf'],
|
||||
'file_inclusion': ['include', 'include_once', 'require'],
|
||||
'file_operation': ['file_put_contents', 'fwrite'],
|
||||
'deserialization': ['unserialize'],
|
||||
'header_injection': ['header', 'mail']
|
||||
}
|
||||
|
||||
# 添加变量追踪映射
|
||||
self.variable_mapping = {}
|
||||
|
||||
# 添加函数调用栈
|
||||
self.call_stack = []
|
||||
|
||||
# 添加更多的漏洞模式
|
||||
self.vulnerability_patterns = {
|
||||
'sql_injection': {
|
||||
'risk_functions': ['query', 'execute'],
|
||||
'safe_patterns': [r'\?|:[a-zA-Z_][a-zA-Z0-9_]*'], # 参数化查询模式
|
||||
'risk_patterns': [r".*\+.*'.*|.*'.*\+.*"] # 字符串拼接模式
|
||||
},
|
||||
'xss': {
|
||||
'risk_functions': ['echo', 'print'],
|
||||
'safe_patterns': [r'htmlspecialchars\(.*\)|htmlentities\(.*\)'],
|
||||
'risk_patterns': [r'<.*>|javascript:']
|
||||
},
|
||||
'path_traversal': {
|
||||
'risk_functions': ['file_get_contents', 'fopen'],
|
||||
'risk_patterns': [r'\.\.\/|\.\.\\']
|
||||
}
|
||||
}
|
||||
|
||||
# 添加更细粒度的漏洞检测规则
|
||||
self.detection_rules = {
|
||||
'java': {
|
||||
'sql_injection': {
|
||||
'patterns': [
|
||||
r'.*Statement\.executeQuery\(.*\+.*\)',
|
||||
r'.*Statement\.execute\(.*\+.*\)',
|
||||
r'.*PreparedStatement.*\+.*\)'
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'PreparedStatement.*\?.*\)',
|
||||
r'.*createQuery\(.*:.*\)'
|
||||
]
|
||||
},
|
||||
'command_injection': {
|
||||
'patterns': [
|
||||
r'Runtime\.exec\(.*\+.*\)',
|
||||
r'ProcessBuilder.*\+.*\)',
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'Runtime\.exec\(new String\[\].*\)'
|
||||
]
|
||||
},
|
||||
'xxe': {
|
||||
'patterns': [
|
||||
r'DocumentBuilder.*parse\(',
|
||||
r'SAXParser.*parse\(',
|
||||
r'XMLReader.*parse\('
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'setFeature\(.*XMLConstants\.FEATURE_SECURE_PROCESSING.*true\)'
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 添加框架特定的漏洞模式
|
||||
self.framework_patterns = {
|
||||
'spring': {
|
||||
'unsafe_redirects': [
|
||||
r'redirect:.*\+',
|
||||
r'sendRedirect\(.*\+.*\)'
|
||||
],
|
||||
'csrf_vulnerable': [
|
||||
r'@CrossOrigin\(.*allowCredentials\s*=\s*true.*\)',
|
||||
r'@RequestMapping.*method\s*=\s*RequestMethod\.POST.*(?!@CrossOrigin)'
|
||||
]
|
||||
},
|
||||
'hibernate': {
|
||||
'hql_injection': [
|
||||
r'createQuery\(.*\+.*\)',
|
||||
r'createSQLQuery\(.*\+.*\)'
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
# 添加 Python 相关的检测规则
|
||||
self.detection_rules['python'] = {
|
||||
'command_injection': {
|
||||
'patterns': [
|
||||
r'os\.system\(.*\+.*\)',
|
||||
r'subprocess\.call\(.*\+.*\)',
|
||||
r'subprocess\.Popen\(.*\+.*\)',
|
||||
r'eval\(.*\+.*\)',
|
||||
r'exec\(.*\+.*\)'
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'subprocess\.run\([^,]+,\s*shell\s*=\s*False\)',
|
||||
r'shlex\.quote\(.*\)'
|
||||
]
|
||||
},
|
||||
'sql_injection': {
|
||||
'patterns': [
|
||||
r'execute\(.*\+.*\)',
|
||||
r'executemany\(.*\+.*\)',
|
||||
r'raw\(.*\+.*\)',
|
||||
r'\.format\(.*\)'
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'execute\([^,]+,\s*\(.*\)\)',
|
||||
r'execute\([^,]+,\s*\[.*\]\)'
|
||||
]
|
||||
},
|
||||
'path_traversal': {
|
||||
'patterns': [
|
||||
r'open\(.*\+.*\)',
|
||||
r'os\.path\.join\(.*\+.*\)',
|
||||
r'__import__\(.*\+.*\)'
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'os\.path\.abspath\(.*\)',
|
||||
r'os\.path\.realpath\(.*\)'
|
||||
]
|
||||
},
|
||||
'deserialization': {
|
||||
'patterns': [
|
||||
r'pickle\.loads\(',
|
||||
r'yaml\.load\(',
|
||||
r'marshal\.loads\('
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'yaml\.safe_load\(',
|
||||
r'json\.loads\('
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
# 添加 JavaScript 相关的检测规则
|
||||
self.detection_rules['javascript'] = {
|
||||
'xss': {
|
||||
'patterns': [
|
||||
r'innerHTML\s*=',
|
||||
r'outerHTML\s*=',
|
||||
r'document\.write\(',
|
||||
r'eval\(',
|
||||
r'\$\(.*\)\.html\('
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'textContent\s*=',
|
||||
r'innerText\s*=',
|
||||
r'createElement\('
|
||||
]
|
||||
},
|
||||
'dom_xss': {
|
||||
'patterns': [
|
||||
r'location\s*=',
|
||||
r'location\.href\s*=',
|
||||
r'location\.search',
|
||||
r'location\.hash'
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'encodeURIComponent\(',
|
||||
r'encodeURI\('
|
||||
]
|
||||
},
|
||||
'prototype_pollution': {
|
||||
'patterns': [
|
||||
r'Object\.assign\(',
|
||||
r'Object\.prototype',
|
||||
r'\.__proto__',
|
||||
r'\.constructor\.prototype'
|
||||
]
|
||||
},
|
||||
'insecure_randomness': {
|
||||
'patterns': [
|
||||
r'Math\.random\(',
|
||||
],
|
||||
'safe_patterns': [
|
||||
r'crypto\.getRandomValues\(',
|
||||
r'window\.crypto\.subtle'
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
# 添加框架特定的检测规则
|
||||
self.framework_patterns['django'] = {
|
||||
'csrf_vulnerable': [
|
||||
r'@csrf_exempt',
|
||||
r'CSRF_COOKIE_SECURE\s*=\s*False'
|
||||
],
|
||||
'sql_injection_risk': [
|
||||
r'raw\(',
|
||||
r'extra\(',
|
||||
r'RawSQL\('
|
||||
]
|
||||
}
|
||||
|
||||
self.framework_patterns['express'] = {
|
||||
'nosql_injection': [
|
||||
r'findOne\(.*\+.*\)',
|
||||
r'find\(.*\+.*\)',
|
||||
r'update\(.*\+.*\)'
|
||||
],
|
||||
'security_misconfiguration': [
|
||||
r'app\.disable\(.*trust\s*proxy.*\)',
|
||||
r'app\.use\(bodyParser\.raw\(\)\)'
|
||||
]
|
||||
}
|
||||
|
||||
def analyze(self, ast_tree):
|
||||
"""
|
||||
执行污点分析
|
||||
"""
|
||||
vulnerabilities = []
|
||||
|
||||
# 遍历AST寻找污点传播路径
|
||||
for node in ast_tree.traverse():
|
||||
if self._is_source(node):
|
||||
taint = self._track_taint(node)
|
||||
if taint:
|
||||
vulnerabilities.append(taint)
|
||||
|
||||
return vulnerabilities
|
||||
|
||||
def _is_source(self, node):
|
||||
"""检查节点是否为污点源"""
|
||||
# 实现基本的污点源检查
|
||||
if hasattr(node, 'name'):
|
||||
return str(node.name) in self.sources
|
||||
return False
|
||||
|
||||
def _track_taint(self, node):
|
||||
"""增强的污点追踪"""
|
||||
if not node:
|
||||
return None
|
||||
|
||||
vulnerabilities = []
|
||||
visited = set()
|
||||
|
||||
def track_recursive(current_node, taint_chain=None, context=None):
|
||||
if not current_node or id(current_node) in visited:
|
||||
return
|
||||
|
||||
visited.add(id(current_node))
|
||||
taint_chain = taint_chain or []
|
||||
context = context or {}
|
||||
|
||||
# 记录变量赋值
|
||||
if self._is_assignment(current_node):
|
||||
self._track_variable_assignment(current_node)
|
||||
|
||||
# 函数调用分析
|
||||
if self._is_function_call(current_node):
|
||||
self._analyze_function_call(current_node, context)
|
||||
|
||||
# 条件语句分析
|
||||
if self._is_condition(current_node):
|
||||
self._analyze_condition_branch(current_node, context)
|
||||
|
||||
# 检查是否经过安全的过滤
|
||||
if self._is_sanitized(current_node, context):
|
||||
context['sanitized'] = True
|
||||
return
|
||||
|
||||
# 检查漏洞模式
|
||||
vuln = self._check_vulnerability_patterns(current_node, context)
|
||||
if vuln:
|
||||
vulnerabilities.append(vuln)
|
||||
|
||||
# 递归分析
|
||||
for child in self._get_node_children(current_node):
|
||||
track_recursive(child, taint_chain + [current_node], context.copy())
|
||||
|
||||
track_recursive(node)
|
||||
return vulnerabilities
|
||||
|
||||
def _calculate_severity(self, vuln_type):
|
||||
"""计算漏洞严重程度"""
|
||||
severity_map = {
|
||||
'rce': 'critical',
|
||||
'sqli': 'high',
|
||||
'xss': 'medium',
|
||||
'file_inclusion': 'high',
|
||||
'file_operation': 'medium',
|
||||
'deserialization': 'high',
|
||||
'header_injection': 'medium'
|
||||
}
|
||||
return severity_map.get(vuln_type, 'low')
|
||||
|
||||
def _get_vulnerability_type(self, node):
|
||||
"""确定漏洞类型"""
|
||||
if hasattr(node, 'name'):
|
||||
node_name = str(node.name)
|
||||
for vuln_type, sinks in self.vulnerability_types.items():
|
||||
if node_name in sinks:
|
||||
return vuln_type
|
||||
return 'unknown'
|
||||
|
||||
def _extract_context(self, node):
|
||||
"""提取漏洞上下文"""
|
||||
context = {
|
||||
'code_snippet': self._get_code_snippet(node),
|
||||
'variables': self._get_related_variables(node),
|
||||
'function_scope': self._get_function_scope(node)
|
||||
}
|
||||
return context
|
||||
|
||||
def _is_sink(self, node):
|
||||
"""检查节点是否为危险函数"""
|
||||
if hasattr(node, 'name'):
|
||||
return str(node.name) in self.sinks
|
||||
return False
|
||||
|
||||
def _analyze_function_call(self, node, context):
|
||||
"""分析函数调用的安全性"""
|
||||
if not hasattr(node, 'name'):
|
||||
return
|
||||
|
||||
func_name = str(node.name)
|
||||
|
||||
# 检查是否是高风险函数
|
||||
for vuln_type, patterns in self.vulnerability_patterns.items():
|
||||
if func_name in patterns['risk_functions']:
|
||||
# 分析函数参数
|
||||
args = self._get_function_args(node)
|
||||
for arg in args:
|
||||
if self._is_tainted(arg, context):
|
||||
# 检查是否使用了安全的编码/过滤方式
|
||||
if not self._has_safe_encoding(arg, patterns['safe_patterns']):
|
||||
context['risks'].append({
|
||||
'type': vuln_type,
|
||||
'function': func_name,
|
||||
'argument': str(arg)
|
||||
})
|
||||
|
||||
def _track_variable_assignment(self, node):
|
||||
"""追踪变量赋值"""
|
||||
if hasattr(node, 'target') and hasattr(node, 'value'):
|
||||
var_name = str(node.target)
|
||||
self.variable_mapping[var_name] = {
|
||||
'value': str(node.value),
|
||||
'tainted': self._is_tainted(node.value),
|
||||
'sanitized': self._is_sanitized(node.value),
|
||||
'location': self._get_node_location(node)
|
||||
}
|
||||
|
||||
def _analyze_condition_branch(self, node, context):
|
||||
"""分析条件分支中的安全检查"""
|
||||
if hasattr(node, 'test'):
|
||||
# 检查是否包含安全验证
|
||||
if self._has_security_check(node.test):
|
||||
context['security_checked'] = True
|
||||
|
||||
# 检查是否有风险的条件判断
|
||||
if self._has_risky_condition(node.test):
|
||||
context['risks'].append({
|
||||
'type': 'unsafe_condition',
|
||||
'condition': str(node.test),
|
||||
'location': self._get_node_location(node)
|
||||
})
|
||||
|
||||
def _has_security_check(self, node):
|
||||
"""检查是否包含安全验证"""
|
||||
security_patterns = [
|
||||
r'validate|verify|check|auth|permission',
|
||||
r'is[A-Z]|has[A-Z]',
|
||||
r'sanitize|escape|encode'
|
||||
]
|
||||
node_str = str(node)
|
||||
return any(re.search(pattern, node_str, re.I) for pattern in security_patterns)
|
||||
|
||||
def _get_data_flow_path(self, node):
|
||||
"""获取数据流路径"""
|
||||
path = []
|
||||
current = node
|
||||
while current and hasattr(current, 'parent'):
|
||||
path.append({
|
||||
'type': type(current).__name__,
|
||||
'value': str(current),
|
||||
'location': self._get_node_location(current)
|
||||
})
|
||||
current = current.parent
|
||||
return path[::-1]
|
||||
|
||||
def _analyze_framework_specific(self, node, context):
|
||||
"""分析框架特定的安全问题"""
|
||||
framework = self._detect_framework(context)
|
||||
if framework and framework in self.framework_patterns:
|
||||
patterns = self.framework_patterns[framework]
|
||||
for vuln_type, rules in patterns.items():
|
||||
if self._match_patterns(str(node), rules):
|
||||
return {
|
||||
'type': vuln_type,
|
||||
'framework': framework,
|
||||
'location': self._get_node_location(node),
|
||||
'severity': 'high',
|
||||
'description': f'发现{framework}框架相关的{vuln_type}漏洞'
|
||||
}
|
||||
return None
|
||||
|
||||
def _analyze_data_validation(self, node):
|
||||
"""分析数据验证逻辑"""
|
||||
validation_info = {
|
||||
'has_validation': False,
|
||||
'validation_type': None,
|
||||
'validation_coverage': 0.0
|
||||
}
|
||||
|
||||
# 检查是否使用了验证注解
|
||||
if self._has_validation_annotations(node):
|
||||
validation_info['has_validation'] = True
|
||||
validation_info['validation_type'] = 'annotation'
|
||||
|
||||
# 检查是否有手动验证代码
|
||||
elif self._has_manual_validation(node):
|
||||
validation_info['has_validation'] = True
|
||||
validation_info['validation_type'] = 'manual'
|
||||
|
||||
# 计算验证覆盖率
|
||||
validation_info['validation_coverage'] = self._calculate_validation_coverage(node)
|
||||
|
||||
return validation_info
|
||||
|
||||
def _analyze_authentication(self, node, context):
|
||||
"""分析认证相关的安全问题"""
|
||||
auth_issues = []
|
||||
|
||||
# 检查认证绕过
|
||||
if self._check_auth_bypass(node):
|
||||
auth_issues.append({
|
||||
'type': 'auth_bypass',
|
||||
'severity': 'critical',
|
||||
'location': self._get_node_location(node)
|
||||
})
|
||||
|
||||
# 检查权限检查
|
||||
if not self._has_permission_check(node):
|
||||
auth_issues.append({
|
||||
'type': 'missing_permission_check',
|
||||
'severity': 'high',
|
||||
'location': self._get_node_location(node)
|
||||
})
|
||||
|
||||
return auth_issues
|
||||
|
||||
def _analyze_secure_configuration(self, node):
|
||||
"""分析安全配置"""
|
||||
config_issues = []
|
||||
|
||||
# 检查安全标头配置
|
||||
if not self._has_security_headers(node):
|
||||
config_issues.append({
|
||||
'type': 'missing_security_headers',
|
||||
'severity': 'medium'
|
||||
})
|
||||
|
||||
# 检查安全cookie配置
|
||||
if not self._has_secure_cookie_config(node):
|
||||
config_issues.append({
|
||||
'type': 'insecure_cookie_config',
|
||||
'severity': 'medium'
|
||||
})
|
||||
|
||||
return config_issues
|
||||
|
||||
def _analyze_language_specific(self, node, language):
|
||||
"""基于语言特性的分析"""
|
||||
if language not in self.detection_rules:
|
||||
return None
|
||||
|
||||
rules = self.detection_rules[language]
|
||||
node_str = str(node)
|
||||
|
||||
for vuln_type, patterns in rules.items():
|
||||
# 检查危险模式
|
||||
if 'patterns' in patterns:
|
||||
for pattern in patterns['patterns']:
|
||||
if re.search(pattern, node_str):
|
||||
# 检查是否有安全模式
|
||||
if 'safe_patterns' in patterns:
|
||||
if any(re.search(safe_pattern, node_str)
|
||||
for safe_pattern in patterns['safe_patterns']):
|
||||
continue
|
||||
|
||||
return {
|
||||
'type': vuln_type,
|
||||
'language': language,
|
||||
'location': self._get_node_location(node),
|
||||
'code': node_str,
|
||||
'severity': self._calculate_severity(vuln_type),
|
||||
'description': f'发现{language}代码中的{vuln_type}漏洞'
|
||||
}
|
||||
return None
|
||||
|
||||
def _check_js_specific_issues(self, node):
|
||||
"""检查JavaScript特有的安全问题"""
|
||||
issues = []
|
||||
|
||||
# 检查不安全的第三方脚本引用
|
||||
if self._is_script_tag(node):
|
||||
if not self._has_integrity_check(node):
|
||||
issues.append({
|
||||
'type': 'insecure_script_include',
|
||||
'severity': 'medium',
|
||||
'location': self._get_node_location(node),
|
||||
'recommendation': '添加 SRI (Subresource Integrity) 校验'
|
||||
})
|
||||
|
||||
# 检查敏感信息泄露
|
||||
if self._contains_sensitive_data(node):
|
||||
issues.append({
|
||||
'type': 'sensitive_data_exposure',
|
||||
'severity': 'high',
|
||||
'location': self._get_node_location(node),
|
||||
'recommendation': '避免在前端代码中硬编码敏感信息'
|
||||
})
|
||||
|
||||
return issues
|
||||
|
||||
def _check_python_specific_issues(self, node):
|
||||
"""检查Python特有的安全问题"""
|
||||
issues = []
|
||||
|
||||
# 检查不安全的模块导入
|
||||
if self._is_import(node):
|
||||
if self._is_dangerous_import(node):
|
||||
issues.append({
|
||||
'type': 'dangerous_import',
|
||||
'severity': 'medium',
|
||||
'location': self._get_node_location(node),
|
||||
'recommendation': '谨慎使用潜在危险的模块'
|
||||
})
|
||||
|
||||
# 检查调试配置
|
||||
if self._is_debug_config(node):
|
||||
issues.append({
|
||||
'type': 'debug_enabled',
|
||||
'severity': 'medium',
|
||||
'location': self._get_node_location(node),
|
||||
'recommendation': '在生产环境中禁用调试模式'
|
||||
})
|
||||
|
||||
return issues
|
||||
@@ -0,0 +1,12 @@
|
||||
import javalang
|
||||
|
||||
class JavaParser:
|
||||
def parse(self, code: str):
|
||||
"""
|
||||
解析Java代码生成AST
|
||||
"""
|
||||
try:
|
||||
ast = javalang.parse.parse(code)
|
||||
return ast
|
||||
except Exception as e:
|
||||
raise Exception(f"Java解析错误: {str(e)}")
|
||||
@@ -0,0 +1,40 @@
|
||||
import ast
|
||||
import subprocess
|
||||
import tempfile
|
||||
import os
|
||||
|
||||
class PHPParser:
|
||||
def parse(self, code: str):
|
||||
"""
|
||||
解析PHP代码生成AST
|
||||
使用 php -l 进行语法检查
|
||||
"""
|
||||
try:
|
||||
# 创建临时文件存储PHP代码
|
||||
with tempfile.NamedTemporaryFile(suffix='.php', mode='w', delete=False) as tmp:
|
||||
tmp.write(code)
|
||||
tmp_path = tmp.name
|
||||
|
||||
# 使用 PHP 命令行进行语法检查
|
||||
result = subprocess.run(['php', '-l', tmp_path],
|
||||
capture_output=True,
|
||||
text=True)
|
||||
|
||||
# 清理临时文件
|
||||
os.unlink(tmp_path)
|
||||
|
||||
if "No syntax errors detected" not in result.stdout:
|
||||
raise Exception(result.stderr)
|
||||
|
||||
# 这里可以添加更详细的AST分析
|
||||
# 目前先返回简单的语法检查结果
|
||||
return {
|
||||
"type": "php_file",
|
||||
"syntax_valid": True,
|
||||
"content": code
|
||||
}
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise Exception(f"PHP解析错误: {str(e)}")
|
||||
except Exception as e:
|
||||
raise Exception(f"PHP解析错误: {str(e)}")
|
||||
@@ -0,0 +1,10 @@
|
||||
FROM python:3.9
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
CMD ["uvicorn", "backend.app:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -0,0 +1,188 @@
|
||||
<template>
|
||||
<div class="container">
|
||||
<h1>AI代码审计工具</h1>
|
||||
|
||||
<!-- API配置部分 -->
|
||||
<div class="config-section">
|
||||
<h2>API配置</h2>
|
||||
<div class="form-group">
|
||||
<input
|
||||
type="text"
|
||||
v-model="apiKey"
|
||||
placeholder="OpenAI API Key"
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
v-model="apiBase"
|
||||
placeholder="API Base URL(可选)"
|
||||
>
|
||||
<button @click="updateConfig">更新配置</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="upload-section">
|
||||
<input
|
||||
type="file"
|
||||
@change="handleFileUpload"
|
||||
accept=".php,.java,.py,.js"
|
||||
>
|
||||
<button @click="startAudit" :disabled="!selectedFile">开始审计</button>
|
||||
</div>
|
||||
|
||||
<div class="results-section" v-if="auditResults">
|
||||
<h2>审计结果</h2>
|
||||
|
||||
<div class="analysis-card">
|
||||
<h3>第一轮分析</h3>
|
||||
<pre>{{ auditResults.first_analysis }}</pre>
|
||||
</div>
|
||||
|
||||
<div class="analysis-card">
|
||||
<h3>第二轮验证</h3>
|
||||
<pre>{{ auditResults.second_analysis }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="loading" v-if="loading">
|
||||
分析中...
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
export default {
|
||||
data() {
|
||||
return {
|
||||
selectedFile: null,
|
||||
auditResults: null,
|
||||
loading: false,
|
||||
apiKey: '',
|
||||
apiBase: '',
|
||||
fileLanguage: null
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
async updateConfig() {
|
||||
try {
|
||||
const response = await fetch('http://localhost:8000/api/configure', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
api_key: this.apiKey,
|
||||
api_base: this.apiBase || undefined
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
alert('API配置已更新');
|
||||
} else {
|
||||
throw new Error('配置更新失败');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('配置更新失败:', error);
|
||||
alert('配置更新失败');
|
||||
}
|
||||
},
|
||||
|
||||
handleFileUpload(event) {
|
||||
const file = event.target.files[0];
|
||||
const supportedTypes = {
|
||||
'.php': 'PHP',
|
||||
'.java': 'Java',
|
||||
'.py': 'Python',
|
||||
'.js': 'JavaScript'
|
||||
};
|
||||
|
||||
const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
|
||||
if (!supportedTypes[fileExt]) {
|
||||
this.$message.error('不支持的文件类型。支持的文件类型包括: .php, .java, .py, .js');
|
||||
return;
|
||||
}
|
||||
|
||||
this.selectedFile = file;
|
||||
this.fileLanguage = supportedTypes[fileExt];
|
||||
},
|
||||
|
||||
async startAudit() {
|
||||
if (!this.selectedFile) return
|
||||
|
||||
this.loading = true
|
||||
const formData = new FormData()
|
||||
formData.append('file', this.selectedFile)
|
||||
|
||||
// 添加API配置
|
||||
if (this.apiKey) {
|
||||
formData.append('api_key', this.apiKey)
|
||||
}
|
||||
if (this.apiBase) {
|
||||
formData.append('api_base', this.apiBase)
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:8000/api/audit', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('审计请求失败')
|
||||
}
|
||||
|
||||
this.auditResults = await response.json()
|
||||
} catch (error) {
|
||||
console.error('审计失败:', error)
|
||||
alert('审计过程中发生错误')
|
||||
} finally {
|
||||
this.loading = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.config-section {
|
||||
margin: 20px 0;
|
||||
padding: 20px;
|
||||
background: #f8f9fa;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.form-group {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
input[type="text"] {
|
||||
flex: 1;
|
||||
padding: 8px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.upload-section {
|
||||
margin: 20px 0;
|
||||
}
|
||||
|
||||
.analysis-card {
|
||||
background: #f5f5f5;
|
||||
padding: 20px;
|
||||
margin: 10px 0;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.loading {
|
||||
text-align: center;
|
||||
margin: 20px 0;
|
||||
font-size: 18px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,8 @@
|
||||
code-audit-tool/
|
||||
├── frontend/ # Vue.js前端
|
||||
├── backend/ # Python FastAPI后端
|
||||
├── core/ # 核心审计逻辑
|
||||
│ ├── analyzers/ # 各种分析器
|
||||
│ ├── parsers/ # 代码解析器
|
||||
│ └── ai/ # AI分析模块
|
||||
└── docker/ # Docker配置文件
|
||||
@@ -0,0 +1,10 @@
|
||||
fastapi>=0.68.0
|
||||
uvicorn>=0.15.0
|
||||
python-multipart>=0.0.5
|
||||
openai>=1.0.0
|
||||
javalang>=0.13.0
|
||||
aiohttp>=3.8.1
|
||||
python-dotenv>=0.19.0
|
||||
pydantic>=2.0.0
|
||||
pydantic-settings>=2.0.0
|
||||
php-ast>=1.1.0
|
||||
Reference in new issue
Block a user