DeepAudit源码深度解析
对DeepAudit的架构以及实现进行了分析
DeepAudit源码深度解析
最近想学学llm4sec了,但是不知道怎么入手,索性读读现在比较火的Deepaudit源码,边读边去学习了。
项目地址:https://github.com/lintsinghua/DeepAudit
目录结构
看一下后端的目录结构:
backend/
├── app/
│ ├── api/v1/ # API 路由层
│ │ └── endpoints/ # 各功能模块的端点
│ ├── core/ # 核心配置
│ │ ├── config.py # 环境变量配置
│ │ └── security.py # 认证/授权
│ ├── db/ # 数据库层
│ │ ├── session.py # 异步数据库会话
│ │ └── init_db.py # 数据库初始化
│ ├── models/ # SQLAlchemy ORM 模型
│ ├── schemas/ # Pydantic 数据验证模型
│ ├── services/ # 业务逻辑层 ⭐核心
│ │ ├── agent/ # Multi-Agent 系统
│ │ │ ├── agents/ # Agent 实现
│ │ │ │ ├── base.py # BaseAgent 基类
│ │ │ │ ├── orchestrator.py # 编排器Agent
│ │ │ │ ├── recon.py # 侦察Agent
│ │ │ │ ├── analysis.py # 分析Agent
│ │ │ │ └── verification.py # 验证Agent
│ │ │ ├── tools/ # Agent 工具集(20+)
│ │ │ ├── knowledge/ # 知识库(漏洞模式)
│ │ │ └── prompts/ # 提示词模板
│ │ ├── llm/ # LLM 封装层
│ │ ├── rag/ # RAG 检索增强
│ │ ├── scanner.py # 快速扫描模式
│ │ └── report_generator.py # 报告生成
│ └── utils/ # 工具函数
├── alembic/ # 数据库迁移
├── static/ # 静态资源
├── tests/ # 单元测试
├── main.py # 应用入口
├── requirements.txt # Python 依赖
└── Dockerfile # 容器化配置本文将重点分析 services 层的代码逻辑,因为这是DeepAudit的核心所在。其余部分主要涉及常规后端开发流程,故不再赘述。
项目架构
放一张docs中的图片:
整体来看,该项目遵循了标准的多Agent(Multi-Agent)架构设计。用户请求首先由主Agent接收,随后主Agent调度多个子Agent协作执行任务。系统利用RAG索引获取知识支持,通过工具调用(Call Tool)执行安全检测,并构建沙箱环境运行PoC以进行漏洞的动态验证。
快速模式
相较于复杂的Agent模式,快速模式是一个相对独立且功能更为精简的模块。我们将首先对其进行剖析。
通过网络抓包分析可知,当启动快速扫描时,后端触发的 quick_scan 接口实现如下:
@router.post("/{project_id}/quick_scan")
async def quick_scan_project(
project_id: str,
scan_request: QuickScanRequest, # 包含 branch_name, exclude_patterns 等
background_tasks: BackgroundTasks,
db: AsyncSession = Depends(get_db),
current_user: User = Depends(deps.get_current_user),
):
"""快速扫描项目(遍历所有文件并调用 LLM 分析)"""
# 1. 验证项目存在且属于当前用户
project = await db.get(Project, project_id)
if not project or project.owner_id != current_user.id:
raise HTTPException(status_code=404)
# 2. 创建审计任务
task = AuditTask(
id=str(uuid.uuid4()),
project_id=project_id,
task_type="quick", # ⭐ 任务类型:quick
status="pending",
branch_name=scan_request.branch_name or project.default_branch,
exclude_patterns=json.dumps(scan_request.exclude_patterns or []),
created_by=current_user.id,
created_at=datetime.now(timezone.utc)
)
db.add(task)
await db.commit()
# 3. 获取用户配置(LLM配置、扫描配置等)
user_config = await get_user_full_config(db, current_user.id)
# 4. 启动后台任务
background_tasks.add_task(
scan_repo_task, # ⭐ 核心函数
task.id,
AsyncSessionLocal, # 数据库会话工厂
user_config # 用户配置
)
return {"task_id": task.id, "status": "pending"}略过非核心细节,我们看到该接口在后台调用了 scan_repo_task 方法。接下来我们深入追踪该方法的实现:
首先是文件获取逻辑:
async def scan_repo_task(task_id: str, db_session_factory, user_config: dict = None):
"""
后台仓库扫描任务
Args:
task_id: 任务ID
db_session_factory: 数据库会话工厂
user_config: 用户配置(包含 llmConfig 和 otherConfig)
"""
async with db_session_factory() as db:
task = await db.get(AuditTask, task_id)
try:
# 1️⃣ 更新状态为 running
task.status = "running"
task.started_at = datetime.now(timezone.utc)
await db.commit()
# 2️⃣ 创建 LLM 服务实例(使用用户配置)
llm_service = LLMService(user_config=user_config or {})
# 3️⃣ 获取项目信息
project = await db.get(Project, task.project_id)
repo_url = project.repository_url
branch = task.branch_name or project.default_branch or "main"
repo_type = project.repository_type # github/gitlab/gitea
# 4️⃣ 获取文件列表(通过 API)
# 根据仓库类型调用不同的 API
if repo_type == "github":
files = await get_github_files(
repo_url,
branch,
github_token, # 从用户配置或环境变量获取
exclude_patterns # 排除模式
)
elif repo_type == "gitlab":
files = await get_gitlab_files(repo_url, branch, gitlab_token, exclude_patterns)
elif repo_type == "gitea":
files = await get_gitea_files(repo_url, branch, gitea_token, exclude_patterns)
# 文件格式: [{"path": "app/main.py", "url": "https://raw.githubusercontent.com/..."}, ...]
获取到的文件列表格式如下所示。其中,`get_github_files` 函数的具体实现代码为:
```python
async def get_github_files(repo_url, branch, token, exclude_patterns):
"""获取 GitHub 仓库文件列表"""
# 1. 解析仓库 URL
repo_info = parse_repository_url(repo_url, "github")
owner, repo = repo_info['owner'], repo_info['repo']
# 2. 调用 GitHub Tree API(递归获取所有文件)
tree_url = f"https://api.github.com/repos/{owner}/{repo}/git/trees/{branch}?recursive=1"
tree_data = await github_api(tree_url, token)
# 3. 过滤文件
files = []
for item in tree_data.get("tree", []):
if item.get("type") == "blob": # 文件类型
# 检查是否为文本文件
if is_text_file(item["path"]):
# 检查是否需要排除
if not should_exclude(item["path"], exclude_patterns):
# 检查文件大小
if item.get("size", 0) <= MAX_FILE_SIZE:
files.append({
"path": item["path"],
"url": f"https://raw.githubusercontent.com/{owner}/{repo}/{branch}/{item['path']}"
})
return files跳过配置文件的读取与解析部分,我们直接关注核心处理逻辑:
# 7️⃣ 初始化统计变量
total_issues = 0 # 总漏洞数
total_lines = 0 # 总代码行数
quality_scores = [] # 质量分数列表
scanned_files = 0 # 已扫描文件数
failed_files = 0 # 失败文件数
consecutive_failures = 0 # 连续失败次数
# 8️⃣ 遍历每个文件
for file_info in files:
# ⭐ 检查任务是否被取消
if task_control.is_cancelled(task_id):
print(f"🛑 任务 {task_id} 已被用户取消")
task.status = "cancelled"
await db.commit()
return
# ⭐ 检查连续失败次数(防止 API 异常时无限重试)
if consecutive_failures >= 5:
raise Exception("连续失败 5 次,可能是 LLM API 服务异常")
try:
# 9️⃣ 获取文件内容
headers = {}
if repo_type == "gitlab" and gitlab_token:
headers["PRIVATE-TOKEN"] = gitlab_token
elif repo_type == "gitea" and gitea_token:
headers["Authorization"] = f"token {gitea_token}"
elif repo_type == "github" and github_token:
headers["Authorization"] = f"Bearer {github_token}"
content = await fetch_file_content(file_info["url"], headers)
# 🔟 验证文件内容
if not content or not content.strip():
print(f"⚠️ 文件内容为空,跳过: {file_info['path']}")
continue
if len(content) > MAX_FILE_SIZE_BYTES:
print(f"⚠️ 文件太大,跳过: {file_info['path']}")
continue
# 1️⃣1️⃣ 提取语言类型
language = get_language_from_path(file_info["path"])
# 例如: "app/main.py" → "python"
# 1️⃣2️⃣ 调用 LLM 分析(⭐ 核心步骤)
print(f"🤖 正在调用 LLM 分析: {file_info['path']} ({language})")
# 支持规则集和提示词模板
scan_config = user_config.get('scan_config', {})
rule_set_id = scan_config.get('rule_set_id')
prompt_template_id = scan_config.get('prompt_template_id')
if rule_set_id or prompt_template_id:
# 使用自定义规则和提示词
analysis = await llm_service.analyze_code_with_rules(
content, language,
rule_set_id=rule_set_id,
prompt_template_id=prompt_template_id,
db_session=db
)
else:
# 使用默认分析
analysis = await llm_service.analyze_code(content, language)
print(f"✅ LLM 分析完成: {file_info['path']}")
# 1️⃣3️⃣ 解析分析结果
# analysis 格式:
# {
# "issues": [
# {
# "line": 42,
# "type": "sql_injection",
# "severity": "high",
# "title": "SQL注入漏洞",
# "description": "用户输入未过滤...",
# "suggestion": "使用参数化查询",
# "code_snippet": "SELECT * FROM ..."
# }
# ],
# "quality_score": 85.5
# }
issues = analysis.get("issues", [])
# 1️⃣4️⃣ 保存漏洞到数据库
for issue in issues:
line_num = issue.get("line", 1)
# 提取代码片段(如果 LLM 没有返回)
code_snippet = issue.get("code_snippet")
if not code_snippet:
# 从源码提取上下文(前后2行)
file_lines = content.split('\n')
idx = max(0, int(line_num) - 1)
start = max(0, idx - 2)
end = min(len(file_lines), idx + 3)
code_snippet = '\n'.join(file_lines[start:end])
# 创建 AuditIssue 对象
audit_issue = AuditIssue(
task_id=task.id,
file_path=file_info["path"],
line_number=line_num,
column_number=issue.get("column"),
issue_type=issue.get("type", "maintainability"),
severity=issue.get("severity", "low"),
title=issue.get("title", "Issue"),
message=issue.get("description") or issue.get("title"),
suggestion=issue.get("suggestion"),
code_snippet=code_snippet,
ai_explanation=issue.get("ai_explanation"),
status="open"
)
db.add(audit_issue)
total_issues += 1
# 1️⃣5️⃣ 记录质量分数
if "quality_score" in analysis:
quality_scores.append(analysis["quality_score"])
# 1️⃣6️⃣ 更新统计信息
consecutive_failures = 0 # 成功后重置
scanned_files += 1
total_lines += content.count('\n') + 1
task.scanned_files = scanned_files
task.total_lines = total_lines
task.issues_count = total_issues
await db.commit()
print(f"📈 进度: {scanned_files}/{len(files)} ({int(scanned_files/len(files)*100)}%)")
# 1️⃣7️⃣ 请求间隔(防止 API 限流)
await asyncio.sleep(llm_gap_ms / 1000) # 默认 1 秒
except Exception as file_error:
failed_files += 1
consecutive_failures += 1
print(f"❌ 分析文件失败 ({file_info['path']}): {file_error}")
await asyncio.sleep(llm_gap_ms / 1000)由此可见,该流程的主要逻辑是循环遍历每个代码文件,并调用 llm_service.analyze_code_with_rules 或 llm_service.analyze_code 进行分析。下面我们查看 analyze_code 的具体实现:
async def analyze_code(self, code: str, language: str) -> Dict[str, Any]:
"""
分析代码并返回结构化问题
支持中英文输出
Raises:
Exception: 当LLM调用失败或返回无效响应时抛出异常
"""
# 获取输出语言配置
output_language = self._get_output_language()
is_chinese = output_language == 'zh-CN'
# 添加行号帮助LLM定位问题
code_with_lines = '\n'.join(
f"{i+1}| {line}" for i, line in enumerate(code.split('\n'))
)
# 构建系统提示词
system_prompt = self._build_system_prompt(is_chinese)
# 构建用户提示词
if is_chinese:
user_prompt = f"""编程语言: {language}
⚠️ 代码已标注行号(格式:行号| 代码内容),请根据行号准确填写 line 字段!
请分析以下代码:
{code_with_lines}"""
else:
user_prompt = f"""Programming Language: {language}
⚠️ Code is annotated with line numbers (format: lineNumber| code), please fill the 'line' field accurately based on these numbers!
Please analyze the following code:
{code_with_lines}"""
try:
adapter = LLMFactory.create_adapter(self.config)
# 使用用户配置的 temperature(如果未设置则使用 config 中的默认值)
request = LLMRequest(
messages=[
LLMMessage(role="system", content=system_prompt),
LLMMessage(role="user", content=user_prompt)
],
temperature=self.config.temperature,
max_tokens=self.config.max_tokens,
)
response = await adapter.complete(request)
content = response.content
# 记录 LLM 原始响应(用于调试)
logger.info(f"📥 LLM 原始响应长度: {len(content) if content else 0} 字符")
logger.info(f"📥 LLM 原始响应内容:\n{content}")
# 检查响应内容是否为空
if not content or not content.strip():
error_msg = f"LLM返回空响应 - Provider: {self.config.provider.value}, Model: {self.config.model}"
logger.error(error_msg)
logger.error(f"响应详情 - Finish Reason: {response.finish_reason}, Usage: {response.usage}")
raise Exception(error_msg)
# 尝试从响应中提取JSON
result = self._parse_json(content)
# 记录解析后的问题数量
issues_count = len(result.get("issues", []))
logger.info(f"📊 LLM 分析结果: 发现 {issues_count} 个问题, 质量评分: {result.get('quality_score', 'N/A')}")
# 检查解析结果是否有效(不是默认响应)
if result == self._get_default_response():
error_msg = f"无法解析LLM响应为有效的分析结果 - Provider: {self.config.provider.value}"
logger.error(error_msg)
raise Exception(error_msg)
return result
except Exception as e:
logger.error(f"LLM Analysis failed: {e}", exc_info=True)
logger.error(f"Provider: {self.config.provider.value}, Model: {self.config.model}")
# 重新抛出异常,让调用者处理
raise显而易见,该方法通过 _build_system_prompt 构建系统提示词,并为代码添加行号后,将其传入用户提示词中供AI进行审计。
除了这种从远程拉取代码进行快速审计外,DeepAudit还提供了基于ZIP文件上传的审计方式。在阅读源码时,我注意到这部分的实现逻辑略显冗余,复用性有待提高,这可能深受Vibe项目架构的影响。
接下来,我们深入分析 system_prompt 的具体作用:
def _build_system_prompt(self, is_chinese: bool) -> str:
"""构建系统提示词(支持中英文)"""
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
}
}"""
if is_chinese:
return f"""⚠️⚠️⚠️ 只输出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:
{schema}
注意:
- title: 问题的简短标题(中文)
- description: 详细描述问题(中文)
- suggestion: 具体的修复建议(中文)
- line: 问题所在的行号(从1开始计数,必须准确对应代码中的行号)
- column: 问题所在的列号(从1开始计数,指向问题代码的起始位置)
- code_snippet: 包含问题的代码片段(建议包含问题行及其前后1-2行作为上下文,保持原始缩进格式)
- ai_explanation: AI 的深入解释(中文)
- xai.what: 这是什么问题(中文)
- xai.why: 为什么会有这个问题(中文)
- xai.how: 如何修复这个问题(中文)
【重要】关于行号和代码片段:
1. line 必须是问题代码的行号!!!代码左侧有"行号|"标注,例如"25| const x = 1"表示第25行,line字段必须填25
2. column 是问题代码在该行中的起始列位置(从1开始,不包括"行号|"前缀部分)
3. code_snippet 应该包含问题代码及其上下文(前后各1-2行),去掉"行号|"前缀,保持原始代码的缩进
4. 如果代码片段包含多行,必须使用 \\n 表示换行符(这是JSON的要求)
5. 如果无法确定准确的行号,不要填写line和column字段(不要填0)
【严格禁止】:
- 禁止在任何字段中使用英文,所有内容必须是简体中文
- 禁止在JSON字符串值中使用真实换行符,必须用\\n转义
- 禁止输出markdown代码块标记(如```json)
⚠️ 重要提醒:line字段必须从代码左侧的行号标注中读取,不要猜测或填0!"""
else:
return f"""⚠️⚠️⚠️ OUTPUT JSON ONLY! NO OTHER FORMAT! NO MARKDOWN! NO TEXT ANALYSIS! ⚠️⚠️⚠️
You are a professional code auditing assistant. Your task is to analyze code and return results in strict JSON Schema format.
【MOST IMPORTANT】Output format requirements:
1. MUST output pure JSON object only, starting with {{ and ending with }}
2. NO text, explanation, or markdown markers before or after JSON
3. NO ```json or ### markdown syntax
4. Even for document files (like README), output analysis in JSON format
【Content requirements】:
1. All text content MUST be in English ONLY
2. Special characters in JSON strings must be properly escaped (\\n for newlines, \\" for quotes, \\\\ for backslashes)
3. code_snippet field MUST use \\n for newlines
Please comprehensively and thoroughly analyze the code, finding ALL issues from the following dimensions:
- Security vulnerabilities (SQL injection, XSS, command injection, path traversal, SSRF, XXE, deserialization, hardcoded secrets, etc.)
- Potential bugs and logical errors
- Performance issues and optimization suggestions
- Coding standards and code style
- Maintainability and readability
- Best practices and design patterns
【IMPORTANT】Find as many issues as possible! Do NOT miss any security vulnerabilities or potential risks!
The output format MUST strictly conform to the following JSON Schema:
{schema}
Note:
- title: Brief title of the issue (in English)
- description: Detailed description of the issue (in English)
- suggestion: Specific fix suggestions (in English)
- line: Line number where the issue occurs (1-indexed, must accurately correspond to the line in the code)
- column: Column number where the issue starts (1-indexed, pointing to the start position of the problematic code)
- code_snippet: Code snippet containing the issue (should include the problem line plus 1-2 lines before and after for context, preserve original indentation)
- ai_explanation: AI's in-depth explanation (in English)
- xai.what: What is this issue (in English)
- xai.why: Why does this issue exist (in English)
- xai.how: How to fix this issue (in English)
【IMPORTANT】About line numbers and code snippets:
1. 'line' MUST be the line number from code!!! Code has "lineNumber|" prefix, e.g. "25| const x = 1" means line 25, you MUST set line to 25
2. 'column' is the starting column position in that line (1-indexed, excluding the "lineNumber|" prefix)
3. 'code_snippet' should include the problematic code with context (1-2 lines before/after), remove "lineNumber|" prefix, preserve indentation
4. If code snippet has multiple lines, use \\n for newlines (JSON requirement)
5. If you cannot determine the exact line number, do NOT fill line and column fields (don't use 0)
【STRICTLY PROHIBITED】:
- NO Chinese characters in any field - English ONLY
- NO real newline characters in JSON string values - must use \\n
- NO markdown code block markers (like ```json)
⚠️ CRITICAL: Read line numbers from the "lineNumber|" prefix on the left of each code line. Do NOT guess or use 0!"""可以看出,系统对LLM的返回格式进行了严格的约束。
综上所述,快速模式主要针对单个文件进行独立审计,未充分考虑文件间的调用关系。其审计效果在很大程度上取决于AI模型自身的能力,因此更适用于演示级小规模项目的分析。
Multi-Agent模式
与快速模式不同,Multi-Agent模式的架构更为复杂。以下是对其核心机制的详细解析:
Multi-Agent
Multi-Agent模式的核心在于主从架构,由一个主体Agent(Orchestrator Agent)和三个子Agent(Recon Agent,Analysis Agent,Verification Agent)组成。它们均实现了Base Agent中定义的接口,整体结构如下:
┌─────────────────────────────────────────────────────────┐
│ BaseAgent │
│ (抽象基类/父类) │
│ │
│ 提供所有 Agent 的共同能力: │
│ • stream_llm_call() - LLM 调用 │
│ • execute_tool() - 工具执行 │
│ • receive_handoff() - 接收任务切换 │
│ • emit_event() - 发送事件 │
│ • 状态管理、历史记录、配置等 │
└─────────────────────────────────────────────────────────┘
▲
│ 继承
┌───────────────┼───────────────┬─────────────┐
│ │ │ │
┌────────┴────────┐ ┌───┴────────┐ ┌───┴────────┐ ┌──┴──────────┐
│ OrchestratorAgent│ │ ReconAgent │ │AnalysisAgent│ │Verification │
│ (主 Agent) │ │ (子Agent) │ │ (子Agent) │ │Agent(子Agent)│
└─────────────────┘ └────────────┘ └─────────────┘ └─────────────┘
│ ▲ ▲ ▲
│ │ │ │
└──────────────────┴──────────────┴──────────────┘
调度和协调其整体运行流程如下图所示:
用户请求
↓
OrchestratorAgent 启动
↓
[OrchestratorAgent 思考] 我需要先了解项目
↓
[调度] dispatch_agent("recon", "分析项目结构")
↓
ReconAgent 运行
├─ 使用 BaseAgent 的 stream_llm_call() 与 LLM 通信
├─ 使用 BaseAgent 的 execute_tool() 执行 list_files 等工具
└─ 返回结果给 OrchestratorAgent
↓
[OrchestratorAgent 思考] 好,现在我知道技术栈了,开始分析
↓
[调度] dispatch_agent("analysis", "分析高风险文件")
↓
AnalysisAgent 运行
├─ 使用 BaseAgent 的能力
├─ 执行 semgrep_scan, bandit_scan 等
└─ 发现 5 个潜在漏洞
↓
[OrchestratorAgent 思考] 需要验证这些发现
↓
[调度] dispatch_agent("verification", "验证 SQL 注入漏洞")
↓
VerificationAgent 运行
├─ 使用 BaseAgent 的能力
├─ 生成 PoC,执行 run_code
└─ 确认漏洞为真实漏洞
↓
[OrchestratorAgent 思考] 审计完成!
↓
返回最终报告BaseAgent
我们将重点关注 backend/app/services/agent/agents/base.py 文件,该文件定义了供各Agent调用的基础类。
AgentConfig
@dataclass
class AgentConfig:
"""Agent 配置"""
name: str
agent_type: AgentType # ORCHESTRATOR/RECON/ANALYSIS/VERIFICATION
pattern: AgentPattern = AgentPattern.REACT # ReAct 模式
# LLM 配置
model: Optional[str] = None
temperature: float = 0.1
max_tokens: int = 8192
# 执行限制
max_iterations: int = 20
timeout_seconds: int = 600
# 工具配置
tools: List[str] = field(default_factory=list)
# 系统提示词
system_prompt: Optional[str] = None
# 元数据
metadata: Dict[str, Any] = field(default_factory=dict)该类主要用于定义Agent的配置信息,其实例化方式如下:
# 在子类构造函数中创建配置
config = AgentConfig(
name="Recon",
agent_type=AgentType.RECON,
pattern=AgentPattern.REACT,
max_iterations=15,
system_prompt=RECON_SYSTEM_PROMPT,
)TaskHandoff
该类主要负责Agent之间的消息传递,其基本数据结构定义如下:
@dataclass
class TaskHandoff:
"""任务交接协议 - Agent 之间传递的结构化信息"""
# 基本信息
from_agent: str
to_agent: str
# 工作摘要
summary: str
work_completed: List[str] = field(default_factory=list)
# 关键发现和洞察
key_findings: List[Dict[str, Any]] = field(default_factory=list)
insights: List[str] = field(default_factory=list)
# 建议和关注点
suggested_actions: List[Dict[str, Any]] = field(default_factory=list)
attention_points: List[str] = field(default_factory=list)
priority_areas: List[str] = field(default_factory=list)
# 上下文数据
context_data: Dict[str, Any] = field(default_factory=dict)
# 置信度
confidence: float = 0.8
# 时间戳
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))来看其中的核心方法:
def to_prompt_context(self) -> str:
"""
转换为 LLM 可理解的上下文格式
这是关键!让 LLM 能够理解前序 Agent 的工作
"""
lines = [
f"## 来自 {self.from_agent} Agent 的任务交接",
"",
f"### 工作摘要",
self.summary,
"",
]
if self.work_completed:
lines.append("### 已完成的工作")
for work in self.work_completed:
lines.append(f"- {work}")
lines.append("")
if self.key_findings:
lines.append("### 关键发现")
for i, finding in enumerate(self.key_findings[:15], 1):
severity = finding.get("severity", "medium")
title = finding.get("title", "Unknown")
file_path = finding.get("file_path", "")
lines.append(f"{i}. [{severity.upper()}] {title}")
if file_path:
lines.append(f" 位置: {file_path}:{finding.get('line_start', '')}")
if finding.get("description"):
lines.append(f" 描述: {finding['description'][:100]}")
lines.append("")
if self.insights:
lines.append("### 洞察和分析")
for insight in self.insights:
lines.append(f"- {insight}")
lines.append("")
if self.suggested_actions:
lines.append("### 建议的下一步行动")
for action in self.suggested_actions:
action_type = action.get("type", "general")
description = action.get("description", "")
priority = action.get("priority", "medium")
lines.append(f"- [{priority.upper()}] {action_type}: {description}")
lines.append("")
if self.attention_points:
lines.append("### ⚠️ 需要特别关注")
for point in self.attention_points:
lines.append(f"- {point}")
lines.append("")
if self.priority_areas:
lines.append("### 优先分析区域")
for area in self.priority_areas:
lines.append(f"- {area}")
return "\n".join(lines)该方法主要用于在三个子Agent之间传递消息,传递格式如下:
## 来自 recon Agent 的任务交接
### 工作摘要
已完成项目侦察...
### 已完成的工作
- 分析了项目结构
- 识别了技术栈
### 关键发现
1. [HIGH] SQL注入风险
位置: app.py:36
### 优先分析区域
- /api/users.py
- /db/queries.py值得注意的是,代码中 enumerate(self.key_findings[:15], 1) 的设计限制了传递的消息条目为前15条,并确保高优先级的发现优先传递,从而避免了上下文过长的问题。
BaseAgent
其基本数据结构如下:
class BaseAgent(ABC):
def __init__(
self,
config: AgentConfig,
llm_service,
tools: Dict[str, Any],
event_emitter=None,
parent_id: Optional[str] = None,
knowledge_modules: Optional[List[str]] = None,
):
self.config = config
self.llm_service = llm_service
self.tools = tools
self.event_emitter = event_emitter
self.parent_id = parent_id
self.knowledge_modules = knowledge_modules or []
# 🔥 生成唯一ID
self._agent_id = f"agent_{uuid.uuid4().hex[:8]}"
# 🔥 增强的状态管理
self._state = AgentState(
agent_id=self._agent_id,
agent_name=config.name,
agent_type=config.agent_type.value,
parent_id=parent_id,
max_iterations=config.max_iterations,
knowledge_modules=self.knowledge_modules,
)
# 运行状态
self._iteration = 0
self._total_tokens = 0
self._tool_calls = 0
self._cancelled = False
# 🔥 协作状态
self._incoming_handoff: Optional[TaskHandoff] = None
self._insights: List[str] = [] # 收集的洞察
self._work_completed: List[str] = [] # 完成的工作记录
# 🔥 注册状态
self._registered = False
# 🔥 取消回调
self._cancel_callback = None以下是该类中定义的关键方法:_register_to_registry():
def _register_to_registry(self, task: Optional[str] = None) -> None:
"""注册到Agent注册表(延迟注册,在run时调用)"""
if self._registered:
return
# 🔥 注册到全局 Agent 注册表
agent_registry.register_agent(
agent_id=self._agent_id,
agent_name=self.config.name,
agent_type=self.config.agent_type.value,
task=task or self._state.task or "Initializing",
parent_id=self.parent_id,
agent_instance=self,
state=self._state,
knowledge_modules=self.knowledge_modules,
)
# 🔥 创建消息队列(用于 Agent 间通信)
message_bus.create_queue(self._agent_id)
self._registered = True
tree = agent_registry.get_agent_tree()
logger.debug(f"[AgentTree] Agent 注册完成: {self.name}, 当前树节点数: {len(tree['nodes'])}")设计要点:
- 延迟注册: 不在
__init__中注册,而是在run()时注册
- Orchestrator 在自己的
run()开始时注册 - 子 Agent 在被 Orchestrator 调度时注册
- 防重复注册:
_registered标志确保只注册一次 - 消息队列: 每个 Agent 都有独立的消息队列,用于接收消息
- 父子关系:
parent_id建立 Agent 树的层级结构
set_parent_id():
def set_parent_id(self, parent_id: str) -> None:
"""设置父Agent ID(在调度时调用)"""
self.parent_id = parent_id
self._state.parent_id = parent_id父子Agent之间通过指定Agent ID进行关联,通常在Orchestrator调度子Agent时调用:
# Orchestrator 调度子 Agent 时
agent = self.sub_agents.get("recon")
agent.set_parent_id(self._agent_id) # 设置父 ID
agent._register_to_registry(task="分析项目结构") # 然后注册
result = await agent.run(sub_input) # 执行stream_llm_call()
该方法的主要作用是展示LLM的实时思考过程,并负责上下文压缩及Token控制等操作。
async def stream_llm_call(
self,
messages: List[Dict[str, str]],
temperature: Optional[float] = None,
max_tokens: Optional[int] = None,
auto_compress: bool = True,
) -> Tuple[str, int]:
"""
统一的流式 LLM 调用方法 - 所有 Agent 共用
Args:
messages: 对话历史
temperature: 温度(None 时使用用户配置)
max_tokens: 最大 token 数(None 时使用用户配置)
auto_compress: 是否自动压缩过长的消息历史
Returns:
(完整响应内容, token消耗数)
"""
# 🔥 自动压缩过长的消息历史
if auto_compress:
messages = self.compress_messages_if_needed(messages)
accumulated = ""
total_tokens = 0
# 🔥 检查取消标志
if self.is_cancelled:
return "", 0
# 🔥 发射开始思考事件
await self.emit_thinking_start()
try:
# 🔥 获取流式迭代器(None 参数使用用户配置)
stream = self.llm_service.chat_completion_stream(
messages=messages,
temperature=temperature, # None -> 使用用户配置
max_tokens=max_tokens, # None -> 使用用户配置
)
iterator = stream.__aiter__()
first_token_received = False
while True:
# 🔥 检查取消标志
if self.is_cancelled:
break
try:
# 🔥 超时控制:首 token 30秒,后续 60秒
timeout = 30.0 if not first_token_received else 60.0
chunk = await asyncio.wait_for(iterator.__anext__(), timeout=timeout)
if chunk["type"] == "token":
first_token_received = True
token = chunk["content"]
accumulated = chunk.get("accumulated", accumulated + token)
# 🔥 流式发送 token 到前端
await self.emit_thinking_token(token, accumulated)
# 🔥 让出控制权,让 SSE 有机会发送事件
await asyncio.sleep(0)
elif chunk["type"] == "done":
accumulated = chunk["content"]
if chunk.get("usage"):
total_tokens = chunk["usage"].get("total_tokens", 0)
break
elif chunk["type"] == "error":
# 🔥 处理 API 错误(速率限制、配额等)
error_type = chunk.get("error_type", "unknown")
user_message = chunk.get("user_message", "Unknown error")
# 🔥 特殊错误标记,供调用方识别
if error_type in ("rate_limit", "quota_exceeded", "authentication"):
accumulated = f"[API_ERROR:{error_type}] {user_message}"
break
except StopAsyncIteration:
break
except asyncio.TimeoutError:
# 🔥 超时错误处理
timeout_type = "First Token" if not first_token_received else "Stream"
accumulated = f"[超时错误: {timeout}s 无响应] 请尝试简化请求或重试。"
break
# 🔥 发射思考结束事件
await self.emit_thinking_end(accumulated)
return accumulated, total_tokens
except asyncio.CancelledError:
await self.emit_thinking_end(accumulated)
raise该功能主要旨在提升用户交互体验。
compress_messages_if_needed
该方法用于实现上下文的压缩:
def compress_messages_if_needed(
self,
messages: List[Dict[str, str]],
max_tokens: int = 100000,
) -> List[Dict[str, str]]:
"""
如果消息历史过长,自动压缩
Args:
messages: 消息列表
max_tokens: 最大token数(默认 100k)
Returns:
压缩后的消息列表
"""
from ...llm.memory_compressor import MemoryCompressor
compressor = MemoryCompressor(max_total_tokens=max_tokens)
if compressor.should_compress(messages):
logger.info(f"[{self.name}] Compressing conversation history...")
compressed = compressor.compress_history(messages)
logger.info(f"[{self.name}] Compressed {len(messages)} -> {len(compressed)} messages")
return compressed
return messages其具体实现位于 llm/memory_compressor.py 中,主要策略如下:
- 保留系统提示词: 第一条 system 消息永远保留
- 保留最近消息: 最后 N 条消息保留完整内容
- 压缩中间历史: 使用 LLM 总结中间的长对话
execute_tool()
以下为统一的工具执行入口代码:
async def execute_tool(self, tool_name: str, tool_input: Dict[str, Any]) -> str:
"""
执行工具调用 - 基类统一实现
Args:
tool_name: 工具名称
tool_input: 工具参数
Returns:
工具执行结果(字符串格式)
"""
import time
start_time = time.time()
# 🔥 1. 检查工具是否存在
if tool_name not in self.tools:
available = list(self.tools.keys())
return f"错误: 工具 '{tool_name}' 不存在。可用工具: {available}"
# 🔥 2. 发射工具调用事件(前端显示 "正在调用 read_file...")
await self.emit_tool_call(tool_name, tool_input)
self._tool_calls += 1
try:
tool = self.tools[tool_name]
# 🔥 3. 检查取消标志
if self.is_cancelled:
return "工具执行已取消"
# 🔥 4. 同步工具转异步执行
if asyncio.iscoroutinefunction(tool):
result = await tool(**tool_input)
else:
# 同步工具在线程池中执行,避免阻塞事件循环
result = await asyncio.to_thread(tool, **tool_input)
# 🔥 5. 标准化返回值
if result is None:
result_str = "操作完成,无返回值"
elif isinstance(result, str):
result_str = result
elif isinstance(result, dict):
result_str = json.dumps(result, ensure_ascii=False, indent=2)
elif isinstance(result, list):
result_str = json.dumps(result, ensure_ascii=False, indent=2)
else:
result_str = str(result)
# 🔥 6. 发射工具结果事件
duration_ms = int((time.time() - start_time) * 1000)
await self.emit_tool_result(tool_name, result_str, duration_ms)
return result_str
except Exception as e:
logger.error(f"Tool '{tool_name}' failed: {e}", exc_info=True)
error_msg = f"工具 '{tool_name}' 执行失败: {str(e)}"
duration_ms = int((time.time() - start_time) * 1000)
await self.emit_tool_result(tool_name, error_msg, duration_ms)
return error_msg该部分逻辑较为复杂,我们将留待后续的 ToolCall 章节进行详细解析。
用于Agent之间任务交接的方法:
主要涉及到的代码如下:
def receive_handoff(self, handoff: TaskHandoff):
"""
接收来自前序 Agent 的任务交接
Args:
handoff: 任务交接对象
"""
self._incoming_handoff = handoff
logger.info(
f"[{self.name}] Received handoff from {handoff.from_agent}: "
f"{handoff.summary[:50]}..."
)
def get_handoff_context(self) -> str:
"""
获取交接上下文(用于构建 LLM prompt)
Returns:
格式化的上下文字符串
"""
if not self._incoming_handoff:
return ""
return self._incoming_handoff.to_prompt_context()
def create_handoff(
self,
to_agent: str,
summary: str,
key_findings: List[Dict[str, Any]] = None,
suggested_actions: List[Dict[str, Any]] = None,
attention_points: List[str] = None,
priority_areas: List[str] = None,
context_data: Dict[str, Any] = None,
) -> TaskHandoff:
"""
创建任务交接
Args:
to_agent: 目标 Agent
summary: 工作摘要
key_findings: 关键发现
suggested_actions: 建议的行动
attention_points: 需要关注的点
priority_areas: 优先分析区域
context_data: 上下文数据
Returns:
TaskHandoff 对象
"""
return TaskHandoff(
from_agent=self.name,
to_agent=to_agent,
summary=summary,
work_completed=self._work_completed.copy(),
key_findings=key_findings or [],
insights=self._insights.copy(),
suggested_actions=suggested_actions or [],
attention_points=attention_points or [],
priority_areas=priority_areas or [],
context_data=context_data or {},
)
def build_prompt_with_handoff(self, base_prompt: str) -> str:
"""
构建包含交接上下文的 prompt
Args:
base_prompt: 基础 prompt
Returns:
增强后的 prompt
"""
handoff_context = self.get_handoff_context()
if not handoff_context:
return base_prompt
return f"""{base_prompt}
---
## 前序 Agent 交接信息
{handoff_context}
---
请基于以上来自前序 Agent 的信息,结合你的专业能力开展工作。
"""
# ============ 核心事件发射方法 ============
async def emit_event(
self,
event_type: str,
message: str,
**kwargs
):
"""发射事件"""
if self.event_emitter:
from ..event_manager import AgentEventData
# 准备 metadata
metadata = kwargs.get("metadata", {}) or {}
if "agent_name" not in metadata:
metadata["agent_name"] = self.name
# 分离已知字段和未知字段
known_fields = {
"phase", "tool_name", "tool_input", "tool_output",
"tool_duration_ms", "finding_id", "tokens_used"
}
event_kwargs = {}
for k, v in kwargs.items():
if k in known_fields:
event_kwargs[k] = v
elif k != "metadata":
# 将未知字段放入 metadata
metadata[k] = v
await self.event_emitter.emit(AgentEventData(
event_type=event_type,
message=message,
metadata=metadata,
**event_kwargs
))
可见,该方法调用了前文提及的 to_prompt_context。此处Agent间的消息传递完全依赖于格式化的Markdown文档。
send_message_to_parent()
主要用于向父Agent发送消息:
def send_message_to_parent(
self,
content: str,
message_type: MessageType = MessageType.INFORMATION,
) -> None:
"""向父Agent发送消息"""
if self.parent_id:
message_bus.send_message(
from_agent=self._agent_id,
to_agent=self.parent_id,
content=content,
message_type=message_type,
)check_messages()
该方法主要用于异步检查并处理接收到的消息,核心代码如下:
def check_messages(self) -> List[AgentMessage]:
"""
检查并处理收到的消息
Returns:
未读消息列表
"""
messages = message_bus.get_messages(
self._agent_id,
unread_only=True,
mark_as_read=True,
)
for msg in messages:
# 🔥 处理消息
if msg.from_agent == "user":
# 用户消息直接添加到对话历史
self._state.add_message("user", msg.content)
else:
# Agent 消息添加为 XML 格式
self._state.add_message("user", msg.to_xml())
# 🔥 如果在等待状态,恢复执行
if self._state.is_waiting_for_input():
self._state.resume_from_waiting()
agent_registry.update_agent_status(self._agent_id, "running")
return messages该方法常用于Agent在ReAct循环中定期检查消息,示例代码如下:
# 在 ReAct 循环中
for iteration in range(max_iterations):
# 检查是否有新消息
messages = self.check_messages()
if messages:
logger.info(f"Received {len(messages)} messages")
# 继续执行...emit事件
此外,类中还定义了多个以 emit 开头的方法,主要用于发送事件以供前端展示或日志记录,示例代码如下:
async def emit_event(self, event_type: str, message: str, **kwargs):
"""
发射事件 - 所有事件的统一入口
Args:
event_type: 事件类型(llm_thought/tool_call/finding_new等)
message: 事件消息
**kwargs: 额外字段(tool_name, metadata等)
"""
if self.event_emitter:
from ..event_manager import AgentEventData
# 🔥 准备 metadata(确保包含 agent_name)
metadata = kwargs.get("metadata", {}) or {}
if "agent_name" not in metadata:
metadata["agent_name"] = self.name
# 🔥 分离已知字段和未知字段
known_fields = {
"phase", "tool_name", "tool_input", "tool_output",
"tool_duration_ms", "finding_id", "tokens_used"
}
event_kwargs = {}
for k, v in kwargs.items():
if k in known_fields:
event_kwargs[k] = v
elif k != "metadata":
# 将未知字段放入 metadata
metadata[k] = v
# 🔥 发射事件到 EventManager
await self.event_emitter.emit(AgentEventData(
event_type=event_type,
message=message,
metadata=metadata,
**event_kwargs
))对于这部分细节,本文不再深入展开。
OrchestratorAgent
Orchestrator Agent作为多Agent系统的大脑,其核心在于System Prompt的设计:
ORCHESTRATOR_SYSTEM_PROMPT = """你是 DeepAudit 的编排 Agent,负责**自主**协调整个安全审计流程。
## 你的角色
你是整个审计流程的**大脑**,不是一个机械执行者。你需要:
1. 自主思考和决策
2. 根据观察结果动态调整策略
3. 决定何时调用哪个子 Agent
4. 判断何时审计完成
## 你可以调度的子 Agent
1. **recon**: 信息收集 Agent - 分析项目结构、技术栈、入口点
2. **analysis**: 分析 Agent - 深度代码审计、漏洞检测
3. **verification**: 验证 Agent - 验证发现的漏洞、生成 PoC
## 你可以使用的操作
### 1. 调度子 Agent
```
Action: dispatch_agent
Action Input: {"agent": "recon|analysis|verification", "task": "具体任务描述", "context": "任务上下文"}
```
### 2. 汇总发现
```
Action: summarize
Action Input: {"findings": [...], "analysis": "你的分析"}
```
### 3. 完成审计
```
Action: finish
Action Input: {"conclusion": "审计结论", "findings": [...], "recommendations": [...]}
```
## 工作方式
每一步,你需要:
1. **Thought**: 分析当前状态,思考下一步应该做什么
- 目前收集到了什么信息?
- 还需要了解什么?
- 应该深入分析哪些地方?
- 有什么发现需要验证?
2. **Action**: 选择一个操作
3. **Action Input**: 提供操作参数
## 输出格式
每一步必须严格按照以下格式:
```
Thought: [你的思考过程]
Action: [dispatch_agent|summarize|finish]
Action Input: [JSON 参数]
```
## 审计策略建议
- 先用 recon Agent 了解项目全貌(只需调度一次)
- 根据 recon 结果,让 analysis Agent 重点审计高风险区域
- 发现可疑漏洞后,用 verification Agent 验证
- 随时根据新发现调整策略,不要机械执行
- 当你认为审计足够全面时,选择 finish
## 重要原则
1. **你是大脑,不是执行器** - 每一步都要思考
2. **动态调整** - 根据发现调整策略
3. **主动决策** - 不要等待,主动推进
4. **质量优先** - 宁可深入分析几个真实漏洞,不要浅尝辄止
5. **避免重复** - 每个 Agent 通常只需要调度一次,如果结果不理想,尝试其他 Agent 或直接完成审计
## 处理子 Agent 结果
- 子 Agent 返回的 Observation 包含它们的分析结果
- 即使结果看起来不完整,也要基于已有信息继续推进
- 不要反复调度同一个 Agent 期望得到不同结果
- 如果 recon 完成后,应该调度 analysis 进行深度分析
- 如果 analysis 完成后有发现,可以调度 verification 验证
- 如果没有更多工作要做,使用 finish 结束审计
现在,基于项目信息开始你的审计工作!"""这段Prompt主要负责向LLM阐述工作目标与职责。
AgentStep
该类用于记录Agent在ReAct循环中的执行步骤:
@dataclass
class AgentStep:
"""执行步骤"""
thought: str # LLM 的思考内容
action: str # LLM 决定的操作
action_input: Dict[str, Any] # 操作参数
observation: Optional[str] = None # 操作执行结果
sub_agent_result: Optional[AgentResult] = None # 子 Agent 返回的完整结果OrchestratorAgent
class OrchestratorAgent(BaseAgent):
def __init__(
self,
llm_service,
tools: Dict[str, Any],
event_emitter=None,
sub_agents: Optional[Dict[str, BaseAgent]] = None,
tracer=None,
):
# 组合增强的系统提示词
full_system_prompt = f"{ORCHESTRATOR_SYSTEM_PROMPT}\n\n{CORE_SECURITY_PRINCIPLES}\n\n{MULTI_AGENT_RULES}"
config = AgentConfig(
name="Orchestrator",
agent_type=AgentType.ORCHESTRATOR,
pattern=AgentPattern.REACT, # ReAct 模式!
max_iterations=20,
system_prompt=full_system_prompt,
)
super().__init__(config, llm_service, tools, event_emitter)
self.sub_agents = sub_agents or {}
self._conversation_history: List[Dict[str, str]] = []
self._steps: List[AgentStep] = []
self._all_findings: List[Dict] = []
# 🔥 Tracer 遥测支持
self.tracer = tracer
# 🔥 存储运行时上下文,用于传递给子 Agent
self._runtime_context: Dict[str, Any] = {}
# 🔥 跟踪已调度的 Agent 任务,避免重复调度
self._dispatched_tasks: Dict[str, int] = {} # agent_name -> dispatch_count
# 🔥 保存各个 Agent 的完整结果,用于传递给后续 Agent
self._agent_results: Dict[str, Dict[str, Any]] = {}首先,代码构建了一个完整的System Prompt。除了前文提及的 ORCHESTRATOR_SYSTEM_PROMPT 外,还整合了以下两部分核心内容:
# 核心安全审计原则
CORE_SECURITY_PRINCIPLES = """
<core_security_principles>
## 代码审计核心原则
### 1. 深度分析优于广度扫描
- 深入分析少数真实漏洞比报告大量误报更有价值
- 每个发现都需要上下文验证
- 理解业务逻辑后才能判断安全影响
### 2. 数据流追踪
- 从用户输入(Source)到危险函数(Sink)
- 识别所有数据处理和验证节点
- 评估过滤和编码的有效性
### 3. 上下文感知分析
- 不要孤立看待代码片段
- 理解函数调用链和模块依赖
- 考虑运行时环境和配置
### 4. 自主决策
- 不要机械执行,要主动思考
- 根据发现动态调整分析策略
- 对工具输出进行专业判断
### 5. 质量优先
- 高置信度发现优于低置信度猜测
- 提供明确的证据和复现步骤
- 给出实际可行的修复建议
</core_security_principles>
"""
# 动态Agent系统规则
MULTI_AGENT_RULES = """
<multi_agent_rules>
## 多Agent协作规则
### Agent层级
1. **Orchestrator** - 编排层,负责调度和协调
2. **Recon** - 侦察层,负责信息收集
3. **Analysis** - 分析层,负责漏洞检测
4. **Verification** - 验证层,负责验证发现
### 通信原则
- 使用结构化的任务交接(TaskHandoff)
- 明确传递上下文和发现
- 避免重复工作
### 子Agent创建
- 每个Agent专注于特定任务
- 使用知识模块增强专业能力
- 最多加载5个知识模块
### 状态管理
- 定期检查消息
- 正确报告完成状态
- 传递结构化结果
### 完成规则
- 子Agent使用 agent_finish
- 根Agent使用 finish_scan
- 确保所有子Agent完成后再结束
</multi_agent_rules>
"""虽然设计理念先进,但仅依赖LLM自主追踪调用链和数据流在实际应用中可能面临挑战。后续我们将关注ToolCall机制如何辅助解决这一问题。
此处定义了几个关键的状态变量:
_all_findings: 收集所有子 Agent 发现的漏洞_dispatched_tasks: 追踪每个 Agent 被调度的次数(防止无限循环)_agent_results: 保存子 Agent 的完整结果,供后续 Agent 使用_runtime_context: 运行时上下文(项目信息、配置等)
下面我们分析核心流程run方法的实现:
async def run(self, input_data: Dict[str, Any]) -> AgentResult:
"""
执行编排任务 - LLM 全程参与!
Args:
input_data: {
"project_info": 项目信息,
"config": 审计配置,
"project_root": 项目根目录,
"task_id": 任务ID,
}
"""
import time
start_time = time.time()
project_info = input_data.get("project_info", {})
config = input_data.get("config", {})
# 🔥 保存运行时上下文,用于传递给子 Agent
self._runtime_context = {
"project_info": project_info,
"config": config,
"project_root": input_data.get("project_root", project_info.get("root", ".")),
"task_id": input_data.get("task_id"),
}
# 构建初始消息
initial_message = self._build_initial_message(project_info, config)
# 初始化对话历史
self._conversation_history = [
{"role": "system", "content": self.config.system_prompt},
{"role": "user", "content": initial_message},
]
self._steps = []
self._all_findings = []
self._agent_results = {}
final_result = None
error_message = None
await self.emit_thinking("🧠 Orchestrator Agent 启动,LLM 开始自主编排决策...")
try:
# 🔥 ReAct 循环 - 最多 20 轮
for iteration in range(self.config.max_iterations):
if self.is_cancelled:
break
self._iteration = iteration + 1
# 🔥 调用 LLM 进行思考和决策(流式输出)
try:
llm_output, tokens_this_round = await self.stream_llm_call(
self._conversation_history,
)
except asyncio.CancelledError:
logger.info(f"[{self.name}] LLM call cancelled")
break
self._total_tokens += tokens_this_round
# 🔥 检测空响应
if not llm_output or not llm_output.strip():
# ... 重试逻辑 ...
continue
# 🔥 解析 LLM 的决策
step = self._parse_llm_response(llm_output)
if not step:
# 格式错误,提示重试
self._conversation_history.append({
"role": "user",
"content": "请按照规定格式输出:Thought + Action + Action Input",
})
continue
self._steps.append(step)
# 🔥 发射 LLM 思考内容事件
if step.thought:
await self.emit_llm_thought(step.thought, iteration + 1)
# 添加 LLM 响应到历史
self._conversation_history.append({
"role": "assistant",
"content": llm_output,
})
# 🔥 执行 LLM 决定的操作
if step.action == "finish":
# LLM 决定完成审计
await self.emit_llm_decision("完成审计", "LLM 判断审计已充分完成")
final_result = step.action_input
break
elif step.action == "dispatch_agent":
# LLM 决定调度子 Agent
agent_name = step.action_input.get("agent", "unknown")
task_desc = step.action_input.get("task", "")
await self.emit_llm_decision(
f"调度 {agent_name} Agent",
f"任务: {task_desc[:100]}"
)
observation = await self._dispatch_agent(step.action_input)
step.observation = observation
# 🔥 发射观察事件
await self.emit_llm_observation(observation)
elif step.action == "summarize":
# LLM 要求汇总
observation = self._summarize_findings()
step.observation = observation
await self.emit_llm_observation(observation)
# 添加观察结果到历史
self._conversation_history.append({
"role": "user",
"content": f"Observation:\n{step.observation}",
})
# 生成最终结果
duration_ms = int((time.time() - start_time) * 1000)
# 🔥 CRITICAL: Log final findings count
logger.info(f"[Orchestrator] Final result: {len(self._all_findings)} findings collected")
return AgentResult(
success=True,
data={
"findings": self._all_findings,
"summary": final_result or self._generate_default_summary(),
"steps": [...],
},
iterations=self._iteration,
tool_calls=self._tool_calls,
tokens_used=self._total_tokens,
duration_ms=duration_ms,
)
except Exception as e:
logger.error(f"Orchestrator failed: {e}", exc_info=True)
return AgentResult(success=False, error=str(e))其整体执行流程如下:
启动
↓
构建初始消息(项目信息 + 配置)
↓
┌─────────────────────────────────┐
│ ReAct 循环 (最多 20 轮) │
│ │
│ 1. 调用 LLM (流式输出) │
│ ↓ │
│ 2. 解析 LLM 输出 │
│ - Thought │
│ - Action │
│ - Action Input │
│ ↓ │
│ 3. 执行操作 │
│ - dispatch_agent │
│ - summarize │
│ - finish │
│ ↓ │
│ 4. 获取 Observation │
│ ↓ │
│ 5. 添加到对话历史 │
│ ↓ │
│ 6. 回到步骤 1 │
│ │
└─────────────────────────────────┘
↓
返回 AgentResult (包含所有发现)此处体现了一个核心设计思想:Agent的调度时机完全由LLM自主决策:
# LLM 每轮输出:
step = self._parse_llm_response(llm_output)
if step.action == "dispatch_agent":
# LLM 自己决定调度哪个 Agent
observation = await self._dispatch_agent(step.action_input)接下来,我们查看相关辅助函数的具体实现:
def _build_initial_message(
self,
project_info: Dict[str, Any],
config: Dict[str, Any],
) -> str:
"""构建初始消息"""
structure = project_info.get('structure', {})
# 🔥 检查是否是限定范围的审计
scope_limited = structure.get('scope_limited', False)
scope_message = structure.get('scope_message', '')
msg = f"""请开始对以下项目进行安全审计。
## 项目信息
- 名称: {project_info.get('name', 'unknown')}
- 语言: {project_info.get('languages', [])}
- 文件数量: {project_info.get('file_count', 0)}
"""
# 🔥 根据是否限定范围显示不同的结构信息
if scope_limited:
msg += f"""
## ⚠️ 审计范围限定
**{scope_message}**
### 目标文件列表
"""
for f in structure.get('files', []):
msg += f"- {f}\n"
else:
msg += f"""
## 目录结构
{json.dumps(structure, ensure_ascii=False, indent=2)}
"""
# 🔥 如果配置了 target_files,明确显示
target_files = config.get('target_files', [])
if target_files:
msg += f"""
## ⚠️ 重要提示
用户指定了 **{len(target_files)}** 个目标文件进行审计。
请确保你的分析集中在这些指定的文件上。
"""
msg += f"""
## 用户配置
- 目标漏洞: {config.get('target_vulnerabilities', ['all'])}
- 验证级别: {config.get('verification_level', 'sandbox')}
## 可用子 Agent
{', '.join(self.sub_agents.keys())}
请开始你的审计工作。首先思考应该如何开展,然后决定第一步做什么。"""
return msg其主要功能是拼接初始Prompt,构建后的Prompt示例如下:
请开始对以下项目进行安全审计。
## 项目信息
- 名称: vulnerable-app
- 语言: ['Python']
- 文件数量: 45
## 目录结构
{
"directories": ["app", "app/api", "app/models", "app/utils"],
"key_files": ["app/main.py", "app/api/routes.py", "app/models/user.py"]
}
## 用户配置
- 目标漏洞: ['sql_injection', 'xss', 'command_injection']
- 验证级别: sandbox
## 可用子 Agent
recon, analysis, verification
请开始你的审计工作。首先思考应该如何开展,然后决定第一步做什么。_parse_llm_response():
该方法主要用于解析LLM的输出并格式化:
def _parse_llm_response(self, response: str) -> Optional[AgentStep]:
"""解析 LLM 响应"""
# 🔥 预处理 - 移除 Markdown 格式标记
cleaned_response = response
cleaned_response = re.sub(r'\*\*Action:\*\*', 'Action:', cleaned_response)
cleaned_response = re.sub(r'\*\*Action Input:\*\*', 'Action Input:', cleaned_response)
cleaned_response = re.sub(r'\*\*Thought:\*\*', 'Thought:', cleaned_response)
# 提取 Thought
thought_match = re.search(r'Thought:\s*(.*?)(?=Action:|$)', cleaned_response, re.DOTALL)
thought = thought_match.group(1).strip() if thought_match else ""
# 提取 Action
action_match = re.search(r'Action:\s*(\w+)', cleaned_response)
if not action_match:
return None
action = action_match.group(1).strip()
# 提取 Action Input
input_match = re.search(r'Action Input:\s*(.*?)(?=Thought:|Observation:|$)', cleaned_response, re.DOTALL)
if not input_match:
return None
input_text = input_match.group(1).strip()
# 移除 markdown 代码块
input_text = re.sub(r'```json\s*', '', input_text)
input_text = re.sub(r'```\s*', '', input_text)
# 使用增强的 JSON 解析器
action_input = AgentJsonParser.parse(
input_text,
default={"raw": input_text}
)
return AgentStep(
thought=thought,
action=action,
action_input=action_input,
)_dispatch_agent():
该方法主要负责子Agent的调度执行。
async def _dispatch_agent(self, params: Dict[str, Any]) -> str:
"""调度子 Agent"""
agent_name = params.get("agent", "")
task = params.get("task", "")
context = params.get("context", "")
# 🔥 尝试大小写不敏感匹配
agent = self.sub_agents.get(agent_name)
if not agent:
agent_name_lower = agent_name.lower()
agent = self.sub_agents.get(agent_name_lower)
if agent:
agent_name = agent_name_lower
if not agent:
available = list(self.sub_agents.keys())
return f"错误: Agent '{agent_name}' 不存在。可用的 Agent: {available}"
# 🔥 检查是否重复调度同一个 Agent
dispatch_count = self._dispatched_tasks.get(agent_name, 0)
if dispatch_count >= 2:
return f"""## ⚠️ 重复调度警告
你已经调度 {agent_name} Agent {dispatch_count} 次了。
如果之前的调度没有返回有用的结果,请考虑:
1. 尝试调度其他 Agent(如 analysis 或 verification)
2. 使用 finish 操作结束审计并汇总已有发现
当前已收集的发现数量: {len(self._all_findings)}
"""
self._dispatched_tasks[agent_name] = dispatch_count + 1
# 🔥 设置父 Agent ID 并注册到注册表(动态 Agent 树)
agent.set_parent_id(self._agent_id)
agent._register_to_registry(task=task)
await self.emit_event(
"dispatch",
f"📤 调度 {agent_name} Agent: {task[:100]}...",
agent=agent_name,
task=task,
)
self._tool_calls += 1
try:
# 🔥 构建子 Agent 输入 - 传递完整的运行时上下文
project_info = self._runtime_context.get("project_info", {}).copy()
if "root" not in project_info:
project_info["root"] = self._runtime_context.get("project_root", ".")
# 🔥 构建完整的 previous_results,包含所有已执行 Agent 的结果
previous_results = {
"findings": self._all_findings,
}
# 将之前 Agent 的完整结果传递给后续 Agent
for prev_agent, prev_data in self._agent_results.items():
previous_results[prev_agent] = {"data": prev_data}
sub_input = {
"task": task,
"task_context": context,
"project_info": project_info,
"config": self._runtime_context.get("config", {}),
"project_root": self._runtime_context.get("project_root", "."),
"previous_results": previous_results,
}
# 🔥 执行子 Agent - 支持取消和超时
agent_timeouts = {
"recon": 300, # 5 分钟
"analysis": 600, # 10 分钟
"verification": 600, # 10 分钟
}
timeout = agent_timeouts.get(agent_name, 300)
# 包装执行,定期检查取消状态
async def run_with_cancel_check():
run_task = asyncio.create_task(agent.run(sub_input))
try:
while not run_task.done():
if self.is_cancelled:
# 传播取消到子 Agent
if hasattr(agent, 'cancel'):
agent.cancel()
run_task.cancel()
raise asyncio.CancelledError("任务已取消")
done, pending = await asyncio.wait(
[run_task],
timeout=0.5,
return_when=asyncio.FIRST_COMPLETED
)
if run_task in done:
return run_task.result()
return await run_task
except asyncio.CancelledError:
if not run_task.done():
if hasattr(agent, 'cancel'):
agent.cancel()
run_task.cancel()
raise
try:
result = await asyncio.wait_for(
run_with_cancel_check(),
timeout=timeout
)
except asyncio.TimeoutError:
return f"## {agent_name} Agent 执行超时\n\n子 Agent 执行超过 {timeout} 秒,已强制终止。"
except asyncio.CancelledError:
return f"## {agent_name} Agent 执行取消\n\n任务已被用户取消"
# 🔥 处理子 Agent 结果
logger.info(f"[Orchestrator] Processing {agent_name} result: success={result.success}")
if result.success and result.data:
data = result.data
# 🔥 保存 Agent 的完整结果,供后续 Agent 使用
self._agent_results[agent_name] = data
# 🔥 收集发现 - 支持多种字段名
raw_findings = data.get("findings", [])
logger.info(f"[Orchestrator] {agent_name} returned {len(raw_findings)} findings")
# 🔥 也检查 initial_findings(来自 Recon)
if "initial_findings" in data:
initial = data.get("initial_findings", [])
for f in initial:
if isinstance(f, dict):
normalized = self._normalize_finding(f)
if normalized not in raw_findings:
raw_findings.append(normalized)
# 🔥 标准化并添加到全局发现列表
for finding in raw_findings:
if isinstance(finding, dict):
standardized = self._normalize_finding(finding)
self._all_findings.append(standardized)
logger.info(f"[Orchestrator] Total findings after {agent_name}: {len(self._all_findings)}")
# 🔥 构建 Observation 返回给 LLM
observation = f"""## {agent_name.capitalize()} Agent 执行完成
### 执行统计
- 迭代次数: {result.iterations}
- 工具调用: {result.tool_calls}
- Token 消耗: {result.tokens_used}
### 发现摘要
发现 {len(raw_findings)} 个问题
"""
# 列出前 10 个发现
for i, finding in enumerate(raw_findings[:10], 1):
severity = finding.get("severity", "medium")
title = finding.get("title", "Unknown")
observation += f"\n{i}. [{severity.upper()}] {title}"
return observation
else:
# 子 Agent 执行失败
return f"## {agent_name} Agent 执行失败\n\n错误: {result.error}"
except Exception as e:
logger.error(f"Failed to dispatch {agent_name}: {e}", exc_info=True)
return f"## {agent_name} Agent 执行异常\n\n{str(e)}"其调度流程大致如下所示:
LLM 决策: "调度 recon Agent"
↓
检查 Agent 是否存在
↓
检查是否重复调度(> 2 次)
↓
设置 parent_id 并注册到 Agent 树
↓
构建 sub_input
- task
- project_info
- config
- previous_results (包含之前所有 Agent 的结果)
↓
执行子 Agent (带超时和取消支持)
↓
处理结果
- 收集 findings
- 保存到 _agent_results
- 添加到 _all_findings
↓
构建 Observation 返回给 LLM
↓
LLM 收到 Observation,决定下一步此处似乎存在设计上的不一致。尽管前文定义了 TaskHandoff 用于Agent间的消息传递,但在实际代码中并未使用相关数据结构。这可能是受限于项目开发阶段或受其他项目(如Vibe)影响。不过,系统采用了另一种有效的消息传递方式,因此整体功能未受明显影响。
_normalize_finding
该方法用于将漏洞发现数据标准化为统一格式,代码如下:
def _normalize_finding(self, finding: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""
标准化发现格式
不同 Agent 可能返回不同格式的发现,这个方法将它们标准化为统一格式
🔥 v2.1: 添加文件路径验证,返回 None 表示发现无效(幻觉)
"""
normalized = dict(finding) # 复制原始数据
# 🔥 处理 location 字段 -> file_path + line_start
if "location" in normalized and "file_path" not in normalized:
location = normalized["location"]
if isinstance(location, str) and ":" in location:
parts = location.split(":")
normalized["file_path"] = parts[0]
try:
normalized["line_start"] = int(parts[1])
except (ValueError, IndexError):
pass
elif isinstance(location, str):
normalized["file_path"] = location
# 🔥 处理 file 字段 -> file_path
if "file" in normalized and "file_path" not in normalized:
normalized["file_path"] = normalized["file"]
# 🔥 处理 line 字段 -> line_start
if "line" in normalized and "line_start" not in normalized:
normalized["line_start"] = normalized["line"]
# 🔥 处理 type 字段 -> vulnerability_type
if "type" in normalized and "vulnerability_type" not in normalized:
# 不是所有 type 都是漏洞类型,比如 "Vulnerability" 只是标记
type_val = normalized["type"]
if type_val and type_val.lower() not in ["vulnerability", "finding", "issue"]:
normalized["vulnerability_type"] = type_val
elif "description" in normalized:
# 尝试从描述中推断漏洞类型
desc = normalized["description"].lower()
if "command injection" in desc or "rce" in desc or "system(" in desc:
normalized["vulnerability_type"] = "command_injection"
elif "sql injection" in desc or "sqli" in desc:
normalized["vulnerability_type"] = "sql_injection"
elif "xss" in desc or "cross-site scripting" in desc:
normalized["vulnerability_type"] = "xss"
elif "path traversal" in desc or "directory traversal" in desc:
normalized["vulnerability_type"] = "path_traversal"
elif "ssrf" in desc:
normalized["vulnerability_type"] = "ssrf"
elif "xxe" in desc:
normalized["vulnerability_type"] = "xxe"
else:
normalized["vulnerability_type"] = "other"
# 🔥 确保 severity 字段存在且为小写
if "severity" in normalized:
normalized["severity"] = str(normalized["severity"]).lower()
else:
normalized["severity"] = "medium"
# 🔥 处理 risk 字段 -> severity
if "risk" in normalized and "severity" not in normalized:
normalized["severity"] = str(normalized["risk"]).lower()
# 🔥 生成 title 如果不存在
if "title" not in normalized:
vuln_type = normalized.get("vulnerability_type", "Unknown")
file_path = normalized.get("file_path", "")
if file_path:
import os
normalized["title"] = f"{vuln_type.replace('_', ' ').title()} in {os.path.basename(file_path)}"
else:
normalized["title"] = f"{vuln_type.replace('_', ' ').title()} Vulnerability"
# 🔥 处理 code 字段 -> code_snippet
if "code" in normalized and "code_snippet" not in normalized:
normalized["code_snippet"] = normalized["code"]
# 🔥 处理 recommendation -> suggestion
if "recommendation" in normalized and "suggestion" not in normalized:
normalized["suggestion"] = normalized["recommendation"]
# 🔥 处理 impact -> 添加到 description
if "impact" in normalized and normalized.get("description"):
if "impact" not in normalized["description"].lower():
normalized["description"] += f"\n\nImpact: {normalized['impact']}"
# 🔥 v2.1: 验证文件路径存在性
file_path = normalized.get("file_path", "")
if file_path and not self._validate_file_path(file_path):
logger.warning(
f"[Orchestrator] 🚫 过滤幻觉发现: 文件不存在 '{file_path}' "
f"(title: {normalized.get('title', 'N/A')[:50]})"
)
return None # 返回 None 表示发现无效
return normalizedReconAgent
ReconAgent的主要职责包括:分析项目结构、识别技术栈与框架、定位关键入口点以及标记高风险区域。
以下是其核心System Prompt。值得注意的是,相比其他Agent,此处对输出格式的描述较为宽泛,其能在实际运行中发挥多大效用有待验证:
RECON_SYSTEM_PROMPT = """你是 DeepAudit 的侦察 Agent,负责收集和分析项目信息。
## 你的职责
作为侦察层,你负责:
1. 分析项目结构和技术栈
2. 识别关键入口点
3. 发现配置文件和敏感区域
4. **推荐需要使用的外部安全工具**
5. 提供初步风险评估
## 侦察目标
### 1. 技术栈识别(用于选择外部工具)
- 编程语言和版本
- Web框架(Django, Flask, FastAPI, Express等)
- 数据库类型
- 前端框架
- **根据技术栈推荐外部工具:**
- Python项目 → bandit_scan, safety_scan
- Node.js项目 → npm_audit
- 所有项目 → semgrep_scan, gitleaks_scan
- 大型项目 → kunlun_scan, osv_scan
### 2. 入口点发现
- HTTP路由和API端点
- Websocket处理
- 定时任务和后台作业
- 消息队列消费者
### 3. 敏感区域定位
- 认证和授权代码
- 数据库操作
- 文件处理
- 外部服务调用
### 4. 配置分析
- 安全配置
- 调试设置
- 密钥管理
## 工作方式
每一步,你需要输出:
```
Thought: [分析当前情况,思考需要收集什么信息]
Action: [工具名称]
Action Input: {"参数1": "值1"}
```
当你完成信息收集后,输出:
```
Thought: [总结收集到的所有信息]
Final Answer: [JSON 格式的结果]
```
## ⚠️ 输出格式要求(严格遵守)
**禁止使用 Markdown 格式标记!** 你的输出必须是纯文本格式:
✅ 正确格式:
```
Thought: 我需要查看项目结构来了解项目组成
Action: list_files
Action Input: {"directory": "."}
```
❌ 错误格式(禁止使用):
```
**Thought:** 我需要查看项目结构
**Action:** list_files
**Action Input:** {"directory": "."}
```
规则:
1. 不要在 Thought:、Action:、Action Input:、Final Answer: 前后添加 `**`
2. 不要使用其他 Markdown 格式(如 `###`、`*斜体*` 等)
3. Action Input 必须是完整的 JSON 对象,不能为空或截断
## 输出格式
```
Final Answer: {
"project_structure": {...},
"tech_stack": {
"languages": [...],
"frameworks": [...],
"databases": [...]
},
"recommended_tools": {
"must_use": ["semgrep_scan", "gitleaks_scan", ...],
"recommended": ["kunlun_scan", ...],
"reason": "基于项目技术栈的推荐理由"
},
"entry_points": [
{"type": "...", "file": "...", "line": ..., "method": "..."}
],
"high_risk_areas": [
"文件路径:行号 - 风险描述"
],
"initial_findings": [
{"title": "...", "file_path": "...", "line_start": ..., "description": "..."}
],
"summary": "项目侦察总结"
}
```
## ⚠️ 重要输出要求
### recommended_tools 格式要求
**必须**根据项目技术栈推荐外部工具:
- `must_use`: 必须使用的工具列表
- `recommended`: 推荐使用的工具列表
- `reason`: 推荐理由
### high_risk_areas 格式要求
每个高风险区域**必须**包含具体的文件路径,格式为:
- `"app.py:36 - SECRET_KEY 硬编码"`
- `"utils/file.py:120 - 使用用户输入构造文件路径"`
- `"api/views.py:45 - SQL 查询使用字符串拼接"`
**禁止**输出纯描述性文本如 "File write operations with user-controlled paths",必须指明具体文件。
### initial_findings 格式要求
每个发现**必须**包含:
- `title`: 漏洞标题
- `file_path`: 具体文件路径
- `line_start`: 行号
- `description`: 详细描述
## 🚨 防止幻觉(关键!)
**只报告你实际读取过的文件!**
1. **file_path 必须来自实际工具调用结果**
- 只使用 list_files 返回的文件列表中的路径
- 只使用 read_file 成功读取的文件路径
- 不要"猜测"典型的项目结构(如 app.py, config.py)
2. **行号必须来自实际代码**
- 只使用 read_file 返回内容中的真实行号
- 不要编造行号
3. **禁止套用模板**
- 不要因为是 "Python 项目" 就假设存在 requirements.txt
- 不要因为是 "Web 项目" 就假设存在 routes.py 或 views.py
❌ 错误做法:
```
list_files 返回: ["main.rs", "lib.rs", "Cargo.toml"]
high_risk_areas: ["app.py:36 - 存在安全问题"] <- 这是幻觉!项目根本没有 app.py
```
✅ 正确做法:
```
list_files 返回: ["main.rs", "lib.rs", "Cargo.toml"]
high_risk_areas: ["main.rs:xx - 可能存在问题"] <- 必须使用实际存在的文件
```
## ⚠️ 关键约束 - 必须遵守!
1. **禁止直接输出 Final Answer** - 你必须先调用工具来收集项目信息
2. **至少调用三个工具** - 使用 rag_query 语义搜索关键入口,read_file 读取文件,list_files 仅查看根目录
3. **没有工具调用的侦察无效** - 不允许仅凭项目名称直接推测
4. **先 Action 后 Final Answer** - 必须先执行工具,获取 Observation,再输出最终结论
错误示例(禁止):
```
Thought: 这是一个 PHP 项目,可能存在安全问题
Final Answer: {...} ❌ 没有调用任何工具!
```
正确示例(必须):
```
Thought: 我需要先查看项目结构来了解项目组成
Action: rag_query
Action Input: {"query": "项目的入口点和路由定义在哪里?", "top_k": 5}
```
**或者**仅查看根目录结构:
```
Thought: 我需要先查看项目根目录结构
Action: list_files
Action Input: {"directory": "."}
```
然后等待 Observation,再继续收集信息或输出 Final Answer。
"""ReconStep
定义了信息收集步骤的数据结构:
@dataclass
class ReconStep:
"""信息收集步骤"""
thought: str
action: Optional[str] = None
action_input: Optional[Dict] = None
observation: Optional[str] = None
is_final: bool = False
final_answer: Optional[Dict] = NoneReconAgent
初始化逻辑如下所示:
def __init__(
self,
llm_service,
tools: Dict[str, Any],
event_emitter=None,
):
# 组合增强的系统提示词
full_system_prompt = f"{RECON_SYSTEM_PROMPT}\n\n{TOOL_USAGE_GUIDE}"
config = AgentConfig(
name="Recon",
agent_type=AgentType.RECON,
pattern=AgentPattern.REACT,
max_iterations=15,
system_prompt=full_system_prompt,
)
super().__init__(config, llm_service, tools, event_emitter)
self._conversation_history: List[Dict[str, str]] = []
self._steps: List[ReconStep] = []此处引入了另一个核心Prompt:
TOOL_USAGE_GUIDE = """
<tool_usage_guide>
## 工具使用指南
### ⚠️ 核心原则:优先使用外部专业工具
**外部工具优先级最高!** 外部安全工具(Semgrep、Bandit、Gitleaks、Kunlun-M 等)是经过业界验证的专业工具,具有:
- 更全面的规则库和漏洞检测能力
- 更低的误报率
- 更专业的安全分析算法
- 持续更新的安全规则
**必须优先调用外部工具,而非依赖内置的模式匹配!**
### 🔧 工具优先级(从高到低)
#### 第一优先级:外部专业安全工具 ⭐⭐⭐
| 工具 | 用途 | 何时使用 |
|------|------|---------|
| `semgrep_scan` | 多语言静态分析 | **每次分析必用**,支持30+语言,OWASP规则 |
| bandit_scan | Python安全扫描 | Python项目必用,检测注入/反序列化等 |
| gitleaks_scan | 密钥泄露检测 | 每次分析必用,检测150+种密钥类型 |
| kunlun_scan | 深度代码审计 | 大型项目推荐,支持PHP/Java/JS深度分析 |
| npm_audit | Node.js依赖漏洞 | package.json项目必用 |
| safety_scan | Python依赖漏洞 | requirements.txt项目必用 |
| osv_scan | 开源漏洞扫描 | 多语言依赖检查 |
| trufflehog_scan | 深度密钥扫描 | 需要验证密钥有效性时使用 |
#### 第二优先级:智能扫描工具 ⭐⭐
| 工具 | 用途 |
|------|------|
| `smart_scan` | 综合智能扫描,快速定位高风险区域 |
| `quick_audit` | 快速审计模式 |
#### 第三优先级:内置分析工具 ⭐
| 工具 | 用途 |
|------|------|
| `pattern_match` | 正则模式匹配(外部工具不可用时的备选) |
| `dataflow_analysis` | 数据流追踪验证 |
| `code_analysis` | 代码结构分析 |
#### 辅助工具(RAG 优先!)
| 工具 | 用途 |
|------|------|
| `rag_query` | 🔥 首选代码搜索工具 - 语义搜索,查找业务逻辑和漏洞上下文 |
| `security_search` | 🔥 首选安全搜索工具 - 查找特定的安全敏感代码模式 |
| `function_context` | 🔥 理解代码结构 - 获取函数调用关系和定义 |
| `read_file` | 读取文件内容验证发现 |
| `list_files` | ⚠️ 仅用于了解根目录结构,严禁用于遍历代码查找内容 |
| `search_code` | ⚠️ 仅用于查找非常具体的字符串常量,严禁作为主要代码搜索手段 |
| `query_security_knowledge` | 查询安全知识库 |
### 🔍 代码搜索工具对比
| 工具 | 特点 | 适用场景 |
|------|------|---------|
| `rag_query` | 🔥 语义搜索,理解代码含义 | **首选!** 查找"处理用户输入的函数"、"数据库查询逻辑" |
| `security_search` | 🔥 安全专用搜索 | **首选!** 查找"SQL注入相关代码"、"认证授权代码" |
| `function_context` | 🔥 函数上下文 | 查找某函数的调用者和被调用者 |
| `search_code` | ❌ 关键词搜索,仅精确匹配 | **不推荐**,仅用于查找确定的常量或变量名 |
**❌ 严禁行为**:
1. **不要** 使用 `list_files` 递归列出所有文件来查找代码
2. **不要** 使用 `search_code` 搜索通用关键词(如 "function", "user"),这会产生大量无用结果
**✅ 推荐行为**:
1. **始终优先使用 RAG 工具** (`rag_query`, `security_search`)
2. `rag_query` 可以理解自然语言,如 "Show me the login function"
3. 仅在确实需要精确匹配特定字符串时才使用 `search_code`
### 📋 推荐分析流程
#### 第一步:快速侦察(5%时间)
```
```
Action: list_files
Action Input: {"directory": ".", "max_depth": 2}
```
了解项目根目录结构(不要遍历全项目)
**🔥 RAG 搜索关键逻辑(RAG 优先!):**
```
Action: rag_query
Action Input: {"query": "用户的登录认证逻辑在哪里?", "top_k": 5}
```
#### 第二步:外部工具全面扫描(60%时间)⚡重点!
**根据技术栈选择对应工具,并行执行多个扫描:**
```
# 通用项目(必做)
Action: semgrep_scan
Action Input: {"target_path": ".", "rules": "p/security-audit"}
Action: gitleaks_scan
Action Input: {"target_path": "."}
# Python项目(必做)
Action: bandit_scan
Action Input: {"target_path": ".", "severity": "medium"}
Action: safety_scan
Action Input: {"requirements_file": "requirements.txt"}
# Node.js项目(必做)
Action: npm_audit
Action Input: {"target_path": "."}
# 大型项目(推荐)
Action: kunlun_scan
Action Input: {"target_path": ".", "rules": "all"}
```
#### 第三步:深度分析(25%时间)
对外部工具发现的问题进行深入分析:
- 使用 `read_file` 查看完整上下文
- 使用 `dataflow_analysis` 追踪数据流
- 验证是否为真实漏洞
#### 第四步:验证和报告(10%时间)
- 确认漏洞可利用性
- 评估影响范围
- 生成修复建议
### ⚠️ 重要提醒
1. **不要跳过外部工具!** 即使内置模式匹配可能更快,外部工具的检测能力更强
2. **并行执行**:可以同时调用多个不相关的外部工具以提高效率
3. **Docker依赖**:外部工具需要Docker环境,如果Docker不可用,再回退到内置工具
4. **结果整合**:综合多个工具的结果,交叉验证提高准确性
### 工具调用格式
```
Action: 工具名称
Action Input: {"参数1": "值1", "参数2": "值2"}
```
### 错误处理指南
当工具执行返回错误时,你会收到详细的错误信息,包括:
- 工具名称和参数
- 错误类型和错误信息
- 堆栈跟踪(如有)
**错误处理策略**:
1. **参数错误** - 检查并修正参数格式
- 确保 JSON 格式正确
- 检查必填参数是否提供
- 验证参数类型(字符串、数字、列表等)
2. **资源不存在** - 调整目标
- 文件不存在:使用 list_files 确认路径
- 工具不可用:使用其他替代工具
3. **权限/超时错误** - 跳过或简化
- 记录问题,继续其他分析
- 尝试更小范围的操作
4. **沙箱错误** - 检查环境
- Docker 不可用时使用代码分析替代
- 记录无法验证的原因
**重要**:遇到错误时,不要放弃!分析错误原因,尝试其他方法完成任务。
### 完成输出格式
```
Final Answer: {
"findings": [...],
"summary": "分析总结"
}
```
</tool_usage_guide>
"""上述工具列表中,rag_query 涉及到了RAG搜索逻辑,这部分内容我们将在后续的RAG章节中深入探讨。
接下来是 run 方法,其核心逻辑在于调用LLM。从代码篇幅来看,大量的代码被用于处理LLM的鲁棒性,以确保执行的稳定性。
async def run(self, input_data: Dict[str, Any]) -> AgentResult:
"""
执行信息收集 - LLM 全程参与!
"""
import time
start_time = time.time()
project_info = input_data.get("project_info", {})
config = input_data.get("config", {})
task = input_data.get("task", "")
task_context = input_data.get("task_context", "")
# 🔥 获取目标文件列表
target_files = config.get("target_files", [])
exclude_patterns = config.get("exclude_patterns", [])
# 构建初始消息
initial_message = f"""请开始收集项目信息。
## 项目基本信息
- 名称: {project_info.get('name', 'unknown')}
- 根目录: {project_info.get('root', '.')}
- 文件数量: {project_info.get('file_count', 'unknown')}
## 审计范围
"""
# 🔥 如果指定了目标文件,明确告知 Agent
if target_files:
initial_message += f"""⚠️ **重要**: 用户指定了 {len(target_files)} 个目标文件进行审计:
"""
for tf in target_files[:10]:
initial_message += f"- {tf}\n"
if len(target_files) > 10:
initial_message += f"- ... 还有 {len(target_files) - 10} 个文件\n"
initial_message += """
请直接读取和分析这些指定的文件,不要浪费时间遍历其他目录。
"""
else:
initial_message += "全项目审计(无特定文件限制)\n"
if exclude_patterns:
initial_message += f"\n排除模式: {', '.join(exclude_patterns[:5])}\n"
initial_message += f"""
## 任务上下文
{task_context or task or '进行全面的信息收集,为安全审计做准备。'}
## 可用工具
{self.get_tools_description()}
请开始你的信息收集工作。首先思考应该收集什么信息,然后**立即**选择合适的工具执行(输出 Action)。不要只输出 Thought,必须紧接着输出 Action。"""
# 初始化对话历史
self._conversation_history = [
{"role": "system", "content": self.config.system_prompt},
{"role": "user", "content": initial_message},
]
self._steps = []
final_result = None
error_message = None # 🔥 跟踪错误信息
await self.emit_thinking("Recon Agent 启动,LLM 开始自主收集信息...")
try:
for iteration in range(self.config.max_iterations):
if self.is_cancelled:
break
self._iteration = iteration + 1
# 🔥 再次检查取消标志(在LLM调用之前)
if self.is_cancelled:
await self.emit_thinking("🛑 任务已取消,停止执行")
break
# 调用 LLM 进行思考和决策(使用基类统一方法)
try:
llm_output, tokens_this_round = await self.stream_llm_call(
self._conversation_history,
# 🔥 不传递 temperature 和 max_tokens,使用用户配置
)
except asyncio.CancelledError:
logger.info(f"[{self.name}] LLM call cancelled")
break
self._total_tokens += tokens_this_round
# 🔥 Enhanced: Handle empty LLM response with better diagnostics
if not llm_output or not llm_output.strip():
empty_retry_count = getattr(self, '_empty_retry_count', 0) + 1
self._empty_retry_count = empty_retry_count
# 🔥 记录更详细的诊断信息
logger.warning(
f"[{self.name}] Empty LLM response in iteration {self._iteration} "
f"(retry {empty_retry_count}/3, tokens_this_round={tokens_this_round})"
)
if empty_retry_count >= 3:
logger.error(f"[{self.name}] Too many empty responses, generating fallback result")
error_message = "连续收到空响应,使用回退结果"
await self.emit_event("warning", error_message)
# 🔥 不是直接 break,而是尝试生成一个回退结果
break
# 🔥 更有针对性的重试提示
retry_prompt = f"""收到空响应。请根据以下格式输出你的思考和行动:
Thought: [你对当前情况的分析]
Action: [工具名称,如 list_files, read_file, search_code]
Action Input: {{"参数名": "参数值"}}
可用工具: {', '.join(self.tools.keys())}
如果你认为信息收集已经完成,请输出:
Thought: [总结收集到的信息]
Final Answer: [JSON格式的结果]"""
self._conversation_history.append({
"role": "user",
"content": retry_prompt,
})
continue
# 重置空响应计数器
self._empty_retry_count = 0
# 解析 LLM 响应
step = self._parse_llm_response(llm_output)
self._steps.append(step)
# 🔥 发射 LLM 思考内容事件 - 展示 LLM 在想什么
if step.thought:
await self.emit_llm_thought(step.thought, iteration + 1)
# 添加 LLM 响应到历史
self._conversation_history.append({
"role": "assistant",
"content": llm_output,
})
# 检查是否完成
if step.is_final:
await self.emit_llm_decision("完成信息收集", "LLM 判断已收集足够信息")
await self.emit_llm_complete(
f"信息收集完成,共 {self._iteration} 轮思考",
self._total_tokens
)
final_result = step.final_answer
break
# 执行工具
if step.action:
# 🔥 发射 LLM 动作决策事件
await self.emit_llm_action(step.action, step.action_input or {})
# 🔥 循环检测:追踪工具调用失败历史
tool_call_key = f"{step.action}:{json.dumps(step.action_input or {}, sort_keys=True)}"
if not hasattr(self, '_failed_tool_calls'):
self._failed_tool_calls = {}
observation = await self.execute_tool(
step.action,
step.action_input or {}
)
# 🔥 检测工具调用失败并追踪
is_tool_error = (
"失败" in observation or
"错误" in observation or
"不存在" in observation or
"文件过大" in observation or
"Error" in observation
)
if is_tool_error:
self._failed_tool_calls[tool_call_key] = self._failed_tool_calls.get(tool_call_key, 0) + 1
fail_count = self._failed_tool_calls[tool_call_key]
# 🔥 如果同一调用连续失败3次,添加强制跳过提示
if fail_count >= 3:
logger.warning(f"[{self.name}] Tool call failed {fail_count} times: {tool_call_key}")
observation += f"\n\n⚠️ **系统提示**: 此工具调用已连续失败 {fail_count} 次。请:\n"
observation += "1. 尝试使用不同的参数(如指定较小的行范围)\n"
observation += "2. 使用 search_code 工具定位关键代码片段\n"
observation += "3. 跳过此文件,继续分析其他文件\n"
observation += "4. 如果已有足够信息,直接输出 Final Answer"
# 重置计数器但保留记录
self._failed_tool_calls[tool_call_key] = 0
else:
# 成功调用,重置失败计数
if tool_call_key in self._failed_tool_calls:
del self._failed_tool_calls[tool_call_key]
# 🔥 工具执行后检查取消状态
if self.is_cancelled:
logger.info(f"[{self.name}] Cancelled after tool execution")
break
step.observation = observation
# 🔥 发射 LLM 观察事件
await self.emit_llm_observation(observation)
# 添加观察结果到历史
self._conversation_history.append({
"role": "user",
"content": f"Observation:\n{observation}",
})
else:
# LLM 没有选择工具,提示它继续
await self.emit_llm_decision("继续思考", "LLM 需要更多信息")
self._conversation_history.append({
"role": "user",
"content": "请继续。你输出了 Thought 但没有输出 Action。请**立即**选择一个工具执行(Action: ...),或者如果信息收集完成,输出 Final Answer。",
})
# 🔥 如果循环结束但没有 final_result,强制 LLM 总结
if not final_result and not self.is_cancelled and not error_message:
await self.emit_thinking("📝 信息收集阶段结束,正在生成总结...")
# 添加强制总结的提示
self._conversation_history.append({
"role": "user",
"content": """信息收集阶段已结束。请立即输出 Final Answer,总结你收集到的所有信息。
请按以下 JSON 格式输出:
```json
{
"project_structure": {"directories": [...], "key_files": [...]},
"tech_stack": {"languages": [...], "frameworks": [...], "databases": [...]},
"entry_points": [{"type": "...", "file": "...", "description": "..."}],
"high_risk_areas": ["file1.py", "file2.js"],
"initial_findings": [{"title": "...", "description": "...", "file_path": "..."}],
"summary": "项目总结描述"
}
```
Final Answer:""",
})
try:
summary_output, _ = await self.stream_llm_call(
self._conversation_history,
# 🔥 不传递 temperature 和 max_tokens,使用用户配置
)
if summary_output and summary_output.strip():
# 解析总结输出
summary_text = summary_output.strip()
summary_text = re.sub(r'```json\s*', '', summary_text)
summary_text = re.sub(r'```\s*', '', summary_text)
final_result = AgentJsonParser.parse(
summary_text,
default=self._summarize_from_steps()
)
except Exception as e:
logger.warning(f"[{self.name}] Failed to generate summary: {e}")
# 处理结果
duration_ms = int((time.time() - start_time) * 1000)
# 🔥 如果被取消,返回取消结果
if self.is_cancelled:
await self.emit_event(
"info",
f"🛑 Recon Agent 已取消: {self._iteration} 轮迭代"
)
return AgentResult(
success=False,
error="任务已取消",
data=self._summarize_from_steps(),
iterations=self._iteration,
tool_calls=self._tool_calls,
tokens_used=self._total_tokens,
duration_ms=duration_ms,
)
# 🔥 如果有错误,返回失败结果
if error_message:
await self.emit_event(
"error",
f"❌ Recon Agent 失败: {error_message}"
)
return AgentResult(
success=False,
error=error_message,
data=self._summarize_from_steps(),
iterations=self._iteration,
tool_calls=self._tool_calls,
tokens_used=self._total_tokens,
duration_ms=duration_ms,
)
# 如果没有最终结果,从历史中汇总
if not final_result:
final_result = self._summarize_from_steps()
# 🔥 记录工作和洞察
self.record_work(f"完成项目信息收集,发现 {len(final_result.get('entry_points', []))} 个入口点")
self.record_work(f"识别技术栈: {final_result.get('tech_stack', {})}")
if final_result.get("high_risk_areas"):
self.add_insight(f"发现 {len(final_result['high_risk_areas'])} 个高风险区域需要重点分析")
if final_result.get("initial_findings"):
self.add_insight(f"初步发现 {len(final_result['initial_findings'])} 个潜在问题")
await self.emit_event(
"info",
f"Recon Agent 完成: {self._iteration} 轮迭代, {self._tool_calls} 次工具调用"
)
return AgentResult(
success=True,
data=final_result,
iterations=self._iteration,
tool_calls=self._tool_calls,
tokens_used=self._total_tokens,
duration_ms=duration_ms,
)
except Exception as e:
logger.error(f"Recon Agent failed: {e}", exc_info=True)
return AgentResult(success=False, error=str(e))_summarize_from_steps()
在 run 方法执行完毕后,该方法用于汇总LLM的执行结果,并对其进行格式化处理。
def _summarize_from_steps(self) -> Dict[str, Any]:
"""从步骤中汇总结果 - 增强版,从 LLM 思考过程中提取更多信息"""
result = {
"project_structure": {},
"tech_stack": {
"languages": [],
"frameworks": [],
"databases": [],
},
"entry_points": [],
"high_risk_areas": [],
"dependencies": {},
"initial_findings": [],
"summary": "",
}
# 🔥 收集所有 LLM 的思考内容
thoughts = []
# 从步骤的观察结果和思考中提取信息
for step in self._steps:
# 收集思考内容
if step.thought:
thoughts.append(step.thought)
if step.observation:
obs_lower = step.observation.lower()
# 识别语言
if "package.json" in obs_lower or ".js" in obs_lower or ".ts" in obs_lower:
result["tech_stack"]["languages"].append("JavaScript/TypeScript")
if "requirements.txt" in obs_lower or "setup.py" in obs_lower or ".py" in obs_lower:
result["tech_stack"]["languages"].append("Python")
if "go.mod" in obs_lower or ".go" in obs_lower:
result["tech_stack"]["languages"].append("Go")
if "pom.xml" in obs_lower or ".java" in obs_lower:
result["tech_stack"]["languages"].append("Java")
if ".php" in obs_lower:
result["tech_stack"]["languages"].append("PHP")
# 识别框架
if "react" in obs_lower:
result["tech_stack"]["frameworks"].append("React")
if "vue" in obs_lower:
result["tech_stack"]["frameworks"].append("Vue")
if "django" in obs_lower:
result["tech_stack"]["frameworks"].append("Django")
if "flask" in obs_lower:
result["tech_stack"]["frameworks"].append("Flask")
if "fastapi" in obs_lower:
result["tech_stack"]["frameworks"].append("FastAPI")
if "express" in obs_lower:
result["tech_stack"]["frameworks"].append("Express")
# 识别数据库
if "mysql" in obs_lower or "pymysql" in obs_lower:
result["tech_stack"]["databases"].append("MySQL")
if "postgres" in obs_lower or "asyncpg" in obs_lower:
result["tech_stack"]["databases"].append("PostgreSQL")
if "mongodb" in obs_lower:
result["tech_stack"]["databases"].append("MongoDB")
if "redis" in obs_lower:
result["tech_stack"]["databases"].append("Redis")
# 🔥 识别高风险区域(从观察中提取)
risk_keywords = ["api", "auth", "login", "password", "secret", "key", "token",
"admin", "upload", "download", "exec", "eval", "sql", "query"]
for keyword in risk_keywords:
if keyword in obs_lower:
# 尝试从观察中提取文件路径
file_matches = re.findall(r'[\w/]+\.(?:py|js|ts|java|php|go|rb)', step.observation)
for file_path in file_matches[:3]:
if file_path not in result["high_risk_areas"]:
result["high_risk_areas"].append(file_path)
# 去重
result["tech_stack"]["languages"] = list(set(result["tech_stack"]["languages"]))
result["tech_stack"]["frameworks"] = list(set(result["tech_stack"]["frameworks"]))
result["tech_stack"]["databases"] = list(set(result["tech_stack"]["databases"]))
result["high_risk_areas"] = list(set(result["high_risk_areas"]))[:20]
# 🔥 汇总 LLM 的思考作为 summary
if thoughts:
result["summary"] = "\n".join(thoughts[-3:])
return resultAnalysisAgent
AnalysisAgent的主要职责是对项目进行深入的安全分析,制定分析策略并审查具体代码。以下是其核心System Prompt:
ANALYSIS_SYSTEM_PROMPT = """你是 DeepAudit 的漏洞分析 Agent,一个**自主**的安全专家。
## 你的角色
你是安全审计的**核心大脑**,不是工具执行器。你需要:
1. 自主制定分析策略
2. 选择最有效的工具和方法
3. 深入分析可疑代码
4. 判断是否是真实漏洞
5. 动态调整分析方向
## ⚠️ 核心原则:优先使用外部专业工具!
**外部工具优先级最高!** 必须首先使用外部安全工具进行扫描,它们有:
- 经过验证的专业规则库
- 更低的误报率
- 更全面的漏洞检测能力
## 🔧 工具优先级(必须按此顺序使用)
### 第一优先级:外部专业安全工具 ⭐⭐⭐ 【必须首先使用!】
- **semgrep_scan**: 全语言静态分析 - **每次分析必用**
参数: target_path (str), rules (str: "auto" 或 "p/security-audit")
示例: {"target_path": ".", "rules": "auto"}
- **bandit_scan**: Python 安全扫描 - **Python项目必用**
参数: target_path (str), severity (str)
示例: {"target_path": ".", "severity": "medium"}
- **gitleaks_scan**: 密钥泄露检测 - **每次分析必用**
参数: target_path (str)
示例: {"target_path": "."}
- **safety_scan**: Python 依赖漏洞 - **有 requirements.txt 时必用**
参数: requirements_file (str)
示例: {"requirements_file": "requirements.txt"}
- **npm_audit**: Node.js 依赖漏洞 - **有 package.json 时必用**
参数: target_path (str)
示例: {"target_path": "."}
- **kunlun_scan**: 深度代码审计(Kunlun-M)
参数: target_path (str), language (str: "php"|"javascript")
示例: {"target_path": ".", "language": "php"}
### 第二优先级:智能扫描工具 ⭐⭐
- **smart_scan**: 智能批量安全扫描
参数: target (str), quick_mode (bool), focus_vulnerabilities (list)
示例: {"target": ".", "quick_mode": true}
- **quick_audit**: 快速文件审计
参数: file_path (str), deep_analysis (bool)
示例: {"file_path": "app/views.py", "deep_analysis": true}
### 第三优先级:内置分析工具 ⭐
- **pattern_match**: 危险模式匹配(外部工具不可用时的备选)
参数: scan_file (str) 或 code (str), pattern_types (list)
示例: {"scan_file": "app/models.py", "pattern_types": ["sql_injection"]}
- **dataflow_analysis**: 数据流追踪
参数: source_code (str), variable_name (str)
### 辅助工具(RAG 优先!)
- **rag_query**: **🔥 首选** 语义搜索代码,理解业务逻辑
参数: query (str), top_k (int)
- **security_search**: **🔥 首选** 安全相关搜索
参数: query (str)
- **read_file**: 读取文件内容
参数: file_path (str), start_line (int), end_line (int)
- **list_files**: ⚠️ 仅列出目录,严禁遍历
- **search_code**: ⚠️ 仅查找常量,严禁通用搜索
## 📋 推荐分析流程(严格按此执行!)
### 第一步:外部工具全面扫描(60%时间)⚡ 最重要!
根据项目技术栈,**必须首先**执行以下外部工具:
```
# 所有项目必做
Action: semgrep_scan
Action Input: {"target_path": ".", "rules": "auto"}
Action: gitleaks_scan
Action Input: {"target_path": "."}
# Python 项目必做
Action: bandit_scan
Action Input: {"target_path": ".", "severity": "medium"}
Action: safety_scan
Action Input: {"requirements_file": "requirements.txt"}
# Node.js 项目必做
Action: npm_audit
Action Input: {"target_path": "."}
```
### 第二步:分析外部工具结果(25%时间)
对外部工具发现的问题进行深入分析:
- 使用 `read_file` 查看完整代码上下文
- 使用 `dataflow_analysis` 追踪数据流
- 验证是否为真实漏洞,排除误报
### 第三步:补充扫描(10%时间)
如果外部工具覆盖不足,使用内置工具补充:
- `smart_scan` 综合扫描
- `pattern_match` 模式匹配
### 第四步:汇总报告(5%时间)
整理所有发现,输出 Final Answer
## ⚠️ 重要提醒
1. **不要跳过外部工具!** 即使内置工具可能更快,外部工具的检测能力更强
2. **Docker依赖**:外部工具需要Docker环境,如果返回"Docker不可用",再使用内置工具
3. **并行执行**:可以连续调用多个外部工具
## 工作方式
每一步,你需要输出:
```
Thought: [分析当前情况,思考下一步应该做什么]
Action: [工具名称]
Action Input: [JSON 格式的参数]
```
当你完成分析后,输出:
```
Thought: [总结所有发现]
Final Answer: [JSON 格式的漏洞报告]
```
## ⚠️ 输出格式要求(严格遵守)
**禁止使用 Markdown 格式标记!** 你的输出必须是纯文本格式:
✅ 正确:
```
Thought: 我需要使用 semgrep 扫描代码。
Action: semgrep_scan
Action Input: {"target_path": ".", "rules": "auto"}
```
❌ 错误(禁止):
```
**Thought:** 我需要扫描
**Action:** semgrep_scan
**Action Input:** {...}
```
## Final Answer 格式
```json
{
"findings": [
{
"vulnerability_type": "sql_injection",
"severity": "high",
"title": "SQL 注入漏洞",
"description": "详细描述",
"file_path": "path/to/file.py",
"line_start": 42,
"code_snippet": "危险代码片段",
"source": "污点来源",
"sink": "危险函数",
"suggestion": "修复建议",
"confidence": 0.9,
"needs_verification": true
}
],
"summary": "分析总结"
}
```
## 重点关注的漏洞类型
- SQL 注入 (query, execute, raw SQL)
- XSS (innerHTML, document.write, v-html)
- 命令注入 (exec, system, subprocess)
- 路径遍历 (open, readFile, path 拼接)
- SSRF (requests, fetch, http client)
- 硬编码密钥 (password, secret, api_key)
- 不安全的反序列化 (pickle, yaml.load, eval)
## 重要原则
1. **外部工具优先** - 首先使用 semgrep、bandit 等专业工具
2. **质量优先** - 宁可深入分析几个真实漏洞,不要浅尝辄止报告大量误报
3. **上下文分析** - 看到可疑代码要读取上下文,理解完整逻辑
4. **自主判断** - 不要机械相信工具输出,要用你的专业知识判断
## 🚨 知识工具使用警告(防止幻觉!)
**知识库中的代码示例仅供概念参考,不是实际代码!**
当你使用 `get_vulnerability_knowledge` 或 `query_security_knowledge` 时:
1. **知识示例 ≠ 项目代码** - 知识库的代码示例是通用示例,不是目标项目的代码
2. **语言可能不匹配** - 知识库可能返回 Python 示例,但项目可能是 PHP/Rust/Go
3. **必须在实际代码中验证** - 你只能报告你在 read_file 中**实际看到**的漏洞
4. **禁止推测** - 不要因为知识库说"这种模式常见"就假设项目中存在
❌ 错误做法(幻觉来源):
```
1. 查询 auth_bypass 知识 -> 看到 JWT 示例
2. 没有在项目中找到 JWT 代码
3. 仍然报告 "JWT 认证绕过漏洞" <- 这是幻觉!
```
✅ 正确做法:
```
1. 查询 auth_bypass 知识 -> 了解认证绕过的概念
2. 使用 read_file 读取项目的认证代码
3. 只有**实际看到**有问题的代码才报告漏洞
4. file_path 必须是你**实际读取过**的文件
```
## ⚠️ 关键约束 - 必须遵守!
1. **禁止直接输出 Final Answer** - 你必须先调用工具来分析代码
2. **至少调用两个工具** - 使用 smart_scan/semgrep_scan 进行扫描,然后用 read_file 查看代码
3. **没有工具调用的分析无效** - 不允许仅凭推测直接报告漏洞
4. **先 Action 后 Final Answer** - 必须先执行工具,获取 Observation,再输出最终结论
错误示例(禁止):
```
Thought: 根据项目信息,可能存在安全问题
Final Answer: {...} ❌ 没有调用任何工具!
```
正确示例(必须):
```
Thought: 我需要先使用智能扫描工具对项目进行全面分析
Action: smart_scan
Action Input: {"scan_type": "security", "max_files": 50}
```
然后等待 Observation,再继续深入分析或输出 Final Answer。
现在开始你的安全分析!首先使用外部工具进行全面扫描。"""AnalysisAgent
首先是初始化方法 __init__,其逻辑与其他Agent类似,均用于构建完整的System Prompt:
def __init__(
self,
llm_service,
tools: Dict[str, Any],
event_emitter=None,
):
# 组合增强的系统提示词,注入核心安全原则和漏洞优先级
full_system_prompt = f"{ANALYSIS_SYSTEM_PROMPT}\n\n{CORE_SECURITY_PRINCIPLES}\n\n{VULNERABILITY_PRIORITIES}"
config = AgentConfig(
name="Analysis",
agent_type=AgentType.ANALYSIS,
pattern=AgentPattern.REACT,
max_iterations=30,
system_prompt=full_system_prompt,
)
super().__init__(config, llm_service, tools, event_emitter)
self._conversation_history: List[Dict[str, str]] = []
self._steps: List[AnalysisStep] = []其中,CORE_SECURITY_PRINCIPLES 定义了核心安全原则:
CORE_SECURITY_PRINCIPLES = """
<core_security_principles>
## 代码审计核心原则
### 1. 深度分析优于广度扫描
- 深入分析少数真实漏洞比报告大量误报更有价值
- 每个发现都需要上下文验证
- 理解业务逻辑后才能判断安全影响
### 2. 数据流追踪
- 从用户输入(Source)到危险函数(Sink)
- 识别所有数据处理和验证节点
- 评估过滤和编码的有效性
### 3. 上下文感知分析
- 不要孤立看待代码片段
- 理解函数调用链和模块依赖
- 考虑运行时环境和配置
### 4. 自主决策
- 不要机械执行,要主动思考
- 根据发现动态调整分析策略
- 对工具输出进行专业判断
### 5. 质量优先
- 高置信度发现优于低置信度猜测
- 提供明确的证据和复现步骤
- 给出实际可行的修复建议
</core_security_principles>
"""接下来是核心的 run 方法实现:
async def run(self, input_data: Dict[str, Any]) -> AgentResult:
"""
执行漏洞分析 - LLM 全程参与!
"""
import time
start_time = time.time()
project_info = input_data.get("project_info", {})
config = input_data.get("config", {})
plan = input_data.get("plan", {})
previous_results = input_data.get("previous_results", {})
task = input_data.get("task", "")
task_context = input_data.get("task_context", "")
# 🔥 处理交接信息
handoff = input_data.get("handoff")
if handoff:
from .base import TaskHandoff
if isinstance(handoff, dict):
handoff = TaskHandoff.from_dict(handoff)
self.receive_handoff(handoff)
# 从 Recon 结果获取上下文
recon_data = previous_results.get("recon", {})
if isinstance(recon_data, dict) and "data" in recon_data:
recon_data = recon_data["data"]
tech_stack = recon_data.get("tech_stack", {})
entry_points = recon_data.get("entry_points", [])
high_risk_areas = recon_data.get("high_risk_areas", plan.get("high_risk_areas", []))
initial_findings = recon_data.get("initial_findings", [])
# 🔥 构建包含交接上下文的初始消息
handoff_context = self.get_handoff_context()
# 🔥 获取目标文件列表
target_files = config.get("target_files", [])
initial_message = f"""请开始对项目进行安全漏洞分析。
## 项目信息
- 名称: {project_info.get('name', 'unknown')}
- 语言: {tech_stack.get('languages', [])}
- 框架: {tech_stack.get('frameworks', [])}
"""
# 🔥 如果指定了目标文件,明确告知 Agent
if target_files:
initial_message += f"""## ⚠️ 审计范围
用户指定了 {len(target_files)} 个目标文件进行审计:
"""
for tf in target_files[:10]:
initial_message += f"- {tf}\n"
if len(target_files) > 10:
initial_message += f"- ... 还有 {len(target_files) - 10} 个文件\n"
initial_message += """
请直接分析这些指定的文件,不要分析其他文件。
"""
initial_message += f"""{handoff_context if handoff_context else f'''## 上下文信息
### ⚠️ 高风险区域(来自 Recon Agent,必须优先分析)
以下是 Recon Agent 识别的高风险区域,请**务必优先**读取和分析这些文件:
{json.dumps(high_risk_areas[:20], ensure_ascii=False)}
**重要**: 请使用 read_file 工具读取上述高风险文件,不要假设文件路径或使用其他路径。
### 入口点 (前10个)
{json.dumps(entry_points[:10], ensure_ascii=False, indent=2)}
### 初步发现 (如果有)
{json.dumps(initial_findings[:5], ensure_ascii=False, indent=2) if initial_findings else "无"}'''}
## 任务
{task_context or task or '进行全面的安全漏洞分析,发现代码中的安全问题。'}
## ⚠️ 分析策略要求
1. **首先**:使用 read_file 读取上面列出的高风险文件
2. **然后**:分析这些文件中的安全问题
3. **最后**:如果需要,使用 smart_scan 或其他工具扩展分析
**禁止**:不要跳过高风险区域直接做全局扫描
## 目标漏洞类型
{config.get('target_vulnerabilities', ['all'])}
## 可用工具
{self.get_tools_description()}
请开始你的安全分析。首先读取高风险区域的文件,然后**立即**分析其中的安全问题(输出 Action)。"""
# 🔥 记录工作开始
self.record_work("开始安全漏洞分析")
# 初始化对话历史
self._conversation_history = [
{"role": "system", "content": self.config.system_prompt},
{"role": "user", "content": initial_message},
]
self._steps = []
all_findings = []
error_message = None # 🔥 跟踪错误信息
await self.emit_thinking("🔬 Analysis Agent 启动,LLM 开始自主安全分析...")
try:
for iteration in range(self.config.max_iterations):
if self.is_cancelled:
break
self._iteration = iteration + 1
# 🔥 再次检查取消标志(在LLM调用之前)
if self.is_cancelled:
await self.emit_thinking("🛑 任务已取消,停止执行")
break
# 调用 LLM 进行思考和决策(流式输出)
# 🔥 使用用户配置的 temperature 和 max_tokens
try:
llm_output, tokens_this_round = await self.stream_llm_call(
self._conversation_history,
# 🔥 不传递 temperature 和 max_tokens,使用用户配置
)
except asyncio.CancelledError:
logger.info(f"[{self.name}] LLM call cancelled")
break
self._total_tokens += tokens_this_round
# 🔥 Enhanced: Handle empty LLM response with better diagnostics
if not llm_output or not llm_output.strip():
empty_retry_count = getattr(self, '_empty_retry_count', 0) + 1
self._empty_retry_count = empty_retry_count
# 🔥 记录更详细的诊断信息
logger.warning(
f"[{self.name}] Empty LLM response in iteration {self._iteration} "
f"(retry {empty_retry_count}/3, tokens_this_round={tokens_this_round})"
)
if empty_retry_count >= 3:
logger.error(f"[{self.name}] Too many empty responses, generating fallback result")
error_message = "连续收到空响应,使用回退结果"
await self.emit_event("warning", error_message)
# 🔥 不是直接 break,而是尝试生成一个回退结果
break
# 🔥 更有针对性的重试提示
retry_prompt = f"""收到空响应。请根据以下格式输出你的思考和行动:
Thought: [你对当前安全分析情况的思考]
Action: [工具名称,如 read_file, search_code, pattern_match, semgrep_scan]
Action Input: {{"参数名": "参数值"}}
可用工具: {', '.join(self.tools.keys())}
如果你已完成分析,请输出:
Thought: [总结所有发现]
Final Answer: {{"findings": [...], "summary": "..."}}"""
self._conversation_history.append({
"role": "user",
"content": retry_prompt,
})
continue
# 重置空响应计数器
self._empty_retry_count = 0
# 解析 LLM 响应
step = self._parse_llm_response(llm_output)
self._steps.append(step)
# 🔥 发射 LLM 思考内容事件 - 展示安全分析的思考过程
if step.thought:
await self.emit_llm_thought(step.thought, iteration + 1)
# 添加 LLM 响应到历史
self._conversation_history.append({
"role": "assistant",
"content": llm_output,
})
# 检查是否完成
if step.is_final:
await self.emit_llm_decision("完成安全分析", "LLM 判断分析已充分")
logger.info(f"[{self.name}] Received Final Answer: {step.final_answer}")
if step.final_answer and "findings" in step.final_answer:
all_findings = step.final_answer["findings"]
logger.info(f"[{self.name}] Final Answer contains {len(all_findings)} findings")
# 🔥 发射每个发现的事件
for finding in all_findings[:5]: # 限制数量
await self.emit_finding(
finding.get("title", "Unknown"),
finding.get("severity", "medium"),
finding.get("vulnerability_type", "other"),
finding.get("file_path", "")
)
# 🔥 记录洞察
self.add_insight(
f"发现 {finding.get('severity', 'medium')} 级别漏洞: {finding.get('title', 'Unknown')}"
)
else:
logger.warning(f"[{self.name}] Final Answer has no 'findings' key or is None: {step.final_answer}")
# 🔥 记录工作完成
self.record_work(f"完成安全分析,发现 {len(all_findings)} 个潜在漏洞")
await self.emit_llm_complete(
f"分析完成,发现 {len(all_findings)} 个潜在漏洞",
self._total_tokens
)
break
# 执行工具
if step.action:
# 🔥 发射 LLM 动作决策事件
await self.emit_llm_action(step.action, step.action_input or {})
# 🔥 循环检测:追踪工具调用失败历史
tool_call_key = f"{step.action}:{json.dumps(step.action_input or {}, sort_keys=True)}"
if not hasattr(self, '_failed_tool_calls'):
self._failed_tool_calls = {}
observation = await self.execute_tool(
step.action,
step.action_input or {}
)
# 🔥 检测工具调用失败并追踪
is_tool_error = (
"失败" in observation or
"错误" in observation or
"不存在" in observation or
"文件过大" in observation or
"Error" in observation
)
if is_tool_error:
self._failed_tool_calls[tool_call_key] = self._failed_tool_calls.get(tool_call_key, 0) + 1
fail_count = self._failed_tool_calls[tool_call_key]
# 🔥 如果同一调用连续失败3次,添加强制跳过提示
if fail_count >= 3:
logger.warning(f"[{self.name}] Tool call failed {fail_count} times: {tool_call_key}")
observation += f"\n\n⚠️ **系统提示**: 此工具调用已连续失败 {fail_count} 次。请:\n"
observation += "1. 尝试使用不同的参数(如指定较小的行范围)\n"
observation += "2. 使用 search_code 工具定位关键代码片段\n"
observation += "3. 跳过此文件,继续分析其他文件\n"
observation += "4. 如果已有足够发现,直接输出 Final Answer"
# 重置计数器但保留记录
self._failed_tool_calls[tool_call_key] = 0
else:
# 成功调用,重置失败计数
if tool_call_key in self._failed_tool_calls:
del self._failed_tool_calls[tool_call_key]
# 🔥 工具执行后检查取消状态
if self.is_cancelled:
logger.info(f"[{self.name}] Cancelled after tool execution")
break
step.observation = observation
# 🔥 发射 LLM 观察事件
await self.emit_llm_observation(observation)
# 添加观察结果到历史
self._conversation_history.append({
"role": "user",
"content": f"Observation:\n{observation}",
})
else:
# LLM 没有选择工具,提示它继续
await self.emit_llm_decision("继续分析", "LLM 需要更多分析")
self._conversation_history.append({
"role": "user",
"content": "请继续分析。你输出了 Thought 但没有输出 Action。请**立即**选择一个工具执行,或者如果分析完成,输出 Final Answer 汇总所有发现。",
})
# 🔥 如果循环结束但没有发现,强制 LLM 总结
if not all_findings and not self.is_cancelled and not error_message:
await self.emit_thinking("📝 分析阶段结束,正在生成漏洞总结...")
# 添加强制总结的提示
self._conversation_history.append({
"role": "user",
"content": """分析阶段已结束。请立即输出 Final Answer,总结你发现的所有安全问题。
即使没有发现严重漏洞,也请总结你的分析过程和观察到的潜在风险点。
请按以下 JSON 格式输出:
```json
{
"findings": [
{
"vulnerability_type": "sql_injection|xss|command_injection|path_traversal|ssrf|hardcoded_secret|other",
"severity": "critical|high|medium|low",
"title": "漏洞标题",
"description": "详细描述",
"file_path": "文件路径",
"line_start": 行号,
"code_snippet": "相关代码片段",
"suggestion": "修复建议"
}
],
"summary": "分析总结"
}
```
Final Answer:""",
})
try:
summary_output, _ = await self.stream_llm_call(
self._conversation_history,
# 🔥 不传递 temperature 和 max_tokens,使用用户配置
)
if summary_output and summary_output.strip():
# 解析总结输出
import re
summary_text = summary_output.strip()
summary_text = re.sub(r'```json\s*', '', summary_text)
summary_text = re.sub(r'```\s*', '', summary_text)
parsed_result = AgentJsonParser.parse(
summary_text,
default={"findings": [], "summary": ""}
)
if "findings" in parsed_result:
all_findings = parsed_result["findings"]
except Exception as e:
logger.warning(f"[{self.name}] Failed to generate summary: {e}")
# 处理结果
duration_ms = int((time.time() - start_time) * 1000)
# 🔥 如果被取消,返回取消结果
if self.is_cancelled:
await self.emit_event(
"info",
f"🛑 Analysis Agent 已取消: {len(all_findings)} 个发现, {self._iteration} 轮迭代"
)
return AgentResult(
success=False,
error="任务已取消",
data={"findings": all_findings},
iterations=self._iteration,
tool_calls=self._tool_calls,
tokens_used=self._total_tokens,
duration_ms=duration_ms,
)
# 🔥 如果有错误,返回失败结果
if error_message:
await self.emit_event(
"error",
f"❌ Analysis Agent 失败: {error_message}"
)
return AgentResult(
success=False,
error=error_message,
data={"findings": all_findings},
iterations=self._iteration,
tool_calls=self._tool_calls,
tokens_used=self._total_tokens,
duration_ms=duration_ms,
)
# 标准化发现
logger.info(f"[{self.name}] Standardizing {len(all_findings)} findings")
standardized_findings = []
for finding in all_findings:
# 确保 finding 是字典
if not isinstance(finding, dict):
logger.warning(f"Skipping invalid finding (not a dict): {finding}")
continue
standardized = {
"vulnerability_type": finding.get("vulnerability_type", "other"),
"severity": finding.get("severity", "medium"),
"title": finding.get("title", "Unknown Finding"),
"description": finding.get("description", ""),
"file_path": finding.get("file_path", ""),
"line_start": finding.get("line_start") or finding.get("line", 0),
"code_snippet": finding.get("code_snippet", ""),
"source": finding.get("source", ""),
"sink": finding.get("sink", ""),
"suggestion": finding.get("suggestion", ""),
"confidence": finding.get("confidence", 0.7),
"needs_verification": finding.get("needs_verification", True),
}
standardized_findings.append(standardized)
await self.emit_event(
"info",
f"Analysis Agent 完成: {len(standardized_findings)} 个发现, {self._iteration} 轮迭代, {self._tool_calls} 次工具调用"
)
# 🔥 CRITICAL: Log final findings count before returning
logger.info(f"[{self.name}] Returning {len(standardized_findings)} standardized findings")
return AgentResult(
success=True,
data={
"findings": standardized_findings,
"steps": [
{
"thought": s.thought,
"action": s.action,
"action_input": s.action_input,
"observation": s.observation[:500] if s.observation else None,
}
for s in self._steps
],
},
iterations=self._iteration,
tool_calls=self._tool_calls,
tokens_used=self._total_tokens,
duration_ms=duration_ms,
)
except Exception as e:
logger.error(f"Analysis Agent failed: {e}", exc_info=True)
return AgentResult(success=False, error=str(e))
该方法尝试接收上层传递的 handoff 数据,但在当前的实现逻辑中,数据传递主要依赖 previous_results。随后调用的LLM响应解析方法与前文类似:
def _parse_llm_response(self, response: str) -> AnalysisStep:
"""解析 LLM 响应 - 增强版,更健壮地提取思考内容"""
step = AnalysisStep(thought="")
# 🔥 v2.1: 预处理 - 移除 Markdown 格式标记(LLM 有时会输出 **Action:** 而非 Action:)
cleaned_response = response
cleaned_response = re.sub(r'\*\*Action:\*\*', 'Action:', cleaned_response)
cleaned_response = re.sub(r'\*\*Action Input:\*\*', 'Action Input:', cleaned_response)
cleaned_response = re.sub(r'\*\*Thought:\*\*', 'Thought:', cleaned_response)
cleaned_response = re.sub(r'\*\*Final Answer:\*\*', 'Final Answer:', cleaned_response)
cleaned_response = re.sub(r'\*\*Observation:\*\*', 'Observation:', cleaned_response)
# 🔥 首先尝试提取明确的 Thought 标记
thought_match = re.search(r'Thought:\s*(.*?)(?=Action:|Final Answer:|$)', cleaned_response, re.DOTALL)
if thought_match:
step.thought = thought_match.group(1).strip()
# 🔥 检查是否是最终答案
final_match = re.search(r'Final Answer:\s*(.*?)$', cleaned_response, re.DOTALL)
if final_match:
step.is_final = True
answer_text = final_match.group(1).strip()
answer_text = re.sub(r'```json\s*', '', answer_text)
answer_text = re.sub(r'```\s*', '', answer_text)
# 使用增强的 JSON 解析器
step.final_answer = AgentJsonParser.parse(
answer_text,
default={"findings": [], "raw_answer": answer_text}
)
# 确保 findings 格式正确
if "findings" in step.final_answer:
step.final_answer["findings"] = [
f for f in step.final_answer["findings"]
if isinstance(f, dict)
]
# 🔥 如果没有提取到 thought,使用 Final Answer 前的内容作为思考
if not step.thought:
before_final = cleaned_response[:cleaned_response.find('Final Answer:')].strip()
if before_final:
before_final = re.sub(r'^Thought:\s*', '', before_final)
step.thought = before_final[:500] if len(before_final) > 500 else before_final
return step
# 🔥 提取 Action
action_match = re.search(r'Action:\s*(\w+)', cleaned_response)
if action_match:
step.action = action_match.group(1).strip()
# 🔥 如果没有提取到 thought,提取 Action 之前的内容作为思考
if not step.thought:
action_pos = cleaned_response.find('Action:')
if action_pos > 0:
before_action = cleaned_response[:action_pos].strip()
before_action = re.sub(r'^Thought:\s*', '', before_action)
if before_action:
step.thought = before_action[:500] if len(before_action) > 500 else before_action
# 🔥 提取 Action Input
input_match = re.search(r'Action Input:\s*(.*?)(?=Thought:|Action:|Observation:|$)', cleaned_response, re.DOTALL)
if input_match:
input_text = input_match.group(1).strip()
input_text = re.sub(r'```json\s*', '', input_text)
input_text = re.sub(r'```\s*', '', input_text)
# 使用增强的 JSON 解析器
step.action_input = AgentJsonParser.parse(
input_text,
default={"raw_input": input_text}
)
# 🔥 最后的 fallback:如果整个响应没有任何标记,整体作为思考
if not step.thought and not step.action and not step.is_final:
if response.strip():
step.thought = response.strip()[:500]
return stepVerificationAgent
VerificationAgent 负责对已发现的漏洞进行验证。以下是其System Prompt,定义了验证专家的角色与职责:
VERIFICATION_SYSTEM_PROMPT = """你是 DeepAudit 的漏洞验证 Agent,一个自主的安全验证专家。
## 你的角色
你是漏洞验证的大脑,不是机械验证器。你需要:
1. 理解每个漏洞的上下文
2. 设计合适的验证策略
3. 编写测试代码进行动态验证
4. 判断漏洞是否真实存在
5. 评估实际影响并生成 PoC
## 核心理念:Fuzzing Harness
即使整个项目无法运行,你也应该能够验证漏洞!方法是:
1. 提取目标函数 - 从代码中提取存在漏洞的函数
2. 构建 Mock - 模拟函数依赖(数据库、HTTP、文件系统等)
3. 编写测试脚本 - 构造各种恶意输入测试函数
4. 分析执行结果 - 判断是否触发漏洞
## 你可以使用的工具
### 🔥 核心验证工具(优先使用)
- run_code: 执行你编写的测试代码(支持 Python/PHP/JS/Ruby/Go/Java/Bash)
- 用于运行 Fuzzing Harness、PoC 脚本
- 你可以完全控制测试逻辑
- 参数: code (str), language (str), timeout (int), description (str)
- extract_function: 从源文件提取指定函数代码
- 用于获取目标函数,构建 Fuzzing Harness
- 参数: file_path (str), function_name (str), include_imports (bool)
### 文件操作
- read_file: 读取代码文件获取上下文
参数: file_path (str), start_line (int), end_line (int)
### 沙箱工具
- sandbox_exec: 在沙箱中执行命令(用于验证命令执行类漏洞)
- sandbox_http: 发送 HTTP 请求(如果有运行的服务)
## 🔥 Fuzzing Harness 编写指南
### 原则
1. 你是大脑 - 你决定测试策略、payload、检测方法
2. 不依赖完整项目 - 提取函数,mock 依赖,隔离测试
3. 多种 payload - 设计多种恶意输入,不要只测一个
4. 检测漏洞特征 - 根据漏洞类型设计检测逻辑
### 命令注入 Fuzzing Harness 示例 (Python)
```python
import os
import subprocess
# === Mock 危险函数来检测调用 ===
executed_commands = []
original_system = os.system
def mock_system(cmd):
print(f"[DETECTED] os.system called: {cmd}")
executed_commands.append(cmd)
return 0
os.system = mock_system
# === 目标函数(从项目代码复制) ===
def vulnerable_function(user_input):
os.system(f"echo {user_input}")
# === Fuzzing 测试 ===
payloads = [
"test", # 正常输入
"; id", # 命令连接符
"| whoami", # 管道
"$(cat /etc/passwd)", # 命令替换
"`id`", # 反引号
"&& ls -la", # AND 连接
]
print("=== Fuzzing Start ===")
for payload in payloads:
print(f"\\nPayload: {payload}")
executed_commands.clear()
try:
vulnerable_function(payload)
if executed_commands:
print(f"[VULN] Detected! Commands: {executed_commands}")
except Exception as e:
print(f"[ERROR] {e}")
```
### SQL 注入 Fuzzing Harness 示例 (Python)
```python
# === Mock 数据库 ===
class MockCursor:
def __init__(self):
self.queries = []
def execute(self, query, params=None):
print(f"[SQL] Query: {query}")
print(f"[SQL] Params: {params}")
self.queries.append((query, params))
# 检测 SQL 注入特征
if params is None and ("'" in query or "OR" in query.upper() or "--" in query):
print("[VULN] Possible SQL injection - no parameterized query!")
class MockDB:
def cursor(self):
return MockCursor()
# === 目标函数 ===
def get_user(db, user_id):
cursor = db.cursor()
cursor.execute(f"SELECT * FROM users WHERE id = '{user_id}'") # 漏洞!
# === Fuzzing ===
db = MockDB()
payloads = ["1", "1'", "1' OR '1'='1", "1'; DROP TABLE users--", "1 UNION SELECT * FROM admin"]
for p in payloads:
print(f"\\n=== Testing: {p} ===")
get_user(db, p)
```
### PHP 命令注入 Fuzzing Harness 示例
```php
// 注意:php -r 不需要 <?php 标签
// Mock $_GET
$_GET['cmd'] = '; id';
$_POST['cmd'] = '; id';
$_REQUEST['cmd'] = '; id';
// 目标代码(从项目复制)
$output = shell_exec($_GET['cmd']);
echo "Output: " . $output;
// 如果有输出,说明命令被执行
if ($output) {
echo "\\n[VULN] Command executed!";
}
```
### XSS 检测 Harness 示例 (Python)
```python
def vulnerable_render(user_input):
# 模拟模板渲染
return f"<div>Hello, {user_input}!</div>"
payloads = [
"test",
"<script>alert(1)</script>",
"<img src=x onerror=alert(1)>",
"{{7*7}}", # SSTI
]
for p in payloads:
output = vulnerable_render(p)
print(f"Input: {p}")
print(f"Output: {output}")
# 检测:payload 是否原样出现在输出中
if p in output and ("<" in p or "{{" in p):
print("[VULN] XSS - input not escaped!")
```
## 验证策略
### 对于可执行的漏洞(命令注入、代码注入等)
1. 使用 `extract_function` 或 `read_file` 获取目标代码
2. 编写 Fuzzing Harness,mock 危险函数来检测调用
3. 使用 `run_code` 执行 Harness
4. 分析输出,确认漏洞是否触发
### 对于数据泄露型漏洞(SQL注入、路径遍历等)
1. 获取目标代码
2. 编写 Harness,mock 数据库/文件系统
3. 检查是否能构造恶意查询/路径
4. 分析输出
### 对于配置类漏洞(硬编码密钥等)
1. 使用 `read_file` 直接读取配置文件
2. 验证敏感信息是否存在
3. 评估影响(密钥是否有效、权限范围等)
## 工作流程
你将收到一批待验证的漏洞发现。对于每个发现:
```
Thought: [分析漏洞类型,设计验证策略]
Action: [工具名称]
Action Input: [参数]
```
验证完所有发现后,输出:
```
Thought: [总结验证结果]
Final Answer: [JSON 格式的验证报告]
```
## ⚠️ 输出格式要求(严格遵守)
**禁止使用 Markdown 格式标记!** 你的输出必须是纯文本格式:
✅ 正确格式:
```
Thought: 我需要读取 search.php 文件来验证 SQL 注入漏洞。
Action: read_file
Action Input: {"file_path": "search.php"}
```
❌ 错误格式(禁止使用):
```
**Thought:** 我需要读取文件
**Action:** read_file
**Action Input:** {"file_path": "search.php"}
```
规则:
1. 不要在 Thought:、Action:、Action Input:、Final Answer: 前后添加 `**`
2. 不要使用其他 Markdown 格式(如 `###`、`*斜体*` 等)
3. Action Input 必须是完整的 JSON 对象,不能为空或截断
## Final Answer 格式
```json
{
"findings": [
{
...原始发现字段...,
"verdict": "confirmed/likely/uncertain/false_positive",
"confidence": 0.0-1.0,
"is_verified": true/false,
"verification_method": "描述验证方法",
"verification_details": "验证过程和结果详情",
"poc": {
"description": "PoC 描述",
"steps": ["步骤1", "步骤2"],
"payload": "完整可执行的 PoC 代码或命令",
"harness_code": "Fuzzing Harness 代码(如果使用)"
},
"impact": "实际影响分析",
"recommendation": "修复建议"
}
],
"summary": {
"total": 数量,
"confirmed": 数量,
"likely": 数量,
"false_positive": 数量
}
}
```
## 验证判定标准
- confirmed: 漏洞确认存在且可利用,有明确证据(如 Harness 成功触发)
- likely: 高度可能存在漏洞,代码分析明确但无法动态验证
- uncertain: 需要更多信息才能判断
- false_positive: 确认是误报,有明确理由
## 🚨 防止幻觉验证(关键!)
Analysis Agent 可能报告不存在的文件!你必须验证:
1. 文件必须存在 - 使用 read_file 读取发现中指定的文件
- 如果 read_file 返回"文件不存在",该发现是 false_positive
- 不要尝试"猜测"正确的文件路径
2. 代码必须匹配 - 发现中的 code_snippet 必须在文件中真实存在
- 如果文件内容与描述不符,该发现是 false_positive
3. 不要"填补"缺失信息 - 如果发现缺少关键信息(如文件路径为空),标记为 uncertain
❌ 错误做法:
```
发现: "SQL注入在 api/database.py:45"
read_file 返回: "文件不存在"
判定: confirmed <- 这是错误的!
```
✅ 正确做法:
```
发现: "SQL注入在 api/database.py:45"
read_file 返回: "文件不存在"
判定: false_positive,理由: "文件 api/database.py 不存在"
```
## ⚠️ 关键约束
1. 必须先调用工具验证 - 不允许仅凭已知信息直接判断
2. 优先使用 run_code - 编写 Harness 进行动态验证
3. PoC 必须完整可执行 - poc.payload 应该是可直接运行的代码
4. 不要假设环境 - 沙箱中没有运行的服务,需要 mock
## 重要原则
1. 你是验证的大脑 - 你决定如何测试,工具只提供执行能力
2. 动态验证优先 - 能运行代码验证的就不要仅靠静态分析
3. 质量优先 - 宁可漏报也不要误报太多
4. 证据支撑 - 每个判定都需要有依据
现在开始验证漏洞发现!"""该流程设计雄心勃勃,但在实际执行中挑战重重。由于许多漏洞的验证需要复杂的依赖环境配置,在空白沙箱中完全模拟所有依赖并不现实,因此目前更适合验证基础的PoC。
VerificationStep
验证步骤的数据结构定义如下:
@dataclass
class VerificationStep:
"""验证步骤"""
thought: str
action: Optional[str] = None
action_input: Optional[Dict] = None
observation: Optional[str] = None
is_final: bool = False
final_answer: Optional[Dict] = NoneVerificationAgent
此外,__init__ 方法同样负责 Prompt 的构建与拼接。
def __init__(
self,
llm_service,
tools: Dict[str, Any],
event_emitter=None,
):
# 组合增强的系统提示词
full_system_prompt = f"{VERIFICATION_SYSTEM_PROMPT}\n\n{CORE_SECURITY_PRINCIPLES}\n\n{VULNERABILITY_PRIORITIES}"
config = AgentConfig(
name="Verification",
agent_type=AgentType.VERIFICATION,
pattern=AgentPattern.REACT,
max_iterations=25,
system_prompt=full_system_prompt,
)
super().__init__(config, llm_service, tools, event_emitter)
self._conversation_history: List[Dict[str, str]] = []
self._steps: List[VerificationStep] = []以下是引入的 VULNERABILITY_PRIORITIES,详细定义了各类漏洞的检测优先级:
VULNERABILITY_PRIORITIES = """
<vulnerability_priorities>
## 漏洞检测优先级
### 🔴 Critical - 远程代码执行类
1. SQL注入 - 未参数化的数据库查询
- Source: 请求参数、表单输入、HTTP头
- Sink: execute(), query(), raw SQL
- 绕过: ORM raw方法、字符串拼接
2. 命令注入 - 不安全的系统命令执行
- Source: 用户可控输入
- Sink: exec(), system(), subprocess, popen
- 特征: shell=True, 管道符, 反引号
3. 代码注入 - 动态代码执行
- Source: 用户输入、配置文件
- Sink: eval(), exec(), pickle.loads(), yaml.unsafe_load()
- 特征: 模板注入、反序列化
### 🟠 High - 信息泄露和权限提升
4. 路径遍历 - 任意文件访问
- Source: 文件名参数、路径参数
- Sink: open(), readFile(), send_file()
- 绕过: ../, URL编码, 空字节
5. SSRF - 服务器端请求伪造
- Source: URL参数、redirect参数
- Sink: requests.get(), fetch(), http.request()
- 内网: 127.0.0.1, 169.254.169.254, localhost
6. 认证绕过 - 权限控制缺陷
- 缺失认证装饰器
- JWT漏洞: 无签名验证、弱密钥
- IDOR: 直接对象引用
### 🟡 Medium - XSS和数据暴露
7. XSS - 跨站脚本
- Source: 用户输入、URL参数
- Sink: innerHTML, document.write, v-html
- 类型: 反射型、存储型、DOM型
8. 敏感信息泄露
- 硬编码密钥、密码
- 调试信息、错误堆栈
- API密钥、数据库凭证
9. XXE - XML外部实体注入
- Source: XML输入、SOAP请求
- Sink: etree.parse(), XMLParser()
- 特征: 禁用external entities
### 🟢 Low - 配置和最佳实践
10. CSRF - 跨站请求伪造
11. 弱加密 - MD5、SHA1、DES
12. 不安全传输 - HTTP、明文密码
13. 日志记录敏感信息
</vulnerability_priorities>
"""此处建议预留扩展接口以支持更多漏洞类型。接下来是核心的 run 方法:
async def run(self, input_data: Dict[str, Any]) -> AgentResult:
"""
执行漏洞验证 - LLM 全程参与!
"""
import time
start_time = time.time()
previous_results = input_data.get("previous_results", {})
config = input_data.get("config", {})
task = input_data.get("task", "")
task_context = input_data.get("task_context", "")
# 🔥 处理交接信息
handoff = input_data.get("handoff")
if handoff:
from .base import TaskHandoff
if isinstance(handoff, dict):
handoff = TaskHandoff.from_dict(handoff)
self.receive_handoff(handoff)
# 收集所有待验证的发现
findings_to_verify = []
# 🔥 优先从交接信息获取发现
if self._incoming_handoff and self._incoming_handoff.key_findings:
findings_to_verify = self._incoming_handoff.key_findings.copy()
logger.info(f"[Verification] 从交接信息获取 {len(findings_to_verify)} 个发现")
else:
# 🔥 修复:处理 Orchestrator 传递的多种数据格式
# 格式1: Orchestrator 直接传递 {"findings": [...]}
if isinstance(previous_results, dict) and "findings" in previous_results:
direct_findings = previous_results.get("findings", [])
if isinstance(direct_findings, list):
for f in direct_findings:
if isinstance(f, dict):
# 🔥 Always verify Critical/High findings to generate PoC, even if Analysis sets needs_verification=False
severity = str(f.get("severity", "")).lower()
needs_verify = f.get("needs_verification", True)
if needs_verify or severity in ["critical", "high"]:
findings_to_verify.append(f)
logger.info(f"[Verification] 从 previous_results.findings 获取 {len(findings_to_verify)} 个发现")
# 格式2: 传统格式 {"phase_name": {"data": {"findings": [...]}}}
if not findings_to_verify:
for phase_name, result in previous_results.items():
if phase_name == "findings":
continue # 已处理
if isinstance(result, dict):
data = result.get("data", {})
else:
data = result.data if hasattr(result, 'data') else {}
if isinstance(data, dict):
phase_findings = data.get("findings", [])
for f in phase_findings:
if isinstance(f, dict):
severity = str(f.get("severity", "")).lower()
needs_verify = f.get("needs_verification", True)
if needs_verify or severity in ["critical", "high"]:
findings_to_verify.append(f)
if findings_to_verify:
logger.info(f"[Verification] 从传统格式获取 {len(findings_to_verify)} 个发现")
# 🔥 如果仍然没有发现,尝试从 input_data 的其他字段提取
if not findings_to_verify:
# 尝试从 task 或 task_context 中提取描述的漏洞
if task and ("发现" in task or "漏洞" in task or "findings" in task.lower()):
logger.warning(f"[Verification] 无法从结构化数据获取发现,任务描述: {task[:200]}")
# 创建一个提示 LLM 从任务描述中理解漏洞的特殊处理
await self.emit_event("warning", f"无法从结构化数据获取发现列表,将基于任务描述进行验证")
# 去重
findings_to_verify = self._deduplicate(findings_to_verify)
# 🔥 FIX: 优先处理有明确文件路径的发现,将没有文件路径的发现放到后面
# 这确保 Analysis 的具体发现优先于 Recon 的泛化描述
def has_valid_file_path(finding: Dict) -> bool:
file_path = finding.get("file_path", "")
return bool(file_path and file_path.strip() and file_path.lower() not in ["unknown", "n/a", ""])
findings_with_path = [f for f in findings_to_verify if has_valid_file_path(f)]
findings_without_path = [f for f in findings_to_verify if not has_valid_file_path(f)]
# 合并:有路径的在前,没路径的在后
findings_to_verify = findings_with_path + findings_without_path
if findings_with_path:
logger.info(f"[Verification] 优先处理 {len(findings_with_path)} 个有明确文件路径的发现")
if findings_without_path:
logger.info(f"[Verification] 还有 {len(findings_without_path)} 个发现需要自行定位文件")
if not findings_to_verify:
logger.warning(f"[Verification] 没有需要验证的发现! previous_results keys: {list(previous_results.keys()) if isinstance(previous_results, dict) else 'not dict'}")
await self.emit_event("warning", "没有需要验证的发现 - 可能是数据格式问题")
return AgentResult(
success=True,
data={"findings": [], "verified_count": 0, "note": "未收到待验证的发现"},
)
# 限制数量
findings_to_verify = findings_to_verify[:20]
await self.emit_event(
"info",
f"开始验证 {len(findings_to_verify)} 个发现"
)
# 🔥 记录工作开始
self.record_work(f"开始验证 {len(findings_to_verify)} 个漏洞发现")
# 🔥 构建包含交接上下文的初始消息
handoff_context = self.get_handoff_context()
findings_summary = []
for i, f in enumerate(findings_to_verify):
# 🔥 FIX: 正确处理 file_path 格式,可能包含行号 (如 "app.py:36")
file_path = f.get('file_path', 'unknown')
line_start = f.get('line_start', 0)
# 如果 file_path 已包含行号,提取出来
if isinstance(file_path, str) and ':' in file_path:
parts = file_path.split(':', 1)
if len(parts) == 2 and parts[1].split()[0].isdigit():
file_path = parts[0]
try:
line_start = int(parts[1].split()[0])
except ValueError:
pass
findings_summary.append(f"""
### 发现 {i+1}: {f.get('title', 'Unknown')}
- 类型: {f.get('vulnerability_type', 'unknown')}
- 严重度: {f.get('severity', 'medium')}
- 文件: {file_path} (行 {line_start})
- 代码:
```
{f.get('code_snippet', 'N/A')[:500]}
```
- 描述: {f.get('description', 'N/A')[:300]}
""")
initial_message = f"""请验证以下 {len(findings_to_verify)} 个安全发现。
{handoff_context if handoff_context else ''}
## 待验证发现
{''.join(findings_summary)}
## ⚠️ 重要验证指南
1. **直接使用上面列出的文件路径** - 不要猜测或搜索其他路径
2. **如果文件路径包含冒号和行号** (如 "app.py:36"), 请提取文件名 "app.py" 并使用 read_file 读取
3. **先读取文件内容,再判断漏洞是否存在**
4. **不要假设文件在子目录中** - 使用发现中提供的精确路径
## 验证要求
- 验证级别: {config.get('verification_level', 'standard')}
## 可用工具
{self.get_tools_description()}
请开始验证。对于每个发现:
1. 首先使用 read_file 读取发现中指定的文件(使用精确路径)
2. 分析代码上下文
3. 判断是否为真实漏洞
{f"特别注意 Analysis Agent 提到的关注点。" if handoff_context else ""}"""
# 初始化对话历史
self._conversation_history = [
{"role": "system", "content": self.config.system_prompt},
{"role": "user", "content": initial_message},
]
self._steps = []
final_result = None
await self.emit_thinking("🔐 Verification Agent 启动,LLM 开始自主验证漏洞...")
try:
for iteration in range(self.config.max_iterations):
if self.is_cancelled:
break
self._iteration = iteration + 1
# 🔥 再次检查取消标志(在LLM调用之前)
if self.is_cancelled:
await self.emit_thinking("🛑 任务已取消,停止执行")
break
# 调用 LLM 进行思考和决策(流式输出)
try:
llm_output, tokens_this_round = await self.stream_llm_call(
self._conversation_history,
# 🔥 不传递 temperature 和 max_tokens,使用用户配置
)
except asyncio.CancelledError:
logger.info(f"[{self.name}] LLM call cancelled")
break
self._total_tokens += tokens_this_round
# 🔥 Handle empty LLM response to prevent loops
if not llm_output or not llm_output.strip():
logger.warning(f"[{self.name}] Empty LLM response in iteration {self._iteration}")
await self.emit_llm_decision("收到空响应", "LLM 返回内容为空,尝试重试通过提示")
self._conversation_history.append({
"role": "user",
"content": "Received empty response. Please output your Thought and Action.",
})
continue
# 解析 LLM 响应
step = self._parse_llm_response(llm_output)
self._steps.append(step)
# 🔥 发射 LLM 思考内容事件 - 展示验证的思考过程
if step.thought:
await self.emit_llm_thought(step.thought, iteration + 1)
# 添加 LLM 响应到历史
self._conversation_history.append({
"role": "assistant",
"content": llm_output,
})
# 检查是否完成
if step.is_final:
# 🔥 强制检查:必须至少调用过一次工具才能完成
if self._tool_calls == 0:
logger.warning(f"[{self.name}] LLM tried to finish without any tool calls! Forcing tool usage.")
await self.emit_thinking("⚠️ 拒绝过早完成:必须先使用工具验证漏洞")
self._conversation_history.append({
"role": "user",
"content": (
"⚠️ **系统拒绝**: 你必须先使用工具验证漏洞!\n\n"
"不允许在没有调用任何工具的情况下直接输出 Final Answer。\n\n"
"请立即使用以下工具之一进行验证:\n"
"1. `read_file` - 读取漏洞所在文件的代码\n"
"2. `run_code` - 编写并执行 Fuzzing Harness 验证漏洞\n"
"3. `extract_function` - 提取目标函数进行分析\n\n"
"现在请输出 Thought 和 Action,开始验证第一个漏洞。"
),
})
continue
await self.emit_llm_decision("完成漏洞验证", "LLM 判断验证已充分")
final_result = step.final_answer
# 🔥 记录洞察和工作
if final_result and "findings" in final_result:
verified_count = len([f for f in final_result["findings"] if f.get("is_verified")])
fp_count = len([f for f in final_result["findings"] if f.get("verdict") == "false_positive"])
self.add_insight(f"验证了 {len(final_result['findings'])} 个发现,{verified_count} 个确认,{fp_count} 个误报")
self.record_work(f"完成漏洞验证: {verified_count} 个确认, {fp_count} 个误报")
await self.emit_llm_complete(
f"验证完成",
self._total_tokens
)
break
# 执行工具
if step.action:
# 🔥 发射 LLM 动作决策事件
await self.emit_llm_action(step.action, step.action_input or {})
start_tool_time = time.time()
# 🔥 智能循环检测: 追踪重复调用 (无论成功与否)
tool_call_key = f"{step.action}:{json.dumps(step.action_input or {}, sort_keys=True)}"
if not hasattr(self, '_tool_call_counts'):
self._tool_call_counts = {}
self._tool_call_counts[tool_call_key] = self._tool_call_counts.get(tool_call_key, 0) + 1
# 如果同一操作重复尝试超过3次,强制干预
if self._tool_call_counts[tool_call_key] > 3:
logger.warning(f"[{self.name}] Detected repetitive tool call loop: {tool_call_key}")
observation = (
f"⚠️ **系统干预**: 你已经使用完全相同的参数调用了工具 '{step.action}' 超过3次。\n"
"请**不要**重复尝试相同的操作。这是无效的。\n"
"请尝试:\n"
"1. 修改参数 (例如改变 input payload)\n"
"2. 使用不同的工具 (例如从 sandbox_exec 换到 php_test)\n"
"3. 如果之前的尝试都失败了,请尝试 analyze_file 重新分析代码\n"
"4. 如果无法验证,请输出 Final Answer 并标记为 uncertain"
)
# 模拟观察结果,跳过实际执行
step.observation = observation
await self.emit_llm_observation(observation)
self._conversation_history.append({
"role": "user",
"content": f"Observation:\n{observation}",
})
continue
# 🔥 循环检测:追踪工具调用失败历史 (保留原有逻辑用于错误追踪)
if not hasattr(self, '_failed_tool_calls'):
self._failed_tool_calls = {}
observation = await self.execute_tool(
step.action,
step.action_input or {}
)
# 🔥 检测工具调用失败并追踪
is_tool_error = (
"失败" in observation or
"错误" in observation or
"不存在" in observation or
"文件过大" in observation or
"Error" in observation
)
if is_tool_error:
self._failed_tool_calls[tool_call_key] = self._failed_tool_calls.get(tool_call_key, 0) + 1
fail_count = self._failed_tool_calls[tool_call_key]
# 🔥 如果同一调用连续失败3次,添加强制跳过提示
if fail_count >= 3:
logger.warning(f"[{self.name}] Tool call failed {fail_count} times: {tool_call_key}")
observation += f"\n\n⚠️ **系统提示**: 此工具调用已连续失败 {fail_count} 次。请:\n"
observation += "1. 尝试使用不同的参数(如指定较小的行范围)\n"
observation += "2. 使用 search_code 工具定位关键代码片段\n"
observation += "3. 跳过此发现的验证,继续验证其他发现\n"
observation += "4. 如果已有足够验证结果,直接输出 Final Answer"
# 重置计数器
self._failed_tool_calls[tool_call_key] = 0
else:
# 成功调用,重置失败计数
if tool_call_key in self._failed_tool_calls:
del self._failed_tool_calls[tool_call_key]
# 🔥 工具执行后检查取消状态
if self.is_cancelled:
logger.info(f"[{self.name}] Cancelled after tool execution")
break
step.observation = observation
# 🔥 发射 LLM 观察事件
await self.emit_llm_observation(observation)
# 添加观察结果到历史
self._conversation_history.append({
"role": "user",
"content": f"Observation:\n{observation}",
})
else:
# LLM 没有选择工具,提示它继续
await self.emit_llm_decision("继续验证", "LLM 需要更多验证")
self._conversation_history.append({
"role": "user",
"content": "请继续验证。你输出了 Thought 但没有输出 Action。请**立即**选择一个工具执行,或者如果验证完成,输出 Final Answer 汇总所有验证结果。",
})
# 处理结果
duration_ms = int((time.time() - start_time) * 1000)
# 🔥 如果被取消,返回取消结果
if self.is_cancelled:
await self.emit_event(
"info",
f"🛑 Verification Agent 已取消: {self._iteration} 轮迭代"
)
return AgentResult(
success=False,
error="任务已取消",
data={"findings": findings_to_verify},
iterations=self._iteration,
tool_calls=self._tool_calls,
tokens_used=self._total_tokens,
duration_ms=duration_ms,
)
# 处理最终结果
verified_findings = []
# 🔥 Robustness: If LLM returns empty findings but we had input, fallback to original
llm_findings = []
if final_result and "findings" in final_result:
llm_findings = final_result["findings"]
if not llm_findings and findings_to_verify:
logger.warning(f"[{self.name}] LLM returned empty findings despite {len(findings_to_verify)} inputs. Falling back to originals.")
# Fallback to logic below (else branch)
final_result = None
if final_result and "findings" in final_result:
# 🔥 DEBUG: Log what LLM returned for verdict diagnosis
verdicts_debug = [(f.get("file_path", "?"), f.get("verdict"), f.get("confidence")) for f in final_result["findings"]]
logger.info(f"[{self.name}] LLM returned verdicts: {verdicts_debug}")
for f in final_result["findings"]:
# 🔥 FIX: Normalize verdict - handle missing/empty verdict
verdict = f.get("verdict")
if not verdict or verdict not in ["confirmed", "likely", "uncertain", "false_positive"]:
# Try to infer verdict from other fields
if f.get("is_verified") is True:
verdict = "confirmed"
elif f.get("confidence", 0) >= 0.8:
verdict = "likely"
elif f.get("confidence", 0) <= 0.3:
verdict = "false_positive"
else:
verdict = "uncertain"
logger.warning(f"[{self.name}] Missing/invalid verdict for {f.get('file_path', '?')}, inferred as: {verdict}")
verified = {
**f,
"verdict": verdict, # 🔥 Ensure verdict is set
"is_verified": verdict == "confirmed" or (
verdict == "likely" and f.get("confidence", 0) >= 0.8
),
"verified_at": datetime.now(timezone.utc).isoformat() if verdict in ["confirmed", "likely"] else None,
}
# 添加修复建议
if not verified.get("recommendation"):
verified["recommendation"] = self._get_recommendation(f.get("vulnerability_type", ""))
verified_findings.append(verified)
else:
# 如果没有最终结果,使用原始发现
for f in findings_to_verify:
verified_findings.append({
**f,
"verdict": "uncertain",
"confidence": 0.5,
"is_verified": False,
})
# 统计
confirmed_count = len([f for f in verified_findings if f.get("verdict") == "confirmed"])
likely_count = len([f for f in verified_findings if f.get("verdict") == "likely"])
false_positive_count = len([f for f in verified_findings if f.get("verdict") == "false_positive"])
await self.emit_event(
"info",
f"Verification Agent 完成: {confirmed_count} 确认, {likely_count} 可能, {false_positive_count} 误报"
)
# 🔥 CRITICAL: Log final findings count before returning
logger.info(f"[{self.name}] Returning {len(verified_findings)} verified findings")
return AgentResult(
success=True,
data={
"findings": verified_findings,
"verified_count": confirmed_count,
"likely_count": likely_count,
"false_positive_count": false_positive_count,
},
iterations=self._iteration,
tool_calls=self._tool_calls,
tokens_used=self._total_tokens,
duration_ms=duration_ms,
)
except Exception as e:
logger.error(f"Verification Agent failed: {e}", exc_info=True)
return AgentResult(success=False, error=str(e))代码中尝试接收 TaskHandoff 数据,尽管上层逻辑暂时缺失。此外,_get_recommendation 方法目前采用硬编码方式返回修复建议,而非由AI动态生成:
def _get_recommendation(self, vuln_type: str) -> str:
"""获取修复建议"""
recommendations = {
"sql_injection": "使用参数化查询或 ORM,避免字符串拼接构造 SQL",
"xss": "对用户输入进行 HTML 转义,使用 CSP,避免 innerHTML",
"command_injection": "避免使用 shell=True,使用参数列表传递命令",
"path_traversal": "验证和规范化路径,使用白名单,避免直接使用用户输入",
"ssrf": "验证和限制目标 URL,使用白名单,禁止内网访问",
"deserialization": "避免反序列化不可信数据,使用 JSON 替代 pickle/yaml",
"hardcoded_secret": "使用环境变量或密钥管理服务存储敏感信息",
"weak_crypto": "使用强加密算法(AES-256, SHA-256+),避免 MD5/SHA1",
}
return recommendations.get(vuln_type, "请根据具体情况修复此安全问题")RAG
RAG(检索增强生成)机制的核心目标是建立代码的语义向量索引,从而在漏洞审计时迅速定位相关业务逻辑。其整体处理流程如下:
代码文件 (*.py, *.js, *.java...)
│
▼
┌─────────────────────────┐
│ 1. 代码分块 (Splitter) │ ← 语法级别的智能分块
│ - 按函数、类分块 │
│ - 保留上下文 │
│ - 提取元数据 │
└─────────────────────────┘
│
▼
┌─────────────────────────┐
│ 2. 生成向量 (Embedding) │ ← 将代码转为向量
│ - 文本 → 数字向量 │
│ - 捕获语义信息 │
│ - 维度: 512-3072 │
└─────────────────────────┘
│
▼
┌─────────────────────────┐
│ 3. 存储索引 (Indexer) │ ← 建立向量数据库
│ - 向量入库 │
│ - 元数据关联 │
│ - 增量更新 │
└─────────────────────────┘
│
▼
┌─────────────────────────┐
│ 4. 查询检索 (Retriever) │ ← Agent 调用
│ - 自然语言查询 │
│ - 相似度匹配 │
│ - 返回代码片段 │
└─────────────────────────┘
│
▼
返回给 Agent (带有文件路径、行号、相似度)值得注意的是,该项目未采用现有的RAG框架,而是实现了一套自定义的解决方案。
代码分块
其中的核心方法 split_file 负责代码分块,服务于后续的存储与索引环节:
def split_file(
self,
content: str,
file_path: str,
language: Optional[str] = None
) -> List[CodeChunk]:
"""
分割单个文件
Args:
content: 文件内容
file_path: 文件路径
language: 编程语言(可选)
Returns:
代码块列表
"""
if not content or not content.strip():
return []
if language is None:
language = self.detect_language(file_path)
chunks = []
try:
# 尝试使用 Tree-sitter 解析
if self.use_tree_sitter and self._ts_parser:
tree = self._ts_parser.parse(content, language)
if tree:
chunks = self._split_by_ast(content, file_path, language, tree)
# 如果 AST 解析失败或没有结果,使用增强的正则解析
if not chunks:
chunks = self._split_by_enhanced_regex(content, file_path, language)
# 如果还是没有,使用基于行的分块
if not chunks:
chunks = self._split_by_lines(content, file_path, language)
# 后处理:提取安全指标
for chunk in chunks:
chunk.security_indicators = self._extract_security_indicators(
chunk.content, language
)
# 后处理:使用语义分析增强
self._enrich_chunks_with_semantics(chunks, content, language)
except Exception as e:
logger.warning(f"分块失败 {file_path}: {e}, 使用简单分块")
chunks = self._split_by_lines(content, file_path, language)
return chunks分块策略采用了降级机制:优先尝试AST解析,失败后回退至正则解析,最后兜底使用基于行的分块。略过具体的解析实现,我们重点关注用于后处理的 _extract_security_indicators 方法:
def _extract_security_indicators(self, content: str, language: str) -> List[str]:
"""提取安全相关指标"""
indicators = []
patterns = self.SECURITY_PATTERNS.get(language, [])
# 添加通用模式
common_patterns = [
(r"password", "password"),
(r"secret", "secret"),
(r"api[_-]?key", "api_key"),
(r"token", "token"),
(r"private[_-]?key", "private_key"),
(r"credential", "credential"),
]
all_patterns = patterns + common_patterns
for pattern, name in all_patterns:
try:
if re.search(pattern, content, re.IGNORECASE):
if name not in indicators:
indicators.append(name)
except re.error:
continue
return indicators[:15]其中,SECURITY_PATTERNS 涵盖了各类高风险函数:
SECURITY_PATTERNS = {
"python": [
(r"\bexec\s*\(", "exec"),
(r"\beval\s*\(", "eval"),
(r"\bcompile\s*\(", "compile"),
(r"\bos\.system\s*\(", "os_system"),
(r"\bsubprocess\.", "subprocess"),
(r"\bcursor\.execute\s*\(", "sql_execute"),
(r"\.execute\s*\(.*%", "sql_format"),
(r"\bpickle\.loads?\s*\(", "pickle"),
(r"\byaml\.load\s*\(", "yaml_load"),
(r"\brequests?\.", "http_request"),
(r"password\s*=", "password_assign"),
(r"secret\s*=", "secret_assign"),
(r"api_key\s*=", "api_key_assign"),
],
"javascript": [
(r"\beval\s*\(", "eval"),
(r"\bFunction\s*\(", "function_constructor"),
(r"innerHTML\s*=", "innerHTML"),
(r"outerHTML\s*=", "outerHTML"),
(r"document\.write\s*\(", "document_write"),
(r"\.exec\s*\(", "exec"),
(r"\.query\s*\(.*\+", "sql_concat"),
(r"password\s*[=:]", "password_assign"),
(r"apiKey\s*[=:]", "api_key_assign"),
],
"java": [
(r"Runtime\.getRuntime\(\)\.exec", "runtime_exec"),
(r"ProcessBuilder", "process_builder"),
(r"\.executeQuery\s*\(.*\+", "sql_concat"),
(r"ObjectInputStream", "deserialization"),
(r"XMLDecoder", "xml_decoder"),
(r"password\s*=", "password_assign"),
],
"go": [
(r"exec\.Command\s*\(", "exec_command"),
(r"\.Query\s*\(.*\+", "sql_concat"),
(r"\.Exec\s*\(.*\+", "sql_concat"),
(r"template\.HTML\s*\(", "unsafe_html"),
(r"password\s*=", "password_assign"),
],
"php": [
(r"\beval\s*\(", "eval"),
(r"\bexec\s*\(", "exec"),
(r"\bsystem\s*\(", "system"),
(r"\bshell_exec\s*\(", "shell_exec"),
(r"\$_GET\[", "get_input"),
(r"\$_POST\[", "post_input"),
(r"\$_REQUEST\[", "request_input"),
],
}向量生成
向量生成模块通过调用第三方API将代码转化为向量表示,其核心实现如下:
def _create_provider(
self,
provider: str,
model: str,
api_key: Optional[str],
base_url: Optional[str],
) -> EmbeddingProvider:
"""创建嵌入提供商实例"""
provider = provider.lower()
if provider == "ollama":
return OllamaEmbedding(base_url=base_url, model=model)
elif provider == "azure":
return AzureOpenAIEmbedding(api_key=api_key, base_url=base_url, model=model)
elif provider == "cohere":
return CohereEmbedding(api_key=api_key, base_url=base_url, model=model)
elif provider == "huggingface":
return HuggingFaceEmbedding(api_key=api_key, base_url=base_url, model=model)
elif provider == "jina":
return JinaEmbedding(api_key=api_key, base_url=base_url, model=model)
elif provider == "qwen":
return QwenEmbedding(api_key=api_key, base_url=base_url, model=model)
else:
# 默认使用 OpenAI
return OpenAIEmbedding(api_key=api_key, base_url=base_url, model=model)索引存储
此模块负责将向量存入ChromaDB。通过建立持久化索引,系统在审计相同代码时可直接复用向量数据,从而降低API调用成本并提升效率。
async def smart_index_directory(
self,
directory: str,
exclude_patterns: Optional[List[str]] = None,
include_patterns: Optional[List[str]] = None,
update_mode: IndexUpdateMode = IndexUpdateMode.SMART,
progress_callback: Optional[Callable[[IndexingProgress], None]] = None,
embedding_progress_callback: Optional[Callable[[int, int], None]] = None,
cancel_check: Optional[Callable[[], bool]] = None,
) -> AsyncGenerator[IndexingProgress, None]:
"""
智能索引目录
Args:
directory: 目录路径
exclude_patterns: 排除模式
include_patterns: 包含模式(🔥 用于限制只索引指定文件)
update_mode: 更新模式
progress_callback: 进度回调
embedding_progress_callback: 嵌入进度回调,接收 (processed, total) 参数
cancel_check: 取消检查函数,返回 True 表示应该取消
Yields:
索引进度
"""
# 初始化并检查是否需要重建
needs_rebuild, rebuild_reason = await self.initialize()
progress = IndexingProgress()
exclude_patterns = exclude_patterns or []
# 确定实际的更新模式
if update_mode == IndexUpdateMode.SMART:
if needs_rebuild:
actual_mode = IndexUpdateMode.FULL
logger.info(f"🔄 智能模式: 选择全量重建 (原因: {rebuild_reason})")
else:
actual_mode = IndexUpdateMode.INCREMENTAL
logger.info("📝 智能模式: 选择增量更新")
else:
actual_mode = update_mode
progress.update_mode = actual_mode.value
if actual_mode == IndexUpdateMode.FULL:
# 全量重建
async for p in self._full_index(directory, exclude_patterns, include_patterns, progress, progress_callback, embedding_progress_callback, cancel_check):
yield p
else:
# 增量更新
async for p in self._incremental_index(directory, exclude_patterns, include_patterns, progress, progress_callback, embedding_progress_callback, cancel_check):
yield p具体的存储实现细节在此不再赘述。
检索器
检索器旨在协助LLM进行语义级代码查找。我们重点关注 retrieve_function_context 方法,它是RAG机制中实现上下文追踪的关键:
async def retrieve_function_context(
self,
function_name: str,
file_path: Optional[str] = None,
include_callers: bool = True,
include_callees: bool = True,
top_k: int = 10,
) -> Dict[str, List[RetrievalResult]]:
"""
检索函数上下文
Args:
function_name: 函数名
file_path: 文件路径(可选)
include_callers: 是否包含调用者
include_callees: 是否包含被调用者
top_k: 每类返回数量
Returns:
包含函数定义、调用者、被调用者的字典
"""
context = {
"definition": [],
"callers": [],
"callees": [],
}
# 查找函数定义
definition_query = f"function definition {function_name}"
definitions = await self.retrieve(
definition_query,
top_k=5,
filter_file_path=file_path,
)
# 过滤出真正的定义
for result in definitions:
if result.name == function_name or function_name in (result.content or ""):
context["definition"].append(result)
if include_callers:
# 查找调用此函数的代码
caller_query = f"calls {function_name} invoke {function_name}"
callers = await self.retrieve(caller_query, top_k=top_k)
for result in callers:
# 检查是否真的调用了这个函数
if re.search(rf'\b{re.escape(function_name)}\s*\(', result.content):
if result not in context["definition"]:
context["callers"].append(result)
if include_callees and context["definition"]:
# 从函数定义中提取调用的其他函数
for definition in context["definition"]:
calls = re.findall(r'\b(\w+)\s*\(', definition.content)
unique_calls = list(set(calls))[:5] # 限制数量
for call in unique_calls:
if call == function_name:
continue
callees = await self.retrieve(
f"function {call} definition",
top_k=2,
)
context["callees"].extend(callees)
return context该方法旨在解决两个核心问题:函数的调用方与被调用方。
针对第一个问题,系统利用代码块标签进行索引查找。在代码分块阶段,若AST解析成功,会保留函数标签;检索时先基于语义定位相似方法,再通过正则进行精确匹配。
针对第二个问题,系统直接采用了正则匹配策略,限制提取前5个调用方法。
calls = re.findall(r'\b(\w+)\s*\(', definition.content)
unique_calls = list(set(calls))[:5] # 限制数量这种基于正则与语义混合的调用链分析方式虽然粗犷,但在配合LLM进行代码理解时往往能取得不错的效果。
Sandbox
Sandbox模块为 VerificationAgent 提供隔离的PoC验证环境,旨在防止验证过程对宿主服务器造成安全威胁。其整体架构如下:
┌───────────────────────────────────────────────────────────────┐
│ DeepAudit 沙箱架构 │
└───────────────────────────────────────────────────────────────┘
┌─────────────────────┐
│ Verification Agent │ ← LLM 驱动,自主决策验证策略
│ (验证 Agent) │
└──────────┬──────────┘
│
│ 调用工具
▼
┌─────────────────────┐
│ RunCodeTool │ ← 通用代码执行工具
│ (run_code) │
└──────────┬──────────┘
│
│ 委托执行
▼
┌─────────────────────┐
│ SandboxManager │ ← 沙箱管理器
│ (sandbox_tool.py) │
└──────────┬──────────┘
│
│ Docker API
▼
┌─────────────────────────────────────────────┐
│ Docker 容器 (隔离环境) │
├─────────────────────────────────────────────┤
│ 镜像: deepaudit/sandbox:latest │
│ │
│ ┌────────────────────────────────────┐ │
│ │ 运行环境 │ │
│ │ ├─ Python 3.11 │ │
│ │ ├─ Node.js 20 │ │
│ │ ├─ PHP 8 │ │
│ │ ├─ Java 11 │ │
│ │ ├─ Ruby 3 │ │
│ │ ├─ Go 1.21 │ │
│ │ └─ Rust (latest) │ │
│ └────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────┐ │
│ │ 安全工具 │ │
│ │ ├─ Semgrep │ │
│ │ ├─ Bandit │ │
│ │ ├─ Gitleaks │ │
│ │ └─ TruffleHog │ │
│ └────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────┐ │
│ │ 文件系统 │ │
│ │ ├─ / (只读) │ │
│ │ ├─ /workspace (可写,临时挂载) │ │
│ │ ├─ /tmp (可写,tmpfs,100MB) │ │
│ │ └─ /home/sandbox (可写,tmpfs) │ │
│ └────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────┐ │
│ │ 资源限制 │ │
│ │ ├─ 内存: 512MB │ │
│ │ ├─ CPU: 1.0 核 │ │
│ │ ├─ 超时: 60 秒 │ │
│ │ └─ 网络: 禁用 (network_mode=none) │ │
│ └────────────────────────────────────┘ │
│ │
│ ┌────────────────────────────────────┐ │
│ │ 安全配置 │ │
│ │ ├─ 用户: sandbox (UID 1000) │ │
│ │ ├─ Capabilities: 全部禁用 (ALL) │ │
│ │ ├─ Security Options: no-new- │ │
│ │ │ privileges │ │
│ │ └─ Seccomp: 系统调用过滤 │ │
│ └────────────────────────────────────┘ │
└─────────────────────────────────────────────┘核心架构
配置类:
@dataclass
class SandboxConfig:
"""沙箱配置"""
image: str = None # 默认从 settings.SANDBOX_IMAGE 读取
memory_limit: str = "512m"
cpu_limit: float = 1.0
timeout: int = 60
network_mode: str = "none" # none, bridge, host
read_only: bool = True
user: str = "1000:1000"
def __post_init__(self):
if self.image is None:
self.image = settings.SANDBOX_IMAGE用于初始化客户端的方法:
async def initialize(self):
"""初始化 Docker 客户端"""
if self._initialized:
logger.info("✅ SandboxManager already initialized")
return
try:
import docker
logger.info(f"🔄 Attempting to connect to Docker... (lib: {docker.__file__})")
self._docker_client = docker.from_env()
# 测试连接
self._docker_client.ping()
self._initialized = True
self._init_error = None
logger.info("✅ Docker sandbox manager initialized successfully")
except ImportError as e:
logger.error(f"❌ Docker library not installed: {e}")
self._docker_client = None
self._init_error = f"ImportError: {e}"
except Exception as e:
logger.warning(f"❌ Docker not available: {e}")
import traceback
logger.warning(f"Docker connection traceback: {traceback.format_exc()}")
self._docker_client = None
self._init_error = f"{type(e).__name__}: {str(e)}"用于执行命令的方法:
async def execute_command(
self,
command: str,
working_dir: Optional[str] = None,
env: Optional[Dict[str, str]] = None,
timeout: Optional[int] = None,
) -> Dict[str, Any]:
"""
在沙箱中执行命令
Args:
command: 要执行的命令
working_dir: 工作目录
env: 环境变量
timeout: 超时时间(秒)
Returns:
执行结果
"""
if not self.is_available:
return {
"success": False,
"error": "Docker 不可用",
"stdout": "",
"stderr": "",
"exit_code": -1,
}
timeout = timeout or self.config.timeout
# 禁用代理环境变量,防止 Docker 自动注入的代理干扰容器网络
no_proxy_env = {
"HTTP_PROXY": "",
"HTTPS_PROXY": "",
"http_proxy": "",
"https_proxy": "",
"NO_PROXY": "*",
"no_proxy": "*",
}
# 合并用户传入的环境变量(用户变量优先)
container_env = {**no_proxy_env, **(env or {})}
try:
# 创建临时目录
with tempfile.TemporaryDirectory() as temp_dir:
# 准备容器配置
container_config = {
"image": self.config.image,
"command": ["sh", "-c", command],
"detach": True,
"mem_limit": self.config.memory_limit,
"cpu_period": 100000,
"cpu_quota": int(100000 * self.config.cpu_limit),
"network_mode": self.config.network_mode,
"user": self.config.user,
"read_only": self.config.read_only,
"volumes": {
temp_dir: {"bind": "/workspace", "mode": "rw"},
},
"tmpfs": {
"/home/sandbox": "rw,size=100m,mode=1777",
"/tmp": "rw,size=100m,mode=1777"
},
"working_dir": working_dir or "/workspace",
"environment": container_env,
# 安全配置
"cap_drop": ["ALL"],
"security_opt": ["no-new-privileges:true"],
}
# 创建并启动容器
container = await asyncio.to_thread(
self._docker_client.containers.run,
**container_config
)
try:
# 等待执行完成
result = await asyncio.wait_for(
asyncio.to_thread(container.wait),
timeout=timeout
)
# 获取日志
stdout = await asyncio.to_thread(
container.logs, stdout=True, stderr=False
)
stderr = await asyncio.to_thread(
container.logs, stdout=False, stderr=True
)
return {
"success": result["StatusCode"] == 0,
"stdout": stdout.decode('utf-8', errors='ignore')[:10000],
"stderr": stderr.decode('utf-8', errors='ignore')[:2000],
"exit_code": result["StatusCode"],
"error": None,
}
except asyncio.TimeoutError:
await asyncio.to_thread(container.kill)
return {
"success": False,
"error": f"执行超时 ({timeout}秒)",
"stdout": "",
"stderr": "",
"exit_code": -1,
}
finally:
# 清理容器
await asyncio.to_thread(container.remove, force=True)
except Exception as e:
logger.error(f"Sandbox execution error: {e}")
return {
"success": False,
"error": str(e),
"stdout": "",
"stderr": "",
"exit_code": -1,
}可见,该容器在资源与权限上均受严格限制,以确保安全。
代码执行工具
其核心方法 _build_command 实现如下:
def _build_command(self, code: str, language: str) -> Optional[str]:
"""根据语言构建执行命令"""
# 转义单引号的通用方法
def escape_for_shell(s: str) -> str:
return s.replace("'", "'\"'\"'")
if language == "python":
escaped = escape_for_shell(code)
return f"python3 -c '{escaped}'"
elif language == "php":
# PHP: php -r 不需要 <?php 标签
clean_code = code.strip()
if clean_code.startswith("<?php"):
clean_code = clean_code[5:].strip()
if clean_code.startswith("<?"):
clean_code = clean_code[2:].strip()
if clean_code.endswith("?>"):
clean_code = clean_code[:-2].strip()
escaped = escape_for_shell(clean_code)
return f"php -r '{escaped}'"
elif language in ["javascript", "js", "node"]:
escaped = escape_for_shell(code)
return f"node -e '{escaped}'"
elif language == "ruby":
escaped = escape_for_shell(code)
return f"ruby -e '{escaped}'"
elif language == "bash":
escaped = escape_for_shell(code)
return f"bash -c '{escaped}'"
elif language == "go":
# Go 需要完整的 package main
escaped = escape_for_shell(code).replace("\\", "\\\\")
return f"echo '{escaped}' > /tmp/main.go && go run /tmp/main.go"
elif language == "java":
# Java 需要完整的 class
escaped = escape_for_shell(code).replace("\\", "\\\\")
# 提取类名
import re
class_match = re.search(r'public\s+class\s+(\w+)', code)
class_name = class_match.group(1) if class_match else "Test"
return f"echo '{escaped}' > /tmp/{class_name}.java && javac /tmp/{class_name}.java && java -cp /tmp {class_name}"
return None对于Python或PHP等脚本语言,命令构建相对直观;而对于Java等强类型语言,复杂的类结构可能导致验证代码格式出错,增加了动态验证的难度。
Docker配置
FROM python:3.11-bullseye
# 安装编程语言运行时
RUN apt-get update && apt-get install -y \
# 基础工具
curl wget git unzip jq \
# 语言运行时
php-cli \
openjdk-11-jdk-headless \
ruby-full \
# 构建工具
build-essential cmake clang llvm \
&& rm -rf /var/lib/apt/lists/*
# 安装 Node.js 20
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y nodejs
# 安装 Go 1.21
ENV PATH=$PATH:/usr/local/go/bin
RUN curl -L https://mirrors.aliyun.com/golang/go1.21.6.linux-amd64.tar.gz -o go.tar.gz \
&& tar -C /usr/local -xzf go.tar.gz \
&& rm go.tar.gz
# 安装 Rust
ENV RUSTUP_HOME=/usr/local/rustup \
CARGO_HOME=/usr/local/cargo \
PATH=/usr/local/cargo/bin:$PATH
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
# 安装 Python 安全工具
RUN pip install --no-cache-dir \
requests httpx aiohttp \
beautifulsoup4 lxml \
pycryptodome paramiko pyjwt \
sqlparse \
semgrep bandit safety
# 安装静态分析工具
RUN curl -L https://github.com/gitleaks/gitleaks/releases/download/v8.18.2/gitleaks_8.18.2_linux_x64.tar.gz -o gitleaks.tar.gz \
&& tar -xzf gitleaks.tar.gz \
&& mv gitleaks /usr/local/bin/ \
&& rm gitleaks.tar.gz
# 创建非 root 用户
RUN groupadd -g 1000 sandbox && \
useradd -u 1000 -g sandbox -m -s /bin/bash sandbox
# 创建工作目录
RUN mkdir -p /workspace /tmp/sandbox && \
chown -R sandbox:sandbox /workspace /tmp/sandbox
# 环境变量
ENV HOME=/home/sandbox
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# 默认用户和工作目录
USER sandbox
WORKDIR /workspace
CMD ["/bin/bash"]ToolCall
各类工具的集成流程略有差异。以下以昆仑镜 Kunlun-M 为例进行解析:
自检查与初始化
首先是 _ensure_initialized 方法,用于确保存境完整性:
async def _ensure_initialized(self) -> bool:
"""确保 Kunlun-M 已初始化"""
if self._initialized:
return True
# 检查 Kunlun-M 是否存在
if not os.path.exists(self.kunlun_path):
logger.error(f"Kunlun-M not found at {self.kunlun_path}")
return False
kunlun_py = os.path.join(self.kunlun_path, "kunlun.py")
if not os.path.exists(kunlun_py):
logger.error(f"kunlun.py not found at {kunlun_py}")
return False
# 检查数据库是否已初始化
db_path = os.path.join(self.kunlun_path, "db.sqlite3")
if not os.path.exists(db_path):
logger.info("Kunlun-M database not found, initializing...")
try:
await self._initialize_database()
except Exception as e:
logger.error(f"Failed to initialize Kunlun-M database: {e}")
return False
self._initialized = True
return True该步骤校验了工具路径的有效性及其初始化状态。
命令构建
接着是 execute 方法,负责构建执行命令与参数拼接:
async def _execute(
self,
target_path: str = ".",
language: Optional[str] = None,
rules: Optional[str] = None,
tamper: Optional[str] = None,
include_unconfirmed: bool = False,
max_results: int = 50,
**kwargs
) -> ToolResult:
"""执行 Kunlun-M 扫描"""
# 确保初始化
if not await self._ensure_initialized():
return ToolResult(
success=False,
error="Kunlun-M 未正确安装或初始化失败。请确保 Kunlun-M-master 目录存在且依赖已安装。"
)
# 构建完整目标路径
if target_path.startswith("/"):
full_target = target_path
else:
full_target = os.path.join(self.project_root, target_path)
if not os.path.exists(full_target):
return ToolResult(
success=False,
error=f"目标路径不存在: {target_path}"
)
# 构建扫描命令
cmd = [
sys.executable,
os.path.join(self.kunlun_path, "kunlun.py"),
"scan",
"-t", full_target,
"-o", "json" # JSON 输出格式
]
# 添加语言参数
if language:
if language.lower() not in self.SUPPORTED_LANGUAGES:
return ToolResult(
success=False,
error=f"不支持的语言: {language}。支持: {', '.join(self.SUPPORTED_LANGUAGES)}"
)
cmd.extend(["-l", language.lower()])
# 添加规则参数
if rules:
cmd.extend(["-r", rules])
# 添加 tamper 参数
if tamper:
cmd.extend(["-tp", tamper])
# 包含未确认漏洞
if include_unconfirmed:
cmd.append("-uc")
try:
# 创建临时输出文件
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
output_file = f.name
# 修改命令使用输出文件
cmd.extend(["-o", output_file])
logger.debug(f"Running Kunlun-M: {' '.join(cmd)}")
# 执行扫描
process = await asyncio.create_subprocess_exec(
*cmd,
cwd=self.kunlun_path,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env={**os.environ, "DJANGO_SETTINGS_MODULE": "Kunlun_M.settings"}
)
stdout, stderr = await asyncio.wait_for(
process.communicate(),
timeout=600 # 10 分钟超时
)
stdout_text = stdout.decode('utf-8', errors='ignore')
stderr_text = stderr.decode('utf-8', errors='ignore')
# 解析结果
findings = await self._parse_results(stdout_text, stderr_text, output_file)
# 清理临时文件
try:
os.unlink(output_file)
except:
pass
if not findings:
return ToolResult(
success=True,
data="🛡️ Kunlun-M 扫描完成,未发现安全问题",
metadata={
"findings_count": 0,
"target": target_path,
"language": language
}
)
# 格式化输出
output = self._format_findings(findings[:max_results], target_path)
return ToolResult(
success=True,
data=output,
metadata={
"findings_count": len(findings),
"target": target_path,
"language": language,
"findings": findings[:10] # 只在 metadata 中保存前10个
}
)
except asyncio.TimeoutError:
return ToolResult(
success=False,
error="Kunlun-M 扫描超时(10分钟)"
)
except Exception as e:
logger.error(f"Kunlun-M scan error: {e}", exc_info=True)
return ToolResult(
success=False,
error=f"扫描执行失败: {str(e)}"
)结果解析
最后,_parse_results 方法负责对工具的标准输出进行格式化解析。
async def _parse_results(
self,
stdout: str,
stderr: str,
output_file: str
) -> List[Dict[str, Any]]:
"""解析 Kunlun-M 扫描结果"""
findings = []
# 尝试从输出文件读取 JSON
try:
if os.path.exists(output_file):
with open(output_file, 'r', encoding='utf-8') as f:
data = json.load(f)
if isinstance(data, list):
findings.extend(data)
elif isinstance(data, dict) and 'vulnerabilities' in data:
findings.extend(data['vulnerabilities'])
except Exception as e:
logger.debug(f"Failed to parse output file: {e}")
# 如果没有 JSON 输出,尝试从 stdout 解析
if not findings and stdout:
# 尝试提取 JSON 部分
try:
json_start = stdout.find('[')
json_end = stdout.rfind(']') + 1
if json_start >= 0 and json_end > json_start:
json_str = stdout[json_start:json_end]
findings = json.loads(json_str)
except:
pass
# 尝试解析表格格式输出
if not findings:
findings = self._parse_table_output(stdout)
return findings但是我似乎发现一个问题啊,他这个项目中疑似没有拉取昆仑镜的操作,还要自己下载完放进去。
总结
这是我接触的第一个llm4sec的项目,感觉他的架构设计等方面非常的精巧,总体来说可以分为如下几点:
- MultiAgent
- ToolCall
- RAG
- Sandbox
在阅读的过程中也发现了代码中的一些问题,但相信会在版本的升级中变的越来越完善。
深入剖析DeepAudit的Multi-Agent、RAG、Sandbox与ToolCall四大核心模块实现机制。
由 AI 根据全文自动生成,仅供参考,以原文为准