AaravMehta-07/Redcore
GitHub: AaravMehta-07/Redcore
一个基于微调 LLM 的自主 AI 红队渗透测试代理,集成 242 个安全工具,能自主规划多阶段攻击、自适应重试并生成附带 MITRE ATT&CK 映射的专业渗透测试报告。
Stars: 2 | Forks: 0
# RedCore — 自主 AI 红队代理






**生产级自主 B2B AI 渗透测试平台。**
RedCore 接收一个纯英文的测试目标,利用自定义微调的 LLM 自主规划多阶段攻击,执行 242 个真实的安全工具,将其输出解析为结构化发现,并在出现新漏洞时自适应地重新规划 —— 最终交付一份包含 MITRE ATT&CK 覆盖热力图的专业渗透测试报告。
[架构](#architecture) · [242 个工具](#tool-coverage-242-tools) · [自定义数据集](#custom-dataset) · [微调](#fine-tuning) · [快速开始](#quick-start) · [API](#api) · [MCP](#mcp-integration)
## RedCore 的与众不同之处
大多数 AI 安全工具只是简单的封装。而 RedCore 是一个能够执行以下操作的**自主代理**:
1. **推理** — 给定一个诸如 *"攻陷 10.0.0.0/24 上的域控制器"* 的高级目标,基于 LLM 的规划器会遵循 MITRE ATT&CK 杀伤链生成完整的多阶段攻击计划
2. **选择** — 一个经过微调的路由 LLM 会针对每个步骤从 242 个选项中挑选出最佳工具,它了解工具的用途、失败模式以及替代方案
3. **执行** — 通过 Docker、WSL2 或子进程运行真实的安全工具,并配备 4 层自适应重试引擎
4. **解析** — 专用解析器将原始工具输出(nmap XML、nuclei JSON、bloodhound CSV 等)转换为包含严重程度、CVE 参考和 MITRE 映射的结构化 `Finding` 对象
5. **重新规划** — 当出现关键发现(例如内部主机上的 Log4Shell)时,系统会重新调用 LLM,以调整剩余计划并立即对其进行漏洞利用
6. **报告** — 生成 Markdown 格式的专业渗透测试报告,并支持完整的 MITRE ATT&CK Navigator 层导出
## 架构
```
┌─────────────────────────────────────────────────────────────────────┐
│ RedCore Agent Loop │
│ │
│ ┌────────────┐ ┌────────────┐ ┌──────────────────────────┐ │
│ │ Planner │───▶│ Router │───▶│ ExecutionEngine │ │
│ │ (LLM) │ │ (LLM) │ │ Docker / WSL2 / subprocess│ │
│ └─────┬──────┘ └────────────┘ └────────────┬─────────────┘ │
│ │ adaptive replan │ ToolResult │
│ │◀──────────────── findings ────────────────┤ │
│ ┌─────▼──────────────────────────────────────────▼─────────────┐ │
│ │ Memory: ChromaDB (RAG) + NetworkX (host/service graph) │ │
│ └───────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
│ │
FastAPI REST API WebSocket Stream
+ CLI (rich) (real-time events)
│
B2B Integrations: Slack | Jira | Teams | Webhook
│
MCP Server → Claude Desktop + any MCP client (all 242 tools)
```
### 代理模块
| 模块 | 文件 | 功能描述 |
|--------|------|-------------|
| **Orchestrator** | `redcore/agent/orchestrator.py` | 顶层自主代理循环 — 协调所有阶段 |
| **Planner** | `redcore/agent/planner.py` | 基于 LLM 的多阶段攻击计划生成 + 自适应重新规划 |
| **Router** | `redcore/agent/router.py` | 基于 LLM 从 242 个工具注册表中执行工具选择 |
| **Reporter** | `redcore/agent/reporter.py` | 结合 MITRE ATT&CK 映射生成渗透测试报告 |
| **Risk Scorer** | `redcore/agent/risk_scorer.py` | 基于 CVSS 的发现严重程度评分 |
| **Deduplicator** | `redcore/agent/deduplicator.py` | 跨任务发现去重 |
| **MITRE Mapper** | `redcore/agent/mitre_mapper.py` | 关键字 + 工具 → ATT&CK 技术映射 + Navigator 层导出 |
### 4 层自适应重试引擎
当工具运行失败时,RedCore 会在放弃前依次进行 4 个层级的升级处理:
```
Layer 1 — Parameter Rotation
└─ Retry with alternative_params from the tool YAML definition
Layer 2 — Tool Substitution (Router)
└─ LLM picks the next-best tool for the same objective
Layer 3 — Strategy Pivot (Orchestrator)
└─ After N consecutive failures, Planner replans remaining steps
Layer 4 — LLM Escalation
└─ Full strategic replan if Planner determines the attack vector is blocked
```
此机制在 `ExecutionEngine` (`redcore/execution/engine.py`) 和 `RedCoreOrchestrator` (`redcore/agent/orchestrator.py`) 中实现。
### 执行后端
RedCore 支持三种工具执行模式 — 可通过 `config.yaml` 进行切换:
| 模式 | 描述 |
|------|-------------|
| `wsl` | 工具在 WSL2 上的 Ubuntu 内运行 — 推荐用于 Windows 主机 |
| `docker` | 工具在 `redcore/toolbox` 容器内运行 — 完全隔离 |
| `subprocess` | 直接使用子进程 — 适用于原生安装了工具的 Linux 主机 |
`WSLExecutor` (`redcore/execution/wsl_executor.py`) 负责处理 Windows → WSL2 的进程桥接、输出路径标准化以及按任务划分的输出目录。
## 工具覆盖范围(242 个工具)
所有 242 个工具均在 YAML (`redcore/tools/definitions/`) 中进行了正式定义,并在启动时加载到单例 `ToolRegistry` 中。每个定义都指定了:命令模板、带有类型和默认值的参数、输出格式、超时时间、MITRE 标签、备用工具以及用于重试的备用参数集。
| 类别 | 主要工具 | 数量 |
|---|---|:---:|
| 侦察 | nmap, rustscan, masscan, amass, subfinder, httpx, dnsx, naabu, fierce, shodan-cli | 25 |
| OSINT | theHarvester, maltego, recon-ng, spiderfoot, sherlock, holehe, maigret | 15 |
| Web 爬虫 | katana, hakrawler, gospider, waybackurls, gau, crawlergo, photon | 10 |
| 目录 Fuzzing | ffuf, gobuster, feroxbuster, dirsearch, wfuzz, dirb | 8 |
| 漏洞扫描 | nuclei, nessus-cli, openvas-cli, nikto, wpscan, testssl.sh | 18 |
| 漏洞利用框架 | metasploit, sliver, covenant, coercer, responder | 10 |
| Web 漏洞利用 | sqlmap, xsstrike, dalfox, commix, ghauri, arjun, jwt_tool | 18 |
| 活动目录 | bloodhound, certipy, kerbrute, impacket-suite, ldapdomaindump | 15 |
| 权限提升 | linpeas, winpeas, wesng, pspy, suid3num, sudo_killer | 12 |
| 横向移动 | chisel, ligolo-ng, crackmapexec, evil-winrm, nxc | 10 |
| 凭据攻击 | hydra, medusa, spray, smartbrute, sprayhound | 12 |
| 密码破解 | hashcat, john, rainbow tables, hcxtools | 8 |
| 云安全 | prowler, pacu, trufflehog, cloudfox, ScoutSuite, Cartography | 18 |
| Kubernetes | kube-hunter, kubescape, trivy, kube-bench, peirates | 10 |
| 无线网络 | aircrack-ng, wifite, kismet, bettercap, hostapd-wpe | 10 |
| 逆向工程 | ghidra, radare2, binwalk, angr, afl-fuzz, pwndbg | 10 |
| Fuzzing | boofuzz, libfuzzer, radamsa, restler, peach fuzzer | 8 |
| Payload 生成 | msfvenom, donut, nimcrypt2, freeze, scarecrow | 8 |
| C2 框架 | sliver, empire, havoc, mythic, brute ratel | 7 |
| API 漏洞利用 | graphql-cop, jwt_tool, dredd, corsy, crapi | 10 |
| **总计** | | **242** |
### 工具注册表
注册表 (`redcore/tools/registry.py`) 是一个单例,它能够:
- 在启动时加载所有 YAML 定义
- 解析别名和名称变体(例如 `nxc` → `crackmapexec`)
- 在执行前验证并填充参数默认值
- 在主工具失败时返回排名靠前的备用工具
- 为 MCP 服务器的动态工具 schema 生成提供支持
大小为 69KB 的 `tool_install_manifest.yaml` 追踪了所有 242 个工具的安装状态、安装方法、验证命令以及准确与别名分类,涵盖了 apt、pipx、go install、cargo 和 gem。
## 自定义数据集
RedCore 基于一个**定制的、包含超过 25 万条记录的确定性数据集**进行了微调 — 完全无需任何外部 API 调用即可生成。
### 数据集生成器 (`dataset_generator/`)
数据集生成器是一个独立的 pipeline,包含 **6 种生成策略**:
```
Phase 1: KB Step Generation
└─ 242 tools × examples × param variants × target variants × tool alts
Augmentation: 50 target IPs × 20 param variants × 5 tool alternates = ~360K steps
Phase 2: KB Plan Generation
└─ 25 red team scenarios × N target IPs → full multi-step AttackPlans
Scenarios: web app pentest, AD compromise, cloud lateral movement, etc.
Phase 3: Tool Result Simulation
└─ Success + 14 failure modes per tool (timeout, auth-fail, scope-blocked, parse-error…)
Output simulator generates realistic stdout/stderr for each tool
Phase 4: Reasoning / Instruction Records
└─ Tool purpose Q&A, scenario approach descriptions, failure recovery reasoning
Phase 5: External Dataset Ingestion
└─ Specialist handlers for: Atomic Red Team, MITRE CTI, Metasploit modules,
CVE/NVD, ExploitDB, PCAP captures, CTF writeups
Generic normalizer fallback for unknown formats
Phase 6: Theory / Knowledge Synthesis
└─ Converts schema records → Q&A knowledge pairs
Generates tool theory: what, when, why, alternatives
Output: knowledge_base.jsonl + theory_finetune.jsonl
```
### 数据集 Schema
四个 JSONL 输出文件,在写入前会经过严格的 schema 验证:
| 文件 | Schema | 描述 |
|------|--------|-------------|
| `attack_steps.jsonl` | `AttackStep` | 包含阶段、参数、MITRE 技术的单个工具调用 |
| `attack_plans.jsonl` | `AttackPlan` | 作为 DAG 的完整多步骤测试计划 |
| `tool_results.jsonl` | `ToolResult` | 原始工具输出 + 解析后的发现(包含成功与失败变体) |
| `reasoning.jsonl` | 自由格式 | 指令遵循:工具选择推理、方法描述 |
### 分布
```
55% AttackStep (~137,500 records)
25% AttackPlan (~62,500 records)
15% ToolResult (~37,500 records)
5% Reasoning (~12,500 records)
```
### 增强系统
该生成器采用交叉乘积增强引擎:
- **`TargetVariator`** — 每个步骤 50 个目标 IP/域名变体(实验室、云、内部网段)
- **`ParamVariator`** — 每个工具 20 个参数变体(端口范围、字典、时间配置、输出格式)
- **`ToolSubstitutor`** — 每个步骤 5 个备用工具变体(同类目、不同二进制文件)
- **`FailureSimulator`** — 14 种失败类型:`timeout`、`auth_fail`、`scope_blocked`、`binary_missing`、`parse_error`、`rate_limited`、`network_unreachable`、`permission_denied` 等
- **`OutputSimulator`** — 生成模仿真实二进制输出模式的逼真工具 stdout/stderr
### 外部数据集处理器
摄取层包含用于真实世界数据集的专用处理器:
- **Atomic Red Team** — YAML 技术文件 → 攻击步骤
- **MITRE CTI** — STIX bundles → 技术映射
- **Metasploit 模块** — Ruby 模块元数据 → 漏洞利用步骤
- **ExploitDB** — CSV 索引 + 漏洞利用代码 → 漏洞记录
- **NVD/CVE JSON** — CVE 描述 → 漏洞 + 利用步骤
- **PCAP 文件** — 网络抓包解析 → ToolResult 记录
所有处理器都会发出预结构化的记录,类型为 `attack_step`、`attack_plan`、`tool_result`、`reasoning` 或 `vulnerability` — 并由生成器的调度器进行路由。
## 微调
### 模型选择
RedCore 支持在多个基础模型上进行微调:
| 模型 | 所需 VRAM | 训练脚本 |
|-------|---------------|-----------------|
| **Qwen 3.5 9B**(主要) | 8GB(4-bit QLoRA) | `train_qwen.py` |
| Mistral-Nemo 12B | 12GB(4-bit QLoRA) | `fine_tuning/train_lora.py` |
| Qwen2.5 7B | 6GB(4-bit QLoRA) | `fine_tuning/train_lora.py` |
| LLaMA-3 8B | 8GB(4-bit QLoRA) | `fine_tuning/train_lora.py` |
### QLoRA 配置(RTX 4060 上的 Qwen 3.5 9B)
```
r = 8 # LoRA rank
lora_alpha = 8
target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"]
lora_dropout = 0
quantization = 4-bit NF4 (bitsandbytes)
seq_length = 512 # constrained by 8GB VRAM
batch_size = 1 × grad_accum 16 (effective ~8K tokens/step)
optimizer = adamw_8bit
lr_scheduler = cosine
learning_rate = 2e-4
epochs = 3
packing = True # 4-5x throughput via Unsloth
```
### Windows 特定工程
训练是在 Windows(RTX 4060)上原生进行的 — 这是一个复杂的环境。`train_qwen.py` 脚本包含:
- **在启动时禁用 TorchDynamo**(triton-windows 缺少 CUDA 调度器后端)
- **triton.ops.matmul_perf_model stub** — 已修补以防止 bitsandbytes 导入失败
- **triton_key stub** — 防止 Windows 上的 torch inductor 缓存崩溃
- **Eager 模式回退** — `_dynamo.config.suppress_errors = True`
- 所有 LoRA、4-bit 量化和梯度检查点功能依然完全可用
`gguf_to_hf_q3_5_9B.py` 脚本负责处理用于部署的 GGUF → HuggingFace SafeTensors 转换。
### 数据格式
训练使用带有一致系统提示词的 **ChatML 格式**:
```
<|im_start|>system
You are RedCore, an advanced adversarial AI assistant built for authorized
penetration testing and red team operations...<|im_end|>
<|im_start|>user
Create an attack plan for: Compromise all hosts in 192.168.10.0/24<|im_end|>
<|im_start|>assistant
{"steps": [...], "rationale": "..."}<|im_end|>
```
`train_qwen.py` 中的 `to_chatml()` 标准化器会自动将任何输入格式(Alpaca、问答、原始补全、RedCore schema)转换为 ChatML — 因此所有 6 个数据集文件都可以放在一起训练,无需进行预处理。
### 自动恢复训练
```
python train_qwen.py # start fresh or auto-resume from last checkpoint (Ctrl+C safe)
```
每 100 步保存一次检查点。重新运行时会自动检测并从上一个检查点恢复。
### 导出为 GGUF (Ollama)
训练结束时会自动导出一个 `Q4_K_M` GGUF 文件:
```
# 训练完成后:
ollama create redcore -f data/finetune/qwen_redcore_lora/Modelfile
ollama run redcore "Generate an attack plan for 192.168.1.0/24"
```
## 快速开始
### 前置条件
- Python 3.11+
- Docker & Docker Compose
- [Ollama](https://ollama.ai)(用于本地 LLM 推理)
### 1. 克隆并安装
```
git clone https://github.com/AaravMehta-07/Redcore.git
cd Redcore
make install
```
### 2. 拉取 LLM 模型
```
ollama serve
ollama pull mistral-nemo # 12GB — or use qwen2.5:7b for smaller footprint
```
### 3. 配置
```
cp config.yaml config.local.yaml
# 编辑 config.local.yaml — 设置你的 LLM 后端、执行模式和集成
```
### 4. 验证配置
```
redcore validate
redcore tools # list all 242 tools
redcore tools --category recon
```
### 5. 运行测试任务
```
redcore run "Pentest all web apps on 192.168.10.0/24" \
--target 192.168.10.0/24 \
--exclude 192.168.10.1
```
### 6. Docker(推荐用于生产环境)
```
make build-docker build-toolbox
make up
make pull-model
# API 运行于:
curl http://localhost:8000/health
curl http://localhost:8000/docs # Swagger UI
```
## API
### 启动任务
```
curl -X POST http://localhost:8000/jobs \
-H "Content-Type: application/json" \
-d '{
"objective": "Find and exploit all web vulnerabilities on 10.0.0.5",
"targets": ["10.0.0.5"],
"excluded_targets": [],
"tenant_id": "client_acme"
}'
```
响应:
```
{"job_id": "abc123", "status": "planning", "created_at": "..."}
```
### 流式传输实时事件(WebSocket)
```
const ws = new WebSocket('ws://localhost:8000/ws/jobs/abc123');
ws.onmessage = (e) => {
const event = JSON.parse(e.data);
// event.event_type: plan_ready | step_start | step_done | finding | replan | complete
console.log(event);
};
```
事件流示例:
```
{"event_type": "plan_ready", "data": {"steps": 18, "phases": ["recon", "scanning", "exploitation"]}}
{"event_type": "step_start", "data": {"tool": "nmap", "phase": "recon"}}
{"event_type": "finding", "data": {"title": "SMB open (port 445)", "severity": "medium"}}
{"event_type": "replan", "data": {"reason": "critical_findings", "findings_count": 2}}
{"event_type": "complete", "data": {"total_findings": 23, "critical": 3, "high": 7}}
```
### 获取发现结果
```
curl http://localhost:8000/findings/abc123?severity=critical
```
### 下载报告
```
curl http://localhost:8000/reports/abc123 -o report.md
```
### MITRE ATT&CK Navigator 层
```
curl http://localhost:8000/mitre/abc123 -o layer.json
# 导入地址:https://mitre-attack.github.io/attack-navigator/
```
## MCP 集成
RedCore 通过 **Model Context Protocol** 公开了所有 242 个工具 — 每个工具定义都会动态转换为 MCP JSON schema。兼容 Claude Desktop 和任何 MCP 客户端。
```
# stdio 模式 (Claude Desktop)
redcore mcp
# HTTP 模式 (API 客户端)
redcore mcp --http --port 8765
```
### Claude Desktop 配置
```
{
"mcpServers": {
"redcore": {
"command": "redcore",
"args": ["mcp", "--scope", "192.168.1.0/24"]
}
}
}
```
Claude 现在可以直接调用 242 个安全工具中的任何一个:
```
> Use nmap to scan 192.168.1.0/24 for open ports
> Run nuclei against http://app.local with CVE templates
> Use kerbrute to enumerate users on the domain controller at 192.168.1.10
```
## B2B 集成
添加到 `config.yaml`:
```
integrations:
slack:
enabled: true
webhook_url: "https://hooks.slack.com/services/..."
channel: "#security-alerts"
jira:
enabled: true
base_url: "https://yourcompany.atlassian.net"
project_key: "SEC"
api_token: "..."
email: "security@yourcompany.com"
teams:
enabled: true
webhook_url: "https://outlook.office.com/webhook/..."
webhook:
enabled: true
url: "https://your-siem.com/redcore"
secret: "your-hmac-secret"
```
## 运行数据集生成器
```
# 完整运行:KB + 所有外部数据集(目标:250K 条记录)
python -m dataset_generator.generator \
--input data/raw \
--output data/generated \
--target 250000
# 仅 KB 运行(无需外部数据)
python -m dataset_generator.generator --kb-only --target 50000
# Dry run:在不写入文件的情况下估算输出数量
python -m dataset_generator.generator --dry-run
# 生成微调就绪的输出(Alpaca 格式)
python -m dataset_generator.generator --finetune-format
# 包含理论/知识综合阶段
python -m dataset_generator.generator --theory-format
```
## 微调
```
# 1. 生成数据集
make prepare-data # runs fine_tuning/prepare_dataset.py
# 2. 训练 LoRA adapter — Qwen 3.5 9B (Windows, RTX 4060+)
python train_qwen.py
# 2b. 或通用脚本 (Linux/任意 GPU):
make fine-tune # runs fine_tuning/train_lora.py
# 3. 评估
make evaluate
# 4. 在 config.yaml 中设置 adapter 路径:
# llm:
# backend: transformers
# adapter_path: data/finetune/qwen_redcore_lora
```
## 测试
```
make test # all tests
make test-unit # unit tests only (tests/unit/)
make lint # ruff check
make type-check # mypy
make format # ruff format
```
单元测试覆盖率:
- `test_agents.py` — planner、router、orchestrator
- `test_parsers.py` — nmap、nuclei、gobuster、hydra、sqlmap、bloodhound 输出解析
- `test_registry.py` — 工具加载、别名解析、参数验证
- `test_safety.py` — 授权范围验证、命令清理器、注入预防
- `test_wsl_executor.py` — WSL2 执行、输出路径标准化、超时处理
## 安全与法律
内置安全控制:
- **强制授权范围验证** — 每次工具调用在执行前都会根据定义的授权范围验证目标
- **命令清理器** — 阻止所有工具参数中的 shell 注入(`;`、`&&`、`|`、反引号等)
- **AES-256-GCM 加密密钥库** — 凭据绝不以明文形式存储
- **JWT 多租户认证** — 在所有 API 端点上实行严格的租户隔离
- **完整审计日志** — 每一项操作都会记录时间戳、任务 ID 和证据哈希值
## 项目结构
```
redcore/
├── agent/ # Orchestrator, Planner, Router, Reporter, MITRE Mapper
├── api/ # FastAPI REST endpoints + WebSocket streaming
├── cli/ # Rich CLI (redcore validate | run | tools | mcp)
├── core/ # Config, safety, logging, evidence collection
├── execution/ # ExecutionEngine, DockerExecutor, WSLExecutor
├── integrations/ # Slack, Jira, Teams, Webhook notifiers
├── llm/ # LLM clients: Ollama, vLLM, OpenAI, Transformers
├── memory/ # ChromaDB vector store + NetworkX graph memory
├── models/ # Pydantic models: Job, Plan, Finding, ToolResult
└── tools/
├── definitions/ # 20 YAML files — 242 tool definitions
├── parsers/ # Output parsers: nmap, nuclei, gobuster, hydra…
├── registry.py # Singleton tool registry + alias resolution
└── mcp_server.py # MCP server exposing all 242 tools
dataset_generator/
├── generator.py # Main orchestrator — 6 generation strategies
├── config.py # All tunable parameters (target counts, aug factors)
├── knowledge_base/ # Tool KB, scenario KB (25 red team scenarios)
├── augmentation/ # TargetVariator, ParamVariator, ToolSubstitutor
├── simulation/ # OutputSimulator, FailureSimulator (14 failure types)
├── ingestion/ # Dataset handlers: Atomic Red Team, CVE, Metasploit…
├── templates/ # Step/Plan/Result template engines
├── validation/ # Schema validator + auto-repair
└── export/ # JSONL exporter, stats reporter, knowledge exporter
fine_tuning/
├── train_lora.py # Generic LoRA training (Mistral, LLaMA, Qwen2.5)
└── prepare_dataset.py # Dataset preparation + train/eval split
train_qwen.py # Qwen 3.5 9B QLoRA on RTX 4060 (Windows)
gguf_to_hf_qwen3_5_9B.py # GGUF → HuggingFace SafeTensors conversion
```
## 许可证
专有 — 保留所有权利。RedCore 是一款商业 B2B 产品。
## 支持
- 问题:[github.com/AaravMehta-07/Redcore/issues](https://github.com/AaravMehta-07/Redcore/issues)标签:AD攻击面, DLL 劫持, Docker, Web报告查看器, 大语言模型, 安全工具集, 安全防御评估, 插件系统, 模拟器, 特权检测, 自动化渗透测试, 请求拦截