### AGENT AUDIT # DeepAudit Agent 审计模块 v3.0.0 ## 概述 Agent 审计模块是 DeepAudit v3.0.0 的核心功能,基于 **Multi-Agent 架构** 实现自主代码安全分析和漏洞验证。 ### 核心特性 - 🤖 **Multi-Agent 协作**: Orchestrator 编排决策,多智能体协作审计 - 🧠 **RAG 知识库增强**: 代码语义理解 + CWE/CVE 漏洞知识库 - 🔒 **沙箱漏洞验证**: Docker 安全容器自动执行 PoC - 🛠️ **专业工具集成**: Semgrep、Bandit、Gitleaks、OSV-Scanner 等 --- ## 架构设计 ### Multi-Agent 工作流 ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ### Agent 职责 | Agent | 职责 | 使用工具 | |-------|------|----------| | **Orchestrator** | 统筹编排,自主决策审计策略 | 任务分配、结果汇总 | | **Recon** | 信息收集,识别技术栈和入口点 | list_files, npm_audit, safety_scan, gitleaks | | **Analysis** | 深度分析,挖掘潜在安全漏洞 | semgrep, bandit, rag_query, code_analysis | | **Verification** | 沙箱验证,确认漏洞真实有效 | sandbox_exec, vulnerability_validation | --- ## 快速开始 ### 1. 部署 Agent 模式 ```bash # 配置环境变量 cp backend/env.example backend/.env # 编辑 .env,设置 AGENT_ENABLED=true # 启动完整服务 docker compose up -d ``` ### 2. 构建沙箱镜像 ```bash cd docker/sandbox ./build.sh ``` ### 3. 使用 Agent 审计 1. 在项目详情页点击 "Agent 审计" 2. 选择目标漏洞类型 3. 可选:上传知识库文件增强检测 4. 启动审计,实时查看 Agent 执行日志 --- ## 工具集 ### 内置工具 | 工具 | 功能 | Agent | |------|------|-------| | `list_files` | 目录浏览 | Recon | | `read_file` | 文件读取 | All | | `search_code` | 代码搜索 | Analysis | | `rag_query` | 语义检索 | Analysis | | `security_search` | 安全代码搜索 | Analysis | | `function_context` | 函数上下文 | Analysis | | `pattern_match` | 模式匹配 | Analysis | | `code_analysis` | LLM 分析 | Analysis | | `dataflow_analysis` | 数据流追踪 | Analysis | | `vulnerability_validation` | 漏洞验证 | Verification | | `sandbox_exec` | 沙箱执行 | Verification | | `verify_vulnerability` | 自动验证 | Verification | ### 外部安全工具 | 工具 | 功能 | 适用场景 | |------|------|----------| | `semgrep_scan` | Semgrep 静态分析 | 多语言快速扫描 | | `bandit_scan` | Bandit Python 扫描 | Python 安全分析 | | `gitleaks_scan` | Gitleaks 密钥检测 | 密钥泄露检测 | | `trufflehog_scan` | TruffleHog 扫描 | 深度密钥扫描 | | `npm_audit` | npm 依赖审计 | Node.js 依赖漏洞 | | `safety_scan` | Safety Python 审计 | Python 依赖漏洞 | | `osv_scan` | OSV 漏洞扫描 | 多语言依赖漏洞 | --- ## RAG 系统 ### 功能特点 - **代码分块**: 基于 Tree-sitter AST 的智能分块 - **向量存储**: ChromaDB 持久化 - **多语言支持**: Python, JavaScript, TypeScript, Java, Go, PHP, Rust 等 - **知识库增强**: 支持上传自定义漏洞知识库 ### 配置 ```env # 嵌入模型配置 EMBEDDING_PROVIDER=openai EMBEDDING_MODEL=text-embedding-3-small # 向量数据库配置 VECTOR_DB_TYPE=chroma ``` --- ## 安全沙箱 ### 功能特点 - **Docker 隔离**: 安全容器执行 PoC - **资源限制**: 内存、CPU 限制 - **网络隔离**: 可配置网络访问 - **seccomp 策略**: 系统调用白名单 ### 配置 ```env SANDBOX_ENABLED=true SANDBOX_IMAGE=deepaudit-sandbox:latest SANDBOX_MEMORY_LIMIT=512m SANDBOX_CPU_LIMIT=1.0 SANDBOX_NETWORK_DISABLED=true ``` ### 沙箱镜像内置工具 - Python 3.11 + Semgrep, Bandit, Safety - Node.js 20 + npm audit - Go 1.21 + OSV-Scanner - Rust + cargo-audit - Gitleaks, TruffleHog --- ## API 接口 ### 创建任务 ```http POST /api/v1/agent-tasks/ Content-Type: application/json { "project_id": "xxx", "name": "安全审计", "target_vulnerabilities": ["sql_injection", "xss"], "verification_level": "sandbox", "max_iterations": 3 } ``` ### 事件流 ```http GET /api/v1/agent-tasks/{task_id}/events Accept: text/event-stream ``` ### 获取发现 ```http GET /api/v1/agent-tasks/{task_id}/findings?verified_only=true ``` ### 任务摘要 ```http GET /api/v1/agent-tasks/{task_id}/summary ``` ### 导出报告 ```http GET /api/v1/agent-tasks/{task_id}/report?format=markdown ``` --- ## 支持的漏洞类型 | 类型 | 说明 | |------|------| | `sql_injection` | SQL 注入 | | `xss` | 跨站脚本 | | `command_injection` | 命令注入 | | `path_traversal` | 路径遍历 | | `ssrf` | 服务端请求伪造 | | `xxe` | XML 外部实体 | | `insecure_deserialization` | 不安全反序列化 | | `hardcoded_secret` | 硬编码密钥 | | `weak_crypto` | 弱加密 | | `authentication_bypass` | 认证绕过 | | `authorization_bypass` | 授权绕过 | | `idor` | 不安全直接对象引用 | --- ## 目录结构 ``` backend/app/services/agent/ ├── __init__.py # 模块导出 ├── event_manager.py # 事件管理 ├── agents/ # Agent 实现 │ ├── __init__.py │ ├── base.py # Agent 基类 │ ├── recon.py # 信息收集 Agent │ ├── analysis.py # 漏洞分析 Agent │ ├── verification.py # 漏洞验证 Agent │ └── orchestrator.py # 编排 Agent ├── tools/ # Agent 工具 │ ├── __init__.py │ ├── base.py # 工具基类 │ ├── rag_tool.py # RAG 工具 │ ├── pattern_tool.py # 模式匹配工具 │ ├── code_analysis_tool.py │ ├── file_tool.py # 文件操作 │ ├── sandbox_tool.py # 沙箱工具 │ └── external_tools.py # 外部安全工具 └── prompts/ # 系统提示词 ├── __init__.py └── system_prompts.py ``` --- ## 故障排除 ### 常见问题 **Q: Agent 审计启动失败** ```bash # 检查服务状态 docker compose ps # 查看后端日志 docker compose logs backend | grep -i agent ``` **Q: RAG 初始化失败** ```bash # 检查嵌入模型配置 # 确保 EMBEDDING_API_KEY 正确设置 ``` **Q: 沙箱执行失败** ```bash # 检查沙箱镜像 docker images | grep deepaudit-sandbox # 重新构建沙箱 cd docker/sandbox && ./build.sh ``` **Q: 外部工具不可用** ```bash # 检查工具安装(本地开发时) which semgrep bandit gitleaks # 或使用 Docker 沙箱执行 ``` ### 日志查看 ```bash # 查看 Agent 日志 docker compose logs -f backend | grep -E "(agent|Agent)" # 查看详细日志 tail -f logs/agent.log ``` --- ## 更多资源 - [部署指南](DEPLOYMENT.md) - 完整部署说明 - [配置说明](CONFIGURATION.md) - 详细配置参数 - [架构详解](AGENT_AUDIT_ARCHITECTURE.md) - 深度架构文档 --- ### AGENT AUDIT ARCHITECTURE # DeepAudit Agent 审计架构文档 ## 目录 1. [系统概述](#1-系统概述) 2. [核心设计理念](#2-核心设计理念) 3. [后端架构](#3-后端架构) - [Agent层级结构](#31-agent层级结构) - [核心基础设施](#32-核心基础设施) - [工具生态系统](#33-工具生态系统) - [知识库与提示词](#34-知识库与提示词) 4. [前端架构](#4-前端架构) 5. [API接口](#5-api接口) 6. [审计任务执行流程](#6-审计任务执行流程) 7. [事件流与遥测](#7-事件流与遥测) 8. [配置与部署](#8-配置与部署) 9. [关键设计模式](#9-关键设计模式) 10. [安全与健壮性](#10-安全与健壮性) 11. [扩展指南](#11-扩展指南) --- ## 1. 系统概述 DeepAudit Agent 审计系统是一个基于大语言模型(LLM)驱动的自主化安全代码分析系统。该系统采用**动态多Agent层级架构**,实现了从代码侦察、漏洞分析到验证确认的完整安全审计流程。 ### 核心特性 | 特性 | 描述 | |------|------| | **LLM中心化决策** | LLM作为系统的"大脑",在各个层级自主做出决策 | | **动态Agent树** | 根据任务需求动态构建层级化的多Agent系统 | | **ReAct模式** | 实现思考-行动-观察(Thought-Action-Observation)循环 | | **事件驱动架构** | 通过SSE实时推送事件到前端 | | **丰富的工具生态** | 20+专业工具覆盖代码分析、模式匹配、漏洞验证 | ### 技术栈 - **后端**: Python 3.11+, FastAPI, LangChain/LiteLLM - **前端**: React 18, TypeScript, Ant Design - **数据库**: PostgreSQL (Supabase) - **通信**: SSE (Server-Sent Events), REST API --- ## 2. 核心设计理念 ### 2.1 LLM自主决策 与传统的规则驱动自动化不同,本系统中**LLM做出所有战略决策**: ``` 传统方式: 规则 → 固定流程 → 结果 DeepAudit: LLM分析 → 自主决策 → 动态调整 → 结果 ``` LLM负责决定: - 何时派发哪个子Agent - 使用哪些工具进行分析 - 何时认为分析已足够充分 - 如何解读和关联发现的问题 ### 2.2 ReAct模式实现 每个Agent的执行遵循ReAct(Reasoning + Acting)模式: ``` ┌─────────────────────────────────────────────────┐ │ LLM 输出 │ ├─────────────────────────────────────────────────┤ │ Thought: 我应该先了解项目结构... │ │ Action: list_files │ │ Action Input: {"directory": ".", "pattern": "*"}│ └─────────────────────────────────────────────────┘ ↓ ┌─────────────────────────────────────────────────┐ │ 系统执行工具 │ ├─────────────────────────────────────────────────┤ │ Observation: [找到 app/, config/, tests/...] │ └─────────────────────────────────────────────────┘ ↓ 反馈给LLM,继续下一轮循环 ``` ### 2.3 层级化Agent协作 ``` ┌───────────────────┐ │ OrchestratorAgent │ │ (策略编排者) │ └─────────┬─────────┘ │ ┌─────────────────┼─────────────────┐ ↓ ↓ ↓ ┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ ReconAgent │ │ AnalysisAgent │ │VerificationAgent│ │ (情报收集) │ │ (漏洞猎手) │ │ (验证确认) │ └───────────────┘ └───────────────┘ └───────────────┘ ``` --- ## 3. 后端架构 ### 3.1 Agent层级结构 所有Agent代码位于 `backend/app/services/agent/agents/` 目录。 #### 3.1.1 BaseAgent 基类 **文件**: `base.py` BaseAgent是所有Agent的抽象基类,提供核心功能: ```python class BaseAgent: """Agent基类 - 提供通用功能""" # 核心配置 config: AgentConfig # 名称、类型、模式、最大token数、最大迭代次数 state: AgentState # 状态管理(status, messages, findings) # 关键方法 async def run(self, input_data: dict) -> AgentResult # 抽象方法 async def stream_llm_call() # 统一的LLM调用(支持流式+自动压缩) async def execute_tool() # 工具执行(带错误处理) # 事件发射 def emit_thinking_token() # 流式输出LLM思考过程 def emit_thinking_start/end() # 思考生命周期 def emit_tool_call/result() # 工具执行生命周期 def emit_finding() # 漏洞发现事件 ``` **关键特性**: - 消息历史压缩(超过100k token时自动截断) - 取消支持(`is_cancelled`属性) - 知识模块动态加载 - 动态父子关系管理 #### 3.1.2 OrchestratorAgent 编排器 **文件**: `orchestrator.py` **角色**: 战略编排与动态任务调度 **最大迭代次数**: 20 ```python class OrchestratorAgent(BaseAgent): """编排器Agent - 协调整体审计流程""" async def run(self, input_data: dict) -> AgentResult: """主ReAct循环 - LLM决定下一步行动""" # dispatch_agent: 派发子Agent # summarize: 汇总当前进度 # finish: 完成审计 async def _dispatch_agent(self, agent_name: str, task: str): """派发ReconAgent、AnalysisAgent或VerificationAgent""" def _parse_llm_response(self, response: str): """从LLM输出中提取Thought/Action/Action Input""" ``` **决策点**: - 决定派发哪个子Agent - 判断何时完成审计 - 汇总所有子Agent的发现 #### 3.1.3 ReconAgent 侦察员 **文件**: `recon.py` **角色**: 项目分析与情报收集 **最大迭代次数**: 15 **主要任务**: - 发现项目结构 - 识别技术栈和框架 - 定位入口点 - 标记高风险区域 **可用工具**: `list_files`, `read_file`, `search_code` **输出格式**: ```json { "project_structure": {...}, "tech_stack": {"languages": ["Python"], "frameworks": ["Django"]}, "entry_points": ["app/views.py", "api/routes.py"], "high_risk_areas": ["auth/", "payment/"], "initial_findings": [...] } ``` #### 3.1.4 AnalysisAgent 分析员 **文件**: `analysis.py` **角色**: 深度代码漏洞分析 **最大迭代次数**: 30 **主要工具**: | 工具 | 描述 | 优先级 | |------|------|--------| | `smart_scan` | 智能批量安全扫描 | **推荐首选** | | `quick_audit` | 快速文件审计 | 二级 | | `pattern_match` | 危险模式检测 | 三级 | | `dataflow_analysis` | 数据流追踪 | 深度分析 | | `semgrep_scan` | Semgrep静态分析 | 外部工具 | | `bandit_scan` | Python安全检测 | 外部工具 | | `gitleaks_scan` | 密钥泄露检测 | 外部工具 | **关注的漏洞类型**: - SQL注入 - XSS跨站脚本 - 命令注入 - 路径遍历 - SSRF服务端请求伪造 #### 3.1.5 VerificationAgent 验证员 **文件**: `verification.py` **角色**: 确认发现并生成PoC **最大迭代次数**: 15 **主要职责**: - 减少误报 - 验证可利用性 - 生成概念验证(PoC) **输出格式**: ```json { "is_verified": true, "poc": { "description": "...", "steps": [...], "payload": "..." }, "exploitability": "high", "confidence": 0.95 } ``` #### 3.1.6 TaskHandoff 任务交接协议 Agent之间通过结构化的`TaskHandoff`进行协作: ```python @dataclass class TaskHandoff: """Agent间的结构化通信协议""" work_completed: str # 已完成的工作 key_findings: List[dict] # 关键发现 insights: List[str] # 洞察 suggested_actions: List[str] # 建议行动 attention_points: List[str] # 需要关注的点 priority_areas: List[str] # 优先区域 context_data: dict # 上下文数据 def to_prompt_context(self) -> str: """转换为LLM可读格式""" ``` --- ### 3.2 核心基础设施 核心基础设施位于 `backend/app/services/agent/core/` 目录。 #### 3.2.1 状态管理 (state.py) ```python class AgentState: """Agent状态跟踪""" status: Literal["created", "running", "waiting", "completed", "failed"] messages: List[Message] # 对话历史 findings: List[Finding] # 发现列表 iterations: int # 当前迭代次数 tool_calls: int # 工具调用次数 ``` #### 3.2.2 执行上下文 (context.py) ```python class ExecutionContext: """分布式追踪的执行上下文""" task_id: str # 任务ID agent_id: str # Agent ID trace_path: str # 追踪路径 (如: Orchestrator > Analysis) depth: int # 嵌套深度 iteration: int # 当前迭代 metadata: dict # 附加元数据 def child_context(self, agent_id: str) -> ExecutionContext: """创建子上下文""" def with_iteration(self, iteration: int) -> ExecutionContext: """带迭代信息的上下文""" ``` #### 3.2.3 熔断器 (circuit_breaker.py) ```python class CircuitBreaker: """熔断器 - 防止级联故障""" # 状态转换: CLOSED -> OPEN -> HALF_OPEN -> CLOSED failure_threshold: int = 5 # 失败阈值 recovery_timeout: float = 30.0 # 恢复超时(秒) async def call(self, func: Callable) -> Any: """受保护的调用""" if self.state == CircuitState.OPEN: raise CircuitOpenError() try: result = await func() self._record_success() return result except Exception as e: self._record_failure() raise ``` #### 3.2.4 重试机制 (retry.py) ```python class RetryStrategy: """指数退避重试""" base_delay: float = 1.0 # 基础延迟(秒) max_delay: float = 60.0 # 最大延迟(秒) max_retries: int = 3 # 最大重试次数 def get_delay(self, attempt: int) -> float: """计算延迟: min(base * (2 ** attempt) + jitter, max)""" ``` #### 3.2.5 速率限制器 (rate_limiter.py) ```python class RateLimiter: """令牌桶算法速率限制""" # 预设限制: # - 外部工具: 0.2 calls/second (每5秒1次) # - LLM调用: 60 calls/minute # - 突发支持: 最多3个并发调用 async def acquire(self, tool_name: str): """获取执行许可""" ``` #### 3.2.6 输入验证 (validation.py) ```python class InputValidator: """输入安全验证""" def validate_file_path(self, path: str) -> bool: """文件路径安全检查""" # - 检查路径遍历攻击 # - 验证文件扩展名 # - 检查符号链接 def validate_file_size(self, path: str, max_size: int = 10_000_000): """文件大小限制(默认10MB)""" ``` #### 3.2.7 错误处理 (errors.py) ```python # 自定义异常层级 class AgentError(Exception): pass class CircuitOpenError(AgentError): pass # 熔断器打开 class AgentExecutionError(AgentError): pass # Agent执行失败 class ToolExecutionError(AgentError): pass # 工具执行失败 class ValidationError(AgentError): pass # 输入验证失败 class TokenLimitError(AgentError): pass # Token超限 ``` --- ### 3.3 工具生态系统 工具代码位于 `backend/app/services/agent/tools/` 目录。 #### 3.3.1 文件操作工具 | 工具 | 文件 | 描述 | |------|------|------| | `FileReadTool` | - | 读取文件内容(支持行范围) | | `ListFilesTool` | - | 列出目录内容(支持glob模式) | | `FileSearchTool` | - | 按关键词搜索代码 | #### 3.3.2 代码分析工具 **SmartScanTool** (`smart_scan_tool.py`) ```python class SmartScanTool: """智能批量安全扫描 - 推荐首选工具""" # 功能: # - 自动检测漏洞模式 # - 聚焦高风险文件 # - 批量处理提高效率 async def execute(self, target: str) -> dict: return { "vulnerabilities": [...], "risk_areas": [...], "recommendations": [...] } ``` **PatternMatchTool** (`pattern_tool.py`) ```python class PatternMatchTool: """基于正则的模式检测""" # 内置模式: # - SQL注入模式 # - XSS模式 # - 命令注入模式 # - 可作为Semgrep的后备 ``` **DataFlowAnalysisTool** (`code_analysis_tool.py`) ```python class DataFlowAnalysisTool: """数据流分析工具""" # 功能: # - 源点到汇点追踪 # - 变量污点分析 # - LLM辅助的数据流理解 ``` #### 3.3.3 外部安全工具 **文件**: `external_tools.py` | 工具 | 描述 | 超时 | 后备方案 | |------|------|------|----------| | `SemgrepTool` | 静态分析规则引擎 | 120s | PatternMatchTool | | `BanditTool` | Python安全linter | 60s | PatternMatchTool | | `GitleaksTool` | 密钥/凭证检测 | 60s | - | #### 3.3.4 完成工具 **FinishTool** (`finish_tool.py`) ```python class FinishTool: """任务完成工具""" async def execute(self, conclusion: str, findings: List[dict]): """标记任务完成并返回最终结果""" ``` --- ### 3.4 知识库与提示词 #### 3.4.1 漏洞知识库 位于 `backend/app/services/agent/knowledge/vulnerabilities/` **按漏洞类型组织**: | 文件 | 漏洞类型 | |------|----------| | `sql_injection.py` | SQL注入 | | `xss.py` | 跨站脚本 | | `csrf.py` | 跨站请求伪造 | | `auth.py` | 认证漏洞 | | `ssrf.py` | 服务端请求伪造 | | `path_traversal.py` | 路径遍历 | | `deserialization.py` | 不安全反序列化 | | `xxe.py` | XML外部实体注入 | | `race_condition.py` | 竞态条件 | | `crypto.py` | 弱加密 | | `injection.py` | 代码/命令注入 | | `business_logic.py` | 业务逻辑漏洞 | | `open_redirect.py` | 开放重定向 | **框架特定知识**: | 文件 | 框架 | |------|------| | `FastAPI.py` | FastAPI安全模式 | | `Django.py` | Django安全问题 | | `Flask.py` | Flask漏洞 | | `Express.js` | Node.js/Express模式 | | `React.js` | 前端安全 | | `Supabase.py` | BaaS安全 | #### 3.4.2 系统提示词 **文件**: `backend/app/services/agent/prompts/system_prompts.py` ```python # 核心安全原则 CORE_SECURITY_PRINCIPLES = """ - 深度分析优于广度覆盖 - 重视数据流追踪 - 上下文感知分析 - 假阳性需验证确认 """ # 漏洞优先级 VULNERABILITY_PRIORITIES = { "critical": ["sql_injection", "command_injection", "code_injection"], "high": ["path_traversal", "ssrf", "auth_bypass"], "medium": ["xss", "information_disclosure", "xxe"], "low": ["csrf", "weak_crypto", "unsafe_transport"] } # 多Agent协作规则 MULTI_AGENT_RULES = """ - 避免重复工作 - 共享上下文信息 - 聚焦自身职责 - 及时交接发现 """ ``` --- ## 4. 前端架构 前端代码位于 `frontend/src/pages/AgentAudit/` 目录。 ### 4.1 目录结构 ``` AgentAudit/ ├── index.tsx # 主页面组件 ├── types.ts # TypeScript类型定义 ├── utils.ts # 工具函数 ├── constants.tsx # 常量配置 ├── hooks/ │ ├── useAgentAuditState.ts # 状态管理(useReducer) │ ├── useResilientStream.ts # SSE流式连接 │ └── index.ts └── components/ ├── Header.tsx # 标题、状态、控制按钮 ├── StatsPanel.tsx # 统计面板 ├── AgentTreeNode.tsx # Agent树节点渲染 ├── AgentDetailPanel.tsx # Agent详情侧边栏 ├── LogEntry.tsx # 单条日志条目 ├── ConnectionStatus.tsx # 连接状态指示器 ├── StatusBadge.tsx # 状态徽章 ├── SplashScreen.tsx # 初始屏幕 ├── AgentErrorBoundary.tsx # 错误边界 ├── ReportExportDialog.tsx # 导出对话框 └── index.ts ``` ### 4.2 状态管理 **文件**: `hooks/useAgentAuditState.ts` ```typescript interface AgentAuditState { task: AgentTask | null; // 当前任务 findings: AgentFinding[]; // 发现列表 agentTree: AgentTreeResponse | null; // Agent树 logs: LogItem[]; // 日志列表 selectedAgentId: string | null; // 选中的Agent connectionStatus: ConnectionStatus; // 连接状态 isAutoScroll: boolean; // 自动滚动 expandedLogIds: Set; // 展开的日志ID } type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'error'; // Reducer Actions type Action = | { type: 'SET_TASK'; payload: AgentTask } | { type: 'SET_FINDINGS'; payload: AgentFinding[] } | { type: 'ADD_LOG'; payload: LogItem } | { type: 'UPDATE_LOG'; payload: { id: string; updates: Partial } } | { type: 'SET_CONNECTION_STATUS'; payload: ConnectionStatus } | { type: 'SELECT_AGENT'; payload: string | null } | { type: 'TOGGLE_LOG_EXPANDED'; payload: string } | { type: 'RESET' }; ``` ### 4.3 事件流处理 **文件**: `hooks/useResilientStream.ts` ```typescript function useResilientStream(taskId: string, options: StreamOptions) { // 功能: // - 弹性SSE连接(自动重连) // - Thinking token逐字符流式更新 // - 按类型过滤事件 // - 组件卸载时自动清理 // 事件处理器 onThinkingToken: (token: string) => void; // 累积thinking内容 onToolStart: (tool: ToolEvent) => void; // 工具开始 onToolEnd: (tool: ToolEvent) => void; // 工具结束 onFinding: (finding: Finding) => void; // 新发现 onComplete: () => void; // 任务完成 onError: (error: Error) => void; // 错误处理 } ``` ### 4.4 日志类型 ```typescript type LogType = | 'thinking' // LLM思考过程(支持流式) | 'tool' // 工具执行(含耗时和状态) | 'phase' // 工作流阶段 | 'finding' // 漏洞发现 | 'info' // 信息消息 | 'error' // 错误消息 | 'dispatch' // 子Agent派发 | 'user'; // 用户操作 interface LogItem { id: string; type: LogType; timestamp: Date; content: string; metadata?: Record; isExpanded?: boolean; isStreaming?: boolean; // thinking类型专用 } ``` ### 4.5 实时更新流程 ``` SSE Stream → useResilientStream → dispatch() → reducer → UI更新 ↓ thinking_token事件 ↓ onThinkingToken回调 ↓ dispatch({type: 'ADD_LOG', payload: {type: 'thinking', content: accumulated}}) ↓ UI渲染LogEntry(流式效果) ``` --- ## 5. API接口 API端点位于 `backend/app/api/v1/endpoints/agent_tasks.py` ### 5.1 任务管理 | 方法 | 端点 | 描述 | |------|------|------| | POST | `/agent-tasks/` | 创建并启动审计任务 | | GET | `/agent-tasks/` | 列出任务(支持过滤) | | GET | `/agent-tasks/{task_id}` | 获取任务详情 | | POST | `/agent-tasks/{task_id}/cancel` | 取消运行中的任务 | ### 5.2 事件流 | 方法 | 端点 | 描述 | |------|------|------| | GET | `/agent-tasks/{task_id}/events` | 基础事件轮询(SSE) | | GET | `/agent-tasks/{task_id}/stream` | 增强事件流(含thinking tokens) | **查询参数**: - `include_thinking`: 是否包含thinking token - `include_tool_calls`: 是否包含工具调用 - `after_sequence`: 从指定序列号后开始 ### 5.3 结果查询 | 方法 | 端点 | 描述 | |------|------|------| | GET | `/agent-tasks/{task_id}/findings` | 获取发现列表(支持分页) | | GET | `/agent-tasks/{task_id}/summary` | 任务摘要与统计 | | PATCH | `/agent-tasks/{task_id}/findings/{finding_id}/status` | 更新发现状态 | | GET | `/agent-tasks/{task_id}/report` | 生成报告(markdown/json) | ### 5.4 高级功能 | 方法 | 端点 | 描述 | |------|------|------| | GET | `/agent-tasks/{task_id}/agent-tree` | Agent层级与执行统计 | | GET | `/agent-tasks/{task_id}/checkpoints` | 执行检查点列表 | | GET | `/agent-tasks/{task_id}/checkpoints/{checkpoint_id}` | 检查点详情 | ### 5.5 创建任务Schema ```python class AgentTaskCreate(BaseModel): project_id: str # 项目ID name: Optional[str] # 任务名称 target_vulnerabilities: List[str] = [ "sql_injection", "xss", "command_injection", "path_traversal", "ssrf" ] verification_level: str = "sandbox" # 验证级别 exclude_patterns: List[str] = [ # 排除模式 "node_modules", "venv", "__pycache__", ".git" ] target_files: Optional[List[str]] # 限定扫描文件 max_iterations: int = 50 # 最大迭代(1-200) timeout_seconds: int = 1800 # 超时(60-7200秒) ``` --- ## 6. 审计任务执行流程 ### 6.1 完整流程图 ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ### 6.2 详细执行示例 **场景**: 用户上传Python项目,执行Agent审计 ``` 1. 用户请求: POST /agent-tasks/ { "project_id": "123", "target_files": ["app/views.py"] } 2. Orchestrator迭代1 - LLM输出: Thought: 我应该先用recon了解项目结构 Action: dispatch_agent Action Input: {"agent": "recon", "task": "分析项目结构"} 3. ReconAgent执行: 迭代1: list_files → 找到 app/views.py, models.py... 迭代2: read_file → 读取app/views.py内容 迭代N: Final Answer → 返回项目结构信息 4. Orchestrator迭代2 - LLM输出: Thought: 这是一个Django项目,让我派发Analysis进行漏洞分析 Action: dispatch_agent Action Input: {"agent": "analysis", "task": "深度漏洞分析"} 5. AnalysisAgent执行: 迭代1: smart_scan → 发现第42行可能存在SQL注入 迭代2: read_file → 确认问题代码 迭代M: Final Answer → 返回结构化的漏洞发现 6. Orchestrator迭代3 - LLM输出: Thought: 发现高危SQL注入,需要验证 Action: dispatch_agent Action Input: {"agent": "verification", "task": "验证SQL注入"} 7. VerificationAgent确认: 返回: {"is_verified": true, "poc": {...}} 8. Orchestrator完成: Thought: 审计完成,共发现1个已验证漏洞 Action: finish Action Input: {"conclusion": "...", "findings": [...]} 9. 后端持久化: - AgentTask.status = COMPLETED - 写入AgentFinding表 10. 前端实时展示: - 日志流式更新 - Agent树动态生长 - 统计数据刷新 - 最终展示发现列表 ``` --- ## 7. 事件流与遥测 ### 7.1 事件管理器 **文件**: `backend/app/services/agent/event_manager.py` ```python class EventManager: """事件管理器 - 内存队列 + 流式迭代""" max_events: int = 1000 # 最大事件数 async def emit(self, event_type: str, message: str, **metadata): """发射事件""" async def stream_events(self): """异步迭代器: async for event in manager.stream_events()""" ``` ### 7.2 事件类型 | 类型 | 描述 | |------|------| | `thinking_start` | LLM开始思考 | | `thinking_token` | 思考token(逐字符) | | `thinking_end` | LLM思考结束 | | `tool_call` | 工具调用开始 | | `tool_result` | 工具执行结果 | | `finding` | 漏洞发现 | | `phase_start` | 阶段开始 | | `phase_complete` | 阶段完成 | | `dispatch` | 子Agent派发 | | `llm_thought` | LLM思考内容 | | `llm_decision` | LLM决策 | | `error` | 错误 | | `warning` | 警告 | | `info` | 信息 | ### 7.3 遥测追踪 **文件**: `backend/app/services/agent/telemetry/tracer.py` ```python class Tracer: """分布式追踪""" def create_span(self, name: str, parent_span: Span = None) -> Span: """创建追踪Span""" # 追踪路径示例: Orchestrator > Analysis > (Verification) # 记录的指标: # - 执行时间 # - Token使用量 # - 工具调用次数 # - 关联ID ``` --- ## 8. 配置与部署 ### 8.1 Agent配置 **文件**: `backend/app/services/agent/config.py` ```python class AgentConfig: """Agent配置 (环境变量前缀: AGENT_)""" # LLM设置 llm_max_retries: int = 3 llm_retry_base_delay: float = 1.0 llm_timeout_seconds: int = 120 llm_max_tokens_per_call: int = 4096 llm_temperature: float = 0.1 llm_stream_enabled: bool = True # Agent迭代限制 orchestrator_max_iterations: int = 20 recon_max_iterations: int = 15 analysis_max_iterations: int = 30 verification_max_iterations: int = 15 # 工具设置 tool_timeout_seconds: int = 60 tool_max_retries: int = 2 semgrep_enabled: bool = True bandit_enabled: bool = True gitleaks_enabled: bool = True # 资源限制 max_file_size_bytes: int = 10_000_000 # 10MB max_files_per_scan: int = 1000 max_total_findings: int = 500 max_context_messages: int = 50 # 熔断器 circuit_breaker_enabled: bool = True circuit_failure_threshold: int = 5 circuit_recovery_timeout_seconds: float = 30.0 # 检查点 checkpoint_enabled: bool = True checkpoint_interval_iterations: int = 5 max_checkpoints_per_task: int = 50 ``` ### 8.2 环境预设 ```python def apply_development_preset(): """开发环境预设""" # 更宽松的限制,更多日志 def apply_production_preset(): """生产环境预设""" # 更严格的限制,优化性能 def apply_testing_preset(): """测试环境预设""" # 快速迭代,最小资源 ``` --- ## 9. 关键设计模式 ### 9.1 LLM中心化决策 ``` ┌─────────────────────────────────────────────┐ │ 传统自动化 │ │ 规则引擎 → 固定流程 → 预定义行为 │ └─────────────────────────────────────────────┘ ┌─────────────────────────────────────────────┐ │ DeepAudit │ │ LLM分析 → 自主决策 → 动态适应 → 智能输出 │ └─────────────────────────────────────────────┘ ``` ### 9.2 ReAct模式 ``` Loop: 1. Thought: LLM思考当前状态和下一步 2. Action: 选择要执行的动作/工具 3. Action Input: 提供参数 4. Observation: 获取执行结果 5. 重复直到达成目标或Final Answer ``` ### 9.3 任务交接协议 ```python # Agent A完成工作后 handoff = TaskHandoff( work_completed="扫描了10个文件,发现3个可疑点", key_findings=[finding1, finding2, finding3], suggested_actions=["验证SQL注入", "检查认证逻辑"], priority_areas=["auth/", "api/"] ) # 转换为下一个Agent的输入 context = handoff.to_prompt_context() # Agent B使用此上下文继续工作 ``` ### 9.4 优雅降级 ``` ┌───────────────────────────────────────────────────┐ │ 优雅降级策略 │ ├───────────────────────────────────────────────────┤ │ • 工具失败不中断执行 (continue_on_tool_failure) │ │ • 后备工具链 (Semgrep → PatternMatch) │ │ • 超时时返回部分结果 │ │ • 熔断器防止级联故障 │ │ • 消息压缩避免token超限 │ └───────────────────────────────────────────────────┘ ``` ### 9.5 范围限定审计 ```python # 支持的范围限定: AgentTaskCreate( exclude_patterns=["node_modules", "*.min.js"], # 排除模式 target_files=["src/auth/", "api/views.py"] # 限定文件 ) # 减少噪音,聚焦LLM注意力 ``` --- ## 10. 安全与健壮性 ### 10.1 安全特性 | 特性 | 描述 | |------|------| | **速率限制** | 防止资源耗尽 | | **熔断器** | 阻止级联故障 | | **输入验证** | 文件路径、大小、扩展名检查 | | **资源限制** | 最大发现数(500)、最大文件大小(10MB) | | **范围过滤** | 可限定扫描范围 | ### 10.2 健壮性特性 | 特性 | 描述 | |------|------| | **指数退避重试** | 处理瞬态故障 | | **上下文压缩** | 自动截断长消息历史 | | **取消支持** | 可随时中断运行任务 | | **检查点** | 长任务恢复点 | | **结构化异常** | 分层错误处理 | --- ## 11. 扩展指南 ### 11.1 添加新Agent类型 ```python # 1. 创建新Agent类 class CustomAgent(BaseAgent): def __init__(self, config: AgentConfig): super().__init__(config) self.config.name = "custom" self.config.max_iterations = 20 async def run(self, input_data: dict) -> AgentResult: # 实现ReAct循环 for iteration in range(self.config.max_iterations): response = await self.stream_llm_call(messages) parsed = self._parse_response(response) if parsed.action == "finish": return AgentResult(data=parsed.data) observation = await self.execute_tool( parsed.action, parsed.action_input ) messages.append({"role": "user", "content": f"Observation: {observation}"}) # 2. 在Orchestrator中注册 orchestrator.register_agent("custom", CustomAgent(config)) ``` ### 11.2 添加新工具 ```python # 1. 实现工具接口 class CustomTool: name: str = "custom_tool" description: str = "自定义工具描述" async def execute(self, **kwargs) -> dict: # 实现工具逻辑 return {"result": "..."} # 2. 在工具注册表中添加 TOOL_REGISTRY["custom_tool"] = CustomTool() ``` ### 11.3 添加漏洞知识 ```python # 创建新的知识模块: knowledge/vulnerabilities/custom_vuln.py CUSTOM_VULN_KNOWLEDGE = { "name": "Custom Vulnerability", "description": "...", "patterns": [ r"pattern1", r"pattern2" ], "examples": [...], "remediation": "..." } ``` ### 11.4 自定义提示词 ```python # 在system_prompts.py中添加 CUSTOM_AGENT_PROMPT = """ 你是一个专门的安全分析Agent。 职责: - ... 可用工具: - ... 输出格式: - ... """ ``` ### 11.5 添加新事件类型 ```python # 在Agent中发射自定义事件 self.emit_event( event_type="custom_event", message="自定义消息", custom_field="value" ) # 在前端处理 switch (event.type) { case 'custom_event': handleCustomEvent(event); break; } ``` --- ## 附录: 关键文件索引 ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- *文档版本: 1.0* *最后更新: 2025-12-13* --- ### AGENT DEPLOYMENT CHECKLIST # DeepAudit Agent 审计功能部署清单 ## 📋 生产部署前必须完成的检查 ### 1. 环境依赖 ✅ ```bash # 后端依赖 cd backend uv pip install chromadb litellm langchain langgraph # 外部安全工具(可选但推荐) pip install semgrep bandit safety # 或者使用系统包管理器 brew install semgrep # macOS apt install semgrep # Ubuntu ``` ### 2. LLM 配置 ✅ 在 `.env` 文件中配置: ```env # LLM 配置(必须) LLM_PROVIDER=openai # 或 azure, anthropic, ollama 等 LLM_MODEL=gpt-4o-mini # 推荐使用 gpt-4 系列 LLM_API_KEY=sk-xxx # 你的 API Key LLM_BASE_URL= # 可选,自定义端点 # 嵌入模型配置(RAG 需要) EMBEDDING_PROVIDER=openai EMBEDDING_MODEL=text-embedding-3-small ``` ### 3. 数据库迁移 ✅ ```bash cd backend alembic upgrade head ``` 确保以下表已创建: - `agent_tasks` - `agent_events` - `agent_findings` ### 4. 向量数据库 ✅ ```bash # 创建向量数据库目录 mkdir -p /var/data/deepaudit/vector_db # 在 .env 中配置 VECTOR_DB_PATH=/var/data/deepaudit/vector_db ``` ### 5. Docker 沙箱(可选) 如果需要漏洞验证功能: ```bash # 拉取沙箱镜像 docker pull python:3.11-slim # 配置沙箱参数 SANDBOX_IMAGE=python:3.11-slim SANDBOX_MEMORY_LIMIT=256m SANDBOX_CPU_LIMIT=0.5 ``` --- ## 🔬 功能测试检查 ### 测试 1: 基础流程 ```bash cd backend PYTHONPATH=. uv run pytest tests/agent/ -v ``` 预期结果:43 个测试全部通过 ### 测试 2: LLM 连接 ```bash cd backend PYTHONPATH=. uv run python -c " import asyncio from app.services.agent.graph.runner import LLMService async def test(): llm = LLMService() result = await llm.analyze_code('print(\"hello\")', 'python') print('LLM 连接成功:', 'issues' in result) asyncio.run(test()) " ``` ### 测试 3: 外部工具 ```bash # 测试 Semgrep semgrep --version # 测试 Bandit bandit --version ``` ### 测试 4: 端到端测试 1. 启动后端:`cd backend && uv run uvicorn app.main:app --reload` 2. 启动前端:`cd frontend && npm run dev` 3. 创建一个项目并上传代码 4. 选择 "Agent 审计模式" 创建任务 5. 观察执行日志和发现 --- ## ⚠️ 已知限制 | 限制 | 影响 | 解决方案 | |------|------|---------| | **LLM 成本** | 每次审计消耗 Token | 使用 gpt-4o-mini 降低成本 | | **扫描时间** | 大项目需要较长时间 | 设置合理的超时时间 | | **误报率** | AI 可能产生误报 | 启用验证阶段过滤 | | **外部工具依赖** | 需要手动安装 | 提供 Docker 镜像 | --- ## 🚀 生产环境建议 ### 1. 资源配置 ```yaml # Kubernetes 部署示例 resources: limits: memory: "2Gi" cpu: "2" requests: memory: "1Gi" cpu: "1" ``` ### 2. 并发控制 ```env # 限制同时运行的任务数 MAX_CONCURRENT_AGENT_TASKS=3 AGENT_TASK_TIMEOUT=1800 # 30 分钟 ``` ### 3. 日志监控 ```python # 配置日志级别 LOG_LEVEL=INFO # 启用 SQLAlchemy 日志(调试用) SQLALCHEMY_ECHO=false ``` ### 4. 安全考虑 - [ ] 限制上传文件大小 - [ ] 限制扫描目录范围 - [ ] 启用沙箱隔离 - [ ] 配置 API 速率限制 --- ## ✅ 部署状态检查 运行以下命令验证部署状态: ```bash cd backend PYTHONPATH=. uv run python -c " print('检查部署状态...') # 1. 检查数据库连接 try: from app.db.session import async_session_factory print('✅ 数据库配置正确') except Exception as e: print(f'❌ 数据库错误: {e}') # 2. 检查 LLM 配置 from app.core.config import settings if settings.LLM_API_KEY: print('✅ LLM API Key 已配置') else: print('⚠️ LLM API Key 未配置') # 3. 检查向量数据库 import os if os.path.exists(settings.VECTOR_DB_PATH or '/tmp'): print('✅ 向量数据库路径存在') else: print('⚠️ 向量数据库路径不存在') # 4. 检查外部工具 import shutil tools = ['semgrep', 'bandit'] for tool in tools: if shutil.which(tool): print(f'✅ {tool} 已安装') else: print(f'⚠️ {tool} 未安装(可选)') print() print('部署检查完成!') " ``` --- ## 📝 结论 Agent 审计功能已经具备**基本的生产能力**,但建议: 1. **先在测试环境验证** - 用一个小项目测试完整流程 2. **监控 LLM 成本** - 观察 Token 消耗情况 3. **逐步开放** - 先给少数用户使用,收集反馈 4. **持续优化** - 根据实际效果调整 prompt 和阈值 如有问题,请查看日志或联系开发团队。 --- ### CONFIGURATION # 配置说明 本文档详细介绍 DeepAudit 的所有配置选项,包括后端环境变量、前端配置和运行时配置。 ## 目录 - [配置方式概览](#配置方式概览) - [后端配置](#后端配置) - [前端配置](#前端配置) - [运行时配置](#运行时配置) - [API 中转站配置](#api-中转站配置) --- ## 配置方式概览 DeepAudit 采用前后端分离架构,数据存储在后端 PostgreSQL 数据库中。 配置优先级(从高到低): | 配置方式 | 适用场景 | 优先级 | |---------|---------|--------| | 运行时配置(浏览器 /admin) | 快速切换 LLM、调试 | 最高 | | 后端环境变量 | 生产部署、团队共享 | 中 | | 默认值 | 开箱即用 | 最低 | --- ## 后端配置 后端配置文件位于 `backend/.env`,首次使用请复制示例文件: ```bash cp backend/env.example backend/.env ``` ### 完整配置参考 ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ### 支持的 LLM 提供商 | Provider | 说明 | 适配器类型 | |----------|------|-----------| | `openai` | OpenAI GPT 系列 | LiteLLM | | `gemini` | Google Gemini | LiteLLM | | `claude` | Anthropic Claude | LiteLLM | | `qwen` | 阿里云通义千问 | LiteLLM | | `deepseek` | DeepSeek | LiteLLM | | `zhipu` | 智谱 AI (GLM) | LiteLLM | | `moonshot` | 月之暗面 Kimi | LiteLLM | | `ollama` | Ollama 本地模型 | LiteLLM | | `baidu` | 百度文心一言 | 原生适配器 | | `minimax` | MiniMax | 原生适配器 | | `doubao` | 字节豆包 | 原生适配器 | ### 配置示例 #### OpenAI ```env LLM_PROVIDER=openai LLM_API_KEY=sk-your-api-key LLM_MODEL=gpt-4o-mini ``` #### 通义千问 ```env LLM_PROVIDER=qwen LLM_API_KEY=sk-your-dashscope-key LLM_MODEL=qwen-turbo ``` #### Ollama 本地模型 ```env LLM_PROVIDER=ollama LLM_MODEL=llama3 LLM_BASE_URL=http://localhost:11434/v1 ``` #### 百度文心一言 ```env LLM_PROVIDER=baidu LLM_API_KEY=your_api_key:your_secret_key LLM_MODEL=ernie-bot-4 ``` --- ## 前端配置 前端配置文件位于 `frontend/.env`,首次使用请复制示例文件: ```bash cp frontend/.env.example frontend/.env ``` ### 完整配置参考 ```env # ========== 后端 API 配置 ========== VITE_API_BASE_URL=/api # 后端 API 地址 # ========== 应用配置 ========== VITE_APP_ID=deepaudit # ========== 代码分析配置 ========== VITE_MAX_ANALYZE_FILES=0 # 最大分析文件数,0表示无限制 VITE_LLM_CONCURRENCY=2 # LLM 并发数 VITE_LLM_GAP_MS=500 # 请求间隔(毫秒) VITE_OUTPUT_LANGUAGE=zh-CN # 输出语言 ``` ### 配置说明 | 配置项 | 说明 | 默认值 | |--------|------|--------| | `VITE_API_BASE_URL` | 后端 API 地址,Docker 部署时使用 `/api` | `/api` | | `VITE_MAX_ANALYZE_FILES` | 单次扫描最大文件数,0表示无限制 | `0` | | `VITE_LLM_CONCURRENCY` | 前端 LLM 并发请求数 | `2` | | `VITE_LLM_GAP_MS` | 前端请求间隔 | `500` | | `VITE_OUTPUT_LANGUAGE` | 分析结果输出语言 | `zh-CN` | --- ## 运行时配置 DeepAudit 支持在浏览器中进行运行时配置,无需重启服务。 ### 访问方式 1. 登录系统后,访问 `/admin` 系统管理页面 2. 或点击侧边栏的"系统管理"菜单 ### 可配置项 #### LLM 配置 - LLM 提供商选择 - API Key 配置 - 模型选择 - 自定义 API 端点(中转站) - 超时时间 - 温度参数 - 最大 Token 数 #### 分析参数 - 最大分析文件数 - 并发请求数 - 请求间隔时间 - 输出语言 #### Git 集成 - GitHub Token - GitLab Token ### 配置优先级 运行时配置 > 后端环境变量 > 默认值 --- ## 数据存储 DeepAudit 采用前后端分离架构,所有数据存储在后端 PostgreSQL 数据库中。 ### 架构说明 ``` ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ 前端 │────▶│ 后端 API │────▶│ PostgreSQL │ │ (React) │ │ (FastAPI) │ │ 数据库 │ └─────────────┘ └─────────────┘ └─────────────┘ ``` ### 特点 - ✅ 数据持久化存储 - ✅ 支持多用户 - ✅ 支持用户认证 - ✅ 数据导入/导出功能 - ✅ 团队协作 ### 数据管理 在 `/admin` 页面的"数据库管理"标签页中,可以: - **导出数据**: 将所有数据导出为 JSON 文件备份 - **导入数据**: 从 JSON 文件恢复数据 - **清空数据**: 删除所有数据(谨慎操作) - **健康检查**: 检查数据库连接状态 --- ## API 中转站配置 许多用户使用 API 中转服务来访问 LLM(更稳定、更便宜、解决网络问题)。 ### 后端配置(推荐) ```env LLM_PROVIDER=openai LLM_API_KEY=中转站提供的Key LLM_BASE_URL=https://your-proxy.com/v1 LLM_MODEL=gpt-4o-mini ``` ### 运行时配置 1. 访问系统管理页面(`/admin`) 2. 在"系统配置"标签页中: - 选择 LLM 提供商 - 填入中转站提供的 API Key - 设置自定义 API 基础 URL 3. 保存配置 ### 常见中转站 | 中转站 | 说明 | |--------|------| | [OpenRouter](https://openrouter.ai/) | 支持多种模型 | | [API2D](https://api2d.com/) | 国内访问友好 | | [CloseAI](https://www.closeai-asia.com/) | 价格实惠 | ### 注意事项 1. 确保中转站支持你选择的模型 2. 中转站的 API 格式需要与 OpenAI 兼容 3. 部分中转站可能有请求限制 --- ## 审计规则配置 DeepAudit 支持自定义审计规则集,可以根据团队需求定制检测规则。 ### 访问方式 1. 登录系统后,访问 `/audit-rules` 审计规则页面 2. 或点击侧边栏的"审计规则"菜单 ### 内置规则集 #### 1. OWASP Top 10(默认) 基于 OWASP Top 10 2021 的安全审计规则集,包含 10 条规则: | 规则代码 | 名称 | 严重程度 | 检测提示词 | |----------|------|----------|------------| | A01 | 访问控制失效 | Critical | 检查是否存在访问控制失效问题:权限检查缺失、越权访问、IDOR(不安全的直接对象引用)、CORS配置错误 | | A02 | 加密机制失效 | Critical | 检查是否存在加密问题:使用弱加密算法(MD5/SHA1/DES)、明文存储密码、硬编码密钥、不安全的随机数生成 | | A03 | 注入攻击 | Critical | 检查是否存在注入漏洞:SQL注入、命令注入、LDAP注入、XPath注入、NoSQL注入、表达式语言注入 | | A04 | 不安全设计 | High | 检查是否存在不安全的设计:缺少速率限制、业务逻辑漏洞、缺少输入验证、信任边界不清 | | A05 | 安全配置错误 | High | 检查是否存在安全配置错误:默认凭证、不必要的功能启用、详细错误信息泄露、缺少安全头 | | A06 | 易受攻击的组件 | High | 检查是否使用了已知漏洞的组件:过时的依赖库、未修补的漏洞、不安全的第三方组件 | | A07 | 身份认证失效 | Critical | 检查是否存在身份认证问题:弱密码策略、会话固定、凭证明文存储、缺少多因素认证 | | A08 | 数据完整性失效 | Critical | 检查是否存在完整性问题:不安全的反序列化、未验证的更新、CI/CD管道安全 | | A09 | 日志监控失效 | Medium | 检查是否存在日志监控问题:缺少安全日志、敏感信息记录到日志、缺少告警机制 | | A10 | SSRF | High | 检查是否存在SSRF漏洞:未验证的URL输入、内网资源访问、云元数据访问 | #### 2. 代码质量规则 通用代码质量检查规则集,包含 8 条规则: | 规则代码 | 名称 | 严重程度 | 检测提示词 | |----------|------|----------|------------| | CQ001 | 函数过长 | Medium | 检查函数是否过长(超过50行),是否应该拆分为更小的函数 | | CQ002 | 重复代码 | Medium | 检查是否存在重复的代码块,可以提取为公共函数或类 | | CQ003 | 嵌套过深 | Low | 检查代码嵌套是否过深(超过4层),影响可读性 | | CQ004 | 魔法数字 | Low | 检查是否存在魔法数字或魔法字符串,应该定义为常量 | | CQ005 | 缺少错误处理 | High | 检查是否缺少必要的错误处理,可能导致程序崩溃 | | CQ006 | 未使用的变量 | Low | 检查是否存在声明但未使用的变量 | | CQ007 | 命名不规范 | Low | 检查命名是否符合语言规范和最佳实践 | | CQ008 | 注释缺失 | Low | 检查复杂逻辑是否缺少必要的注释说明 | #### 3. 性能优化规则 性能问题检测规则集,包含 5 条规则: | 规则代码 | 名称 | 严重程度 | 检测提示词 | |----------|------|----------|------------| | PERF001 | N+1查询 | High | 检查是否存在N+1查询问题,在循环中执行数据库查询 | | PERF002 | 内存泄漏 | Critical | 检查是否存在内存泄漏:未关闭的资源、循环引用、大对象未释放 | | PERF003 | 低效算法 | Medium | 检查是否存在低效算法,如O(n²)可优化为O(n)或O(nlogn) | | PERF004 | 不必要的对象创建 | Medium | 检查是否在循环中创建不必要的对象,应该移到循环外 | | PERF005 | 同步阻塞 | Medium | 检查是否存在同步阻塞操作,应该使用异步方式 | ### 自定义规则集 可以创建自定义规则集,每条规则包含: - **规则代码**: 唯一标识符(如 SEC001) - **规则名称**: 规则的简短描述 - **规则描述**: 详细说明 - **类别**: security / bug / performance / style / maintainability - **严重程度**: critical / high / medium / low - **自定义提示词**: 增强 LLM 检测的提示词(关键字段) - **修复建议**: 问题修复模板 - **参考链接**: CWE/OWASP 等参考资料 ### 规则集导入/导出 支持 JSON 格式的规则集导入导出,方便团队共享: ```json { "name": "自定义安全规则", "description": "团队自定义的安全检测规则", "language": "all", "rule_type": "security", "rules": [ { "rule_code": "CUSTOM001", "name": "敏感信息硬编码", "description": "检测代码中硬编码的敏感信息", "category": "security", "severity": "critical", "custom_prompt": "检查是否存在硬编码的密码、API Key、Token、私钥等敏感信息", "fix_suggestion": "使用环境变量或配置文件存储敏感信息" } ] } ``` --- ## 提示词模板配置 DeepAudit 支持自定义审计提示词模板,可以针对不同场景优化分析效果。 ### 访问方式 1. 登录系统后,访问 `/prompts` 提示词管理页面 2. 或点击侧边栏的"提示词管理"菜单 ### 内置模板 #### 1. 默认代码审计(默认) 全面的代码审计提示词,涵盖安全、性能、代码质量等多个维度: ``` 你是一个专业的代码审计助手。请从以下维度全面分析代码: - 安全漏洞(SQL注入、XSS、命令注入、路径遍历、SSRF、XXE、反序列化、硬编码密钥等) - 潜在的 Bug 和逻辑错误 - 性能问题和优化建议 - 编码规范和代码风格 - 可维护性和可读性 - 最佳实践和设计模式 请尽可能多地找出代码中的所有问题,不要遗漏任何安全漏洞或潜在风险! ``` #### 2. 安全专项审计 专注于安全漏洞检测的提示词模板: ``` 你是一个专业的安全审计专家。请专注于检测以下安全问题: 【注入类漏洞】 - SQL注入(包括盲注、时间盲注、联合查询注入) - 命令注入(OS命令执行) - LDAP注入、XPath注入、NoSQL注入 【跨站脚本(XSS)】 - 反射型XSS、存储型XSS、DOM型XSS 【认证与授权】 - 硬编码凭证、弱密码策略、会话管理问题、权限绕过 【敏感数据】 - 敏感信息泄露、不安全的加密、明文传输敏感数据 【其他安全问题】 - SSRF、XXE、反序列化漏洞、路径遍历、文件上传漏洞、CSRF 请详细说明每个漏洞的风险等级、利用方式和修复建议。 ``` #### 3. 性能优化审计 专注于性能问题检测的提示词模板: ``` 你是一个专业的性能优化专家。请专注于检测以下性能问题: 【数据库性能】 - N+1查询问题、缺少索引、不必要的全表扫描、大量数据一次性加载、未使用连接池 【内存问题】 - 内存泄漏、大对象未及时释放、缓存使用不当、循环中创建大量对象 【算法效率】 - 时间复杂度过高、不必要的重复计算、可优化的循环、递归深度过大 【并发问题】 - 线程安全问题、死锁风险、资源竞争、不必要的同步 【I/O性能】 - 同步阻塞I/O、未使用缓冲、频繁的小文件操作、网络请求未优化 请提供具体的优化建议和预期的性能提升。 ``` #### 4. 代码质量审计 专注于代码质量和可维护性的提示词模板: ``` 你是一个专业的代码质量审计专家。请专注于检测以下代码质量问题: 【代码规范】 - 命名不规范(变量、函数、类)、代码格式不一致、注释缺失或过时、魔法数字/字符串 【代码结构】 - 函数过长(超过50行)、类职责不单一、嵌套层级过深、重复代码 【可维护性】 - 高耦合低内聚、缺少错误处理、硬编码配置、缺少日志记录 【设计模式】 - 违反SOLID原则、可使用设计模式优化的场景、过度设计 【测试相关】 - 难以测试的代码、缺少边界条件处理、依赖注入问题 请提供具体的重构建议和代码示例。 ``` ### 自定义模板 可以创建自定义提示词模板: - **模板名称**: 模板的简短名称 - **模板描述**: 模板用途说明 - **中文提示词**: 中文版本的系统提示词 - **英文提示词**: 英文版本的系统提示词 - **模板变量**: 可在提示词中使用的变量 ### 提示词测试 在创建或编辑模板时,可以使用"测试"功能验证提示词效果: 1. 选择测试代码语言(支持 Python、JavaScript、Java、Go、Swift、Kotlin 等) 2. 输入测试代码片段(或使用内置示例代码) 3. 选择输出语言(中文/英文) 4. 点击"测试"按钮查看分析结果 ### 在审计任务中使用 创建审计任务时,可以选择: 1. **规则集**: 选择要应用的审计规则集 2. **提示词模板**: 选择要使用的提示词模板 --- ## 提示词架构详解 本节详细说明 DeepAudit 如何构建发送给 LLM 的完整提示词。 ### 提示词组成结构 发送给 LLM 的提示词由以下部分组成: ``` ┌─────────────────────────────────────────────────────────────┐ │ System Prompt (系统提示词) │ ├─────────────────────────────────────────────────────────────┤ │ ① 提示词模板内容 (来自数据库或默认模板) │ │ - 定义 AI 的角色和任务 │ │ - 指定分析维度和重点 │ ├─────────────────────────────────────────────────────────────┤ │ ② 输出格式要求 │ │ - JSON Schema 定义 │ │ - 字段说明和约束 │ ├─────────────────────────────────────────────────────────────┤ │ ③ 审计规则 (如果选择了规则集) │ │ - 规则代码、名称、描述 │ │ - 每条规则的检测提示词 │ └─────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────┐ │ User Prompt (用户提示词) │ ├─────────────────────────────────────────────────────────────┤ │ ④ 编程语言 │ │ ⑤ 带行号的代码内容 │ └─────────────────────────────────────────────────────────────┘ ``` ### 完整系统提示词示例(中文版) 以下是使用默认模板 + OWASP Top 10 规则集时,发送给 LLM 的完整系统提示词: ``` 你是一个专业的代码审计助手。请从以下维度全面分析代码: - 安全漏洞(SQL注入、XSS、命令注入、路径遍历、SSRF、XXE、反序列化、硬编码密钥等) - 潜在的 Bug 和逻辑错误 - 性能问题和优化建议 - 编码规范和代码风格 - 可维护性和可读性 - 最佳实践和设计模式 请尽可能多地找出代码中的所有问题,不要遗漏任何安全漏洞或潜在风险! 【输出格式要求】 1. 必须只输出纯JSON对象 2. 禁止在JSON前后添加任何文字、说明、markdown标记 3. 所有文本字段(title, description, suggestion等)必须使用中文输出 4. 输出格式必须符合以下 JSON Schema: { "issues": [ { "type": "security|bug|performance|style|maintainability", "severity": "critical|high|medium|low", "title": "string", "description": "string", "suggestion": "string", "line": 1, "column": 1, "code_snippet": "string", "rule_code": "string (optional, if matched a specific rule)" } ], "quality_score": 0-100, "summary": { "total_issues": number, "critical_issues": number, "high_issues": number, "medium_issues": number, "low_issues": number } } 【审计规则】请特别关注以下规则: - [A01] 访问控制失效: 检测权限绕过、越权访问、IDOR等访问控制问题 检测要点: 检查是否存在访问控制失效问题:权限检查缺失、越权访问、IDOR(不安全的直接对象引用)、CORS配置错误 - [A02] 加密机制失效: 检测弱加密、明文传输、密钥管理不当等问题 检测要点: 检查是否存在加密问题:使用弱加密算法(MD5/SHA1/DES)、明文存储密码、硬编码密钥、不安全的随机数生成 - [A03] 注入攻击: 检测SQL注入、命令注入、LDAP注入等注入漏洞 检测要点: 检查是否存在注入漏洞:SQL注入、命令注入、LDAP注入、XPath注入、NoSQL注入、表达式语言注入 ... (其他规则) ``` ### 用户提示词示例 ``` 编程语言: Python 代码已标注行号(格式:行号| 代码内容),请根据行号准确填写 line 字段。 请分析以下代码: 1| import sqlite3 2| 3| def get_user(user_id): 4| conn = sqlite3.connect('users.db') 5| cursor = conn.cursor() 6| query = f"SELECT * FROM users WHERE id = {user_id}" 7| cursor.execute(query) 8| return cursor.fetchone() ``` ### 不使用自定义模板时的默认提示词 当没有选择提示词模板时,系统使用硬编码的默认提示词(中文版): ``` ⚠️⚠️⚠️ 只输出JSON,禁止输出其他任何格式!禁止markdown!禁止文本分析!⚠️⚠️⚠️ 你是一个专业的代码审计助手。你的任务是分析代码并返回严格符合JSON Schema的结果。 【最重要】输出格式要求: 1. 必须只输出纯JSON对象,从{开始,到}结束 2. 禁止在JSON前后添加任何文字、说明、markdown标记 3. 禁止输出```json或###等markdown语法 4. 如果是文档文件(如README),也必须以JSON格式输出分析结果 【内容要求】: 1. 所有文本内容必须统一使用简体中文 2. JSON字符串值中的特殊字符必须正确转义(换行用\n,双引号用\",反斜杠用\\) 3. code_snippet字段必须使用\n表示换行 请从以下维度全面、彻底地分析代码,找出所有问题: - 安全漏洞(SQL注入、XSS、命令注入、路径遍历、SSRF、XXE、反序列化、硬编码密钥等) - 潜在的 Bug 和逻辑错误 - 性能问题和优化建议 - 编码规范和代码风格 - 可维护性和可读性 - 最佳实践和设计模式 【重要】请尽可能多地找出代码中的所有问题,不要遗漏任何安全漏洞或潜在风险! 输出格式必须严格符合以下 JSON Schema: { "issues": [ { "type": "security|bug|performance|style|maintainability", "severity": "critical|high|medium|low", "title": "string", "description": "string", "suggestion": "string", "line": 1, "column": 1, "code_snippet": "string", "ai_explanation": "string", "xai": { "what": "string", "why": "string", "how": "string", "learn_more": "string(optional)" } } ], "quality_score": 0-100, "summary": { "total_issues": number, "critical_issues": number, "high_issues": number, "medium_issues": number, "low_issues": number }, "metrics": { "complexity": 0-100, "maintainability": 0-100, "security": 0-100, "performance": 0-100 } } 注意: - title: 问题的简短标题(中文) - description: 详细描述问题(中文) - suggestion: 具体的修复建议(中文) - line: 问题所在的行号(从1开始计数,必须准确对应代码中的行号) - column: 问题所在的列号(从1开始计数,指向问题代码的起始位置) - code_snippet: 包含问题的代码片段 - ai_explanation: AI 的深入解释(中文) - xai.what: 这是什么问题(中文) - xai.why: 为什么会有这个问题(中文) - xai.how: 如何修复这个问题(中文) 【重要】关于行号和代码片段: 1. line 必须是问题代码的行号!代码左侧有"行号|"标注 2. column 是问题代码在该行中的起始列位置 3. code_snippet 应该包含问题代码及其上下文(前后各1-2行) 4. 如果代码片段包含多行,必须使用 \n 表示换行符 5. 如果无法确定准确的行号,不要填写line和column字段 【严格禁止】: - 禁止在任何字段中使用英文,所有内容必须是简体中文 - 禁止在JSON字符串值中使用真实换行符,必须用\n转义 - 禁止输出markdown代码块标记(如```json) ⚠️ 重要提醒:line字段必须从代码左侧的行号标注中读取,不要猜测或填0! ``` ### 提示词优先级 1. **用户选择的提示词模板** > **数据库默认模板** > **硬编码默认提示词** 2. 规则集是可选的,如果选择了规则集,规则会追加到系统提示词末尾 --- ## 更多资源 - [部署指南](DEPLOYMENT.md) - 详细的部署说明 - [LLM 平台支持](LLM_PROVIDERS.md) - 各 LLM 平台的配置方法 - [常见问题](FAQ.md) - 配置相关问题解答 --- ### DEPLOYMENT # 部署指南 本文档详细介绍 DeepAudit v3.0.0 的各种部署方式,包括 Docker Compose 一键部署、Agent 审计模式部署和本地开发环境搭建。 ## 目录 - [快速开始](#快速开始) - [Docker Compose 部署(推荐)](#docker-compose-部署推荐) - [Agent 审计模式部署](#agent-审计模式部署) - [生产环境部署](#生产环境部署) - [本地开发部署](#本地开发部署) - [常见部署问题](#常见部署问题) --- ## 快速开始 最快的方式是使用 Docker Compose 一键部署: ```bash # 1. 克隆项目 git clone https://github.com/lintsinghua/DeepAudit.git cd DeepAudit # 2. 配置后端环境变量 cp backend/env.example backend/.env # 编辑 backend/.env,配置 LLM API Key # 3. 启动所有服务 docker compose up -d # 4. 访问应用 # 前端: http://localhost:3000 # 后端 API: http://localhost:8000/docs ``` ### 演示账户 系统启动时会自动创建演示账户,包含示例项目和审计数据,可直接体验完整功能: - 📧 邮箱:`demo@example.com` - 🔑 密码:`demo123` > ⚠️ **安全提示**: 生产环境部署后,请删除演示账户或修改密码。 --- ## Docker Compose 部署(推荐) 完整的前后端分离部署方案,包含前端、后端、PostgreSQL 数据库以及 Agent 模式所需服务。 ### 系统要求 | 资源 | 最低配置(含 Agent 模式) | |------|---------------------------| | 内存 | 4GB+ | | 磁盘 | 10GB+ | | Docker | 20.10+ | | Docker Compose | 2.0+ | ### 部署步骤 ```bash # 1. 克隆项目 git clone https://github.com/lintsinghua/DeepAudit.git cd DeepAudit # 2. 配置后端环境变量 cp backend/env.example backend/.env ``` 编辑 `backend/.env` 文件,配置必要参数: ```env # 数据库配置(Docker Compose 会自动处理) POSTGRES_SERVER=db POSTGRES_USER=postgres POSTGRES_PASSWORD=postgres POSTGRES_DB=deepaudit # 安全配置(生产环境请修改) SECRET_KEY=your-super-secret-key-change-this-in-production # LLM 配置(必填) LLM_PROVIDER=openai LLM_API_KEY=sk-your-api-key LLM_MODEL=gpt-4o-mini # 可选:API 中转站 # LLM_BASE_URL=https://your-proxy.com/v1 ``` ```bash # 3. 启动所有服务 docker compose up -d # 4. 查看服务状态 docker compose ps # 5. 查看日志 docker compose logs -f ``` ### 服务说明 | 服务 | 端口 | 说明 | |------|------|------| | `frontend` | 3000 | React 前端应用(生产构建) | | `backend` | 8000 | FastAPI 后端 API | | `db` | 5432 | PostgreSQL 15 数据库 | ### 访问地址 - 前端应用: http://localhost:3000 - 后端 API: http://localhost:8000 - API 文档 (Swagger): http://localhost:8000/docs - API 文档 (ReDoc): http://localhost:8000/redoc ### 常用命令 ```bash # 停止所有服务 docker compose down # 停止并删除数据卷(清除数据库) docker compose down -v # 重新构建镜像 docker compose build --no-cache # 查看特定服务日志 docker compose logs -f backend # 进入容器调试 docker compose exec backend sh docker compose exec db psql -U postgres -d deepaudit ``` --- ## Agent 审计模式部署 v3.0.0 新增的 Multi-Agent 深度审计功能,需要额外的服务支持。 ### 功能特点 - 🤖 **Multi-Agent 架构**: Orchestrator/Analysis/Recon/Verification 多智能体协作 - 🧠 **RAG 知识库**: 代码语义理解 + CWE/CVE 漏洞知识库 - 🔒 **沙箱验证**: Docker 安全容器执行 PoC ### 部署步骤 ```bash # 1. 配置 Agent 相关参数 # 编辑 backend/.env,确保以下配置正确 # Agent 配置 AGENT_ENABLED=true AGENT_MAX_ITERATIONS=5 # 嵌入模型配置 EMBEDDING_PROVIDER=openai EMBEDDING_MODEL=text-embedding-3-small EMBEDDING_API_KEY= # 留空则使用 LLM_API_KEY # 向量数据库配置(使用 ChromaDB) VECTOR_DB_TYPE=chroma # 沙箱配置 SANDBOX_ENABLED=true ``` ```bash # 2. 启动包含 Agent 服务的完整部署 docker compose up -d ``` ### Agent 模式服务说明 | 服务 | 端口 | 说明 | |------|------|------| | `redis` | 6379 | 任务队列(可选) | ### 构建安全沙箱镜像 沙箱用于安全地执行漏洞验证 PoC: ```bash # 进入沙箱目录 cd docker/sandbox # 构建沙箱镜像 ./build.sh # 验证镜像构建成功 docker images | grep deepaudit-sandbox ``` 沙箱镜像包含: - Python 3.11 + 安全工具 (Semgrep, Bandit, Safety) - Node.js 20 + npm audit - Go 1.21 + gosec - Rust (cargo-audit) - Gitleaks, TruffleHog, OSV-Scanner ### 验证 Agent 模式 ```bash # 检查所有服务状态 docker compose ps # 查看 Agent 日志 docker compose logs -f backend | grep -i agent ``` --- ## 生产环境部署 Docker Compose 默认配置已适用于生产环境: - 前端:构建生产版本,使用 serve 提供静态文件服务 - 后端:使用 uv 管理依赖,镜像内包含所有依赖 - 数据库:使用 Docker Volume 持久化数据 ### 生产环境安全建议 1. **修改默认密钥**:务必修改 `SECRET_KEY` 为随机字符串 2. **配置 HTTPS**:使用 Nginx 反向代理并配置 SSL 证书 3. **限制 CORS**:在生产环境配置具体的前端域名 4. **数据库安全**:修改默认数据库密码,限制访问 IP 5. **API 限流**:配置 Nginx 或应用层限流 6. **日志监控**:配置日志收集和监控告警 7. **删除演示账户**:生产环境请删除或禁用 demo 账户 ### Nginx 反向代理配置(可选) 如需使用 Nginx 提供 HTTPS 和统一入口: ```nginx server { listen 80; server_name your-domain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; server_name your-domain.com; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; # 前端 location / { proxy_pass http://localhost:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # API 代理 location /api/ { proxy_pass http://localhost:8000/api/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # SSE 事件流(Agent 审计日志) location /api/v1/agent-tasks/ { proxy_pass http://localhost:8000/api/v1/agent-tasks/; proxy_http_version 1.1; proxy_set_header Connection ""; proxy_buffering off; proxy_cache off; proxy_read_timeout 86400; } } ``` --- ## 本地开发部署 适合需要开发或自定义修改的场景。 ### 环境要求 | 依赖 | 版本要求 | 说明 | |------|---------|------| | Node.js | 20+ | 前端运行环境 | | Python | 3.11+ | 后端运行环境 | | PostgreSQL | 15+ | 数据库 | | pnpm | 8+ | 推荐的前端包管理器 | | uv | 最新版 | 推荐的 Python 包管理器 | ### 数据库准备 ```bash # 方式一:使用 Docker 启动 PostgreSQL(推荐) docker run -d \ --name deepaudit-db \ -e POSTGRES_USER=postgres \ -e POSTGRES_PASSWORD=postgres \ -e POSTGRES_DB=deepaudit \ -p 5432:5432 \ postgres:15-alpine # 方式二:使用本地 PostgreSQL createdb deepaudit ``` ### 后端启动 ```bash # 1. 进入后端目录 cd backend # 2. 安装 uv(如未安装) curl -LsSf https://astral.sh/uv/install.sh | sh # 3. 同步依赖 uv sync # 4. 配置环境变量 cp env.example .env # 编辑 .env 文件,配置数据库和 LLM 参数 # 5. 初始化数据库 uv run alembic upgrade head # 6. 启动后端服务(开发模式,支持热重载) uv run uvicorn app.main:app --reload --port 8000 ``` ### 前端启动 ```bash # 1. 进入前端目录 cd frontend # 2. 安装依赖 pnpm install # 3. 配置环境变量(可选) cp .env.example .env # 4. 启动开发服务器 pnpm dev # 5. 访问应用 # 浏览器打开 http://localhost:5173 ``` ### 开发工具 ```bash # 前端代码检查 cd frontend pnpm lint pnpm type-check # 前端代码格式化 pnpm format # 后端类型检查 cd backend uv run mypy app # 后端代码格式化 uv run ruff format app ``` --- ## 数据存储 DeepAudit 采用前后端分离架构,所有数据存储在后端 PostgreSQL 数据库中。 ### 数据管理 在 `/admin` 页面的"数据库管理"标签页中,可以: - **导出数据**: 将所有数据导出为 JSON 文件备份 - **导入数据**: 从 JSON 文件恢复数据 - **清空数据**: 删除所有数据(谨慎操作) - **健康检查**: 检查数据库连接状态和数据完整性 ### 数据库备份 ```bash # 导出 PostgreSQL 数据 docker compose exec db pg_dump -U postgres deepaudit > backup.sql # 恢复数据 docker compose exec -T db psql -U postgres deepaudit < backup.sql ``` --- ## 常见部署问题 ### Docker 相关 **Q: 容器启动失败,提示端口被占用** ```bash # 检查端口占用 lsof -i :3000 lsof -i :8000 lsof -i :5432 # 停止占用端口的进程,或修改 docker-compose.yml 中的端口映射 ``` **Q: 数据库连接失败** ```bash # 检查数据库容器状态 docker compose ps db # 查看数据库日志 docker compose logs db # 确保数据库健康检查通过后再启动后端 docker compose up -d db docker compose exec db pg_isready -U postgres docker compose up -d backend ``` **Q: 构建时网络问题(代理相关)** 如果构建时遇到网络问题,检查 Docker Desktop 的代理设置: 1. 打开 Docker Desktop → Settings → Resources → Proxies 2. 关闭代理或配置正确的代理地址 3. 重启 Docker Desktop 4. 重新构建:`docker compose build --no-cache` ### Agent 模式相关 **Q: 沙箱镜像构建失败** ```bash # 检查 Docker 服务状态 docker info # 使用国内镜像源重新构建 cd docker/sandbox # 编辑 Dockerfile,使用国内镜像源 ./build.sh ``` ### 后端相关 **Q: PDF 导出功能报错(WeasyPrint 依赖问题)** Docker 镜像已包含 WeasyPrint 所需的系统依赖。本地开发时需要安装: ```bash # macOS brew install pango cairo gdk-pixbuf libffi # Ubuntu/Debian sudo apt-get install libpango-1.0-0 libpangoft2-1.0-0 libcairo2 libgdk-pixbuf-2.0-0 libglib2.0-0 # Windows - 参见 FAQ.md 中的详细说明 ``` **Q: LLM API 请求超时** ```env # 增加超时时间 LLM_TIMEOUT=300 # 降低并发数 LLM_CONCURRENCY=1 # 增加请求间隔 LLM_GAP_MS=3000 ``` ### 前端相关 **Q: 前端无法连接后端 API** Docker Compose 部署时,前端通过 `http://localhost:8000/api/v1` 访问后端。确保: 1. 后端容器正常运行:`docker compose ps backend` 2. 后端端口 8000 可访问:`curl http://localhost:8000/docs` 本地开发时,检查 `frontend/.env` 中的 API 地址配置: ```env VITE_API_BASE_URL=http://localhost:8000/api/v1 ``` --- ## 更多资源 - [配置说明](CONFIGURATION.md) - 详细的配置参数说明 - [Agent 审计](AGENT_AUDIT.md) - Multi-Agent 审计模块详解 - [LLM 平台支持](LLM_PROVIDERS.md) - 各 LLM 平台的配置方法 - [常见问题](FAQ.md) - 更多问题解答 - [贡献指南](../CONTRIBUTING.md) - 参与项目开发 --- ### FAQ # 常见问题 (FAQ) 本文档收集了 DeepAudit 使用过程中的常见问题和解决方案。 ## 目录 - [快速入门](#快速入门) - [LLM 配置](#llm-配置) - [网络问题](#网络问题) - [功能使用](#功能使用) - [部署问题](#部署问题) - [性能优化](#性能优化) --- ## 快速入门 ### Q: 如何快速开始使用? 最快的方式是使用 Docker Compose: ```bash # 1. 克隆项目 git clone https://github.com/lintsinghua/DeepAudit.git cd DeepAudit # 2. 配置 LLM API Key cp backend/env.example backend/.env # 编辑 backend/.env,填入你的 API Key # 3. 启动服务 docker-compose up -d # 4. 访问 http://localhost:5173 ``` ### Q: 演示账户是什么? 系统启动时会自动创建演示账户,包含示例项目和审计数据: - 📧 邮箱:`demo@example.com` - 🔑 密码:`demo123` 演示账户拥有管理员权限,可体验所有功能。生产环境请删除或修改密码。 ### Q: 不想用 Docker,如何本地运行? 参见 [部署指南 - 本地开发部署](DEPLOYMENT.md#本地开发部署)。 ### Q: 支持哪些编程语言? DeepAudit 支持所有主流编程语言的代码分析,包括但不限于: - **Web**: JavaScript, TypeScript, HTML, CSS - **后端**: Python, Java, Go, Rust, C/C++, C# - **移动端**: Swift, Kotlin, Dart - **脚本**: Shell, PowerShell, Ruby, PHP - **其他**: SQL, YAML, JSON, Markdown --- ## LLM 配置 ### Q: 如何快速切换 LLM 平台? **方式一:浏览器运行时配置(推荐)** 1. 访问 `http://localhost:5173/admin` 系统管理页面 2. 在"系统配置"标签页选择不同的 LLM 提供商 3. 填入对应的 API Key 4. 保存即可,无需重启 **方式二:修改后端环境变量** 编辑 `backend/.env`: ```env # 切换到 OpenAI LLM_PROVIDER=openai LLM_API_KEY=sk-your-key # 切换到通义千问 LLM_PROVIDER=qwen LLM_API_KEY=sk-your-dashscope-key # 切换到 DeepSeek LLM_PROVIDER=deepseek LLM_API_KEY=sk-your-key ``` 修改后需要重启后端服务。 ### Q: 百度文心一言的 API Key 格式是什么? 百度需要同时提供 API Key 和 Secret Key,用冒号分隔: ```env LLM_PROVIDER=baidu LLM_API_KEY=your_api_key:your_secret_key LLM_MODEL=ernie-bot-4 ``` 获取地址:https://console.bce.baidu.com/qianfan/ ### Q: 如何使用 Ollama 本地大模型? ```bash # 1. 安装 Ollama curl -fsSL https://ollama.com/install.sh | sh # macOS/Linux # Windows: 访问 https://ollama.com/download # 2. 拉取模型 ollama pull llama3 # 或 codellama、qwen2.5、deepseek-coder # 3. 确保 Ollama 服务运行 ollama serve # 4. 配置后端 # 在 backend/.env 中设置: LLM_PROVIDER=ollama LLM_MODEL=llama3 LLM_BASE_URL=http://localhost:11434/v1 ``` **推荐模型**: - `llama3` - 综合能力强 - `codellama` - 代码专用 - `qwen2.5` - 中文支持好 - `deepseek-coder` - 代码分析强 ### Q: 哪个 LLM 平台性价比最高? | 场景 | 推荐 | 原因 | |------|------|------| | 免费使用 | Gemini / 智谱 GLM-4-Flash | 有免费配额 | | 低成本 | DeepSeek | 价格仅为 GPT-4 的 1/10 | | 最佳性能 | GPT-4o / Claude Sonnet | 代码理解能力最强 | | 敏感代码 | Ollama 本地模型 | 完全本地化 | --- ## 网络问题 ### Q: 遇到请求超时怎么办? **方案一:增加超时时间** ```env LLM_TIMEOUT=300 # 增加到 300 秒 ``` **方案二:使用 API 中转站** ```env LLM_PROVIDER=openai LLM_API_KEY=中转站提供的Key LLM_BASE_URL=https://your-proxy.com/v1 ``` **方案三:切换到国内平台** 通义千问、DeepSeek、智谱 AI 等国内平台访问更稳定。 **方案四:降低并发** ```env LLM_CONCURRENCY=1 # 降低并发数 LLM_GAP_MS=3000 # 增加请求间隔 ``` ### Q: 如何配置 API 中转站? ```env LLM_PROVIDER=openai LLM_API_KEY=中转站提供的Key LLM_BASE_URL=https://your-proxy.com/v1 LLM_MODEL=gpt-4o-mini ``` 常见中转站: - [OpenRouter](https://openrouter.ai/) - [API2D](https://api2d.com/) - [CloseAI](https://www.closeai-asia.com/) ### Q: 提示 "API Key 无效" 怎么办? 1. 检查 API Key 是否正确复制(注意前后空格) 2. 确认 API Key 未过期或被禁用 3. 检查 LLM_PROVIDER 是否与 API Key 匹配 4. 如果使用中转站,确认 LLM_BASE_URL 配置正确 --- ## 功能使用 ### Q: 如何分析 GitHub/GitLab 仓库? 1. 在"项目管理"页面点击"添加项目" 2. 选择"GitHub 仓库"或"GitLab 仓库" 3. 输入仓库 URL(如 `https://github.com/user/repo`) 4. 如果是私有仓库,需要配置 Token: - GitHub: 在 `backend/.env` 中设置 `GITHUB_TOKEN` - GitLab: 在 `backend/.env` 中设置 `GITLAB_TOKEN` ### Q: 如何上传 ZIP 文件分析? 1. 在"项目管理"页面点击"添加项目" 2. 选择"上传 ZIP" 3. 选择本地 ZIP 文件上传 4. 系统会自动解压并分析 ### Q: 如何使用即时分析功能? 1. 访问"即时分析"页面 2. 直接粘贴代码片段 3. 选择编程语言 4. 点击"分析"按钮 ### Q: 如何导出审计报告? 1. 完成代码分析后,进入"审计报告"页面 2. 点击"导出"按钮 3. 选择导出格式: - **JSON**: 结构化数据,适合程序处理 - **PDF**: 专业报告,适合交付 ### Q: 分析结果不准确怎么办? 1. **切换更强的模型**:如 GPT-4o、Claude Sonnet 2. **调整温度参数**:降低 `LLM_TEMPERATURE` 到 0.1 以下 3. **增加上下文**:确保代码文件完整 4. **人工复核**:AI 分析结果仅供参考,建议结合人工审查 --- ## 部署问题 ### Q: Docker 容器启动失败? **端口被占用**: ```bash # 检查端口占用 lsof -i :5173 lsof -i :8000 lsof -i :5432 # 停止占用进程或修改 docker-compose.yml 中的端口 ``` **数据库连接失败**: ```bash # 确保数据库先启动 docker-compose up -d db docker-compose exec db pg_isready -U postgres docker-compose up -d backend ``` ### Q: Windows 导出 PDF 报错怎么办? PDF 导出功能使用 WeasyPrint 库,在 Windows 系统上需要安装 GTK 依赖。 **方法一:使用 MSYS2 安装(推荐)** ```bash # 1. 下载并安装 MSYS2: https://www.msys2.org/ # 2. 打开 MSYS2 终端,执行: pacman -S mingw-w64-x86_64-pango mingw-w64-x86_64-gtk3 # 3. 将 MSYS2 的 bin 目录添加到系统 PATH: # C:\msys64\mingw64\bin ``` **方法二:使用 GTK3 Runtime** 1. 下载 GTK3 Runtime: https://github.com/nickvidal/gtk3-runtime/releases 2. 安装后将安装目录添加到系统 PATH **方法三:使用 Docker 部署(最简单)** ```bash docker-compose up -d backend ``` Docker 镜像已包含所有依赖,无需额外配置。 ### Q: macOS 上 PDF 导出报错? ```bash # 安装依赖 brew install pango cairo gdk-pixbuf libffi # 重启后端服务 ``` ### Q: 前端无法连接后端 API? 检查 `frontend/.env` 中的 API 地址配置: ```env # 本地开发 VITE_API_BASE_URL=http://localhost:8000/api/v1 # Docker Compose 部署 VITE_API_BASE_URL=/api ``` ### Q: 数据库迁移失败? ```bash cd backend source .venv/bin/activate # 查看当前迁移状态 alembic current # 重新执行迁移 alembic upgrade head # 如果有问题,可以回滚 alembic downgrade -1 ``` --- ## 性能优化 ### Q: 分析速度太慢怎么办? **1. 增加并发数** ```env LLM_CONCURRENCY=5 # 增加并发(注意 API 限流) LLM_GAP_MS=500 # 减少请求间隔 ``` **2. 限制分析文件数**(默认无限制) ```env MAX_ANALYZE_FILES=30 # 设置单次分析文件数限制 ``` **3. 使用更快的模型** - `gpt-4o-mini` 比 `gpt-4o` 快 - `qwen-turbo` 比 `qwen-max` 快 - `glm-4-flash` 比 `glm-4` 快 **4. 使用本地模型** Ollama 本地模型没有网络延迟,适合大量文件分析。 ### Q: 如何减少 API 调用费用? 1. **使用便宜的模型**:DeepSeek、通义千问 Turbo 2. **减少分析文件数**:设置 `MAX_ANALYZE_FILES` 3. **过滤不必要的文件**:排除测试文件、配置文件等 4. **使用本地模型**:Ollama 完全免费 ### Q: 内存占用过高? 1. **减少并发数**:`LLM_CONCURRENCY=1` 2. **限制文件大小**:`MAX_FILE_SIZE_BYTES=102400`(100KB) 3. **使用更小的本地模型**:如 `deepseek-coder:1.3b` --- ## 数据管理 ### Q: 如何备份数据? 在 `/admin` 页面的"数据库管理"标签页中,点击"导出数据"按钮,可以将所有数据导出为 JSON 文件。 也可以直接备份 PostgreSQL 数据库: ```bash # 导出数据 docker-compose exec db pg_dump -U postgres deepaudit > backup.sql # 恢复数据 docker-compose exec -T db psql -U postgres deepaudit < backup.sql ``` ### Q: 如何恢复数据? 在 `/admin` 页面的"数据库管理"标签页中,点击"导入数据"按钮,选择之前导出的 JSON 文件即可恢复。 ### Q: 如何清空所有数据? 在 `/admin` 页面的"数据库管理"标签页中,点击"清空数据"按钮。 ⚠️ **警告**:此操作不可恢复,请先备份重要数据! --- ## 其他问题 ### Q: 如何更新到最新版本? ```bash # 拉取最新代码 git pull origin main # 重新构建镜像 docker-compose build --no-cache # 重启服务 docker-compose up -d ``` ### Q: 如何参与贡献? 参见 [贡献指南](../CONTRIBUTING.md)。 --- ## 还有问题? 如果以上内容没有解决你的问题,欢迎: - 提交 [GitHub Issue](https://github.com/lintsinghua/DeepAudit/issues) - 发送邮件至 lintsinghua@qq.com 提问时请提供: 1. 操作系统和版本 2. 部署方式(Docker/本地) 3. 错误日志或截图 4. 复现步骤 --- ### LLM PROVIDERS # LLM 平台支持 DeepAudit 支持 10+ 主流 LLM 平台,可根据需求自由选择。本文档介绍各平台的配置方法。 ## 目录 - [平台概览](#平台概览) - [国际平台](#国际平台) - [国内平台](#国内平台) - [本地部署](#本地部署) - [API 中转站](#api-中转站) - [选择建议](#选择建议) --- ## 平台概览 | 平台类型 | 平台名称 | Provider | 特点 | 获取 API Key | |---------|---------|----------|------|-------------| | **国际平台** | OpenAI GPT | `openai` | 稳定可靠,生态完善 | [获取](https://platform.openai.com/api-keys) | | | Google Gemini | `gemini` | 免费配额充足 | [获取](https://makersuite.google.com/app/apikey) | | | Anthropic Claude | `claude` | 代码理解能力强 | [获取](https://console.anthropic.com/) | | | DeepSeek | `deepseek` | 性价比极高,代码能力强 | [获取](https://platform.deepseek.com/) | | **国内平台** | 阿里云通义千问 | `qwen` | 国内访问快,中文好 | [获取](https://dashscope.console.aliyun.com/) | | | 智谱 AI (GLM) | `zhipu` | 中文支持好 | [获取](https://open.bigmodel.cn/) | | | 月之暗面 Kimi | `moonshot` | 长文本处理强 | [获取](https://platform.moonshot.cn/) | | | 百度文心一言 | `baidu` | 企业级服务 | [获取](https://console.bce.baidu.com/qianfan/) | | | MiniMax | `minimax` | 多模态能力 | [获取](https://www.minimaxi.com/) | | | 字节豆包 | `doubao` | 高性价比 | [获取](https://console.volcengine.com/ark) | | **本地部署** | Ollama | `ollama` | 完全本地化,隐私安全 | [安装](https://ollama.com/) | --- ## 国际平台 ### OpenAI GPT OpenAI 是最成熟的 LLM 平台,模型性能稳定,代码理解能力强。 **获取 API Key**: https://platform.openai.com/api-keys **配置示例**: ```env LLM_PROVIDER=openai LLM_API_KEY=sk-your-api-key LLM_MODEL=gpt-4o-mini ``` **常用模型**: `gpt-4o`、`gpt-4o-mini`、`gpt-4-turbo`、`o1`、`o1-mini` 等 > 💡 模型列表会持续更新,请访问 [OpenAI 官网](https://platform.openai.com/docs/models) 查看最新模型。 --- ### Google Gemini Google 的 Gemini 系列模型,免费配额充足,适合个人使用。 **获取 API Key**: https://makersuite.google.com/app/apikey **配置示例**: ```env LLM_PROVIDER=gemini LLM_API_KEY=your-api-key LLM_MODEL=gemini-2.0-flash ``` **常用模型**: `gemini-2.0-flash`、`gemini-1.5-pro`、`gemini-1.5-flash` 等 > 💡 Gemini 有免费配额限制,超出后需付费。请访问 [Google AI Studio](https://ai.google.dev/) 查看最新模型。 --- ### Anthropic Claude Claude 在代码理解和生成方面表现优秀,特别适合代码审计场景。 **获取 API Key**: https://console.anthropic.com/ **配置示例**: ```env LLM_PROVIDER=claude LLM_API_KEY=sk-ant-your-api-key LLM_MODEL=claude-sonnet-4-20250514 ``` **常用模型**: `claude-sonnet-4-*`、`claude-opus-4-*`、`claude-3.5-sonnet-*` 等 > 💡 Claude 模型名称包含日期后缀,请访问 [Anthropic 官网](https://docs.anthropic.com/en/docs/about-claude/models) 查看最新模型。 --- ### DeepSeek DeepSeek 是国产模型中代码能力最强的之一,性价比极高。 **获取 API Key**: https://platform.deepseek.com/ **配置示例**: ```env LLM_PROVIDER=deepseek LLM_API_KEY=sk-your-api-key LLM_MODEL=deepseek-chat ``` **常用模型**: `deepseek-chat`、`deepseek-coder`、`deepseek-reasoner` 等 > 💡 DeepSeek 价格仅为 GPT-4 的 1/10,代码能力接近 GPT-4,性价比极高。 --- ## 国内平台 ### 阿里云通义千问 通义千问是阿里云的大模型服务,国内访问速度快,中文理解能力强。 **获取 API Key**: https://dashscope.console.aliyun.com/ **配置示例**: ```env LLM_PROVIDER=qwen LLM_API_KEY=sk-your-dashscope-key LLM_MODEL=qwen-turbo ``` **常用模型**: `qwen-max`、`qwen-plus`、`qwen-turbo`、`qwen-coder-*` 等 --- ### 智谱 AI (GLM) 智谱 AI 的 GLM 系列模型,中文支持好,有免费配额。 **获取 API Key**: https://open.bigmodel.cn/ **配置示例**: ```env LLM_PROVIDER=zhipu LLM_API_KEY=your-api-key LLM_MODEL=glm-4-flash ``` **常用模型**: `glm-4`、`glm-4-flash`、`glm-4-air`、`codegeex-4` 等 --- ### 月之暗面 Kimi Kimi 以长文本处理能力著称,适合分析大型代码文件。 **获取 API Key**: https://platform.moonshot.cn/ **配置示例**: ```env LLM_PROVIDER=moonshot LLM_API_KEY=sk-your-api-key LLM_MODEL=moonshot-v1-8k ``` **常用模型**: `moonshot-v1-8k`、`moonshot-v1-32k`、`moonshot-v1-128k`、`kimi-*` 等 --- ### 百度文心一言 百度的企业级大模型服务,适合企业用户。 **获取 API Key**: https://console.bce.baidu.com/qianfan/ **⚠️ 特殊配置**: 百度需要同时提供 API Key 和 Secret Key,用冒号分隔: ```env LLM_PROVIDER=baidu LLM_API_KEY=your_api_key:your_secret_key LLM_MODEL=ernie-bot-4 ``` **常用模型**: `ernie-bot-4`、`ernie-bot-turbo`、`ernie-bot` 等 --- ### MiniMax MiniMax 提供多模态能力,支持文本、语音等多种输入。 **获取 API Key**: https://www.minimaxi.com/ **配置示例**: ```env LLM_PROVIDER=minimax LLM_API_KEY=your-api-key LLM_MODEL=abab6.5-chat ``` --- ### 字节豆包 字节跳动的大模型服务,性价比高。 **获取 API Key**: https://console.volcengine.com/ark **配置示例**: ```env LLM_PROVIDER=doubao LLM_API_KEY=your-api-key LLM_MODEL=doubao-pro-4k ``` --- ## 本地部署 ### Ollama Ollama 支持在本地运行开源大模型,完全本地化,隐私安全,适合处理敏感代码。 **安装 Ollama**: ```bash # macOS / Linux curl -fsSL https://ollama.com/install.sh | sh # Windows # 访问 https://ollama.com/download 下载安装包 ``` **拉取模型**: ```bash # 通用模型 ollama pull llama3 ollama pull qwen2.5 # 代码专用模型 ollama pull codellama ollama pull deepseek-coder ollama pull qwen2.5-coder ``` **配置示例**: ```env LLM_PROVIDER=ollama LLM_MODEL=llama3 LLM_BASE_URL=http://localhost:11434/v1 ``` **推荐模型**: | 模型 | 特点 | |------|------| | `llama3` / `llama3.1` / `llama3.2` | Meta 开源,综合能力强 | | `qwen2.5` / `qwen2.5-coder` | 阿里开源,中文支持好 | | `codellama` | Meta 代码专用模型 | | `deepseek-coder` / `deepseek-coder-v2` | DeepSeek 代码模型 | | `mistral` / `mixtral` | Mistral AI 开源模型 | **硬件要求**: | 模型参数 | 最低内存 | 推荐内存 | |---------|---------|---------| | 7B | 8GB | 16GB | | 13B | 16GB | 32GB | | 70B | 64GB | 128GB | > 💡 访问 [Ollama 模型库](https://ollama.com/library) 查看所有可用模型。 --- ## API 中转站 如果直接访问国际平台有困难,可以使用 API 中转站。 **配置方式**: ```env LLM_PROVIDER=openai LLM_API_KEY=中转站提供的Key LLM_BASE_URL=https://your-proxy.com/v1 LLM_MODEL=gpt-4o-mini ``` --- ## 选择建议 ### 按场景选择 | 场景 | 推荐 | 原因 | |------|------|------| | 日常使用 | OpenAI / 通义千问 / DeepSeek | 性价比高,稳定 | | 深度分析 | Claude / GPT-4o | 代码理解能力最强 | | 敏感代码 | Ollama 本地模型 | 完全本地化,隐私安全 | | 预算有限 | DeepSeek / 智谱 GLM-4-Flash | 价格极低或有免费配额 | | 长文件分析 | Kimi / Gemini | 支持长上下文 | ### 按预算选择 | 预算 | 推荐方案 | |------|---------| | 免费 | Gemini (免费配额) / 智谱 GLM-4-Flash / Ollama | | 低预算 | DeepSeek / 通义千问 Turbo | | 中等预算 | GPT-4o-mini / Claude Haiku | | 高预算 | GPT-4o / Claude Sonnet | --- ## 更多资源 - [配置说明](CONFIGURATION.md) - 详细的配置参数说明 - [部署指南](DEPLOYMENT.md) - 部署相关说明 - [常见问题](FAQ.md) - LLM 相关问题解答 --- ### PAPER ARCHITECTURE # DeepAudit: System Architecture for Academic Paper This document provides the system architecture description suitable for top-tier academic conferences (ICSE, FSE, CCS, S&P, USENIX Security, etc.). ## Architecture Diagram --- ## System Overview **DeepAudit** is an LLM-driven intelligent code security audit system that employs a **hierarchical multi-agent architecture** with **Retrieval-Augmented Generation (RAG)** and **sandbox-based vulnerability verification**. ### Key Contributions 1. **LLM-Driven Multi-Agent Orchestration**: A dynamic agent hierarchy where the LLM serves as the central decision-making brain, autonomously orchestrating specialized agents for reconnaissance, analysis, and verification. 2. **RAG-Enhanced Vulnerability Detection**: Integration of semantic code understanding with vulnerability knowledge bases (CWE/CVE) to reduce false positives and improve detection accuracy. 3. **Sandbox-Based Exploit Verification**: Docker-isolated execution environment for automated PoC generation and vulnerability confirmation. --- ## Architecture Components ### Layer 1: User Interface Layer ``` ┌─────────────────────────────────────────────────────────────────┐ │ User Interface Layer │ ├─────────────────────────────────────────────────────────────────┤ │ ┌───────────────────┐ ┌───────────────────────────────────┐ │ │ │ Web Frontend │ │ API Gateway │ │ │ │ (React + TS) │◄──►│ REST API / SSE Event Stream │ │ │ └───────────────────┘ └───────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ``` **Components:** - **Web Frontend**: React 18 + TypeScript SPA with real-time log streaming - **API Gateway**: FastAPI-based REST endpoints with SSE for real-time events ### Layer 2: Multi-Agent Orchestration Layer ``` ┌─────────────────────────────────────────────────────────────────┐ │ Multi-Agent Orchestration Layer │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────┐ │ │ │ Orchestrator Agent │ ◄─── LLM Provider │ │ │ (ReAct Loop) │ (GPT-4/Claude) │ │ └──────────┬──────────┘ │ │ │ │ │ ┌────────────────┼────────────────┐ │ │ ▼ ▼ ▼ │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Recon Agent │ │Analysis Agent│ │Verification │ │ │ │ │ │ │ │ Agent │ │ │ │ • Structure │ │ • SAST │ │ • PoC Gen │ │ │ │ • Tech Stack │ │ • Pattern │ │ • Sandbox │ │ │ │ • Entry Pts │ │ • Dataflow │ │ • Validation │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘ ``` **Key Design Decisions:** | Component | Design Choice | Rationale | |-----------|---------------|-----------| | Orchestrator | LLM-driven ReAct loop | Dynamic strategy adaptation based on findings | | Sub-Agents | Specialized roles | Domain expertise separation for precision | | Communication | TaskHandoff protocol | Structured context passing between agents | | Iteration Limits | Configurable (20/30/15) | Prevent infinite loops while ensuring depth | ### Layer 3: RAG Knowledge Enhancement Layer ``` ┌─────────────────────────────────────────────────────────────────┐ │ RAG Knowledge Enhancement Layer │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │ Code Chunker│ │ Embedding │ │ Vector Database │ │ │ │(Tree-sitter)│───►│ Model │───►│ (ChromaDB) │ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ │ │ │ │ ┌─────────────────────────────────────────────────┼───────────┐│ │ │ CWE/CVE Knowledge Base │ ││ │ │ • SQL Injection patterns ▼ ││ │ │ • XSS signatures ┌───────────────────┐ ││ │ │ • Command Injection │ Semantic Retriever│ ││ │ │ • Path Traversal └───────────────────┘ ││ │ │ • SSRF patterns ││ │ │ • ... ││ │ └─────────────────────────────────────────────────────────────┘│ │ │ └─────────────────────────────────────────────────────────────────┘ ``` **RAG Pipeline:** 1. **Code Chunking**: Tree-sitter based AST-aware chunking for semantic preservation 2. **Embedding**: Support for OpenAI text-embedding-3-small/large, local models 3. **Vector Store**: ChromaDB for lightweight deployment 4. **Retrieval**: Semantic similarity search with vulnerability pattern matching ### Layer 4: Security Tool Integration Layer ``` ┌─────────────────────────────────────────────────────────────────┐ │ Security Tool Integration Layer │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────────────────────────────────────────────────────┐│ │ │ SAST Tools ││ │ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ ││ │ │ │ Semgrep │ │ Bandit │ │Kunlun-M │ │Pattern Match │ ││ │ │ │ (Multi) │ │ (Python) │ │ (PHP/JS) │ │ (Fallback) │ ││ │ │ └──────────┘ └──────────┘ └──────────┘ └──────────────┘ ││ │ └─────────────────────────────────────────────────────────────┘│ │ │ │ ┌────────────────────────┐ ┌────────────────────────────────┐ │ │ │ Secret Detection │ │ Dependency Analysis │ │ │ │ • Gitleaks │ │ • OSV-Scanner │ │ │ │ • TruffleHog │ │ • npm audit / pip-audit │ │ │ └────────────────────────┘ └────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘ ``` **Tool Selection Strategy:** | Category | Primary Tool | Fallback | Coverage | |----------|-------------|----------|----------| | Multi-lang SAST | Semgrep | PatternMatch | 20+ languages | | Python Security | Bandit | PatternMatch | Python-specific | | PHP/JS Analysis | Kunlun-M | Semgrep | Semantic analysis | | Secret Detection | Gitleaks | TruffleHog | Git history scan | | Dependencies | OSV-Scanner | npm/pip audit | Multi-ecosystem | ### Layer 5: Sandbox Verification Layer ``` /* Detailed source-code truncated for AI context efficiency. */ ``` **Verification Workflow:** 1. **PoC Generation**: LLM generates exploitation code based on vulnerability analysis 2. **Sandbox Setup**: Docker container with strict security constraints 3. **Execution**: Run PoC in isolated environment 4. **Validation**: Check execution results against expected vulnerability behavior 5. **Confidence Scoring**: Assign verification confidence (0-1) --- ## Data Flow Diagram ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- ## Algorithm: Multi-Agent Audit Orchestration ``` Algorithm 1: LLM-Driven Multi-Agent Security Audit Input: Project P, Target vulnerabilities V, Configuration C Output: Findings F, Verification Results R 1: Initialize Orchestrator Agent with LLM 2: Create sub-agents: Recon, Analysis, Verification 3: findings ← ∅ 4: verified_results ← ∅ 5: 6: // Phase 1: Reconnaissance 7: recon_result ← ReconAgent.run(P, V) 8: high_risk_areas ← recon_result.priority_areas 9: 10: // Phase 2: Orchestration Loop 11: while iteration < MAX_ITERATIONS do 12: thought, action ← LLM.reason(context, history) 13: 14: if action = "dispatch_agent" then 15: agent ← select_agent(action.params) 16: result ← agent.run(action.task, context) 17: findings ← findings ∪ result.findings 18: update_context(result) 19: else if action = "finish" then 20: break 21: end if 22: 23: iteration ← iteration + 1 24: end while 25: 26: // Phase 3: Verification 27: for each f ∈ findings where f.severity ≥ HIGH do 28: poc ← LLM.generate_poc(f) 29: result ← Sandbox.execute(poc) 30: verified_results ← verified_results ∪ {(f, result)} 31: end for 32: 33: return (findings, verified_results) ``` --- ## Evaluation Metrics For academic evaluation, we suggest the following metrics: ### Detection Effectiveness | Metric | Formula | Description | |--------|---------|-------------| | Precision | TP / (TP + FP) | Accuracy of reported vulnerabilities | | Recall | TP / (TP + FN) | Coverage of actual vulnerabilities | | F1-Score | 2 × (P × R) / (P + R) | Harmonic mean of precision and recall | ### Efficiency Metrics | Metric | Description | |--------|-------------| | Time-to-Detection (TTD) | Time from start to first vulnerability found | | Total Audit Time | End-to-end execution time | | LLM Token Usage | Total tokens consumed during audit | | Tool Invocation Count | Number of external tool calls | ### Verification Quality | Metric | Description | |--------|-------------| | Verification Rate | Percentage of findings verified via sandbox | | False Positive Reduction | % reduction after verification | | PoC Success Rate | Successful exploit demonstrations | --- ## Comparison with Related Work | System | Multi-Agent | RAG | Sandbox | LLM-Driven | |--------|-------------|-----|---------|------------| | CodeQL | ✗ | ✗ | ✗ | ✗ | | Semgrep | ✗ | ✗ | ✗ | ✗ | | Snyk Code | ✗ | ✗ | ✗ | Partial | | GitHub Copilot | ✗ | ✗ | ✗ | ✓ | | **DeepAudit** | **✓** | **✓** | **✓** | **✓** | --- ## LaTeX TikZ Diagram Code For LaTeX papers, you can use the following TikZ code: ```latex \begin{figure}[t] \centering \begin{tikzpicture}[ node distance=1cm, box/.style={rectangle, draw, rounded corners, minimum width=2.5cm, minimum height=0.8cm, align=center}, agent/.style={box, fill=blue!10}, tool/.style={box, fill=orange!10}, rag/.style={box, fill=green!10}, sandbox/.style={box, fill=red!10}, arrow/.style={->, >=stealth, thick} ] % Orchestrator \node[agent] (orch) {Orchestrator Agent}; % Sub-agents \node[agent, below left=1.5cm and 1cm of orch] (recon) {Recon Agent}; \node[agent, below=1.5cm of orch] (analysis) {Analysis Agent}; \node[agent, below right=1.5cm and 1cm of orch] (verify) {Verification Agent}; % Connections \draw[arrow] (orch) -- (recon); \draw[arrow] (orch) -- (analysis); \draw[arrow] (orch) -- (verify); % Tools \node[tool, below=1cm of analysis] (tools) {SAST Tools\\Semgrep, Bandit, Kunlun-M}; % RAG \node[rag, left=1cm of tools] (rag) {RAG Pipeline\\Vector DB + CWE/CVE}; % Sandbox \node[sandbox, right=1cm of tools] (sandbox) {Docker Sandbox\\PoC Verification}; % Tool connections \draw[arrow] (analysis) -- (tools); \draw[arrow, dashed] (tools) -- (rag); \draw[arrow] (verify) -- (sandbox); % LLM \node[box, fill=purple!10, above=0.5cm of orch] (llm) {LLM Provider\\GPT-4 / Claude}; \draw[arrow, <->] (orch) -- (llm); \end{tikzpicture} \caption{DeepAudit System Architecture} \label{fig:architecture} \end{figure} ``` --- ## Citation If you use DeepAudit in your research, please cite: ```bibtex @software{deepaudit2024, title = {DeepAudit: LLM-Driven Multi-Agent Code Security Audit System with RAG Enhancement and Sandbox Verification}, author = {Lin Tsinghua}, year = {2024}, url = {https://github.com/lintsinghua/DeepAudit}, version = {3.0.0} } ``` --- ### SECURITY TOOLS SETUP # DeepAudit 安全工具安装指南 本文档介绍如何一键安装 DeepAudit Agent 审计所需的外部安全工具和沙盒环境。 ## 安装的工具 | 工具 | 用途 | 安装方式 | |------|------|----------| | **Semgrep** | 静态代码分析,支持 30+ 语言 | pip | | **Bandit** | Python 专用安全扫描 | pip | | **Safety** | Python 依赖漏洞扫描 | pip | | **Gitleaks** | Git 密钥泄露检测 | 二进制/brew | | **OSV-Scanner** | 多语言依赖漏洞扫描 | 二进制/brew | | **TruffleHog** | 高级密钥扫描 (可选) | pip/二进制 | | **Docker 沙盒** | 漏洞验证隔离环境 | Docker | ## 快速开始 ### macOS / Linux ```bash # 进入项目目录 cd /path/to/XCodeReviewer # 运行安装脚本 ./scripts/setup_security_tools.sh ``` ### Windows **方式 1: 双击运行** ``` 直接双击 scripts\setup_security_tools.bat ``` **方式 2: PowerShell** ```powershell # 进入项目目录 cd C:\path\to\XCodeReviewer # 运行 PowerShell 脚本 .\scripts\setup_security_tools.ps1 ``` **方式 3: 命令行参数** ```powershell # 全部安装 .\scripts\setup_security_tools.ps1 -InstallAll # 仅安装 Python 工具 .\scripts\setup_security_tools.ps1 -PythonOnly # 仅验证安装状态 .\scripts\setup_security_tools.ps1 -VerifyOnly ``` ## 安装选项 脚本提供以下安装选项: 1. **全部安装 (推荐)** - 安装所有工具 + 构建 Docker 沙盒 2. **仅 Python 工具** - `pip install semgrep bandit safety` 3. **仅系统工具** - 下载 gitleaks, osv-scanner 二进制 4. **仅 Docker 沙盒** - 构建 `deepaudit-sandbox:latest` 镜像 5. **仅验证安装状态** - 检查已安装的工具 ## 手动安装 如果自动脚本无法工作,可以手动安装: ### Python 工具 ```bash pip install semgrep bandit safety # 可选 pip install trufflehog ``` ### macOS 系统工具 ```bash brew install gitleaks osv-scanner # 可选 brew install trufflehog ``` ### Windows 系统工具 **使用 Scoop (推荐):** ```powershell # 安装 Scoop (如果没有) Set-ExecutionPolicy RemoteSigned -Scope CurrentUser irm get.scoop.sh | iex # 安装工具 scoop install gitleaks ``` **使用 Winget:** ```powershell winget install --id=Gitleaks.Gitleaks -e ``` **手动下载:** - Gitleaks: https://github.com/gitleaks/gitleaks/releases - OSV-Scanner: https://github.com/google/osv-scanner/releases - TruffleHog: https://github.com/trufflesecurity/trufflehog/releases ### Docker 沙盒 ```bash cd docker/sandbox docker build -t deepaudit-sandbox:latest . # 验证 docker run --rm deepaudit-sandbox:latest python3 --version ``` ## 环境配置 安装完成后,确保 `backend/.env` 包含以下沙盒配置: ```env # 沙盒配置 SANDBOX_IMAGE=deepaudit-sandbox:latest SANDBOX_MEMORY_LIMIT=512m SANDBOX_CPU_LIMIT=1.0 SANDBOX_TIMEOUT=60 SANDBOX_NETWORK_MODE=none ``` ## 验证安装 运行以下命令验证安装: ```bash # 检查各工具版本 semgrep --version bandit --version safety --version gitleaks version osv-scanner --version # 检查 Docker 沙盒 docker image inspect deepaudit-sandbox:latest ``` ## 常见问题 ### Q: pip install 失败? 尝试使用 pip3 或指定 Python 版本: ```bash python3 -m pip install semgrep bandit safety ``` ### Q: Windows 上 PATH 未生效? 重启终端或手动添加工具目录到系统 PATH: ``` %LOCALAPPDATA%\DeepAudit\tools ``` ### Q: Docker 构建失败? 1. 确保 Docker Desktop 已启动 2. 检查网络连接 3. 尝试手动拉取基础镜像: ```bash docker pull python:3.11-slim-bookworm ``` ### Q: 某些工具不可用? 工具有回退机制: - `semgrep_scan` 失败 → 使用 `pattern_match` - `bandit_scan` 失败 → 使用 `pattern_match` - 沙盒不可用 → 跳过动态验证 ## 工具配置 工具的超时和开关可以在 `backend/app/services/agent/config.py` 中配置: ```python # 工具开关 semgrep_enabled: bool = True bandit_enabled: bool = True gitleaks_enabled: bool = True # 超时配置 semgrep_timeout_seconds: int = 120 bandit_timeout_seconds: int = 60 ``` ## 支持 如有问题,请: 1. 查看日志输出 2. 运行 `-VerifyOnly` 检查安装状态 3. 提交 Issue 到项目仓库 ---