stephen-devops/THF-QwenModel
GitHub: stephen-devops/THF-QwenModel
一个基于 LangChain 和大语言模型的 AI 威胁狩猎框架,允许安全分析师通过自然语言对话式查询 Wazuh SIEM 数据并进行深度安全分析。
Stars: 0 | Forks: 0
# THF (威胁狩猎框架)
一个基于 AI 的自然语言接口,使用 LangChain 和 Anthropic Claude 为 Wazuh SIEM 提供支持。
# 📖 用户指南
## 概述
THF (Threat Hunting Framework) 是一个复杂的 AI 驱动的安全分析平台,为 Wazuh SIEM 数据提供会话式界面。该系统通过 LangChain 利用 Claude AI (Anthropic 的 Claude Sonnet 4),使安全分析师能够使用自然语言查询来调查安全事件、分析警报并了解其安全态势。
该框架将用户查询转换为结构化的函数调用,对 Wazuh OpenSearch 后端和 Wazuh API 执行这些调用,并在多轮对话中保持完整的上下文,从而返回具有可操作性的安全洞察。
## 安装说明与设置
### 前置条件
- Python 3.9+
- Anthropic API 密钥
- Wazuh OpenSearch 集群的访问权限
- Redis(可选,用于缓存)
### 安装步骤
1. 克隆仓库:
git clone https://github.com/resilmesh2/THF.git
cd THF/
2. 安装所需依赖
pip install -r requirements.txt
3. 配置环境变量
cp .env.example .env
## 环境变量
### 编辑 .env 并配置您的 API 密钥
必须在您的 `.env` 文件中配置以下环境变量:
**Anthropic 配置:**
- `ANTHROPIC_API_KEY` - 您的 Anthropic API 密钥,用于访问 Claude AI
**OpenSearch 配置:**
- `OPENSEARCH_HOST` - 您的 OpenSearch 主机地址
- `OPENSEARCH_PORT` - OpenSearch 端口(默认:9200)
- `OPENSEARCH_USER` - OpenSearch 用户名(默认:admin)
- `OPENSEARCH_PASSWORD` - OpenSearch 密码
- `OPENSEARCH_USE_SSL` - 为 OpenSearch 连接启用 SSL(true/false)
**Wazuh API 配置:**
- `WAZUH_API_HOST` - Wazuh API 主机地址(默认:localhost)
- `WAZUH_API_PORT` - Wazuh API 端口(默认:55000)
- `WAZUH_API_USERNAME` - Wazuh API 用户名
- `WAZUH_API_PASSWORD` - Wazuh API 密码
- `WAZUH_API_USE_SSL` - 为 Wazuh API 启用 SSL(true/false)
- `WAZUH_API_VERIFY_CERTS` - 验证 SSL 证书(true/false)
**Redis 配置(可选):**
- `REDIS_HOST` - Redis 主机地址(默认:localhost)
- `REDIS_PORT` - Redis 端口(默认:6379)
- `REDIS_PASSWORD` - Redis 密码(如无需要请留空)
**应用配置:**
- `LOG_LEVEL` - 日志级别(INFO、DEBUG、WARNING、ERROR)
- `API_HOST` - FastAPI 主机绑定(默认:0.0.0.0)
- `API_PORT` - FastAPI 端口(Docker 默认为 8000,本地默认为 8000)
**端口说明:**
- **Docker**:容器运行在端口 8000,映射到主机端口 8030(通过 `http://localhost:8030` 访问)
- **本地**:应用程序直接运行在端口 8000(通过 `http://localhost:8000` 访问)
## 运行应用程序
安装依赖项后,您需要启动 FastAPI 后端和 Streamlit 前端 UI。
1. 首先,启动 FastAPI 后端服务器:
uvicorn main:app --host 0.0.0.0 --port 8000
2. 然后在一个新终端中,启动 Streamlit UI:
streamlit run ./streamlit_ui.py
后端将在 `http://localhost:8000` 上可用,UI 默认在 `http://localhost:8501` 上可用。
**注意:**使用 Docker 时,由于端口映射(docker-compose.yml 中的 `8030:8000`),后端需通过 `http://localhost:8030` 访问。
3. 访问 Streamlit UI 并开始威胁狩猎:
- 打开浏览器并导航至 `http://localhost:8501`
- 在文本输入框中输入自然语言安全查询
- 按 Enter 键或点击输入框外部提交
可以尝试的威胁狩猎查询示例:
Show me the top 10 hosts with most alerts the past two days
What alerts are there for user SYSTEM?
Find hosts with more than 20 failed login attempts
Which agents are disconnected?
Which users accessed host win10-01 in the last 24 hours?
Find T1055 process injection techniques detected in the last 12 hours.
Check for Log4Shell vulnerabilities on our Windows hosts.
## 功能
### 8 项核心安全能力
1. **analyze_alerts** - 警报分析,包括排名、过滤、计数、分布
2. **investigate_entity** - 实体调查(主机、用户、进程、文件)
3. **detect_threats** - MITRE ATT&CK 技术、战术、威胁行为者
4. **map_relationships** - 实体关系、活动关联
5. **find_anomalies** - 阈值、行为、趋势检测
6. **trace_timeline** - 按时间顺序的事件重建
7. **check_vulnerabilities** - CVE 检查和漏洞评估
8. **monitor_agents** - Agent 状态、健康和连接监控
### 详细安全意图与子操作分解
#### 1. 分析警报
| 子操作 | 描述 |
|------------|-------------|
| **计数** | 返回定量的警报量分析,并按严重程度、规则、Agent 和时间模式提供统计细分。 |
| **过滤** | 检索与过滤条件匹配的特定警报文档,并提供用于调查的上下文摘要。 |
| **分布** | 跨安全维度(Agent、用户、进程、规则、级别严重性、时间标准、规则组、地理位置)执行全面的单维或多维警报模式分析,提供用于威胁分析的交叉关联、百分比细分和时间模式。 |
| **排名/堆叠** | 按警报频率对实体进行排名或堆叠(例如,警报最多的主机、用户、规则,最严重的警报等)。 |
**示例查询:**
**计数:**
- "Count all critical alerts from the last 24 hours"
- "Count alerts by user and integrity level for today"
- "Count high severity alerts with MITRE technique breakdown for the past 2 days"
**过滤:**
- "Filter the dataset for alerts with severity level 15"
- "Find alerts with process name 'powershell.exe'"
- "Filter all critical alerts with rule group 'sysmon' in the past 12 hours"
**分布:**
- "Show me alert distribution by rule group this week"
- "Show me a distribution of alerts by severity levels and hourly time periods over the past three days"
- "Give me alert correlations between users, hosts, and severity levels"
**排名/堆叠:**
- "Rank hosts by alert frequency"
- "What are the most frequently triggered security rules on host U209-PC-BLEE in the last 24 hours?"
- "Show me the most active host in terms of security alerts over the past 6 hours"
#### 2. 发现异常
| 子操作 | 描述 |
|------------|-------------|
| **行为基线** | 通过将较长天数期间的当前行为与 RCF 学习的基线进行比较,检测实体活动中的长期行为活动。 |
| **基于阈值的检测** | 通过将实时数据与由 RCF 学习的基线建立的动态指标阈值(警报计数、主机活动、用户活动、警报严重性)进行比较,检测短时间内突然爆发的巨大异常活动。检测到的异常活动包括暴力破解活动或蠕虫传播。 |
| **趋势分析** | 检测不断升级和渐进的网络异常活动趋势,这些趋势在长期内不断升级并积聚动力,包括内部威胁升级检测或零日漏洞利用。 |
**示例查询:**
**基于阈值的检测:**
- "Detect sudden spikes in failed login attempts for the past 12 hours."
- "Find authentication brute force attempts with exceeding user diversity anomalies in the last 2 hours using 3-day RCF baseline"
- "Detect rapid malware spread with host diversity exceeding 20 affected systems and alert volume over 500 in the last 1 hour using 3-day RCF baseline"
- "Find critical alert volume threshold breaches on hosts in the last 12 days using 3-day RCF learned baselines"
**行为基线:**
- "Find coordinated activities involving user SYSTEM in the last 4 hours."
- "Detect compromised user account behaviour with abnormal user activity patterns and process execution deviations in the last 2 days using 7-day RCF behavioural baseline with high sensitivity"
- "Detect insider threat behaviour with unusual user activity diversity and abnormal host access patterns in the last 21 days using 60-day RCF behavioural baseline with medium sensitivity"
**趋势分析:**
- "Show me escalating threat trends over the past week"
- "Find increasing alert volume trends in the last 24 hours with high sensitivity using 7-day baseline"
- "Detect lateral movement with progressive host spread trends and temporal escalation in the last 24 hours using 14-day RCF trend baseline with high sensitivity"
- "Find insider threat escalation patterns with increasing user activity and severity progression in the last 7 days using 30-day RCF trend baseline"
#### 3. 调查实体
| 子操作 | 描述 |
|------------|-------------|
| **警报检索** | 检索并分析指定实体(用户帐户、主机、文件、进程)的警报。这提供了警报随时间顺序分布的统计细分以及最近触发的警报。 |
| **详细信息** | 提供有关实体的全面详细信息、完整配置文件,包括总警报数、详细的 MITRE ATT&CK 关联、风险评分和警报严重性细分。 |
| **活动分析** | 对实体执行行为分析以识别行为模式,包括警报活动突发、高峰使用时间段、进程执行和用户交互,从而提供对指定实体正常行为的洞察。 |
| **状态监控** | 提供实体的操作和性能分析,包括最近的安全警报、Agent 连接状态、服务状态以及实体的整体健康状况评分。 |
**示例查询:**
**警报检索:**
- "Show me all alerts for host win10-01."
- "Give all alerts from host 012 for the last 6 hours."
- "What alerts have been triggered by user SYSTEM this week?"
**详细信息:**
- "Get detailed information about user administrator"
- "Show me detailed information for host U209-PC-BLEE for today"
- "Get full detail information for host 192.168.201.33 including risk score"
**活动分析:**
- "Analyze activity patterns for process powershell.exe"
- "Analyze activity patterns for host win10-02 over the last three days"
- "Track activity patterns for host Win10-01 over the past four days"
**状态监控:**
- "Show a status report on the host U209-PC-BLEE"
- "What's the current security status of host MAIL-SERVER?"
- "Give a status report on host with the IP address 192.168.201.33"
#### 4. 映射关系
| 子操作 | 描述 |
|------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| **实体到实体** | 通过在安全数据中查找共享事件或直接交互,映射指定实体(主机、用户、进程、文件)之间的直接关系。识别哪些实体相互交互,并基于警报严重性评估关系的强度、类型和风险评分,以用于安全调查和横向移动检测。 |
| **行为关联** | 识别跨多个实体在相似时间范围内发生的、相关的行为模式或活动,表明存在协调行动、攻击链或系统性活动。 |
**示例查询:**
**实体到实体:**
- "Show me which hosts user SYSTEM accessed today."
- "Which users have accessed host with IP 192.168.201.33 in the past 24 hours?"
- "Show me all files that were loaded by the svchost.exe process over the past 6 hours"
- "What files were deleted by process TiWorker.exe on May 15 2025?"
- "Show me a process injecting into another process on Aug 13 2025"
**行为关联:**
- "Analyse correlated activities between host win10-01 and other entities in the last 6 hours"
- "Find coordinated activities involving user SYSTEM in the last 4 hours"
- "Detect unusual access sequences from host with IP 192.168.201.33 for the past hour"
#### 5. 追踪时间线
| 子操作 | 描述 |
|------------|-------------|
| **显示序列** | 按安全事件发生的顺序生成按时间顺序排列的时间线,例如主机上的操作序列、由用户执行的操作或涉及特定进程的操作。 |
| **攻击演进** | 跟踪攻击随时间的演变和发展,识别攻击链。关注关键事件并展示攻击者如何从最初的妥协阶段转移到后续阶段。 |
| **时间关联** | 查找在时间上接近发生的事件(在指定的时间窗口内),帮助识别可能是攻击或事件一部分的相关活动。 |
**示例查询:**
**显示序列:**
- "Show me the event sequence for host server-01 from 2pm to 4pm."
- "Display the sequence of events yesterday between 06:00:00 and 12:00:00"
- "Show a sequential timeline of all critical alerts over the past 12 hours"
- "Show me any detailed sequence of authentication events on agent 012 over the past 2 days"
**攻击演进:**
- "Show a timeline of events preceding a T1059.003 alert over the past hour"
- "Trace how the attack developed on win10-01 from initial access at 09:47:45 UTC"
- "Show attack evolution for host with IP address 192.168.201.33 over past two hours"
**时间关联:**
- "Show me any temporal correlations between events for host win10-01 in the last four hours"
- "Identify coordinated activity patterns across multiple entities within 10-minute windows"
- "Show temporally correlated events for user SYSTEM for the past three days"
## 使用 THF 进行威胁狩猎
### 入门
1. **提出初始问题**:从广泛的查询开始,以了解您的安全态势
- "Show me an alert breakdown for U209-PC-BLEE over the past 12 hours."
- "Show me critical alerts from today"
- "Which agents are disconnected?"
- "What are the top 10 hosts with most alerts?"
2. **后续问题**:THF 会记住之前查询的上下文
- 查看警报后:"Give me more details on those critical alerts from this time frame."
- 查看主机后:"What about authentication failures on that host?"
- 调查后:"Show me a timeline for those events"
3. **调查实体**:深入探究特定的主机、用户、进程或文件
- "What alerts are there for host win10-01?"
- "Show me all activity for user administrator in the last 24 hours"
- "What files did powershell.exe create today?"
4. **检测威胁**:寻找 MITRE ATT&CK 技术和可疑模式
- "Find T1055 process injection techniques detected recently"
- "Show me unusual login patterns from yesterday"
- "Are there any credential dumping attempts?"
5. **映射关系**:了解实体之间的连接
- "Which users accessed host win10-01 today?"
- "What processes did cmd.exe create?"
- "Show me files accessed by suspicious processes"
### 会话管理
- 每次对话在多个查询中保持上下文
- 使用侧边栏中的 "Reset Session" 按钮开始新的调查
- 查看会话信息以了解对话历史
```
# 重置 session memory
POST /reset?session_id=your-session-id
# 获取 session 信息
GET /session/{session_id}
# 列出所有活跃 session
GET /sessions
```
### 健康与系统信息
```
# 健康检查
```bash
curl http://localhost:8000/health
# 或者如果使用 Docker:curl http://localhost:8030/health
```
## 路线图
### 已完成功能 ✓
- [x] 基于 Claude Sonnet 4 的自然语言接口
- [x] 基于会话的对话记忆
- [x] 跨查询的上下文保留
- [x] 8 个核心安全分析意图,包含 30 多个子操作
- [x] Streamlit Web 界面
- [x] FastAPI REST API
- [x] OpenSearch 和 Wazuh API 集成
- [x] 智能路由和字段检测
- [x] 自然语言时间解析
- [x] MITRE ATT&CK 威胁检测
- [x] 实体关系映射
- [x] 基于 RCF 基线的异常检测
- [x] 全面的日志记录和追踪
### 计划功能
- [ ] 使用本地模型替换 Claude Sonnet 4.5 以加速威胁狩猎响应
- [ ] 支持自定义 Wazuh 规则和解码器
- [ ] 与外部威胁情报源集成
- [ ] 具有基于角色的访问控制的多租户支持
- [ ] 高级可视化功能和仪表板
- [ ] 使用 Redis 缓存查询结果
- [ ] 自动生成报告
- [ ] 定时的威胁狩猎查询
- [ ] 与工单系统集成 (Jira、ServiceNow)
- [ ] 移动应用界面
# 🔧 技术文档
## 应用程序架构
```
User Query → Context Processor → LangChain Agent → Tool Selection → Function Execution → OpenSearch/Wazuh API → Response Generation → User
↓ ↓
Session Memory Function Dispatcher
```
### 核心组件
#### 1. WazuhSecurityAgent (`agent/wazuh_agent.py`)
管理整个查询处理生命周期的中央编排器:
- **LLM 模型**:Claude Sonnet 4
- **Agent 类型**:STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION
- **会话管理**:用于隔离对话上下文的唯一会话 ID
- **内存系统**:ConversationSummaryBufferMemory(每个会话 1500 token 限制)
- **最大迭代次数**:3 次,并带有提前停止机制以优化 API 使用
- **超时**:每次 API 调用 30 秒,带有指数退避重试逻辑
- **主要特性**:
- 基于会话的对话内存可防止用户之间的上下文干扰
- 在 API 过载(529 错误)时自动重试,带有 2 秒、4 秒的退避机制
- 跨多轮对话的上下文保留
- 实时 Agent 状态管理
#### 2. ConversationContextProcessor (`agent/context_processor.py`)
智能上下文分析和保留系统:
- **上下文检测**:识别上下文引用("these alerts"、"that host"、"this process")
- **实体提取**:从对话历史中提取主机、用户、进程、文件、IP
- **时间上下文**:跨查询保留时间范围
- **查询丰富**:自动将先前的过滤器应用于后续查询
- **检测策略**:
- 显式关键字匹配
- 数字引用跟踪
- 定冠词模式
- 实体引用提取
#### 3. 安全功能模块 (`functions/`)
8 个专用模块,包含 30 多个子操作,用于全面的安全分析:
- **analyze_alerts**:警报排名、过滤、计数、分布分析
- **investigate_entity**:深入调查(主机、用户、进程、文件、IP)
- **detect_threats**:MITRE ATT&CK 技术、战术、威胁行为者、IoCs
- **map_relationships**:带有行为关联的实体关系映射
- **find_anomalies**:使用 RCF 基线进行阈值、行为、趋势检测
- **trace_timeline**:按时间顺序的事件重建和攻击演进
- **check_vulnerabilities**:CVE 检查、补丁状态、漏洞评估
- **monitor_agents**:Agent 状态、健康、连接监控
#### 4. 数据集成层 (`functions/_shared/`)
**WazuhOpenSearchClient**:
- 支持 SSL 的异步 OpenSearch 连接
- 智能字段映射(自动检测 agent.id 与 agent.name)
- 使用通配符和术语查询的智能查询构建
- 自然语言时间范围解析("3 days ago"、"yesterday 6am-11am")
- Wazuh 数组字段规范化
**WazuhAPIClient**:
- 带有 token 缓存的 JWT 认证
- Agent 状态监控(active、disconnected、never_connected)
- Agent 搜索和汇总统计
- 全面的 Agent 信息检索
#### 5. Web 界面
**FastAPI 后端** (`main.py`):
- 带有 WebSocket 支持的异步 REST API
- 会话管理端点
- 健康检查和监控
- 用于生产环境的 CORS 配置
**Streamlit UI** (`streamlit_ui.py`):
- 实时对话界面
- 会话管理(创建、重置、查看信息)
- 示例查询建议
- API 健康状态指示器
- 带有时间戳的对话历史
#### 6. 类型安全与验证 (`schemas/`)
- 用于所有函数参数的 Pydantic schemas
- 基于枚举的动作/类型选择
- 自动 JSON 序列化
- 请求/响应验证
## 高级用法
### REST API
查询助手:
```
curl -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{"query": "Show me critical alerts from the last hour"}'
```
### 查询端点
```
POST /query
Content-Type: application/json
{
"query": "Show me critical alerts from the last hour",
"session_id": "optional-session-id"
}
```
## 开发
### 项目结构
```
THF/
├── agent/ # Core LLM agent implementation
│ ├── wazuh_agent.py # Main LangChain agent orchestrator
│ ├── context_processor.py # Conversation context analysis
│ └── __init__.py
├── functions/ # Security analysis function modules
│ ├── analyze_alerts/ # Alert ranking, filtering, counting, distribution
│ ├── investigate_entity/ # Host, user, process, file investigation
│ ├── map_relationships/ # Entity relationship mapping and correlation
│ ├── detect_threats/ # MITRE ATT&CK detection, threat actors, IoCs
│ ├── find_anomalies/ # Threshold, behavioral, trend anomaly detection
│ ├── trace_timeline/ # Event timeline reconstruction
│ ├── check_vulnerabilities/ # CVE checking, vulnerability assessment
│ ├── monitor_agents/ # Agent status, health, version monitoring
│ ├── smart_routing/ # Intelligent query routing
│ └── _shared/ # Shared utilities
│ ├── opensearch_client.py # OpenSearch integration
│ ├── wazuh_api_client.py # Wazuh API integration
│ ├── time_parser.py # Natural language time parsing
│ └── utils.py # Common utilities
├── tools/ # LangChain tool wrappers
├── schemas/ # Pydantic validation schemas
├── assets/ # Static assets (logos, images)
├── tests/ # Test suite
├── docs/ # Documentation
├── main.py # FastAPI backend server
├── streamlit_ui.py # Streamlit web UI
├── demo_server.py # Demo/testing server
├── start_ui.py # UI launcher script
├── requirements.txt # Python dependencies
├── README.md # This file
└── .env # Environment configuration
```
### 关键架构特性
#### 基于会话的内存管理
- **隔离上下文**:每个用户会话维护独立的对话内存
- **防止内存干扰**:并发用户之间互不干扰
- **上下文感知的后续查询**:系统记住先前查询中的实体、过滤器和时间范围
- **Token 优化**:ConversationSummaryBufferMemory 具有 1500 token 限制
#### 智能上下文保留
`ConversationContextProcessor` (agent/context_processor.py:1) 分析对话以:
- 检测上下文引用("these alerts"、"that host")
- 从先前的响应中提取实体
- 跨查询保留时间上下文
- 使用相关的过滤器丰富后续查询
#### 智能路由与字段检测
- **自动字段映射**:检测是使用 agent.id 还是 agent.name
- **进程智能**:跨 originalFileName、image、commandLine 进行搜索
- **多字段搜索**:全面覆盖主机、进程、文件
- **自然语言时间解析**:支持 "3 days ago"、"yesterday 6am-11am"
标签:Agent, AI助手, AI安全, AI驱动安全, Anthropic Claude, API集成, Chat Copilot, Claude Sonnet 4, DLL 劫持, Function Call, Kubernetes, LangChain, LLM, NLP, Python, Qwen LLM, Redis, SecOps, Unmanaged PE, Wazuh, 云安全架构, 信息收集自动化, 函数调用, 可观测性, 多轮对话, 大语言模型, 子域名变形, 安全信息和事件管理, 安全分析平台, 安全告警分析, 安全态势感知, 安全运营, 对话式接口, 扫描框架, 搜索引擎查询, 无后门, 无线安全, 网络安全, 网络安全审计, 轻量级, 逆向工具, 隐私保护