Reversecore_MCP
A security-first MCP server that empowers AI agents to perform automated reverse engineering, malware analysis, forensics, vulnerability research, and SAST — powered by Radare2, YARA, LIEF, Capstone, and more.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/sjkim1127/Reversecore_MCP with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/sjkim1127/Reversecore_MCP'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/sjkim1127--reversecore-mcp)HTML
<a href="/listings/sjkim1127--reversecore-mcp"><img src="/api/listings/sjkim1127--reversecore-mcp/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
These steps run a script from the network that findsafeskills does not scan.
⚡ One-Line Automated Setup (Recommended)
Automatically detects installed AI agents (**Cursor, Claude Code, Windsurf, Claude Desktop, Antigravity, VS Code Cline/Roo Code, Codex**) and registers Reversecore_MCP with automatic backups and zero manual JSON editing:
# macOS / Linux curl -fsSL https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.sh | bash # Or via uvx (zero installation required) uvx --from reversecore-mcp reversecore-setup # Or via pipx pipx run reversecore-mcp setup # Windows (PowerShell) irm https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.ps1 | iex
**Common Setup Options:**
reversecore-mcp setup --tiered # Tiered Mode: 15 essential tools (>90% context token reduction) reversecore-mcp setup --docker # Configure Docker container execution reversecore-mcp setup --dry-run # Preview configuration changes without writing reversecore-mcp setup --list # Inspect detected clients and config paths reversecore-mcp setup --remove # Unregister Reversecore from all clients
---
Manual Installation Options
Option 1 — PyPI (Simplest)
pip install reversecore-mcp reversecore-mcp
> **Prerequisites:** Radare2 must be installed on your system (`r2 --version`). YARA is installed automatically via `yara-python`.
Option 2 — Docker (Recommended for Full Functionality)
All analysis engines (Radare2, r2ghidra, YARA, Binwalk, Sleuth Kit, GDB, etc.) come pre-installed:
docker run -i --rm \ -v /path/to/your/samples:/app/workspace \ -e REVERSECORE_WORKSPACE=/app/workspace \ -e MCP_TRANSPORT=stdio \ ghcr.io/sjkim1127/reversecore_mcp:latest
Option 3 — Build from Source (Docker Compose)
git clone https://github.com/sjkim1127/Reversecore_MCP.git cd Reversecore_MCP ./scripts/run-docker.sh # auto-detects Intel / Apple Silicon
Or manually:
docker compose --profile x86 up -d # Intel/AMD docker compose --profile arm64 up -d # Apple Silicon (M1/M2/M3)
Option 4 — Python (Local Development)
git clone https://github.com/sjkim1127/Reversecore_MCP.git cd Reversecore_MCP python -m venv venv && source venv/bin/activate pip install -r requirements.txt python -m reversecore_mcp.server
> **Prerequisites for local mode:** Radare2 must be installed on your system (`r2 --version`). Individual tool backends (YARA, LIEF, Capstone, etc.) are installed via pip. For full forensics support, you'll also need Volatility3, Scapy, and Sleuth Kit.
---
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/plugin.json · Manifest · 34 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "name": "reversecore-mcp",
- "version": "1.0.0",
- "description": "Enterprise-grade AI reverse engineering MCP server: Radare2, r2ghidra, ESIL emulation, Go/Rust, Electron ASAR, Unity IL2CPP, and feature code reconstruction.",
- "author": {
- "name": "Reversecore Team",
- "url": "https://github.com/sjkim1127/Reversecore_MCP"
- },
- "repository": "https://github.com/sjkim1127/Reversecore_MCP",
- "license": "MIT",
- "keywords": [
- "reverse-engineering",
- "binary-analysis",
- "decompiler",
- "radare2",
- "ghidra",
- "malware-analysis",
- "mcp-server"
- ],
- "skills": "./.agents/skills",
- "mcpServers": {
- "reversecore": {
- "command": "python3",
- "args": [
- "-m",
- "reversecore_mcp"
- ],
- "env": {
- "REVERSECORE_TIERED_MODE": "true",
- "REVERSECORE_SCHEMA_PROFILE": "compact"
- }
- }
- }
- }
README.md · README · 1,813 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- <div align="center">
- **English** · [한국어](README.ko.md) · [日本語](README.ja.md) · [简体中文](README.zh-CN.md)
- <br />
- <img src="icon.png" alt="Reversecore MCP" width="440" />
- # Reversecore MCP
- ### AI-Powered Binary Reverse Engineering, Malware Analysis & Vulnerability Research via MCP
- **An enterprise-grade Model Context Protocol server for malware triage, decompilation, modern runtime security auditing (Go/Rust, Electron, Unity), crash analysis, and digital forensics — backed by verifiable byte-level evidence.**
- ---
- [](https://github.com/sjkim1127/Reversecore_MCP/actions/workflows/main.yml)
- [](https://www.python.org/)
- [](LICENSE)
- [](#testing)
- [](#testing)
- [](https://github.com/jlowin/fastmcp)
- [](https://pypi.org/project/reversecore-mcp/)
- [](https://github.com/sjkim1127/Reversecore_MCP/pkgs/container/reversecore_mcp)
- [](https://skills.sh)
- [](https://scorecard.dev/viewer/?uri=github.com/sjkim1127/Reversecore_MCP)
- [](https://hvtracker.net/agents/reversecore-mcp)
- [](https://youtu.be/wJGW2bp3c5A)
- [](https://safeskill.dev/scan/sjkim1127-reversecore-mcp)
- <br />
- **[Quick Start](#quick-start) · [Security Analysis Workflows](#-security-analysis-workflows) · [Supported Targets](#what-you-can-analyze) · [Context Efficiency](#-context-efficiency-tiered-router-compact-schema--paging) · [Tool Catalog (186 Tools)](#tool-catalog-186-tools) · [FAQ](#faq)**
- </div>
- ### ⚡ Instant One-Line Setup
- Automatically detects installed AI clients (**Cursor, Claude Code, Windsurf, Claude Desktop, OpenAI Codex, Antigravity, Cline/Roo Code**) and registers Reversecore MCP with automatic configuration backups:
- ```bash
- # Option 1: Zero-install CLI setup (Recommended)
- pipx run reversecore-mcp setup
- # Option 2: One-line shell installer (macOS / Linux)
- curl -fsSL https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.sh | bash
- # Option 3: Install Agent Skill (skills.sh / Cursor / Claude Code / Codex)
- npx skills add sjkim1127/Reversecore_MCP
- ```
- > 💡 **Reduce LLM context token usage by 94.4%:** Run `pipx run reversecore-mcp setup --tiered` to expose 15 core security tools + 8 domain sub-agents while keeping all 186 tools callable on demand.
- ---
- ## Table of Contents
- - [What is Reversecore MCP?](#what-is-reversecore-mcp)
- - [🛡️ Security Analysis Workflows](#-security-analysis-workflows)
- - [What You Can Analyze](#what-you-can-analyze)
- - [⚡ Context Efficiency: Tiered Router, Compact Schema & Paging](#-context-efficiency-tiered-router-compact-schema--paging)
- - [Architecture](#architecture)
- - [Tool Catalog (194 Tools)](#tool-catalog-194-tools)
- - [Guided Analysis Prompts (34 Modes)](#guided-analysis-prompts-34-modes)
- - [MCP Resources (11 URIs)](#mcp-resources-11-uris)
- - [Quick Start](#quick-start)
- - [Connect to Your AI Client](#connect-to-your-ai-client)
- - [Configuration](#configuration)
- - [Security Model](#security-model)
- - [Development](#development)
- - [CI/CD Pipeline](#cicd-pipeline)
- - [Docker Build Architecture](#docker-build-architecture)
- - [System Requirements](#system-requirements)
- - [Project Structure](#project-structure)
- - [Error Handling](#error-handling)
- - [Adding New Tools](#adding-new-tools)
- - [Contributing](#contributing)
- - [Documentation](#documentation)
- - [License](#license)
- ---
- ## What is Reversecore MCP?
- Reversecore MCP is a [Model Context Protocol](https://modelcontextprotocol.io/) server that wraps **194 analysis tools** into a unified interface for AI-assisted security research, malware triage, vulnerability discovery, and digital forensics.
- Instead of manually switching between disassemblers, decompilers, YARA scanners, and forensics utilities, you describe your investigation goal in natural language:
- ```text
- "Decompile the main payload of this suspicious sample, recover its custom string decryption
- routine, extract all C2 IOCs, map behaviors to MITRE ATT&CK, and generate a triage report."
- ```
- Each tool runs locally (or inside an isolated Docker container) and returns a structured `ToolResult` (`ToolSuccess` or `ToolError`) with byte-level provenance so the AI can chain multi-step security investigations without hallucinating findings.
- ---
- ## 🛡️ Security Analysis Workflows
- ### Workflow 1: Malware Cryptor / DGA Recovery & Safe Emulation Verification
- Modern malware families encrypt C2 configurations or generate domains dynamically (DGA). Translating decompiled C into a Python decryptor by hand is error-prone due to subtle 32/64-bit integer wrap-around and bitwise shifts. Reversecore MCP reconstructs the routine and **verifies 100% behavioral equivalence inside Radare2's ESIL CPU emulator** without executing live malware on the host.
- **Prompt:**
- ```text
- "Analyze the config decryption function at 0x401180 in sample.bin, write a safe Python
- decryptor script, and verify with ESIL emulation that its output matches the binary."
- ```
- **Agent Tool Chain & Verified Output:**
- ```
- 1. r2_decompile("sample.bin", "0x401180", detail="summary")
- └─ Returns compact complexity/API summary + cache handle: evidence_id="ev_9a4c102f8b11"
- 2. inspect_analysis_view(evidence_id="ev_9a4c102f8b11", facet="lines", offset=0, limit=40)
- └─ Streams exact pseudo-C lines on demand without exhausting context window
- 3. reconstruct_feature_code(
- file_path="sample.bin",
- address_or_symbol="sym.decrypt_word",
- target_language="python",
- test_inputs=["0x0", "0xff", "0xffff"]
- )
- ├─ Decompilation & Synthesis: r2ghidra -> clean Python function (decrypt_word)
- ├─ Binary Emulation: Radare2 ESIL VM (isolated register/memory state, zero host execution)
- ├─ Equivalence Verdict: VERIFIED (branch_parity: true, test_vectors_evaluated: 3, emulation_successful: true)
- └─ Reconstructed Code:
- def decrypt_word(param_1: Any = 0, param_2: Any = 0, *args: Any, **kwargs: Any) -> Any:
- uVar1 = (param_1 ^ param_2) * 0x45d9f3b
- return uVar1 >> 0x10 ^ uVar1
- ```
- ---
- ### Workflow 2: Modern Runtime Threat & Supply-Chain Auditing (Go/Rust, Electron ASAR, Unity)
- Threat actors increasingly write cross-platform ransomware in **stripped Go/Rust** or distribute trojanized **Electron (`app.asar`)** desktop installers. Reversecore MCP provides built-in pure-Python static parsers to recover stripped symbols and audit runtime security boundaries:
- **Prompt:**
- ```text
- "Audit this suspicious installer's app.asar for insecure BrowserWindow settings and
- suspicious IPC handlers, and recover function symbols from its bundled stripped Go helper."
- ```
- **Agent Tool Chain & Verified Output:**
- ```
- 1. inspect_electron_asar("app.asar", search_pattern="ipcMain|child_process|shell")
- ├─ Format: Chromium Pickle ASAR (header_size: 48,210 bytes, 642 files)
- ├─ Exposed IPC Handlers: 14 channels mapped across main and preload scripts
- └─ Security Audit Findings:
- • [HIGH] nodeIntegration: true detected in BrowserWindow configuration
- • [MEDIUM] sandbox: false detected in renderer window options
- 2. inspect_go_rust_binary("helper_daemon.elf")
- ├─ Runtime Detected: Go (gopclntab magic 0xfffffff1, Go 1.22)
- ├─ Symbol Recovery: 148 stripped package/function names recovered from .gopclntab
- └─ Suspicious Packages Identified:
- • main.establishBeaconLoop @ 0x48a200
- • main.encryptLocalVolume @ 0x48b940
- ```
- ---
- ### Workflow 3: Zero-Day Crash Triage, Taint Analysis & Adaptive YARA/Vaccine Generation
- From an ASan/GDB crash log or a packed binary with dormant logic bombs, Reversecore MCP chains crash classification, source-to-sink taint reachability, and automated detection rule synthesis.
- **Prompt:**
- ```text
- "Triage this ASan crash log on daemon.bin, verify whether untrusted network input reaches
- the vulnerable memcpy sink, scan for dormant backdoors, and generate a YARA rule."
- ```
- **Agent Tool Chain & Verified Output:**
- ```
- 1. cve_triage_crash(crash_log_or_text=asan_log)
- └─ Bug Class: heap-buffer-overflow (READ) | CWE-125 | Faulting Function: parse_packet+0x84
- 2. taint_trace("daemon.bin", function_name="parse_packet", verify_with_angr=True)
- └─ Source→Sink Confirmed: recv() → memcpy() at 0x402190 (unbounded length field)
- 3. dormant_detector("daemon.bin")
- └─ Discovered 1 orphan function (0x404800) with time-bomb trigger (cmp eax, 0x67758ac0)
- 4. adaptive_vaccine(threat_report={...}, action="both")
- ├─ Generated YARA detection rule with wildcarded address displacement masking
- └─ Synthesized binary mitigation patch neutralizing the vulnerable/malicious branch
- ```
- ---
- ## What You Can Analyze
- | Target Category | Security & Reverse Engineering Capabilities | Engine / Requirement |
- |---|---|---|
- | **Native Binaries (PE / ELF / Mach-O)** | Disassembly, r2ghidra C decompilation, CFG, C++ RTTI, struct recovery, imports/exports, section entropy, Authenticode/certificates | **Radare2 + r2ghidra + LIEF** (x86, x64, ARM32, ARM64, MIPS, RISC-V, PowerPC) |
- | **Malware & Packed Executables** | Packer/compiler identification, CAPA behavioral capability mapping, dormant backdoor/time-bomb detection, IOC extraction, YARA & Sigma rules, binary vaccines | **YARA + CAPA + DIE + Custom Heuristics** |
- | **Stripped Go & Rust Malware / Binaries** | Go `.gopclntab` (`go1.2`–`go1.20+`) symbol recovery, Rust `.dep-v0` (`cargo-auditable`) dependency tree & vulnerable crate auditing, `_ZN...E` demangling | **Built-in pure Python** (`inspect_go_rust_binary`) — no Go/Rust SDK required |
- | **Electron Desktop Apps (`app.asar`)** | Supply-chain & client security audit: Chromium Pickle VFS parser, `ipcMain`/`contextBridge` surface mapping, `nodeIntegration`/`contextIsolation` checks | **Built-in pure Python** (`inspect_electron_asar`) — zero external dependencies |
- | **Unity IL2CPP Binaries** | Mobile/client security audit: `global-metadata.dat` (`0xFAB11BAF`, v24–v31+) header encryption/entropy detection, C# class/method/string recovery, `libil2cpp.so` correlation | **Built-in pure Python** (`inspect_unity_il2cpp`) — no Unity required |
- | **Cryptor / Routine Reconstruction** | Decompiled routine translation into safe C/Python scripts with ESIL register/memory equivalence verification and Obligation Ledger | **r2ghidra + ESIL Simulator** (`reconstruct_feature_code`) |
- | **Vulnerabilities & Crash Dumps** | ASan/GDB crash triage, delta-debugging PoC minimization, source-to-sink taint analysis, angr symbolic path solving, ROP gadget chains | **angr + pwntools + ROPgadget + GDB** |
- | **Memory, Network & Disk Forensics** | Process & code-injection hunting in RAM dumps, PCAP DNS/C2/stream reconstruction, NTFS MFT & deleted file recovery, artifact timeline correlation | **Volatility3 + Scapy + Sleuth Kit + Binwalk** |
- ---
- ## ⚡ Context Efficiency: Tiered Router, Compact Schema & Paging
- Large reverse-engineering MCP servers often suffer from **context window bloat**: advertising 180+ verbose tool schemas and returning 50,000-line decompilations can exhaust an LLM's context in 2 turns. Reversecore MCP solves this with a 4-layer optimization architecture:
- | Optimization Layer | How to Enable | Context Savings & Behavior |
- |---|---|---|
- | **1. Tiered Router Mode** | `REVERSECORE_PROFILE=tiered`<br>*(or `reversecore-mcp setup --tiered`)* | **-94.4% prompt token overhead.** Exposes 12 daily core tools + 3 router tools (`call_expert_agent`, `search_tools`, `execute_domain_tool`) backed by 8 domain sub-agents (`vulnerability_hunter`, `forensics`, `malware_analyst`, `deobfuscator`, `symbolic_engine`, `diff_analyst`, `source_auditor`, `modern_runtime`). |
- | **2. Compact Schema Profile** | `REVERSECORE_SCHEMA_PROFILE=compact` | **~65% smaller `tools/list` payload.** Strips verbose docstring examples, flattens deep `anyOf`/`oneOf` unions, and caps JSON Schema depth at 10 while retaining full server-side Pydantic validation. |
- | **3. Summary-First Paging** | Pass `detail="summary"` to `r2_decompile`, `Radare2_disassemble*`, `Radare2_list_strings`, `memory_extract_strings` | Returns a compact structural digest + an `evidence_id` handle (`ev_<12-hex>`). Call `inspect_analysis_view(evidence_id, facet, offset, limit, filter_query)` to paginate or filter lines/strings/functions on demand. |
- | **4. On-Demand Guidance** | Built-in tools: `search_guidance` & `read_guidance_section` | Instead of stuffing 20,000 words of manuals into the system prompt, the agent queries built-in reversing playbooks (`playbook:target-routing`, `playbook:go-rust-reversing`, `playbook:electron-asar`, `playbook:unity-il2cpp`, `playbook:epistemological-discipline`) only when needed. |
- ---
- ## Architecture
- ```
- AI Client (Claude / Cursor / any MCP-compatible client)
- │ MCP Protocol (stdio or HTTP/SSE)
- ▼
- ┌──────────────────────────────────────────────────────┐
- │ FastMCP 3.4.11 Server │
- │ 194 registered tools · Fully async │
- │ Python 3.10–3.12 │
- ├────────────────────┬─────────────────────────────────┤
- │ Guided Prompts │ Dynamic Resources │
- │ (22 analysis │ (11 URI-based: per-binary │
- │ modes) │ strings, IOCs, ASM, CFG, …) │
- ├────────────────────┴─────────────────────────────────┤
- │ Core Infrastructure │
- │ Config · Security · Validators · Exceptions (17) │
- │ R2 Pool · Metrics · Memory (SQLite) · Task Queue │
- │ MITRE Mapper · Evidence Engine · Resilience Layer │
- │ Arch Registry (x86/ARM/MIPS/RISC-V/PPC) │
- │ Result Cache (SHA256) · Analysis Cache (Redis+SQL) │
- │ SAST (Python AST + C/C++ Regex) · Plugin System │
- ├──────────────────────────────────────────────────────┤
- │ Analysis Engines │
- │ Radare2 6.0.4 │ YARA 4.3.1 · LIEF · Capstone │
- │ r2ghidra │ CAPA · angr · Qiling │
- │ Volatility3 · Scapy│ DIE · Binwalk · Sleuth Kit │
- │ pwntools · ROPgadget│ Keystone (assembler) │
- └──────────────────────────────────────────────────────┘
- ```
- The server supports Python 3.10–3.12. The optional `angr` symbolic execution
- engine is installed on Python 3.12 and newer, where a secure compatible release
- is available; Python 3.10 and 3.11 installs omit `angr`.
- ### Core Infrastructure (37 modules)
- The `reversecore_mcp/core/` directory contains the shared infrastructure that all tools build on:
- | Module | Purpose |
- |---|---|
- | `config.py` | Pydantic BaseSettings with 34+ environment variables |
- | `security.py` | Input sanitization, command argument validation |
- | `validators.py` | File and binary path validation with TOCTOU mitigation, symlink resolution |
- | `r2_pool.py` | Thread-safe Radare2 connection pool with configurable size |
- | `r2_helpers.py` | Structured Radare2 output parsing |
- | `metrics.py` | Per-tool execution times, call counts, error rates, cache statistics |
- | `memory.py` | Async SQLite-backed AI memory store for persisting analysis findings across sessions |
- | `mitre_mapper.py` | MITRE ATT&CK technique ID mapping engine |
- | `evidence.py` | Evidence classification system: `OBSERVED`, `INFERRED`, `POSSIBLE` |
- | `resilience.py` | Retry, circuit-breaker, and timeout decorator patterns |
- | `task_queue.py` | Background task queue via Redis + arq |
- | `extension_registry.py` | Plugin registration and lifecycle management |
- | `arch_registry.py` | Multi-architecture mapping (x86, x86_64, ARM32, ARM64, MIPS, RISC-V, PPC → r2 arch/bits/registers) |
- | `result_cache.py` | SHA256-based tool result caching decorator (`@cache_tool_result`) |
- | `analysis_cache.py` | Multi-level decompilation cache (L1: Redis, L2: SQLite) |
- | `result.py` | `ToolSuccess` / `ToolError` Pydantic models |
- | `exceptions.py` | 17 exception classes with `RCMCP-E*` error codes |
- | `decorators.py` | `@log_execution`, `@track_metrics` |
- | `error_handling.py` | `@handle_tool_errors` decorator |
- | `error_formatting.py` | Structured error response formatting |
- | `execution.py` | Safe subprocess execution with timeout and output limits |
- | `command_spec.py` | Command specification for subprocess calls |
- | `loader.py` | Dynamic tool module loader |
- | `plugin.py` | Plugin base class |
- | `extension.py` | Extension base class |
- | `container.py` | Container/sandbox execution support |
- | `audit.py` | Audit logging |
- | `binary_cache.py` | Binary file caching |
- | `json_utils.py` | JSON serialization via orjson (3-5x faster than stdlib json) |
- | `logging_config.py` | Loguru-based structured logging |
- | `report_generator.py` | Report rendering engine (Markdown, PDF via xhtml2pdf) |
- | `resource_manager.py` | MCP resource lifecycle management |
- | `sast/python_ast_scanner.py` | Python AST-based vulnerability scanner |
- | `sast/regex_scanner.py` | C/C++ regex-based vulnerability scanner |
- | `sast/rule_manager.py` | SAST rule loading and management |
- ---
- ## Tool Catalog (194 Tools)
- > 📖 **[Authoritative Tool Catalog & Parameter Reference (186 Tools)](docs/TOOLS.md)**
- > 📊 **[Tool Profile Footprint & Context Benchmark Matrix](docs/benchmarks/profile_footprint.md)**
- Every tool returns a structured `ToolResult` — either a `ToolSuccess` with typed `data` or a `ToolError` with an `RCMCP-E*` error code. Tools are organized into 11 domain plugins across 6 modular execution profiles (`tiered`, `full`, `static`, `malware`, `forensics`, `vuln-research`):
- | Profile | Registered Tools | Schema Size | LLM Context Saving vs Full | Recommended Domain |
- |---|:---:|:---:|:---:|---|
- | `tiered` | **15** | ~11.5 KB | **-94.4%** (~28,500 tokens) | ⚡ **Daily interactive AI pair programming** (12 core tools + 3 sub-agent router tools accessing all 186 tools on demand) |
- | `full` | **186** | 144.2 KB | Baseline (0%) | Complete enterprise reverse engineering suite |
- | `vuln-research` | **138** | 96.4 KB | **-33.1%** (~10,000 tokens) | Fuzzing, ASan crash triage, CVE hunting, exploit research |
- | `static` | **132** | 91.2 KB | **-36.8%** (~11,100 tokens) | Disassembly, decompilation (r2ghidra), LIEF, modern runtimes, static triage |
- | `malware` | **100** | 76.5 KB | **-46.9%** (~14,100 tokens) | Threat triage, YARA scanning, deobfuscation, anti-analysis |
- | `forensics` | **81** | 51.8 KB | **-64.1%** (~19,300 tokens) | Memory forensics (Volatility3), network PCAP (Scapy), disk |
- ### ⚡ Tiered Tools & Multi-Agent Architecture (`REVERSECORE_PROFILE=tiered`)
- Exposing all 186 tools to an LLM on every turn wastes **~30,000+ tokens** of prompt context. Tiered mode solves this by exposing **only 15 high-frequency tools** while retaining seamless access to all 186 tools via specialized Sub-Agents and a dynamic tool router:
- 1. **Tier-1: Daily Core Tools (12 tools)**:
- - `run_file`, `parse_binary_with_lief`, `get_server_health`
- - `Radare2_open_file`, `Radare2_close_file`, `Radare2_list_functions`, `Radare2_list_strings`, `Radare2_disassemble_function`, `Radare2_decompile_function`
- - `extract_iocs`, `run_yara`, `create_analysis_report`
- 2. **Tier-2: Domain Expert Sub-Agents & Universal Router (3 tools)**:
- - `call_expert_agent`: Dispatches high-level multi-step domain tasks to specialized Sub-Agents:
- - `modern_runtime`: Stripped Go (`gopclntab`) & Rust (`.dep-v0` crates), Electron `app.asar` IPC/security audit, Unity IL2CPP (`global-metadata.dat`), feature code reconstruction (`reconstruct_feature_code`), paged view inspection (`inspect_analysis_view`), and on-demand guidance (`search_guidance`)
- - `vulnerability_hunter`: CVE scanning, dangerous API auditing, ROP gadget collection, heap analysis, crash triage
- - `forensics`: Network PCAP analysis, C2 extraction, Volatility3 memory dumps, SleuthKit disk carving
- - `malware_analyst`: IOC extraction, dormant backdoors, CAPA capability mapping, adaptive vaccines
- - `deobfuscator`: DIE packer detection, string decryption, API hash resolution, dead-code elimination
- - `symbolic_engine`: angr symbolic path reachability, constraint solving, dataflow taint tracing
- - `diff_analyst`: Semantic binary diffing, 1-day patch review, cross-binary annotation transfer
- - `source_auditor`: AST vulnerability scanning (Python) and regex pattern auditing (C/C++)
- - `search_tools`: Dynamic keyword and domain search across all 186 tools with parameter schemas and example invocations.
- - `execute_domain_tool`: Universal execution gateway to invoke any of the 186 specialized tools on demand with custom arguments.
- Enable tiered mode via `reversecore-mcp setup --tiered` or `export REVERSECORE_PROFILE=tiered`.
- ---
- ### 🔍 Static Analysis Plugin (24 tools)
- | # | Tool | Backend | Description |
- |---|---|---|---|
- | 1 | `run_strings` | `strings` CLI | ASCII/Unicode string extraction with configurable min-length |
- | 2 | `run_binwalk` | Binwalk | Firmware deep-scan for embedded signatures and filesystems |
- | 3 | `run_binwalk_extract` | Binwalk | Extract embedded files discovered by binwalk |
- | 4 | `parse_binary_with_lief` | LIEF | Full PE/ELF/Mach-O header, section, import/export, TLS parsing |
- | 5 | `detect_packer` | DIE | Quick packer/compiler detection |
- | 6 | `detect_packer_deep` | DIE (`diec`) | Deep packer/protector analysis via Detect It Easy |
- | 7 | `run_capa` | CAPA (Mandiant FLARE) | Capability detection — "encrypts data", "creates persistence", etc. |
- | 8 | `run_capa_quick` | CAPA | Quick capability scan with a rule subset |
- | 9 | `generate_signature` | Radare2 | Generate binary signatures for identification |
- | 10 | `generate_yara_rule` | Radare2 + YARA | Generate YARA detection rules from binary patterns |
- | 11 | `generate_advanced_yara_rule` | Radare2 + YARA | Advanced YARA rules with behavioral indicators |
- | 12 | `scan_for_versions` | LIEF + strings | Scan binary for embedded version strings |
- | 13 | `extract_rtti_info` | Radare2 | Extract C++ RTTI (Run-Time Type Information) |
- | 14 | `diff_binaries` | Radare2 | Semantic binary diff between two file versions |
- | 15 | `analyze_variant_changes` | Radare2 | Analyze changes between binary variants |
- | 16 | `match_libraries` | Radare2 | Identify statically linked libraries by function fingerprint |
- | 17 | `patch_diff_1day` | Radare2 + heuristics | Automated patch diff analysis for 1-day vulnerability research |
- | 18 | `analyze_patch_diff_auto` | Radare2 + inference | Automated patch vulnerability inference |
- | 19 | `emulate_binary` | Radare2 ESIL | Register/memory-traced code emulation |
- | 20 | `generate_fuzzing_harness` | Qiling + AFL++ | Generate a fuzzing harness targeting a specific function |
- | 21 | `run_fuzzing_campaign` | AFL++ | Run a full fuzzing campaign with crash collection |
- | 22 | `triage_crash` | GDB | Crash parsing and exploitability assessment |
- | 23 | `verify_path_and_get_args` | angr | Symbolic execution — prove path reachability and compute concrete inputs |
- | 24 | `taint_trace` | Radare2 + angr | Data-flow taint analysis from sources to sinks |
- ---
- ### 🔐 Source Code Audit Plugin (1 tool)
- | # | Tool | Backend | Description |
- |---|---|---|---|
- | 25 | `audit_source_code` | AST + Regex | Python AST scanning + C/C++ regex scanning for dangerous patterns |
- ---
- ### 🛠️ Common Utilities Plugin (20 tools)
- **File Operations (5 tools)**
- | # | Tool | Description |
- |---|---|---|
- | 26 | `run_file` | File type, architecture, and compiler fingerprinting |
- | 27 | `copy_to_workspace` | Copy a file into the analysis workspace |
- | 28 | `create_directory` | Create a directory in the workspace |
- | 29 | `list_workspace` | List all files in the workspace |
- | 30 | `scan_workspace` | Full workspace scan with file metadata |
- **Patch Explanation (1 tool)**
- | # | Tool | Description |
- |---|---|---|
- | 31 | `explain_patch` | Explain a binary patch in natural language |
- **Assembler (1 tool)**
- | # | Tool | Backend | Description |
- |---|---|---|---|
- | 32 | `assemble_instructions` | Keystone | Assemble instructions to machine code (x86, ARM, MIPS, etc.) |
- **AI Memory Management (11 tools)**
- These tools let the AI persist and recall findings across analysis sessions using an async SQLite database:
- | # | Tool | Description |
- |---|---|---|
- | 33 | `create_memory_session` | Start a new memory session for an analysis |
- | 34 | `store_analysis_finding` | Persist an analysis finding with tags |
- | 35 | `query_analysis_memories` | Search past findings by query |
- | 36 | `get_binary_analysis_context` | Retrieve all context for a specific binary |
- | 37 | `tag_analysis_session` | Add tags to a session for organization |
- | 38 | `search_memories_by_tag` | Find sessions/findings by tag |
- | 39 | `delete_analysis_session` | Remove a session and its findings |
- | 40 | `cleanup_expired_sessions` | Remove sessions older than a threshold |
- | 41 | `list_analysis_sessions` | List all active sessions |
- | 42 | `export_memory_store` | Export all memories to a portable format |
- | 43 | `import_memory_store` | Import memories from an export file |
- **Server Monitoring (2 tools)**
- | # | Tool | Description |
- |---|---|---|
- | 44 | `get_server_health` | Uptime, memory usage, loaded tools, Python version |
- | 45 | `get_tool_metrics` | Per-tool call counts, mean execution times, error rates, cache hit/miss |
- ---
- ### ⚙️ Radare2 & r2ghidra Plugin (30 tools)
- All Radare2 tools use a thread-safe connection pool (`r2_pool.py`) that automatically manages r2pipe sessions.
- | # | Tool | Description |
- |---|---|---|
- | 46 | `Radare2_open_file` | Open a binary file in Radare2 |
- | 47 | `Radare2_close_file` | Close a Radare2 session |
- | 48 | `Radare2_list_open_files` | List currently open files |
- | 49 | `Radare2_analyze_binary` | Run full auto-analysis (`aaa`) |
- | 50 | `Radare2_list_functions` | List all detected functions |
- | 51 | `Radare2_disassemble_function` | Disassemble a specific function |
- | 52 | `Radare2_disassemble_address` | Disassemble at a specific address |
- | 53 | `Radare2_decompile_function` | Decompile via r2ghidra (Ghidra engine embedded in r2, no JVM needed) |
- | 54 | `Radare2_list_exports` | List exported symbols |
- | 55 | `Radare2_list_imports` | List imported functions |
- | 56 | `Radare2_list_sections` | List binary sections with entropy |
- | 57 | `Radare2_list_strings` | List strings found in the binary |
- | 58 | `Radare2_find_cross_references` | Track function calls and data references |
- | 59 | `Radare2_search_bytes` | Search for byte patterns in the binary |
- | 60 | `Radare2_get_binary_info` | Get binary metadata (arch, format, endianness) |
- | 61 | `Radare2_execute_command` | Execute a raw Radare2 command |
- | 62 | `Radare2_esil_emulate` | ESIL emulation at a specific address |
- | 63 | `Radare2_get_hexdump` | Hex dump at a virtual address |
- | 64 | `Radare2_get_cfg_data` | Extract control flow graph data |
- | 65 | `Radare2_generate_cfg_png` | Generate CFG as PNG image |
- | 66 | `Radare2_generate_callgraph` | Generate function call graph |
- | 67 | `Radare2_recover_structures` | Auto-recover C structs and persist to annotation database |
- | 68 | `Radare2_decompile_with_r2ghidra` | High-quality C decompilation with caching |
- | 69 | `Radare2_annotate_binary` | Add annotations to the binary |
- | 70 | `Radare2_get_annotations` | Retrieve annotations |
- | 71 | `Radare2_export_annotations` | Export annotations to file |
- | 72 | `Radare2_import_annotations` | Import annotations from file |
- | 73 | `Radare2_detect_crypto_constants` | Detect cryptographic constants (AES S-box, etc.) |
- | 74 | `Radare2_find_gadgets` | Find ROP/JOP gadgets |
- | 75 | `Radare2_calculate_entropy` | Calculate per-section entropy |
- ---
- ### 🦠 Malware Analysis Plugin (9 tools)
- | # | Tool | Backend | Description |
- |---|---|---|---|
- | 76 | `dormant_detector` | Radare2 + heuristics | Find hidden backdoors, orphan functions, time-bombs, logic bombs |
- | 77 | `adaptive_vaccine` | YARA + Radare2 | Generate detection YARA rules + binary patches to neutralize threats |
- | 78 | `vulnerability_hunter` | Radare2 + analysis | Detect dangerous API patterns (strcpy, sprintf) and ROP gadget chains |
- | 79 | `extract_iocs` | Regex + LIEF | Extract IPs, URLs, domains, hashes, registry keys, crypto addresses |
- | 80 | `run_yara` | YARA | Scan with custom rule files and built-in rulesets |
- | 81 | `generate_poc_exploit` | pwntools | Generate proof-of-concept exploit code |
- | 82 | `build_rop_chain` | ROPgadget + pwntools | Automated ROP chain construction |
- | 83 | `autonomous_vuln_hunt` | Radare2 + angr | Autonomous vulnerability hunting pipeline |
- | 84 | `analyze_heap_exploit` | Radare2 + heuristics | Heap exploitation analysis (UAF, double-free, overflow) |
- ---
- ### 🕵️ Digital Forensics Plugin (22 tools)
- **Memory Forensics (6 tools)**
- | # | Tool | Backend | Description |
- |---|---|---|---|
- | 85 | `memory_analyze` | Volatility3 | Full memory dump analysis |
- | 86 | `memory_list_processes` | Volatility3 | List running processes from memory dump |
- | 87 | `memory_detect_injections` | Volatility3 | Detect code injection in process memory |
- | 88 | `memory_extract_strings` | Volatility3 | Extract strings from process memory |
- | 89 | `memory_dump_module` | Volatility3 | Dump a loaded module from memory |
- | 90 | `memory_list_symbols` | Volatility3 | List symbols from memory |
- **Disk Forensics (6 tools)**
- | # | Tool | Backend | Description |
- |---|---|---|---|
- | 91 | `disk_list_partition` | Sleuth Kit | List disk partitions |
- | 92 | `disk_list_files` | Sleuth Kit | List files in a disk image |
- | 93 | `disk_recover_deleted` | Sleuth Kit | Recover deleted files |
- | 94 | `disk_analyze_mft` | Sleuth Kit | Analyze NTFS Master File Table |
- | 95 | `disk_extract_file` | Sleuth Kit | Extract a file from disk image |
- | 96 | `disk_hash_verify` | Sleuth Kit | Verify file integrity via hash |
- **Network Forensics (5 tools)**
- | # | Tool | Backend | Description |
- |---|---|---|---|
- | 97 | `pcap_analyze` | Scapy | PCAP analysis: protocol breakdown, anomalies |
- | 98 | `pcap_list_connections` | Scapy | List all network connections |
- | 99 | `pcap_extract_dns` | Scapy | Extract DNS queries and responses |
- | 100 | `pcap_extract_c2` | Scapy | Identify potential C2 communication |
- | 101 | `pcap_reconstruct_stream` | Scapy | Reconstruct TCP streams |
- **Artifact Analysis (5 tools)**
- | # | Tool | Backend | Description |
- |---|---|---|---|
- | 102 | `artifact_collect` | Custom parsers | Collect browser history, registry hives, event logs, prefetch |
- | 103 | `artifact_correlate_ioc` | Custom parsers | Correlate artifacts with known IOCs |
- | 104 | `artifact_generate_yara` | YARA | Generate YARA rules from artifact patterns |
- | 105 | `artifact_timeline` | Custom parsers | Build timeline from multiple artifact sources |
- | 106 | `artifact_report` | Custom parsers | Generate artifact analysis report |
- ---
- ### 📝 Report Generation Plugin (14 tools)
- | # | Tool | Description |
- |---|---|---|
- | 107 | `get_system_time` | Get server timestamp (prevents AI from hallucinating dates) |
- | 108 | `set_timezone` | Set the reporting timezone |
- | 109 | `get_timezone_info` | Get current timezone information |
- | 110 | `start_report_session` | Start a timed analysis session with unique ID |
- | 111 | `end_report_session` | Finalize session: compute duration, lock IOC/ATT&CK lists |
- | 112 | `get_report_session_status` | Check session status |
- | 113 | `list_report_sessions` | List all active/completed sessions |
- | 114 | `add_ioc` | Collect and tag IOCs during a live session |
- | 115 | `add_analysis_note` | Add categorized notes (finding, warning, behavior) |
- | 116 | `add_mitre_technique` | Document MITRE ATT&CK technique IDs |
- | 117 | `set_severity` | Set session severity (low/medium/high/critical) |
- | 118 | `create_analysis_report` | Render report in 4 modes: `full_analysis`, `quick_triage`, `ioc_summary`, `executive_brief` |
- | 119 | `generate_vex_report` | Generate a VEX (Vulnerability Exploitability eXchange) report |
- | 120 | `generate_sigma_rule` | Generate SIGMA detection rules |
- ---
- ## Guided Analysis Prompts (22 Modes)
- Prompts are pre-built analysis workflows that prime the AI with a structured persona, step-by-step tool usage sequences, and evidence classification rules. You activate them by referencing the prompt name in your AI client.
- ### Malware Analysis (9 prompts)
- | Prompt | Use Case |
- |---|---|
- | `full_analysis_mode` | 6-phase comprehensive analysis: triage → disassembly → behavior → network → persistence → report |
- | `malware_analysis_mode` | Focused malware analysis with threat classification |
- | `basic_analysis_mode` | Rapid triage for initial assessment and quick verdicts |
- | `apt_hunting_mode` | APT-specific hunting: lateral movement, persistence, data exfiltration |
- | `malware_defense_mode` | Defense-oriented: generate detection rules and mitigations |
- | `unpacking_mode` | Analyze and bypass packing/obfuscation (Themida, VMProtect, UPX) |
- | `c2_extraction_mode` | Extract and analyze C2 communication infrastructure |
- | `ransomware_triage_mode` | Ransomware-specific triage: encryption analysis, key recovery assessment |
- | `code_similarity_mode` | Compare binaries for code similarity and shared lineage |
- ### Security Research (6 prompts)
- | Prompt | Use Case |
- |---|---|
- | `vulnerability_research_mode` | Bug hunting: buffer overflows, UAF, command injection |
- | `crypto_analysis_mode` | Cryptographic implementation analysis and weakness detection |
- | `firmware_analysis_mode` | IoT/embedded firmware: binwalk extraction, UART strings, hardcoded credentials |
- | `patch_analysis_mode` | Security patch analysis and regression testing |
- | `source_code_audit_mode` | Source code security audit (Python, C, C++) |
- | `autonomous_vuln_hunt_mode` | Autonomous vulnerability hunting pipeline |
- ### CVE Research & Exploit Development (5 prompts)
- | Prompt | Use Case |
- |---|---|
- | `taint_analysis_mode` | Data-flow taint analysis: automated source→sink path discovery |
- | `heap_exploit_mode` | Heap exploitation analysis and PoC generation |
- | `fuzzing_mode` | Fuzzing campaign setup and crash triage |
- | `patch_diff_auto_mode` | Automated patch diff for 1-day vulnerability research |
- | `cve_discovery_pipeline_mode` | Full CVE discovery pipeline: from patch diff to working exploit |
- ### Other (2 prompts)
- | Prompt | Use Case |
- |---|---|
- | `game_analysis_mode` | Game client analysis: anti-cheat detection, protocol RE, memory inspection |
- | `report_generation_mode` | Structured session workflow with MITRE ATT&CK technique mapping |
- > **How prompts work:** Each prompt primes the AI with a structured analysis persona. It includes Chain-of-Thought reasoning checkpoints (where the AI must stop and evaluate before proceeding) and evidence classification rules that prevent the AI from stating speculation as fact. Every finding must be labeled as `OBSERVED` (directly verified), `INFERRED` (logically derived from static analysis), or `POSSIBLE` (requires further verification).
- ---
- ## MCP Resources (11 URIs)
- Resources are read-only data endpoints that AI clients can access through URI templates. They complement tools by providing structured data without requiring explicit tool calls.
- ### Static Resources
- | URI | Description |
- |---|---|
- | `reversecore://guide` | Tool usage guide with file path rules and best practices |
- | `reversecore://guide/structures` | Structure recovery and cross-reference analysis technical guide |
- | `reversecore://tools` | Complete documentation for all 194 registered tools |
- | `reversecore://logs` | Application logs (last 100 lines) |
- ### Dynamic Resources (Per-Binary Virtual Filesystem)
- These URIs resolve per-binary and invoke the corresponding analysis tools on demand:
- | URI Template | Description |
- |---|---|
- | `reversecore://{filename}/strings` | Extract all strings from a binary |
- | `reversecore://{filename}/iocs` | Extract IOCs (IPs, URLs, emails, hashes) |
- | `reversecore://{filename}/func/{address}/code` | Decompiled pseudo-C code for a function |
- | `reversecore://{filename}/func/{address}/asm` | Disassembly for a function |
- | `reversecore://{filename}/func/{address}/cfg` | Control flow graph in Mermaid format |
- | `reversecore://{filename}/functions` | List of all functions in the binary |
- | `reversecore://{filename}/dormant_detector` | Dormant detector analysis results |
- ---
- ## Quick Start
- ### ⚡ One-Line Automated Setup (Recommended)
- Automatically detects installed AI agents (**Cursor, Claude Code, Windsurf, Claude Desktop, Antigravity, VS Code Cline/Roo Code, Codex**) and registers Reversecore_MCP with automatic backups and zero manual JSON editing:
- ```bash
- # macOS / Linux
- curl -fsSL https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.sh | bash
- # Or via uvx (zero installation required)
- uvx --from reversecore-mcp reversecore-setup
- # Or via pipx
- pipx run reversecore-mcp setup
- # Windows (PowerShell)
- irm https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.ps1 | iex
- ```
- **Common Setup Options:**
- ```bash
- reversecore-mcp setup --tiered # Tiered Mode: 15 essential tools (>90% context token reduction)
- reversecore-mcp setup --docker # Configure Docker container execution
- reversecore-mcp setup --dry-run # Preview configuration changes without writing
- reversecore-mcp setup --list # Inspect detected clients and config paths
- reversecore-mcp setup --remove # Unregister Reversecore from all clients
- ```
- ---
- ### Manual Installation Options
- #### Option 1 — PyPI (Simplest)
- ```bash
- pip install reversecore-mcp
- reversecore-mcp
- ```
- > **Prerequisites:** Radare2 must be installed on your system (`r2 --version`). YARA is installed automatically via `yara-python`.
- ### Option 2 — Docker (Recommended for Full Functionality)
- All analysis engines (Radare2, r2ghidra, YARA, Binwalk, Sleuth Kit, GDB, etc.) come pre-installed:
- ```bash
- docker run -i --rm \
- -v /path/to/your/samples:/app/workspace \
- -e REVERSECORE_WORKSPACE=/app/workspace \
- -e MCP_TRANSPORT=stdio \
- ghcr.io/sjkim1127/reversecore_mcp:latest
- ```
- ### Option 3 — Build from Source (Docker Compose)
- ```bash
- git clone https://github.com/sjkim1127/Reversecore_MCP.git
- cd Reversecore_MCP
- ./scripts/run-docker.sh # auto-detects Intel / Apple Silicon
- ```
- Or manually:
- ```bash
- docker compose --profile x86 up -d # Intel/AMD
- docker compose --profile arm64 up -d # Apple Silicon (M1/M2/M3)
- ```
- ### Option 4 — Python (Local Development)
- ```bash
- git clone https://github.com/sjkim1127/Reversecore_MCP.git
- cd Reversecore_MCP
- python -m venv venv && source venv/bin/activate
- pip install -r requirements.txt
- python -m reversecore_mcp.server
- ```
- > **Prerequisites for local mode:** Radare2 must be installed on your system (`r2 --version`). Individual tool backends (YARA, LIEF, Capstone, etc.) are installed via pip. For full forensics support, you'll also need Volatility3, Scapy, and Sleuth Kit.
- ---
- ## Connect to Your AI Client
- Add the server configuration to your IDE client settings (e.g., `~/.cursor/mcp.json` or `claude_desktop_config.json`).
- ### ⚡ Option 1: Docker Exec Mode (Recommended)
- If you have the container running via Docker Compose, this mode channels stdio directly into the running container. Zero startup latency, persistent memory, and full tool availability.
- ```json
- {
- "mcpServers": {
- "Reversecore_MCP": {
- "command": "docker",
- "args": [
- "exec",
- "-i",
- "-e",
- "MCP_TRANSPORT=stdio",
- "reversecore-mcp-arm64",
- "python",
- "-m",
- "reversecore_mcp.server"
- ]
- }
- }
- }
- ```
- > Replace `reversecore-mcp-arm64` with `reversecore-mcp` if you are on Intel/AMD.
- ---
- ### 🌐 Option 2: SSE HTTP Mode
- For network-based streaming (Server-Sent Events):
- ```json
- {
- "mcpServers": {
- "Reversecore_MCP": {
- "url": "http://localhost:8000/mcp/sse"
- }
- }
- }
- ```
- ---
- ### 📦 Option 3: Stdio Mode (Docker-on-Demand)
- Runs a fresh, isolated container for every session:
- <details>
- <summary>🍎 macOS</summary>
- ```json
- {
- "mcpServers": {
- "reversecore": {
- "command": "docker",
- "args": [
- "run", "-i", "--rm",
- "-v", "/Users/YOUR_USERNAME/samples:/app/workspace",
- "-e", "REVERSECORE_WORKSPACE=/app/workspace",
- "-e", "MCP_TRANSPORT=stdio",
- "ghcr.io/sjkim1127/reversecore_mcp:latest"
- ]
- }
- }
- }
- ```
- </details>
- <details>
- <summary>🐧 Linux</summary>
- ```json
- {
- "mcpServers": {
- "reversecore": {
- "command": "docker",
- "args": [
- "run", "-i", "--rm",
- "-v", "/home/YOUR_USERNAME/samples:/app/workspace",
- "-e", "REVERSECORE_WORKSPACE=/app/workspace",
- "-e", "MCP_TRANSPORT=stdio",
- "ghcr.io/sjkim1127/reversecore_mcp:latest"
- ]
- }
- }
- }
- ```
- </details>
- <details>
- <summary>🪟 Windows</summary>
- ```json
- {
- "mcpServers": {
- "reversecore": {
- "command": "docker",
- "args": [
- "run", "-i", "--rm",
- "-v", "C:/samples:/app/workspace",
- "-e", "REVERSECORE_WORKSPACE=/app/workspace",
- "-e", "MCP_TRANSPORT=stdio",
- "ghcr.io/sjkim1127/reversecore_mcp:latest"
- ]
- }
- }
- }
- ```
- </details>
- > **⚠️ Important — File Paths Inside Docker**
- >
- > Your local folder is mounted to `/app/workspace` inside the container.
- > Always reference files by **filename only**, not by your local full path.
- >
- > | ❌ Wrong | ✅ Correct |
- > |---|---|
- > | `r2_decompile("/Users/john/samples/mal.exe")` | `r2_decompile("mal.exe")` |
- ---
- ## Configuration
- All settings can be provided via environment variables or a `.env` file (see [`.env.example`](.env.example)). Settings are managed via Pydantic BaseSettings with the `REVERSECORE_` prefix.
- ### Core Settings
- | Variable | Default | Description |
- |---|---|---|
- | `MCP_TRANSPORT` | `stdio` | Transport mode: `stdio` or `http` |
- | `REVERSECORE_WORKSPACE` | `./` (cwd) | Analysis workspace directory |
- | `REVERSECORE_READ_DIRS` | `""` | Comma-separated list of additional read-only directories |
- | `REVERSECORE_STRICT_PATHS` | `false` | Raise errors for missing paths instead of warnings |
- | `REVERSECORE_STRUCTURED_ERRORS` | `false` | Enable structured error responses with error codes |
- | `REVERSECORE_DEFAULT_TOOL_TIMEOUT` | `120` | Default tool execution timeout in seconds |
- | `REVERSECORE_MAX_OUTPUT_SIZE` | `10000000` | Maximum output size for tools (bytes) |
- | `REVERSECORE_FORENSICS_MAX_RECOVERED_BYTES` | `500000000` | Maximum bytes recovered from one disk inode |
- ### HTTP Mode Settings
- | Variable | Default | Description |
- |---|---|---|
- | `MCP_HOST` | `0.0.0.0` | Host interface to bind (auto-overrides to `127.0.0.1` if no API key) |
- | `MCP_PORT` | `8000` | Port for HTTP server |
- | `MCP_API_KEY` | *(unset)* | API key for HTTP authentication (`X-API-Key` or `Authorization: Bearer`) |
- | `REVERSECORE_RATE_LIMIT` | `60` | Max requests per minute (HTTP mode only, via slowapi) |
- | `MAX_UPLOAD_SIZE` | `100000000` | Maximum upload size (100 MB default) |
- | `FILE_RETENTION_MINUTES` | `1440` | Retention period for uploaded files (24h default) |
- ### Radare2 Settings
- | Variable | Default | Description |
- |---|---|---|
- | `REVERSECORE_R2_POOL_SIZE` | `3` | Number of Radare2 connections in the pool |
- | `REVERSECORE_R2_POOL_TIMEOUT` | `30` | Timeout for acquiring a connection from the pool |
- | `REVERSECORE_R2_EXTENSIONS` | `""` | Comma-separated list of r2 extension classes (`module:ClassName`) |
- | `REVERSECORE_GHIDRA_MAX_PROJECTS` | `3` | Max cached r2ghidra decompiler projects |
- | `REVERSECORE_GHIDRA_EXTENSIONS` | `""` | Comma-separated list of Ghidra extension classes |
- | `MAX_EMULATION_INSTRUCTIONS` | `1000` | Maximum ESIL emulation instructions |
- ### Sandbox Settings
- | Variable | Default | Description |
- |---|---|---|
- | `REVERSECORE_SANDBOX_ENABLED` | `false` | Enable sandbox execution for dynamic analysis tools |
- | `REVERSECORE_SANDBOX_MODE` | `auto` | Sandbox mode: `auto`, `host`, `container`, `disabled` |
- | `REVERSECORE_SANDBOX_DOCKER_IMAGE` | `reversecore-sandbox:latest` | Docker image for sandbox execution |
- | `REVERSECORE_SANDBOX_CPU_LIMIT` | `1.0` | CPU core limit for sandbox containers |
- | `REVERSECORE_SANDBOX_MEMORY_LIMIT` | `512m` | Memory limit for sandbox containers |
- | `REVERSECORE_SANDBOX_PIDS_LIMIT` | `100` | PID limit for sandbox containers |
- | `REVERSECORE_SANDBOX_USER` | `nobody` | Non-root user for sandbox execution |
- ### Storage & Queue
- | Variable | Default | Description |
- |---|---|---|
- | `REDIS_URL` | `redis://localhost:6379/0` | Redis URL for task queue and result caching |
- | `MEMORY_DB_PATH` | `~/.reversecore_mcp/memory.db` | Path to AI memory SQLite database |
- | `REVERSECORE_LIEF_MAX_FILE_SIZE` | `1000000000` | Maximum file size for LIEF parsing (1 GB) |
- ### Logging
- | Variable | Default | Description |
- |---|---|---|
- | `LOG_LEVEL` | `INFO` | Logging verbosity: `DEBUG`, `INFO`, `WARNING`, `ERROR` |
- | `LOG_FILE` | `<tempdir>/reversecore/app.log` | Path to log file |
- | `LOG_FORMAT` | `human` | Log format: `human` (readable) or `json` (structured) |
- ### Plugins & SAST
- | Variable | Default | Description |
- |---|---|---|
- | `REVERSECORE_PLUGIN_DIRS` | `""` | Comma-separated directories to scan for extension plugins |
- | `REVERSECORE_SAST_RULES_PATH` | `""` | Path to custom YAML SAST rules file |
- ---
- ## Security Model
- Security is implemented as defense-in-depth, with protections at multiple layers:
- ### Input & Path Safety
- | Control | Implementation |
- |---|---|
- | **No shell injection** | All subprocess calls use list arguments, never shell strings (`execution.py`) |
- | **Path traversal prevention** | `validate_file_path()` and `validate_binary_path()` resolve symlinks and confine access to the workspace (`validators.py`) |
- | **TOCTOU mitigation** | `bypass_cache=True` flag re-validates paths to prevent race conditions |
- | **Input sanitization** | All parameters sanitized before execution (`security.py`) |
- | **CSRF protection** | Dashboard forms require token-based CSRF validation (`dashboard/__init__.py`) |
- ### Network & Authentication
- | Control | Implementation |
- |---|---|
- | **Timing-attack-safe auth** | `secrets.compare_digest()` for API key comparison (`web/auth.py`) |
- | **Restricted auth vectors** | Only `X-API-Key` and `Authorization: Bearer` headers accepted; no query params or cookies |
- | **Loopback-only fallback** | Without `MCP_API_KEY`, HTTP access restricted to `127.0.0.1` (`web/middleware.py`) |
- | **Rate limiting** | Configurable per-minute limits via slowapi |
- | **Security headers** | HSTS, X-Content-Type-Options, X-Frame-Options, CSP on all HTTP responses (`web/middleware.py`) |
- | **Minimized `/health`** | Public endpoint returns only `{"status": "alive"}`; details behind authentication (`web/endpoints.py`) |
- ### Container & Runtime
- | Control | Implementation |
- |---|---|
- | **Non-root execution** | Runs as `appuser` (UID 1000) with minimal capabilities |
- | **Resource limits** | Docker Compose enforces CPU (2.0) and memory (4 GB) limits |
- | **Sandbox isolation** | Optional container-based sandboxing for dynamic analysis tools |
- ### CI/CD Security Gates
- | Control | Implementation |
- |---|---|
- | **Secrets scanning** | Gitleaks runs on every commit (pre-commit hook + CI) |
- | **SAST** | Bandit scans all Python code on every commit |
- | **CodeQL** | GitHub CodeQL static analysis on every push to `main` |
- | **Dependency auditing** | pip-audit on every push — no unreviewed CVEs |
- | **Container scanning** | Trivy scans Docker images for vulnerabilities (LOW through CRITICAL) |
- | **Exploit safety gate** | POC templates scanned with Bandit; Hypothesis DAST fuzzing; container isolation verified |
- ### Structured Error Handling
- All 17 exception classes carry `RCMCP-E*` error codes for programmatic handling. See [Error Handling](#error-handling) for the full hierarchy.
- ---
- ## Development
- ### Setup
- ```bash
- git clone https://github.com/sjkim1127/Reversecore_MCP.git
- cd Reversecore_MCP
- python -m venv venv && source venv/bin/activate
- pip install -r requirements.txt
- pip install -r requirements-dev.txt
- pre-commit install # installs Ruff, Bandit, Gitleaks hooks
- ```
- ### Testing
- ```bash
- # Full test suite with coverage report
- pytest tests/ -v
- # Unit tests only (fast, no external dependencies)
- pytest tests/unit/ -v
- # Integration tests (requires Docker)
- pytest tests/integration/ -v
- # Run with coverage threshold enforcement
- pytest tests/unit/ --cov=reversecore_mcp --cov-fail-under=80
- # Run a specific test
- pytest tests/unit/test_cli_tools.py::TestRunFile::test_success -v
- # Security boundary tests
- pytest tests/ -m security -v
- # Benchmarks
- pytest tests/ -m benchmark -v
- ```
- **Test status:**
- - ✅ **1,957 unit tests** passing across Python 3.10 / 3.11 / 3.12
- - 📊 **87% code coverage** (80% minimum enforced in CI)
- - 🔒 Zero Bandit findings
- - ⚡ Fully async test suite via `pytest-asyncio`
- **Test markers:**
- | Marker | Purpose |
- |---|---|
- | `@pytest.mark.unit` | Fast unit tests |
- | `@pytest.mark.integration` | Tests requiring Docker or external tools |
- | `@pytest.mark.slow` | Long-running tests |
- | `@pytest.mark.benchmark` | Performance benchmarks |
- | `@pytest.mark.security` | Security boundary validation tests |
- ### Code Quality
- ```bash
- ruff check reversecore_mcp/ # Lint (E, W, F, I, B, C4, UP rules)
- ruff format reversecore_mcp/ # Format
- mypy reversecore_mcp/ # Type check (0 errors across 108 files)
- bandit -r reversecore_mcp/ # Security scan (all severities)
- pip-audit # Dependency CVE scan
- ```
- ### Pre-commit Hooks
- The following hooks run automatically on every commit:
- 1. **Ruff** — lint with auto-fix + format check
- 2. **trailing-whitespace** — remove trailing whitespace
- 3. **end-of-file-fixer** — ensure files end with newline
- 4. **check-yaml / check-json** — validate YAML/JSON syntax
- 5. **check-added-large-files** — block files > 1 MB
- 6. **check-merge-conflict** — detect unresolved merge markers
- 7. **detect-private-key** — prevent accidental key commits
- 8. **Bandit** — Python security scanning
- ---
- ## CI/CD Pipeline
- Every push to `main` triggers 11 pipeline jobs. All must pass before deployment.
- ```
- Lint & Security Gate Unit Tests (Python Matrix)
- ├─ Gitleaks (secret scan) ├─ pytest 3.10 --cov-fail-under=80
- ├─ Hadolint (Dockerfile lint) ├─ pytest 3.11 --cov-fail-under=80
- ├─ Ruff check + format └─ pytest 3.12 --cov-fail-under=80
- ├─ Mypy type check (108 files)
- ├─ Bandit (all severities) Wheel Smoke Test
- ├─ pip-audit (no CVEs) └─ Build wheel → install in /tmp
- └─ Security boundary tests → verify plugin discovery
- → assert __file__ under sys.prefix
- CodeQL Analysis
- └─ Python SAST Docker Verification
- ├─ Build reversecore-mcp:ci
- Exploit Safety Gate ├─ Trivy container scan
- ├─ Bandit on POC templates ├─ Image size check (< 5 GB)
- ├─ Hypothesis DAST fuzzing ├─ CLI tool verification
- ├─ Performance benchmarks ├─ Integration tests in container
- └─ Container isolation test └─ E2E tool invocation
- In-Container Smoke Test Build Base Image (amd64 + arm64)
- ├─ Copy test ELF into container ├─ Compile YARA 4.3.1
- └─ Run scripts/smoke_test.py ├─ Compile Radare2 6.0.4
- ├─ Compile r2ghidra
- Deploy (amd64 + arm64) └─ Push to GHCR
- ├─ Build app image
- ├─ Push to GHCR Merge Manifests
- └─ Trivy rescan on published └─ Multi-arch manifest → :latest
- ```
- > **Zero-bypass policy:** CI/CD failures are never resolved by modifying pipeline configuration. Root causes are always fixed directly in source code or dependencies.
- ---
- ## Docker Build Architecture
- The Docker build uses a two-layer approach to keep build times manageable:
- ### Layer 1: Base Image (`Dockerfile.base`)
- A multi-stage build that compiles all slow-to-build, rarely-changing dependencies from source:
- ```
- compiler-toolchain (python:3.12-slim-bookworm + build tools)
- ├── compiler-yara (YARA 4.3.1 from source) [parallel]
- ├── compiler-r2 (Radare2 6.0.4 from source) [parallel]
- │ └── compiler-r2ghidra (r2ghidra plugin) [sequential]
- └── compiler-pip (pip install into /opt/venv) [parallel]
- base (final runtime: python:3.12-slim-bookworm)
- ├── Runtime packages: file, binutils, gdb, binwalk, graphviz, nasm, sleuthkit
- ├── /opt/yara (compiled YARA)
- ├── /opt/radare2 (compiled r2 + r2ghidra)
- ├── /opt/venv (Python packages)
- └── Non-root user: appuser (UID 1000)
- ```
- This image is rebuilt only when tool versions change. Build time: ~12 minutes.
- ### Layer 2: Application Image (`Dockerfile`)
- Inherits from the base image and copies application code:
- ```
- FROM base image
- ├── COPY reversecore_mcp/ (application code)
- ├── COPY scripts/ (smoke test, benchmarks)
- ├── pip install any new requirements
- ├── Security package upgrades
- └── CMD ["python", "-m", "reversecore_mcp.server"]
- ```
- Build time: ~60 seconds.
- ### Docker Compose
- Three services with architecture-specific profiles:
- | Service | Profile | Description |
- |---|---|---|
- | `reversecore-mcp` | `default`, `x86` | Intel/AMD x86_64 |
- | `reversecore-mcp-arm64` | `arm64`, `macos` | Apple Silicon ARM64 |
- | `redis` | all profiles | Redis 7 Alpine for task queue and caching |
- Resource limits: 2.0 CPU cores, 4 GB memory per container.
- ---
- ## System Requirements
- | Component | Minimum | Recommended |
- |---|---|---|
- | CPU | 4 cores | 8+ cores |
- | RAM | 8 GB | 16 GB |
- | Storage | 20 GB | 50 GB SSD |
- | OS | Linux / macOS | Docker environment (any OS) |
- | Docker | 20.10+ | 24.0+ |
- | Python (local mode) | 3.10 | 3.11 or 3.12 |
- ---
- ## Project Structure
- ```
- reversecore_mcp/
- ├── core/ # Infrastructure layer (37 modules)
- │ ├── config.py # Pydantic BaseSettings (34+ env vars)
- │ ├── exceptions.py # Exception hierarchy (17 classes, RCMCP-E* codes)
- │ ├── security.py # Input sanitization & command arg validation
- │ ├── validators.py # Path validators (TOCTOU-hardened, symlink-safe)
- │ ├── r2_pool.py # Thread-safe Radare2 connection pool
- │ ├── r2_helpers.py # Structured Radare2 output parsing
- │ ├── metrics.py # Per-tool timing, counts, error rates, cache stats
- │ ├── decorators.py # @log_execution, @track_metrics
- │ ├── error_handling.py # @handle_tool_errors decorator
- │ ├── error_formatting.py # Structured error formatting
- │ ├── execution.py # Safe subprocess with timeout/output limits
- │ ├── command_spec.py # Command specifications
- │ ├── memory.py # Async SQLite AI memory store
- │ ├── mitre_mapper.py # MITRE ATT&CK mapping engine
- │ ├── evidence.py # Evidence classification (OBSERVED/INFERRED/POSSIBLE)
- │ ├── resilience.py # Retry, circuit-breaker, timeout patterns
- │ ├── task_queue.py # Background task queue (Redis + arq)
- │ ├── extension_registry.py # Plugin registration system
- │ ├── arch_registry.py # Multi-arch mapping (x86/ARM/MIPS/RISC-V/PPC)
- │ ├── result_cache.py # SHA256-based tool result caching
- │ ├── analysis_cache.py # Multi-level decompilation cache (Redis + SQLite)
- │ ├── result.py # ToolSuccess / ToolError Pydantic models
- │ ├── loader.py # Dynamic tool module loader
- │ ├── plugin.py # Plugin base class
- │ ├── extension.py # Extension base class
- │ ├── container.py # Container/sandbox execution
- │ ├── audit.py # Audit logging
- │ ├── binary_cache.py # Binary file caching
- │ ├── json_utils.py # orjson-backed JSON (3-5x faster)
- │ ├── logging_config.py # Loguru logging configuration
- │ ├── report_generator.py # Report rendering (Markdown, PDF)
- │ ├── resource_manager.py # MCP resource lifecycle
- │ └── sast/ # Source code scanners
- │ ├── python_ast_scanner.py # Python AST vulnerability scanner
- │ ├── regex_scanner.py # C/C++ regex vulnerability scanner
- │ ├── rule_manager.py # SAST rule loader
- │ └── default_rules.yaml # Default scanning rules
- │
- ├── tools/ # MCP tool implementations (194 tools)
- │ ├── analysis/ # Static analysis (24 tools)
- │ │ ├── static_analysis.py # file, strings, binwalk
- │ │ ├── lief_tools.py # LIEF binary parser
- │ │ ├── capa_tools.py # CAPA capability detection
- │ │ ├── die_tools.py # Detect It Easy packer detection
- │ │ ├── diff_tools.py # Binary diffing
- │ │ ├── emulation_tools.py # ESIL emulation
- │ │ ├── fuzz_tools.py # Fuzzing harness generator
- │ │ ├── fuzzing_campaign.py # Full fuzzing campaign runner
- │ │ ├── symbolic_analysis.py # angr symbolic execution
- │ │ ├── signature_tools.py # Library signature matching
- │ │ ├── source_auditor.py # SAST (Python + C/C++)
- │ │ ├── crash_triage.py # GDB crash triage
- │ │ ├── taint_analysis.py # Source→sink taint tracing
- │ │ ├── advanced_yara.py # Advanced YARA generation
- │ │ ├── patch_vuln_inference.py # Patch vulnerability inference
- │ │ └── cache_tools.py # Analysis cache management
- │ │
- │ ├── radare2/ # Disassembly & decompilation (30 tools)
- │ │ ├── radare2_mcp_tools.py # Core Radare2 tool set
- │ │ ├── r2ghidra_tools.py # r2ghidra decompiler (cached)
- │ │ ├── r2_analysis.py # Deep function analysis
- │ │ ├── r2_db.py # SQLite annotation + cache DB
- │ │ ├── r2_esil_simulator.py # Multi-arch ESIL simulator
- │ │ └── r2_session.py # Stateful analysis sessions
- │ │
- │ ├── malware/ # Threat detection (9 tools)
- │ │ ├── dormant_detector.py # Backdoor/logic bomb detection
- │ │ ├── ioc_tools.py # IOC extraction
- │ │ ├── yara_tools.py # YARA scanning
- │ │ ├── adaptive_vaccine.py # YARA rule + patch generation
- │ │ ├── vulnerability_hunter.py # Dangerous API detection
- │ │ ├── autonomous_hunter.py # Autonomous vuln hunting pipeline
- │ │ ├── heap_exploit.py # Heap exploitation analysis
- │ │ ├── poc_generator.py # PoC exploit generation
- │ │ └── rop_builder.py # ROP chain construction
- │ │
- │ ├── forensics/ # Digital forensics (22 tools)
- │ │ ├── memory.py # Volatility3 memory forensics
- │ │ ├── network.py # Scapy PCAP analysis
- │ │ ├── disk.py # Sleuth Kit disk forensics
- │ │ └── artifact.py # Browser/registry/event log analysis
- │ │
- │ ├── report/ # Report generation (14 tools)
- │ │ ├── report_mcp_tools.py # MCP-registered report tools
- │ │ ├── report_tools.py # Report rendering logic
- │ │ ├── session.py # Session state management
- │ │ ├── converter.py # Format conversion (Markdown → PDF/HTML)
- │ │ ├── email.py # SMTP report delivery
- │ │ ├── sigma_generator.py # SIGMA rule generation
- │ │ └── vex_generator.py # VEX report generation
- │ │
- │ └── common/ # Shared utilities (20 tools)
- │ ├── file_operations.py # File ops, workspace management
- │ ├── server_tools.py # Server health, tool metrics
- │ ├── memory_tools.py # AI memory management (11 tools)
- │ ├── patch_explainer.py # Binary patch explanation
- │ └── assembler.py # Keystone assembler
- │
- ├── prompts/ # AI reasoning prompts (22 modes)
- │ ├── malware.py # 9 malware analysis prompts
- │ ├── security.py # 6 security research prompts
- │ ├── cve_research.py # 5 CVE/exploit research prompts
- │ ├── game.py # Game client analysis prompt
- │ ├── report.py # Report generation prompt
- │ ├── server_health.py # Server inspection prompts
- │ └── common.py # Shared constants (DOCKER_PATH_RULE, LANGUAGE_RULE)
- │
- ├── dashboard/ # Web dashboard (FastAPI + HTMX)
- │ ├── templates/ # Jinja2 templates with HTMX fragments
- │ └── static/ # htmx.min.js (local, CSP-compliant)
- │
- ├── web/ # HTTP transport layer
- │ ├── auth.py # API key authentication middleware
- │ ├── middleware.py # Security headers, loopback restriction
- │ └── endpoints.py # /health, file upload, dashboard routes
- │
- ├── resources.py # 11 MCP resources (static + dynamic per-binary)
- └── server.py # FastMCP server entry point
- ```
- **Other directories:**
- ```
- tests/
- ├── unit/ # 1,957 unit tests
- ├── integration/ # Docker-based integration tests
- ├── fixtures/ # Test binaries, YARA rules, sample data
- └── conftest.py # Shared pytest fixtures
- scripts/
- ├── smoke_test.py # Multi-layer in-container smoke test
- ├── check_release_metadata.py # Version consistency validation
- ├── fetch_test_binaries.py # Download test fixtures
- ├── run-docker.sh # Auto-detect architecture and start
- └── ... # Benchmarks, analysis scripts
- docs/
- ├── getting-started/ # Installation guide
- ├── development/ # Architecture, contributing, testing guides
- ├── api/ # Tool and module reference
- └── user-guide/ # Analysis workflows
- ```
- ---
- ## Error Handling
- All custom exceptions inherit from `ReversecoreError` and carry structured error codes:
- | Exception | Code | Type | When |
- |---|---|---|---|
- | `ReversecoreError` | `RCMCP-E000` | `UNKNOWN_ERROR` | Base class for all errors |
- | `ValidationError` | `RCMCP-E001` | `VALIDATION_ERROR` | Invalid input, bad parameters |
- | `ExecutionTimeoutError` | `RCMCP-E002` | `TIMEOUT_ERROR` | Tool exceeded timeout |
- | `ToolNotFoundError` | `RCMCP-E003` | `TOOL_ERROR` | Required CLI tool not installed |
- | `OutputLimitExceededError` | `RCMCP-E004` | `OUTPUT_ERROR` | Output exceeded max size |
- | `ToolExecutionError` | `RCMCP-E005` | `EXECUTION_ERROR` | Subprocess returned non-zero |
- | `BinaryAnalysisError` | `RCMCP-E100` | `BINARY_ANALYSIS_ERROR` | General binary analysis failure |
- | `DecompilationError` | `RCMCP-E101` | `DECOMPILATION_ERROR` | r2ghidra decompilation failed |
- | `DisassemblyError` | `RCMCP-E102` | `DISASSEMBLY_ERROR` | Radare2 disassembly failed |
- | `StructureRecoveryError` | `RCMCP-E103` | `STRUCTURE_RECOVERY_ERROR` | C struct recovery failed |
- | `SignatureGenerationError` | `RCMCP-E104` | `SIGNATURE_GENERATION_ERROR` | YARA/signature generation failed |
- | `EmulationError` | `RCMCP-E105` | `EMULATION_ERROR` | ESIL emulation failed |
- | `ToolTimeoutError` | `RCMCP-E200` | `TOOL_TIMEOUT_ERROR` | External tool timed out |
- | `GhidraConnectionError` | `RCMCP-E201` | `GHIDRA_CONNECTION_ERROR` | r2ghidra connection issue |
- | `Radare2Error` | `RCMCP-E202` | `RADARE2_ERROR` | Radare2 command failed |
- | `WorkspaceError` | `RCMCP-E300` | `WORKSPACE_ERROR` | Workspace file access error |
- | `SecurityViolationError` | `RCMCP-E301` | `SECURITY_VIOLATION` | Security policy violation |
- | `PathTraversalError` | `RCMCP-E302` | `PATH_TRAVERSAL` | Path traversal attempt detected |
- AI clients can use the `error_code` field to programmatically handle failures and decide whether to retry, try an alternative tool, or report the error to the user.
- ---
- ## Adding New Tools
- Follow this pattern to add a new MCP tool:
- ```python
- # reversecore_mcp/tools/analysis/my_tool.py
- from reversecore_mcp.core.decorators import log_execution
- from reversecore_mcp.core.result import ToolResult, success, failure
- from reversecore_mcp.core.security import validate_file_path
- @log_execution()
- async def my_analysis_tool(
- file_path: str,
- option: str | None = None,
- ) -> ToolResult:
- """Analyze a binary for X.
- Args:
- file_path: Path to the binary file (relative to workspace).
- option: Optional analysis option.
- Returns:
- ToolResult with status='success' and structured content.
- """
- try:
- safe_path = validate_file_path(file_path)
- result = await perform_analysis(safe_path)
- return success({"result": result})
- except Exception as e:
- return failure(
- error_code="RCMCP-E100",
- message=str(e),
- hint="Check that the file exists and is a valid binary.",
- )
- ```
- Then register it in the appropriate plugin's `__init__.py` and add tests in `tests/unit/`.
- ---
- ## Contributing
- 1. Fork the repository
- 2. Create a feature branch: `git checkout -b feat/my-feature`
- 3. Write tests alongside your code — coverage must not drop below 80%
- 4. Ensure all gates pass: `pytest`, `ruff check`, `mypy`, `bandit`
- 5. Open a pull request with a clear description
- Please read the [Contributing Guide](docs/development/contributing.md) for code standards, docstring conventions (Google-style), and the pull request checklist.
- ---
- ## Documentation
- | Document | Description |
- |---|---|
- | [Installation Guide](docs/getting-started/installation.md) | Detailed setup for all environments |
- | [Architecture Guide](docs/development/architecture.md) | System design & component details |
- | [Contributing Guide](docs/development/contributing.md) | Code standards, docstrings, PR workflow |
- | [Testing Guide](docs/development/testing.md) | Test patterns, fixtures, and coverage |
- | [API Reference](docs/api/) | Tool and module reference |
- | [User Guide](docs/user-guide/) | Analysis workflows |
- ---
- ## Usage Examples
- ### Example 1: Basic Malware Triage
- ```
- User: "Analyze this suspicious file sample.exe"
- AI calls:
- 1. run_file("sample.exe") → PE32 executable, x86, MSVC
- 2. detect_packer("sample.exe") → Not packed
- 3. extract_iocs("sample.exe") → 3 IPs, 2 URLs, 1 mutex
- 4. run_capa("sample.exe") → "creates persistence", "encrypts data"
- 5. dormant_detector("sample.exe") → 2 orphan functions with network calls
- 6. generate_yara_rule("sample.exe") → Detection rule generated
- AI response: "This PE32 binary shows ransomware-like behavior. CAPA detected
- encryption and persistence capabilities. I found 2 hidden network functions
- that may serve as a backup C2 channel. Here's a YARA rule for detection..."
- ```
- ### Example 2: Vulnerability Research with Taint Analysis
- ```
- User: "Find exploitable bugs in this network daemon"
- AI activates: taint_analysis_mode
- AI calls:
- 1. taint_trace("daemon", verify_with_angr=True)
- → Found 3 source→sink paths:
- recv() → strcpy() [CWE-120, CONFIRMED by angr]
- read() → sprintf() [CWE-134, LIKELY]
- getenv() → system() [CWE-78, POSSIBLE]
- 2. vulnerability_hunter("daemon")
- → 12 dangerous API calls, 4 exploitable patterns
- 3. generate_poc_exploit(target="daemon", vuln_type="bof", offset=128)
- → Python exploit script generated
- AI response: "I found a confirmed stack buffer overflow where recv() data
- flows directly into strcpy() at 0x40123C. angr proved the path is reachable.
- Here's a working PoC..."
- ```
- ### Example 3: Digital Forensics Investigation
- ```
- User: "Analyze this memory dump from a compromised server"
- AI calls:
- 1. memory_list_processes("memdump.raw")
- → 47 processes, 2 with suspicious names
- 2. memory_detect_injections("memdump.raw")
- → Code injection detected in PID 1842 (svchost.exe)
- 3. memory_extract_strings("memdump.raw", pid=1842)
- → C2 domain strings extracted
- 4. artifact_correlate_ioc(artifacts={"domains": ["evil-c2.com"]})
- → Matches known APT group IOCs
- 5. create_analysis_report(template_type="full_analysis")
- → PDF report with timeline and MITRE ATT&CK mapping
- ```
- ### Example 4: Patch Diffing for 1-day Research
- ```
- User: "Compare the patched and unpatched versions to find what was fixed"
- AI activates: patch_diff_auto_mode
- AI calls:
- 1. diff_binaries("libfoo-1.0.so", "libfoo-1.1.so")
- → 3 functions changed, 1 new function
- 2. patch_diff_1day("libfoo-1.0.so", "libfoo-1.1.so")
- → Automated analysis: bounds check added at parse_header()
- 3. r2_decompile("libfoo-1.0.so", "parse_header")
- → Decompiled vulnerable version (no bounds check)
- 4. r2_decompile("libfoo-1.1.so", "parse_header")
- → Decompiled patched version (memcpy size limited)
- AI response: "The patch adds a bounds check in parse_header() at 0x12340.
- The old version copies user-controlled length bytes via memcpy without
- validation, creating a heap buffer overflow (CWE-122)."
- ```
- ---
- ## Multi-Architecture Support
- The `arch_registry.py` module maps architecture names to Radare2 configuration parameters, enabling tools to work across different CPU architectures without manual configuration:
- | Architecture | Key | r2 Arch | Bit Widths | PC Register | SP Register |
- |---|---|---|---|---|---|
- | Intel 32-bit | `x86` | `x86` | 32 | `eip` | `esp` |
- | Intel/AMD 64-bit | `x86_64` | `x86` | 64 | `rip` | `rsp` |
- | ARM 32-bit / Thumb | `arm32` | `arm` | 16, 32 | `r15` | `r13` |
- | ARM 64-bit (AArch64) | `arm64` | `arm` | 64 | `pc` | `sp` |
- | MIPS | `mips` | `mips` | 32, 64 | `pc` | `sp` |
- | RISC-V | `riscv` | `riscv` | 32, 64 | `pc` | `sp` |
- | PowerPC | `ppc` | `ppc` | 32, 64 | `pc` | `r1` |
- **Alias resolution** is handled automatically:
- - `amd64` → `x86_64`
- - `aarch64` → `arm64`
- - `arm` with `bits=64` → `arm64`
- - `arm` with `bits=16` or `bits=32` → `arm32`
- Tools like `Radare2_esil_emulate`, `assemble_instructions`, and `r2_simulate_patch` use this registry to configure the analysis environment correctly for any target binary.
- ---
- ## Result Cache System
- Two caching layers minimize redundant computation:
- ### Tool Result Cache (`result_cache.py`)
- The `@cache_tool_result` decorator caches any tool's output based on a SHA256 hash of the binary file and the tool's keyword arguments:
- ```
- Cache key = SHA256( "<tool_name>::{sorted_json_kwargs}" )
- ```
- **Storage backend:** SQLite database via `r2_db.py`, accessible through `get_cached_result()` and `set_cached_result()` tools.
- **Metrics:** Cache hits and misses are tracked via `metrics_collector.record_cache_hit()` and `record_cache_miss()`, visible through the `get_tool_metrics` tool.
- ### Analysis Cache (`analysis_cache.py`)
- A multi-level cache specifically for decompilation results (which are expensive to compute):
- | Level | Backend | Key Format | TTL | Purpose |
- |---|---|---|---|---|
- | L1 | Redis | `ghidra:decompile:{file_hash}:{function_address}:{decompiler}` | 1 hour (3600s) | Fast, shared across sessions |
- | L2 | SQLite | Table `decompilation_cache` | Persistent | Survives Redis restarts |
- **Import/Export:** The `export_analysis_cache` and `import_analysis_cache` tools allow saving cache state to/from `rcpack` files for sharing between environments.
- ---
- ## AI Memory System
- The AI memory system (`memory_tools.py` + `core/memory.py`) provides persistent, queryable storage for analysis findings across sessions. This allows the AI to:
- - **Remember** what it previously found about a binary
- - **Cross-reference** findings between different samples
- - **Tag** and **search** sessions by topic, malware family, or technique
- ### How It Works
- ```
- create_memory_session("analysis of ransomware sample")
- │
- ├── store_analysis_finding("Found AES-256 encryption at 0x401000", tags=["crypto", "ransomware"])
- ├── store_analysis_finding("C2 beacon interval: 30 seconds", tags=["c2", "network"])
- └── tag_analysis_session(tags=["ransomware", "financial-sector"])
- # Later, in a different session:
- query_analysis_memories("ransomware encryption")
- → Returns previous findings about ransomware encryption patterns
- get_binary_analysis_context("sample.exe")
- → Returns all findings ever recorded for this binary
- ```
- **Storage:** Async SQLite database at the path configured by `MEMORY_DB_PATH` (default: `~/.reversecore_mcp/memory.db`).
- **Portability:** Use `export_memory_store` and `import_memory_store` to transfer the entire memory database between environments.
- ---
- ## Web Dashboard
- When running in HTTP mode (`MCP_TRANSPORT=http`), a web dashboard is available at `http://localhost:8000/dashboard`. It provides:
- - Binary upload with drag-and-drop
- - Real-time analysis status
- - Interactive function list and disassembly view
- - IOC extraction results
- - Server health monitoring
- **Tech stack:** FastAPI + Jinja2 templates + HTMX (loaded locally from `dashboard/static/`, no CDN dependency for CSP compliance).
- **Security features:**
- - CSRF tokens on all state-changing forms
- - Jinja2 auto-escaping enabled
- - All user input sanitized via `html.escape()` before display
- - Path traversal protection via `validate_file_path()`
- ---
- ## Deployment
- ### Production Checklist
- Before deploying to production:
- | Item | How |
- |---|---|
- | Set API key | `MCP_API_KEY=<strong-random-key>` |
- | Use non-root user | Built-in: container runs as `appuser` (UID 1000) |
- | Set resource limits | Default: 2 CPU / 4 GB RAM in `docker-compose.yml` |
- | Enable structured logging | `LOG_FORMAT=json` for log aggregation |
- | Configure Redis | `REDIS_URL=redis://<host>:6379/0` for task queue and caching |
- | Set workspace path | `REVERSECORE_WORKSPACE=/path/to/isolated/directory` |
- | Review rate limits | `REVERSECORE_RATE_LIMIT=60` (requests/min, adjust as needed) |
- | Enable sandbox | `REVERSECORE_SANDBOX_ENABLED=true` for dynamic analysis isolation |
- ### Health Checks
- The server provides HTTP health check endpoints for orchestration:
- ```bash
- # Liveness (always 200 if process is running)
- curl http://localhost:8000/health/live
- # Readiness (checks tool availability)
- curl http://localhost:8000/health/ready
- # Full health (requires API key if configured)
- curl -H "X-API-Key: <key>" http://localhost:8000/health
- ```
- These endpoints are exempted from API key authentication so load balancers and container orchestrators can probe them.
- ### Container Healthcheck
- The Docker image includes a built-in `HEALTHCHECK` instruction that verifies TCP connectivity to port 8000 every 30 seconds. Docker and Kubernetes will automatically restart unhealthy containers.
- ---
- ## Troubleshooting
- ### Common Issues
- <details>
- <summary><b>Tool returns RCMCP-E003: Tool not found</b></summary>
- The required CLI tool is not installed in the environment.
- **Solution:** If using Docker, verify the tool is in the base image:
- ```bash
- docker exec reversecore-mcp-arm64 which r2 yara binwalk tsk_recover gdb
- ```
- If using local Python installation, install the missing tool:
- ```bash
- # macOS
- brew install radare2 yara binwalk sleuthkit
- # Ubuntu/Debian
- apt install radare2 yara binwalk sleuthkit
- ```
- </details>
- <details>
- <summary><b>Timeout error (RCMCP-E002 / RCMCP-E200)</b></summary>
- Analysis exceeded the configured timeout.
- **Solution:** Increase the timeout:
- ```bash
- export REVERSECORE_DEFAULT_TOOL_TIMEOUT=300 # 5 minutes
- ```
- For large binaries (>100 MB), consider using quick-scan variants:
- - `run_capa_quick` instead of `run_capa`
- - `detect_packer` instead of `detect_packer_deep`
- </details>
- <details>
- <summary><b>Path traversal error (RCMCP-E302)</b></summary>
- You referenced a file outside the workspace directory.
- **Solution:** Copy the file into the workspace first:
- ```
- copy_to_workspace("/path/to/file.exe")
- ```
- Or mount additional directories as read-only:
- ```bash
- export REVERSECORE_READ_DIRS=/opt/samples,/mnt/evidence
- ```
- </details>
- <details>
- <summary><b>Docker container won't start on Apple Silicon</b></summary>
- Make sure you're using the ARM64 profile:
- ```bash
- docker compose --profile arm64 up -d
- ```
- Or use the auto-detection script:
- ```bash
- ./scripts/run-docker.sh
- ```
- </details>
- <details>
- <summary><b>Redis connection refused</b></summary>
- The task queue requires a running Redis instance.
- **Solution:** Start Redis alongside the main service:
- ```bash
- docker compose --profile arm64 up -d # Starts both reversecore and redis
- ```
- Or disable Redis-dependent features by not setting `REDIS_URL`.
- </details>
- <details>
- <summary><b>r2ghidra decompilation produces empty output</b></summary>
- This usually means the function wasn't analyzed first.
- **Solution:** Run analysis before decompilation:
- ```
- Radare2_analyze_binary("sample.exe")
- Radare2_decompile_function("sample.exe", "main")
- ```
- </details>
- ---
- ## FAQ
- <details>
- <summary><b>Does this replace Ghidra or IDA Pro?</b></summary>
- No. This project is a complement, not a replacement. It uses r2ghidra (the Ghidra decompiler engine embedded in Radare2) for decompilation. It does not provide a GUI, and it does not have the interactive analysis workflow of a full disassembler. Its purpose is to let AI assistants perform analysis tasks programmatically.
- </details>
- <details>
- <summary><b>Is a separate Ghidra or JDK installation needed?</b></summary>
- No. The r2ghidra plugin embeds the Ghidra decompiler engine directly inside Radare2. No JDK, no Ghidra installation, no Ghidra project files. Just `r2` with the `r2ghidra` plugin compiled in.
- </details>
- <details>
- <summary><b>What MCP clients are supported?</b></summary>
- Any client that implements the [Model Context Protocol](https://modelcontextprotocol.io/) specification. Tested with: Claude Desktop, Cursor, Windsurf, and Google Antigravity. The server supports both stdio and HTTP/SSE transports.
- </details>
- <details>
- <summary><b>Can I analyze Windows PE files on Linux/macOS?</b></summary>
- Yes. Static analysis (disassembly, decompilation, string extraction, IOC extraction, YARA scanning) works on any file format regardless of host OS. Dynamic analysis (emulation, fuzzing) may have limitations depending on the target architecture.
- </details>
- <details>
- <summary><b>How safe is it to analyze malware with this tool?</b></summary>
- The Docker container provides isolation: non-root user, no network by default in CI, resource limits. For live malware analysis, we recommend running in a dedicated VM or using the sandbox feature (`REVERSECORE_SANDBOX_ENABLED=true`). Static analysis tools (r2, YARA, strings) never execute the target binary.
- </details>
- <details>
- <summary><b>What's the maximum file size?</b></summary>
- Default limits:
- - Upload: 100 MB (`MAX_UPLOAD_SIZE`)
- - LIEF parsing: 1 GB (`REVERSECORE_LIEF_MAX_FILE_SIZE`)
- - Tool output: 10 MB (`REVERSECORE_MAX_OUTPUT_SIZE`)
- All limits are configurable via environment variables.
- </details>
- ---
- ## Acknowledgments
- This project is built on the work of many open-source projects:
- | Project | Role in Reversecore MCP |
- |---|---|
- | [Radare2](https://radare.org/) | Disassembly, emulation, binary analysis |
- | [r2ghidra](https://github.com/radareorg/r2ghidra) | Ghidra decompiler engine for Radare2 |
- | [FastMCP](https://github.com/jlowin/fastmcp) | MCP server framework |
- | [YARA](https://virustotal.github.io/yara/) | Pattern matching for malware detection |
- | [LIEF](https://lief-project.github.io/) | Binary format parsing (PE, ELF, Mach-O) |
- | [CAPA](https://github.com/mandiant/capa) | Mandiant FLARE capability detection |
- | [angr](https://angr.io/) | Symbolic execution engine |
- | [Capstone](https://www.capstone-engine.org/) | Disassembly framework |
- | [Keystone](https://www.keystone-engine.org/) | Assembly framework |
- | [pwntools](https://github.com/Gallopsled/pwntools) | Exploit development toolkit |
- | [ROPgadget](https://github.com/JonathanSalwan/ROPgadget) | ROP gadget finder |
- | [Volatility3](https://github.com/volatilityfoundation/volatility3) | Memory forensics framework |
- | [Scapy](https://scapy.net/) | Network packet analysis |
- | [Sleuth Kit](https://sleuthkit.org/) | Disk forensics toolkit |
- | [Binwalk](https://github.com/ReFirmLabs/binwalk) | Firmware analysis |
- | [Detect It Easy](https://github.com/horsicq/DIE-engine) | Packer/compiler detection |
- ---
- ## License
- MIT — see [LICENSE](LICENSE) for details.
- ---
- <div align="center">
- **[GitHub](https://github.com/sjkim1127/Reversecore_MCP)** · **[PyPI](https://pypi.org/project/reversecore-mcp/)** · **[FastMCP Docs](https://github.com/jlowin/fastmcp)** · **[MCP Spec](https://modelcontextprotocol.io/)** · **[Radare2](https://radare.org/)** · **[YARA](https://virustotal.github.io/yara/)**
- </div>
install.ps1 · Bundled script · 124 lines · 1 finding marked
- # ==============================================================================
- # Reversecore_MCP One-line Installer & Setup Wizard (Windows PowerShell)
- #
- # Usage:
- # irm https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.ps1 | iex
- Note: Runs a downloaded PowerShell script (iex / Invoke-Expression)
- Line 5 on GitHub
- # .\install.ps1 [options]
- # ==============================================================================
- [CmdletBinding()]
- param(
- [switch]$All,
- [string]$Clients,
- [string]$Mode = "auto",
- [switch]$Docker,
- [switch]$Uvx,
- [switch]$Pipx,
- [string]$Command,
- [string[]]$Args,
- [switch]$DryRun,
- [switch]$Remove,
- [switch]$List,
- [switch]$Tiered
- )
- $ErrorActionPreference = "Stop"
- function Find-Python {
- $candidates = @("python", "py -3.12", "py -3.11", "py -3.10", "py")
- foreach ($cmd in $candidates) {
- try {
- $parts = $cmd.Split(" ")
- $exe = $parts[0]
- $cmdArgs = @()
- if ($parts.Length -gt 1) {
- $cmdArgs = $parts[1..($parts.Length - 1)]
- }
- $testArgs = $cmdArgs + @("-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
- $ver = & $exe $testArgs 2>$null
- if ($ver -and [version]$ver -ge [version]"3.10") {
- return $cmd
- }
- } catch {}
- }
- return $null
- }
- # Pass-through arguments to python setup script
- $passArgs = @($args)
- if ($All) { $passArgs += "--all" }
- if ($Clients) { $passArgs += @("--clients", $Clients) }
- if ($Docker) { $passArgs += "--docker" }
- if ($Uvx) { $passArgs += "--uvx" }
- if ($Pipx) { $passArgs += "--pipx" }
- if ($Command) { $passArgs += @("--command", $Command) }
- if ($DryRun) { $passArgs += "--dry-run" }
- if ($Remove) { $passArgs += "--remove" }
- if ($List) { $passArgs += "--list" }
- if ($Tiered) { $passArgs += "--tiered" }
- # If inside local repository clone
- if (Test-Path "reversecore_mcp\setup.py") {
- if (Test-Path "venv\Scripts\python.exe") {
- & "venv\Scripts\python.exe" -m reversecore_mcp.setup @passArgs
- exit $LASTEXITCODE
- }
- $py = Find-Python
- if ($py) {
- $parts = $py.Split(" ")
- $exe = $parts[0]
- $cmdArgs = @()
- if ($parts.Length -gt 1) {
- $cmdArgs = $parts[1..($parts.Length - 1)]
- }
- & $exe ($cmdArgs + @("-m", "reversecore_mcp.setup") + $passArgs)
- exit $LASTEXITCODE
- }
- }
- # If reversecore-mcp is in PATH
- if (Get-Command "reversecore-mcp" -ErrorAction SilentlyContinue) {
- & reversecore-mcp setup @passArgs
- exit $LASTEXITCODE
- }
- # If uvx is available
- if (Get-Command "uvx" -ErrorAction SilentlyContinue) {
- Write-Host "🚀 Running Reversecore setup via uvx..." -ForegroundColor Cyan
- & uvx --from reversecore-mcp reversecore-setup @passArgs
- exit $LASTEXITCODE
- }
- # If pipx is available
- if (Get-Command "pipx" -ErrorAction SilentlyContinue) {
- Write-Host "🚀 Running Reversecore setup via pipx..." -ForegroundColor Cyan
- & pipx run reversecore-mcp setup @passArgs
- exit $LASTEXITCODE
- }
- # Fallback: install in isolated virtualenv
- $py = Find-Python
- if ($py) {
- $installDir = Join-Path $env:USERPROFILE ".reversecore-mcp"
- $venvDir = Join-Path $installDir "venv"
- $venvPython = Join-Path $venvDir "Scripts\python.exe"
- Write-Host "📦 Installing Reversecore_MCP into isolated environment: $venvDir" -ForegroundColor Cyan
- if (-not (Test-Path $venvDir)) {
- $parts = $py.Split(" ")
- $exe = $parts[0]
- $cmdArgs = @()
- if ($parts.Length -gt 1) {
- $cmdArgs = $parts[1..($parts.Length - 1)]
- }
- & $exe ($cmdArgs + @("-m", "venv", $venvDir))
- }
- Write-Host "⬇️ Fetching reversecore-mcp package..." -ForegroundColor Cyan
- & $venvPython -m pip install --upgrade --quiet pip reversecore-mcp
- & $venvPython -m reversecore_mcp.setup @passArgs
- exit $LASTEXITCODE
- }
- Write-Error "Python 3.10+ or uv / pipx is required to install Reversecore_MCP."
- exit 1
install.sh · Bundled script · 135 lines · 2 findings marked
- #!/usr/bin/env bash
- # ==============================================================================
- # Reversecore_MCP One-line Installer & Setup Wizard
- #
- # Usage:
- # curl -fsSL https://reversecore.ai/install.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 6 on GitHub
- # curl -fsSL https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.sh | bash
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 7 on GitHub
- # ./install.sh [options]
- #
- # Supported Options:
- # --all Configure all detected clients automatically
- # --clients Comma-separated client list (cursor, claude_code, windsurf, etc.)
- # --docker Use Docker container mode
- # --uvx Use uvx runner mode
- # --pipx Use pipx runner mode
- # --tiered Enable Tiered Tools / Agents Mode (15 tools, >90% lower LLM context tokens)
- # --dry-run Preview configuration changes without writing
- # --remove Unregister Reversecore_MCP from clients
- # --list List detected clients and exit
- # ==============================================================================
- set -euo pipefail
- # Print banner
- print_banner() {
- cat << 'EOF'
- ========================================================================
- ____ __ __ ____ ____
- / __ \___ _ _____ _____________ _________ ________ / |/ // ___// __ \
- / /_/ / _ \ | / / _ \/ ___/ ___/ _ \/ ___/ __ \/ ___/ _ \/ /|_/ / / / / /_/ /
- / _, _/ __/ |/ / __/ / (__ ) __/ /__/ /_/ / / / __/ / / / / /___/ ____/
- /_/ |_|\___/|___/\___/_/ /____/\___/\___/\____/_/ \___/_/ /_/ \____/_/
- Reversecore_MCP One-line Installer & Setup Wizard
- ========================================================================
- EOF
- }
- # Restore standard input from controlling terminal when script is piped (curl | bash)
- restore_tty() {
- if [ ! -t 0 ] && [ -e /dev/tty ]; then
- exec 0< /dev/tty
- fi
- }
- # Find suitable Python 3.10+ executable
- find_python() {
- local candidate
- for candidate in python3 python python3.12 python3.11 python3.10; do
- if command -v "$candidate" >/dev/null 2>&1; then
- if "$candidate" -c "import sys; exit(0 if sys.version_info >= (3, 10) else 1)" 2>/dev/null; then
- command -v "$candidate"
- return 0
- fi
- fi
- done
- return 1
- }
- main() {
- restore_tty
- # If running inside a local git clone with reversecore_mcp available
- if [ -f "reversecore_mcp/setup.py" ]; then
- if [ -x "venv/bin/python" ]; then
- exec venv/bin/python -m reversecore_mcp.setup "$@"
- elif [ -x ".venv/bin/python" ]; then
- exec .venv/bin/python -m reversecore_mcp.setup "$@"
- else
- local local_py
- if local_py="$(find_python)"; then
- exec "$local_py" -m reversecore_mcp.setup "$@"
- fi
- fi
- fi
- # If reversecore-mcp binary is already installed and in PATH
- if command -v reversecore-mcp >/dev/null 2>&1; then
- exec reversecore-mcp setup "$@"
- fi
- # If uvx is available
- if command -v uvx >/dev/null 2>&1; then
- echo "🚀 Running Reversecore setup via uvx..."
- exec uvx --from reversecore-mcp reversecore-setup "$@"
- fi
- # If pipx is available
- if command -v pipx >/dev/null 2>&1; then
- echo "🚀 Running Reversecore setup via pipx..."
- exec pipx run reversecore-mcp setup "$@"
- fi
- # Fallback: check for Python 3.10+ and install in an isolated user environment
- local py_bin
- if py_bin="$(find_python)"; then
- local install_dir="$HOME/.reversecore-mcp"
- local venv_dir="$install_dir/venv"
- echo "📦 Installing Reversecore_MCP into isolated environment: $venv_dir"
- mkdir -p "$install_dir"
- if [ ! -d "$venv_dir" ]; then
- "$py_bin" -m venv "$venv_dir"
- fi
- echo "⬇️ Fetching reversecore-mcp package..."
- "$venv_dir/bin/pip" install --upgrade --quiet pip reversecore-mcp
- # Try to symlink executable to ~/.local/bin if directory exists or is in PATH
- if [ -d "$HOME/.local/bin" ]; then
- ln -sf "$venv_dir/bin/reversecore-mcp" "$HOME/.local/bin/reversecore-mcp" || true
- ln -sf "$venv_dir/bin/reversecore-setup" "$HOME/.local/bin/reversecore-setup" || true
- fi
- exec "$venv_dir/bin/python" -m reversecore_mcp.setup "$@"
- fi
- # If Docker is available and user wants Docker mode
- for arg in "$@"; do
- if [ "$arg" = "--docker" ] && command -v docker >/dev/null 2>&1; then
- echo "🐳 Running setup via Docker container..."
- exec docker run --rm -it \
- -v "$HOME:$HOME" \
- -e "HOME=$HOME" \
- ghcr.io/sjkim1127/reversecore-mcp:latest \
- python -m reversecore_mcp.setup "$@"
- fi
- done
- print_banner
- echo "❌ Error: Python 3.10+ or uv / pipx is required to install Reversecore_MCP." >&2
- echo "Please install Python 3.10+ (https://www.python.org/) or uv (https://astral.sh/uv)." >&2
- exit 1
- }
- main "$@"
reversecore_mcp/prompts/malware.py · Bundled script · 1,219 lines · 1 finding marked
- """Prompts for malware analysis modes."""
- from reversecore_mcp.prompts.common import DOCKER_PATH_RULE, LANGUAGE_RULE
- def full_analysis_mode(filename: str = "target_binary") -> str:
- """Expert mode that analyzes a file completely from A to Z with maximum AI reasoning."""
- return f"""
- You are an Elite Reverse Engineering Expert with 20+ years of experience in:
- - Malware analysis and threat intelligence (APT, Ransomware, RAT, Rootkits)
- - Binary exploitation and vulnerability research (0-day hunting)
- - Anti-analysis bypass and advanced evasion techniques
- - Cryptographic analysis and protocol reverse engineering
- - Firmware and embedded systems security
- - Code deobfuscation and unpacking (Themida, VMProtect, custom packers)
- Your mission: Perform a COMPREHENSIVE security analysis of '{filename}'
- that leaves no stone unturned. You will identify ALL threats, understand
- their purpose, and generate actionable intelligence.
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- [CRITICAL: Evidence-Based Analysis Rule]
- ==========================================
- **Every finding MUST be labeled with an evidence level:**
- 🔍 [OBSERVED] - Directly observed through dynamic analysis, logs, or traces
- Example: "Procmon captured CreateMutexA('WNcry@2ol7') call"
- Confidence: 100%
- 🔎 [INFERRED] - Logically inferred from static analysis (high confidence)
- Example: "CryptEncrypt import suggests encryption capability"
- Confidence: 70-85%
- ❓ [POSSIBLE] - Possible based on patterns, requires verification
- Example: "SMB functions present, may attempt lateral movement"
- Confidence: 40-60%
- **NEVER state 'confirmed' or 'detected' for inferred/possible findings!**
- Use language like:
- - OBSERVED: "확인됨", "detected", "observed"
- - INFERRED: "추정됨", "likely", "suggests"
- - POSSIBLE: "가능성 있음", "may", "could"
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 1: INITIAL TRIAGE & THREAT CLASSIFICATION ██
- ═══════════════════════════════════════════════════════════════════════════
- [STEP 1.1] File Intelligence Gathering
- Build your initial mental model with these foundational tools:
- ```
- detect_packer("{filename}") # FIRST: Packer/Compiler/Protector detection
- run_file("{filename}") # File type, architecture, compiler
- parse_binary_with_lief("{filename}") # PE/ELF structure, sections, entropy
- run_strings("{filename}", min_length=5) # Extract all meaningful strings
- extract_iocs("{filename}") # IP, URL, Email, Bitcoin, Hashes
- ```
- **Why detect_packer First?**
- - If packed (UPX, Themida, VMProtect), skip deep analysis until unpacked
- - Compiler info helps understand the binary's origin
- - Protector detection guides anti-analysis strategy
- [REASONING CHECKPOINT 1 - THREAT HYPOTHESIS]
- Before proceeding, form initial hypotheses by answering:
- **File Characteristics:**
- Q1: What is the exact file format? (PE32/PE64/ELF/Mach-O/Script?)
- Q2: What compiler/language produced this? (MSVC/GCC/Go/Rust/Python?)
- Q3: Is it packed? (Section entropy > 7.0? Suspicious section names?)
- Q4: What's the apparent purpose? (Installer/DLL/Service/Standalone?)
- **Initial Threat Assessment:**
- Q5: Based on strings, what capabilities might this have?
- - Network? (socket, http, connect, send, recv)
- - File System? (CreateFile, DeleteFile, encrypt, ransom)
- - Persistence? (Registry, Service, Scheduled Task)
- - Credential Theft? (chrome, firefox, password, vault)
- - Evasion? (IsDebugger, Sleep, VM, sandbox)
- Q6: What malware family does this MOST LIKELY belong to?
- Form a hypothesis: "This appears to be [type] because [evidence]"
- **Threat Score (0-100):**
- Calculate preliminary threat score based on IOCs and strings found.
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 2: HIDDEN THREAT DISCOVERY ██
- ═══════════════════════════════════════════════════════════════════════════
- [STEP 2.1] Dormant Detector Analysis (Critical for APT/Backdoors)
- ```
- dormant_detector("{filename}")
- ```
- This is your PRIMARY tool for finding hidden threats. Analyze results carefully:
- **Orphan Functions (No Cross-References):**
- - Why would legitimate code have unreferenced functions?
- - Possible explanations: Dead code, conditional activation, backdoor
- - Size matters: Small orphans (<50 bytes) = likely dead code
- Large orphans (>100 bytes) = SUSPICIOUS, investigate!
- **Magic Value Triggers:**
- - Date/Time checks = Time bombs (activates on specific date)
- - Environment checks = Targeted attacks (specific hostname/user)
- - Network triggers = C2 activation conditions
- [STEP 2.2] Library Identification & Filtering
- ```
- match_libraries("{filename}")
- ```
- **Why This Matters:**
- - Standard library code is NOT interesting - filter it out!
- - Focus only on CUSTOM code that's unique to this binary
- - Low match percentage (< 50%) = Heavy custom code = More suspicious
- [REASONING CHECKPOINT 2 - THREAT CONFIRMATION]
- Update your hypothesis based on Phase 2 findings:
- **Hidden Threat Assessment:**
- Q7: Were orphan functions found? What do they appear to do?
- Q8: Were magic value triggers found? What conditions activate them?
- Q9: What percentage is standard library vs custom code?
- Q10: Does this change your initial threat hypothesis? How?
- **Confidence Level:**
- - HIGH: Clear malicious indicators found
- - MEDIUM: Suspicious but needs deeper analysis
- - LOW: Appears benign but continue analysis
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 3: DEEP BEHAVIORAL ANALYSIS ██
- ═══════════════════════════════════════════════════════════════════════════
- [STEP 3.1] Import Analysis - Capability Mapping
- ```
- run_radare2("{filename}", "iij")
- ```
- Map imports to MITRE ATT&CK techniques:
- | Import Pattern | Capability | MITRE Technique |
- |---------------|------------|-----------------|
- | CreateProcess, ShellExecute | Execution | T1059 |
- | RegSetValue, RegCreateKey | Persistence | T1547 |
- | socket, connect, send | C2 Communication | T1071 |
- | CryptEncrypt, CryptDecrypt | Data Encryption | T1486 |
- | CreateToolhelp32Snapshot | Process Discovery | T1057 |
- | VirtualAlloc, WriteProcessMemory | Process Injection | T1055 |
- | IsDebuggerPresent, CheckRemoteDebugger | Anti-Analysis | T1622 |
- [STEP 3.2] Cross-Reference Analysis for Suspicious APIs
- For each dangerous API found, trace backwards:
- ```
- analyze_xrefs("{filename}", "CreateProcessW")
- analyze_xrefs("{filename}", "VirtualAlloc")
- analyze_xrefs("{filename}", "InternetOpenW")
- ```
- **Think Like an Analyst:**
- - WHO calls this dangerous function?
- - WHAT data is passed to it?
- - WHEN is it called? (startup, trigger, always?)
- - HOW can this be weaponized?
- [STEP 3.3] Execution Path Tracing (Sink Analysis)
- ```
- trace_execution_path("{filename}", "system", max_depth=3)
- trace_execution_path("{filename}", "connect", max_depth=3)
- trace_execution_path("{filename}", "CryptEncrypt", max_depth=3)
- ```
- **Key Question:** Can untrusted input reach these dangerous sinks?
- - If YES → Potential vulnerability or intentional malicious path
- - If NO → Function may be used legitimately
- [REASONING CHECKPOINT 3 - BEHAVIORAL PROFILE]
- Build a complete behavioral profile:
- **Capabilities Confirmed:**
- Q11: What execution capabilities does this have?
- Q12: What persistence mechanisms are implemented?
- Q13: What data exfiltration methods exist?
- Q14: What evasion techniques are present?
- **Kill Chain Position:**
- Where does this fit in the cyber kill chain?
- [ ] Reconnaissance → [ ] Weaponization → [ ] Delivery →
- [ ] Exploitation → [ ] Installation → [ ] C2 → [ ] Actions
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 4: CODE-LEVEL DEEP DIVE ██
- ═══════════════════════════════════════════════════════════════════════════
- [STEP 4.1] Decompilation of Critical Functions
- For each suspicious function identified in Phases 2-3:
- ```
- r2_decompile("{filename}", "<suspicious_function_address>")
- ```
- If the code is obfuscated or complex:
- ```
- r2_decompile("{filename}", "<address>")
- ```
- **Code Analysis Framework:**
- When reading decompiled code, look for:
- 1. **String Decryption Routines:**
- - XOR loops, Base64, custom encoding
- - Key material (hardcoded or derived)
- 2. **Network Communication:**
- - C2 server addresses (IP, domain)
- - Protocol structure (HTTP, custom binary)
- - Encryption/authentication
- 3. **Anti-Analysis Tricks:**
- - Timing checks (GetTickCount differences)
- - Environment detection (VM, sandbox, debugger)
- - Self-modification (unpacking, decryption)
- 4. **Payload Delivery:**
- - Download and execute patterns
- - Process injection techniques
- - Fileless execution methods
- [STEP 4.2] Structure Recovery
- For data-heavy malware (credential stealers, etc.):
- ```
- r2_recover_structures("{filename}", "<data_handling_function>")
- ```
- **Look For:**
- - Credential structures (username, password, url)
- - Configuration structures (C2 list, encryption keys)
- - Exfiltration buffers
- [STEP 4.3] Emulation for Dynamic Behavior (If Needed)
- If code appears to unpack or decrypt at runtime:
- ```
- emulate_machine_code("{filename}", "<unpacking_function>", max_steps=1000)
- ```
- **Caution:** Only emulate small, contained routines.
- [REASONING CHECKPOINT 4 - INTENT DETERMINATION]
- Determine the TRUE PURPOSE of this binary:
- Q15: What is the PRIMARY malicious function?
- Q16: What is the SECONDARY function (if any)?
- Q17: Is this a:
- [ ] Dropper/Downloader → Delivers next stage
- [ ] RAT/Backdoor → Persistent access
- [ ] Stealer → Data theft
- [ ] Ransomware → Encryption/extortion
- [ ] Wiper → Destruction
- [ ] Loader → Executes in-memory payloads
- [ ] Rootkit → Stealth/persistence
- [ ] Cryptominer → Resource theft
- Q18: What's the sophistication level? (1-10)
- 1-3: Script kiddie / commodity malware
- 4-6: Professional cybercrime
- 7-9: Advanced threat actor / APT
- 10: Nation-state level
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 5: DEFENSE ARTIFACT GENERATION ██
- ═══════════════════════════════════════════════════════════════════════════
- [STEP 5.1] Enhanced YARA Rule Generation (Low False Positive)
- **IMPORTANT: Use enhanced YARA generator with structural conditions!**
- Simple string-only rules have HIGH false positive rates.
- Use `generate_enhanced_yara_rule` with structural conditions:
- ```python
- generate_enhanced_yara_rule(
- "{filename}",
- rule_name="Sample_Detection",
- strings=["unique_string1", "unique_string2", "unique_string3"],
- imports=["CryptEncrypt", "CreateServiceA"], # Optional but reduces FP
- file_type="PE",
- min_filesize=100000, # Minimum file size
- max_filesize=5000000, # Maximum file size
- section_names=[".rsrc"], # Required section names (optional)
- )
- ```
- **Good Enhanced YARA Signatures Include:**
- - Unique strings (C2 domains, mutex names, registry keys)
- - Structural conditions (PE header, file size range)
- - Import table checks (at least 1-2 dangerous APIs)
- - Minimum string match threshold (default: 2/3 of strings)
- [STEP 5.2] MITRE ATT&CK Mapping with Confidence Levels
- **CRITICAL: Every MITRE technique MUST have a confidence level!**
- Use this format in your report:
- | Technique ID | Name | Tactic | Confidence | Evidence |
- |-------------|------|--------|------------|----------|
- | T1486 | Data Encrypted for Impact | Impact | ✅ CONFIRMED | CryptEncrypt + ransom note strings |
- | T1055 | Process Injection | Defense Evasion | 🟢 HIGH | VirtualAllocEx + WriteProcessMemory imports |
- | T1570 | Lateral Tool Transfer | Lateral Movement | 🟡 MEDIUM | SMB API imports (no observed network activity) |
- | T1021 | Remote Services | Lateral Movement | 🔴 LOW | Possible based on port 445 reference |
- **Confidence Levels:**
- - ✅ CONFIRMED: Multiple independent evidence sources
- - 🟢 HIGH: Strong single evidence (observed or high-confidence inferred)
- - 🟡 MEDIUM: Inferred from API/patterns (needs verification)
- - 🔴 LOW: Possible based on weak indicators
- [STEP 5.3] Vulnerability Hunter Report (Automated)
- For comprehensive defense artifacts:
- ```
- vulnerability_hunter("{filename}", mode="full")
- ```
- This generates:
- - Detection rules (YARA)
- - Behavioral indicators
- - Remediation recommendations
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 6: FINAL SYNTHESIS & INTELLIGENCE REPORT ██
- ═══════════════════════════════════════════════════════════════════════════
- Synthesize ALL findings into a comprehensive intelligence report:
- ```markdown
- # 🔬 Binary Analysis Intelligence Report
- ## Executive Summary
- | Attribute | Value |
- |-----------|-------|
- | **File** | {filename} |
- | **SHA256** | [hash] |
- | **Verdict** | MALICIOUS / SUSPICIOUS / CLEAN |
- | **Threat Type** | [Ransomware/RAT/Stealer/etc.] |
- | **Sophistication** | [1-10] |
- | **Confidence** | [HIGH/MEDIUM/LOW] |
- ## Threat Overview
- **One-Line Summary:** [What this malware does in plain language]
- **Detailed Description:**
- [2-3 paragraphs explaining the malware's purpose, behavior, and impact]
- ## Technical Analysis
- ### File Characteristics
- | Property | Value |
- |----------|-------|
- | Type | PE32/PE64/ELF |
- | Compiler | MSVC/GCC/etc |
- | Packed | Yes/No (packer name) |
- | Size | X bytes |
- | Entropy | X.XX |
- ### Capabilities (MITRE ATT&CK Mapping with Confidence)
- | Technique ID | Technique Name | Tactic | Confidence | Evidence |
- |-------------|----------------|--------|------------|----------|
- | T1486 | Data Encrypted for Impact | Impact | ✅ CONFIRMED | [specific finding + source] |
- | T1055 | Process Injection | Defense Evasion | 🟢 HIGH | [specific finding] |
- | ... | ... | ... | ... | ... |
- ### Indicators of Compromise (IOCs)
- **Network:**
- - C2: [IP/domain]
- - User-Agent: [string]
- - URI Pattern: [path]
- **Host:**
- - Mutex: [name]
- - Registry: [key]
- - Files: [paths]
- **Hashes:**
- - SHA256: [hash]
- - Imphash: [hash]
- - SSDEEP: [hash]
- ### Hidden Threats Discovered
- | Function | Address | Purpose | Trigger |
- |----------|---------|---------|---------|
- | [name] | 0x... | [purpose] | [condition] |
- ### Decompiled Code Highlights
- ```c
- // Key malicious function
- [relevant code snippet with comments]
- ```
- ## Detection & Response
- ### YARA Rules
- ```yara
- [generated YARA rule]
- ```
- ### Detection Opportunities
- 1. **Network:** [specific signatures]
- 2. **Endpoint:** [behavioral indicators]
- 3. **Memory:** [patterns to scan for]
- ### Remediation Steps
- 1. **Immediate:** [containment actions]
- 2. **Short-term:** [eradication steps]
- 3. **Long-term:** [prevention measures]
- ## Analyst Notes
- - **Confidence Assessment:** [Detailed breakdown: X observed, Y inferred, Z possible]
- - **Evidence Summary:**
- - 🔍 Observed findings: [count] (highest confidence)
- - 🔎 Inferred findings: [count] (medium-high confidence)
- - ❓ Possible findings: [count] (requires verification)
- - **Gaps in Analysis:** [what couldn't be determined and why]
- - **Recommended Next Steps:** [additional analysis or dynamic analysis needed]
- - **Recommended Next Steps:** [additional analysis needed]
- ## Appendix
- - Full IOC list
- - All function addresses analyzed
- - Raw tool outputs (summarized)
- ```
- ═══════════════════════════════════════════════════════════════════════════
- ██ EXECUTION INSTRUCTIONS ██
- ═══════════════════════════════════════════════════════════════════════════
- BEGIN ANALYSIS NOW.
- **Critical Guidelines:**
- 1. Execute Phase 1 tools first to build your initial hypothesis
- 2. At each REASONING CHECKPOINT, explicitly state your thinking
- 3. Update your hypothesis as new evidence emerges
- 4. Don't skip phases - each builds on the previous
- 5. Show confidence levels for each major conclusion
- 6. If you hit a dead end, explain why and adjust approach
- **Quality Standards:**
- - Every claim must have supporting evidence
- - Every tool call must have a clear purpose
- - Every finding must map to a threat or be explicitly ruled out
- - The final report must be actionable for defenders
- Remember: You are not just running tools - you are THINKING like an expert
- malware analyst. Each finding should trigger new questions and hypotheses.
- The goal is UNDERSTANDING, not just detection.
- START PHASE 1 NOW.
- """
- def malware_analysis_mode(filename: str = "target_binary") -> str:
- """Focused analysis on Malware behaviors (Ransomware, Stealer, Backdoor)."""
- return f"""
- You are a Malware Analyst.
- Analyze the file '{filename}' focusing on malicious behaviors and indicators of compromise (IOCs).
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- [CRITICAL: Evidence-Based Analysis]
- ==========================================
- **Every finding MUST be labeled with an evidence level:**
- 🔍 [OBSERVED] - Directly observed (sandbox, Procmon, API trace)
- Confidence: 100% - Use "detected", "confirmed", "확인됨"
- 🔎 [INFERRED] - Inferred from static analysis (imports, strings)
- Confidence: 70-85% - Use "likely", "suggests", "추정됨"
- ❓ [POSSIBLE] - Possible based on patterns (needs verification)
- Confidence: 40-60% - Use "may", "could", "가능성 있음"
- [Analysis SOP]
- 1. Behavioral Triage:
- - Check for Ransomware indicators (crypto constants, file enumeration) using `run_yara` and `run_strings`.
- - Check for Stealer behaviors (browser paths, credential vaults) using `run_strings`.
- - Check for Backdoor/C2 (socket APIs, connect, listen) using `run_radare2` imports.
- → Label each finding: [🔍 OBSERVED] or [🔎 INFERRED]
- 2. Evasion Detection:
- - Use `dormant_detector` to find anti-analysis tricks (IsDebuggerPresent, sleep loops, time checks).
- - Check for packing using `parse_binary_with_lief`.
- → Orphan functions = [❓ POSSIBLE] hidden behavior
- 3. Persistence Mechanism:
- - Look for Registry keys (Run, RunOnce), Service creation, or Scheduled Tasks in strings or imports.
- → API import only = [🔎 INFERRED], Registry log = [🔍 OBSERVED]
- 4. Payload Analysis:
- - Decompile suspicious functions using `r2_decompile` to understand the payload logic.
- 5. Reporting:
- - Map behaviors to MITRE ATT&CK framework with confidence levels:
- | Technique | Confidence | Evidence |
- |-----------|------------|----------|
- | T1486 | ✅ CONFIRMED | CryptEncrypt + ransom note |
- | T1055 | 🟢 HIGH | VirtualAllocEx import |
- - Extract all IOCs (C2, Hashes, Mutexes).
- - Generate enhanced YARA rule: `generate_enhanced_yara_rule()` with structural conditions.
- """
- def basic_analysis_mode(filename: str = "target_binary") -> str:
- """Rapid analysis mode that quickly identifies basic static analysis and threat elements."""
- return f"""
- You are a Reverse Engineering Security Analyst.
- Perform 'Rapid Static Analysis' on the file '{filename}' to identify initial threats.
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- [Analysis SOP (Standard Operating Procedure)]
- Never use time-consuming deep analysis tools (Ghidra, Decompile, Emulation).
- Use only the following lightweight tools to get results quickly:
- 0. Packer Detection (FIRST!):
- - `detect_packer("{filename}")`: Check for packer/compiler/protector.
- - If packed → Note packer name and consider unpacking before deep analysis.
- 1. Identification:
- - `run_file("{filename}")`: Identify the exact file type.
- - `parse_binary_with_lief("{filename}")`: Check binary structure, entropy, and section information to determine packing status.
- 2. Strings & IOCs Analysis:
- - `run_strings("{filename}", min_length=5)`: Extract meaningful strings.
- - Based on the results, run `extract_iocs` to identify C2 IPs, URLs, emails, Bitcoin addresses, etc.
- 3. API & Capabilities Summary:
- - `run_radare2("{filename}", "ii")`: Quickly list import functions to infer the file's main behavior (network connection, file manipulation, etc.).
- 4. Quick Triage Report:
- - Summarize the file's identity, major IOCs found, and suspicious API behaviors.
- - Estimate the probability of the file being malicious (High/Medium/Low).
- - Advise the next step:
- * General Malware -> `malware_analysis_mode`
- * Complex/Hidden Threats -> `full_analysis_mode` or `apt_hunting_mode`
- * Game/Firmware -> Specialized modes
- """
- def apt_hunting_mode(filename: str = "target_binary") -> str:
- """Advanced Persistent Threat (APT) detection using Dormant Detector and Smart Decompiler."""
- return f"""
- You are an APT Hunter - specialized in detecting sophisticated, state-sponsored malware.
- Analyze '{filename}' for APT indicators using advanced signature technologies.
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- [CRITICAL: Evidence-Based Analysis]
- ==========================================
- APT hunting requires RIGOROUS evidence standards. Never speculate without evidence.
- 🔍 [OBSERVED] - Dynamic analysis confirmed (sandbox, memory forensics)
- Example: "Network capture shows C2 beacon to 1.2.3.4:443"
- 🔎 [INFERRED] - High-confidence static analysis
- Example: "Custom XOR encryption routine at 0x401000"
- ❓ [POSSIBLE] - Pattern matching, needs verification
- Example: "Code similarity with APT29 tooling"
- **Attribution requires MULTIPLE [🔍 OBSERVED] + [🔎 INFERRED] findings!**
- [APT Hunting SOP]
- 1. Dormant Detector Analysis (Primary Detection):
- Use `dormant_detector("{filename}")` to find APT characteristics:
- - Orphan Functions: APTs often hide backdoors in unused code paths [❓ POSSIBLE]
- - Magic Value Triggers: Look for date/time bombs or environment checks [🔎 INFERRED]
- - Conditional Execution: APT malware activates only in specific conditions
- 2. Smart Decompiler Refinement:
- For each suspicious function from Dormant Detector:
- - Run `r2_decompile("{filename}", address)`
- - Analyze refined code for APT patterns
- 3. MITRE ATT&CK with Confidence Levels:
- | Technique ID | Name | Confidence | Evidence Source |
- |-------------|------|------------|------------------|
- | T1055 | Process Injection | 🟢 HIGH | [🔎 INFERRED] VirtualAllocEx+WriteProcessMemory |
- | T1071.001 | HTTPS C2 | ✅ CONFIRMED | [🔍 OBSERVED] PCAP + [🔎 INFERRED] imports |
- | T1070.006 | Timestomping | 🟡 MEDIUM | [🔎 INFERRED] SetFileTime import |
- 4. APT Attribution Standards:
- - NEVER attribute without multiple independent evidence sources
- - Use "Code similarities suggest" not "This is APT29"
- - List evidence explicitly for any attribution claim
- 5. Defense Generation:
- If APT confirmed:
- - Use `generate_enhanced_yara_rule()` with structural conditions
- - Document TTPs with evidence levels
- - Create IOC list with confidence ratings
- [Report Format]
- ## 🎯 APT Hunting Report
- ### Evidence Summary
- | Level | Count | Examples |
- |-------|-------|----------|
- | 🔍 OBSERVED | X | (list key findings) |
- | 🔎 INFERRED | Y | (list key findings) |
- | ❓ POSSIBLE | Z | (list hypotheses) |
- ### Dormant Detector Findings
- - Orphan Functions: [count] [❓ POSSIBLE hidden functionality]
- - Logic Bombs: [triggers found] [🔎 INFERRED/🔍 OBSERVED]
- - Emulation Results: [ESIL verification] [🔍 OBSERVED]
- ### APT Assessment
- - Sophistication Level: [1-10] (evidence-based)
- - Attribution: ["Possible APT29" or "Unknown - insufficient evidence"]
- - Confidence: [✅ CONFIRMED / 🟢 HIGH / 🟡 MEDIUM / 🔴 LOW]
- - Key Evidence: [list of evidence supporting attribution]
- Begin APT analysis now.
- """
- def malware_defense_mode(filename: str = "target_binary") -> str:
- """Automated 3-phase threat detection and defense generation (DISCOVER → UNDERSTAND → NEUTRALIZE)."""
- return f"""
- You are a Malware Defense Specialist - an elite automated threat hunter.
- Execute a complete defense automation workflow on '{filename}' using the Malware Defense System.
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- [Malware Defense SOP - 3 Phase Pipeline]
- OPTION 1: Full Automation (Recommended)
- ----------------------------------------
- Use `vulnerability_hunter("{filename}", mode="full")` for complete automation:
- - Phase 1 (DISCOVER): Dormant Detector finds hidden threats
- - Phase 2 (UNDERSTAND): Smart Decompiler analyzes intent
- - Phase 3 (NEUTRALIZE): Adaptive Vaccine generates defenses
- This single command will:
- 1. Scan for orphan functions and logic bombs
- 2. Analyze suspicious code with AI-powered decompilation
- 3. Generate YARA rules and provide actionable recommendations
- 4. Return a comprehensive threat report with confidence scores
- OPTION 2: Step-by-Step (For Complex Analysis)
- ----------------------------------------------
- If you need granular control, execute phases manually:
- Phase 1 - DISCOVER:
- - `dormant_detector("{filename}")` → Find hidden threats
- - Review orphan_functions and suspicious_logic in results
- - Identify high-priority targets for Phase 2
- Phase 2 - UNDERSTAND:
- For each threat found in Phase 1:
- - `r2_decompile("{filename}", address)` → Get readable code
- - Analyze the refined_code to understand intent
- - Look for patterns: backdoor, time_bomb, data_exfiltration
- Phase 3 - NEUTRALIZE:
- For confirmed threats:
- - `adaptive_vaccine(threat_report, action="yara")` → Generate detection rule
- - Deploy YARA rules to endpoints
- - Follow recommendations from Malware Defense report
- [Output Requirements]
- Present results in this format:
- ## 🛡️ Malware Defense Analysis Report
- ### Phase 1: Discovery Results
- - Threats Discovered: [count]
- - Orphan Functions: [list]
- - Suspicious Logic: [list]
- ### Phase 2: Threat Understanding
- For each threat:
- - Function: [name @ address]
- - Intent: [backdoor/time_bomb/etc.]
- - Confidence: [0.0-1.0]
- - Key Code Snippet: [refined code]
- ### Phase 3: Defense Measures
- - YARA Rules Generated: [count]
- - Recommendations:
- * Immediate Actions
- * Investigation Steps
- * Remediation Plan
- ### Final Verdict
- - Overall Risk: CRITICAL/HIGH/MEDIUM/LOW
- - Recommended Actions: [priority list]
- Start Malware Defense System now.
- """
- def unpacking_mode(filename: str = "target_binary") -> str:
- """Guide for unpacking packed binaries (UPX, Themida, VMProtect, custom packers)."""
- return f"""
- You are an Expert Binary Unpacker with deep knowledge of packing techniques.
- Your mission: Analyze and unpack '{filename}' to reveal the original code.
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 1: PACKER IDENTIFICATION & ENTROPY QUANTIFICATION ██
- ═══════════════════════════════════════════════════════════════════════════
- 1. Automated Packer Signature Scan:
- ```
- detect_packer("{filename}")
- detect_packer_deep("{filename}")
- ```
- 2. Quantitative Section Entropy & Header Analysis:
- Run LIEF analysis to inspect sections:
- ```
- parse_binary_with_lief("{filename}")
- ```
- Identify packing indicator thresholds:
- - **High Entropy**: Check the `entropy` field of each section. Any section with `entropy > 7.0` indicates encryption or high compression (packed).
- - **Size Discrepancy**: Look at the section header sizes. If `virtual_size` is significantly larger than `raw_size` (e.g. `virtual_size > raw_size * 3` or `raw_size == 0` for a non-empty virtual section), it is a classic indicator of memory expansion for code unpacking.
- - **Suspicious Section Names**: Keep an eye out for standard packer section names (e.g., `.UPX0`, `.UPX1`, `.themida`, `.vmp0`, `PESpin`).
- 3. Heuristic Manual Fallback:
- If automated scanners return no packer detection but entropy is high, scan strings for packer/protector signatures:
- ```
- run_strings("{filename}", min_length=4)
- ```
- Filter output for keyword signatures: `UPX!`, `Themida`, `VMProtect`, `ASPack`, `PESpin`, `MEW`, `Upack`.
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 2: UNPACKING STRATEGY & STATIC DEOBFUSCATION ██
- ═══════════════════════════════════════════════════════════════════════════
- Choose your strategy based on packer characteristics:
- **UPX / Compressed (Simple)**
- - Try standard CLI unpacking: run `upx -d {filename}` (if upx CLI is installed).
- - If modified UPX headers block CLI decompression, locate the tail jump manually.
- **Virtualized/Virtual VMs (Themida/VMProtect)**
- - Static analysis is extremely difficult due to VM handlers.
- - Strategy: Focus on the boundaries of virtualized blocks. Decompile around entrypoints using `r2_decompile` to identify where arguments are pushed into VM routines, or analyze non-virtualized API helpers.
- **Custom Packer Stub Analysis**
- - Find the entrypoint stub:
- ```
- r2_decompile("{filename}", "entry0")
- ```
- Look for:
- - Large memory allocation APIs: `VirtualAlloc`, `VirtualProtect`.
- - Dynamic API loaders: `LoadLibraryA`, `GetProcAddress`.
- - Decryption loop structures: XOR/ADD loops over a byte array.
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 3: ORIGINAL ENTRY POINT (OEP) DISCOVERY ██
- ═══════════════════════════════════════════════════════════════════════════
- To locate the Original Entry Point (OEP) where control transitions from packer stub to original executable:
- 1. Disassemble around the packer entrypoint:
- ```
- Radare2_run_command("{filename}", "pdf @ entry0")
- ```
- 2. Identify OEP Transition Patterns:
- - **Pushad/Popad**: Packers often save state with `pushad` at the very beginning and restore it with `popad` right before jumping. Locate the `popad` and look for a following `jmp` or `call` instruction.
- - **Tail Jump**: A long jump instruction directing control to a different memory section (e.g. from `.UPX1` to `.UPX0` or an address far from the current offset).
- 3. Verify OEP Header Signatures:
- Decompile the target address to check if it matches compiler startup entry sequences:
- - MSVC: `call __security_init_cookie` or `jmp __tmainCRTStartup`
- - GCC: `xor ebp, ebp` followed by `pop rsi` or `mov rdx, rsp`
- ═══════════════════════════════════════════════════════════════════════════
- ██ REPORT FORMAT ██
- ═══════════════════════════════════════════════════════════════════════════
- ## 📦 Unpacking Analysis Report
- ### 1. Packer Profile
- - **Identified Packer**: [e.g., UPX / Themida / Custom / None]
- - **Section Entropy**: [List sections with entropy > 7.0]
- - **Header Anomalies**: [e.g., RawSize vs VirtualSize differences]
- ### 2. Stub Analysis
- - **Unpacking Logic**: [e.g., VirtualAlloc + XOR Decryption loop detected]
- - **Dynamic API Resolvers**: [e.g., LoadLibrary/GetProcAddress xrefs]
- ### 3. Entry Point Transitions
- - **Stub Entry Address**: `0x...`
- - **Tail Jump Address**: `0x...`
- - **Suspected OEP**: `0x...`
- ### 4. Next Steps
- - Recommended unpacking procedure and OEP patching instructions.
- """
- def c2_extraction_mode(filename: str = "target_binary") -> str:
- """Specialized analysis for extracting C2 (Command & Control) server information."""
- return f"""
- You are a C2 Infrastructure Analyst specializing in extracting command and control details.
- Your mission: Extract ALL C2 communication details from '{filename}' using data-flow tracing.
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 1: AUTOMATED IOC & ENCODED STRING SCANNING ██
- ═══════════════════════════════════════════════════════════════════════════
- 1. Extract Config & Direct Network Indicators:
- ```
- extract_iocs("{filename}")
- run_strings("{filename}", min_length=5)
- ```
- 2. Identify Encoded Config blocks:
- Look for base64 strings (`=`, `==` padding), high-entropy byte blobs (potential XOR encrypted data), or registry string targets.
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 2: API CROSS-REFERENCE & ARGUMENT TRACING (SOP) ██
- ═══════════════════════════════════════════════════════════════════════════
- Follow this systematic procedure to trace where C2 endpoints are stored in memory and loaded at runtime:
- 1. Find Network API Imports:
- ```
- Radare2_list_imports("{filename}")
- ```
- Look for: `connect`, `InternetConnectA`, `InternetConnectW`, `getaddrinfo`, `WSAConnect`, `InternetOpenUrlA`, `HttpOpenRequestA`.
- 2. Query Cross-References (Xrefs) to Connections:
- For every network API found, check who calls it. Example:
- ```
- Radare2_xrefs_to("{filename}", "connect")
- ```
- 3. Trace Register/Stack Loading Arguments:
- For each xref calling address, decompile or disassemble the calling context:
- ```
- r2_decompile("{filename}", "<calling_function_address_or_symbol>")
- ```
- If decompilation is partial, dump raw assembly surrounding the call site:
- ```
- Radare2_run_command("{filename}", "pd 20 @ <xref_call_offset-0x30>")
- ```
- - **Analyze Parameter Loading**:
- - In x64 calling conventions: Check registers `rcx` (1st arg), `rdx` (2nd arg - socket address struct containing IP/Port), `r8` (3rd arg), `r9` (4th arg).
- - In x86 calling conventions: Look at the `push` instructions preceding the `call` instruction.
- - **Identify Static Buffer Offsets**:
- Look for instructions like `lea rdx, [0x40a000]` or `mov dword [esp+4], 0x40a000`. This address `0x40a000` is the static C2 config buffer.
- 4. Extract Hardcoded Memory Buffers:
- Dump the strings or raw bytes directly from the static buffer address found in the previous step:
- ```
- Radare2_run_command("{filename}", "ps @ <buffer_address_e.g._0x40a000>")
- Radare2_run_command("{filename}", "px 128 @ <buffer_address_e.g._0x40a000>")
- ```
- If bytes look obfuscated, check for a preceding decryption loop (e.g. XOR with a key byte) in the calling function.
- ═══════════════════════════════════════════════════════════════════════════
- ██ PHASE 3: PROTOCOL & COMMAND STRUCTURE ANALYSIS ██
- ═══════════════════════════════════════════════════════════════════════════
- 1. Decompile Packet Formatting logic:
- Locate the functions sending data (`send`, `sendto`, `WSASend`, `InternetWriteFile`) and trace backwards to see how the buffer is populated:
- ```
- r2_decompile("{filename}", "<send_function_caller>")
- ```
- 2. Extract C2 Configuration Structs:
- If the binary parses structured config files (e.g., custom JSON or binary blobs), recover the structural layout:
- ```
- r2_recover_structures("{filename}", "<config_parsing_function>")
- ```
- 3. Document C2 Commands:
- Find the packet parsing command dispatcher (typically a `switch` table on a byte opcode). Document command IDs and their corresponding actions (e.g. `0x01` = spawn shell, `0x02` = download file).
- ═══════════════════════════════════════════════════════════════════════════
- ██ REPORT FORMAT ██
- ═══════════════════════════════════════════════════════════════════════════
- ## 🌐 C2 Extraction Report
- ### 1. C2 Servers Identified
- | Role | Endpoint (IP/Domain) | Port | Transport | Confidence |
- |------|----------------------|------|-----------|------------|
- | Primary | [value] | [port] | [e.g. TCP/HTTPS] | [HIGH/MED] |
- | Backup | [value] | [port] | [e.g. DNS] | [LOW] |
- ### 2. Argument Tracing Path
- - **Target Network API**: `[e.g., InternetConnectA]`
- - **Call Site Offset**: `0x...`
- - **Parameter Register/Stack Offset**: `[e.g. RDX / push 0x40a080]`
- - **Static Configuration Buffer**: `0x...`
- - **Obfuscation**: [e.g. Plaintext / XOR 0x5A Key / Base64]
- ### 3. C2 Protocol Specs
- - **User-Agent / Headers**: [Captured strings]
- - **Beacon Interval**: [Pattern / Hardcoded seconds]
- - **Opcode Command Table**:
- | Command Opcode | Handler Function | Action / Purpose |
- |----------------|------------------|------------------|
- | `0x...` | `sym.func_...` | [e.g., Execute shell command] |
- ### 4. Extracted IOCs for Network Defense
- ```
- # Domain Blocks
- [Domain List]
- # IP Blocks
- [IP List]
- ```
- Begin C2 extraction now.
- """
- def ransomware_triage_mode(filename: str = "target_binary") -> str:
- """Specialized analysis for ransomware - encryption, keys, recovery potential."""
- return f"""
- You are a Ransomware Response Specialist.
- Your mission: Analyze '{filename}' to assess encryption strength and recovery possibility.
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- ⚠️ CRITICAL: This is time-sensitive incident response!
- Focus on: Can victims recover their files WITHOUT paying?
- [PHASE 1: RANSOMWARE IDENTIFICATION]
- ===================================
- 1. Initial Triage:
- ```
- detect_packer("{filename}")
- run_file("{filename}")
- run_strings("{filename}", min_length=5)
- ```
- 2. Look for ransomware indicators:
- - Ransom note text ("Your files are encrypted", "Bitcoin", "decrypt")
- Note: Quoted as data in code: Has the wording of a ransom note
- Line 964 on GitHub
- - File extension patterns (.encrypted, .locked, .cry)
- - Known ransomware family signatures
- 3. Check YARA rules:
- ```
- run_yara("{filename}", "ransomware_rules.yar")
- ```
- [PHASE 2: ENCRYPTION ANALYSIS]
- =============================
- 1. Identify crypto imports:
- ```
- run_radare2("{filename}", "iij")
- ```
- Key APIs:
- | API | Implication |
- |-----|-------------|
- | CryptEncrypt | Windows Crypto API |
- | CryptGenKey | Key generation |
- | CryptAcquireContext | Crypto provider |
- | BCryptEncrypt | Modern crypto |
- | OpenSSL functions | OpenSSL crypto |
- 2. Look for crypto constants:
- - AES S-boxes
- - RSA public exponents (0x10001)
- - ChaCha20 constants
- - Salsa20 sigma
- 3. Analyze encryption routine:
- ```
- r2_decompile("{filename}", "<crypto_function>")
- ```
- [PHASE 3: KEY RECOVERY ASSESSMENT]
- =================================
- **Recovery Possibility Checklist:**
- ✅ POSSIBLE RECOVERY if:
- - [ ] Key derived from predictable seed (time, hostname)
- - [ ] Key hardcoded in binary
- - [ ] Weak RNG used (CRT rand(), GetTickCount)
- - [ ] Key stored locally before C2 contact
- - [ ] Implementation bugs (ECB mode, key reuse)
- ❌ UNLIKELY RECOVERY if:
- - [ ] RSA + AES hybrid with online key
- - [ ] Keys sent to C2 before encryption
- - [ ] Strong RNG (CryptGenRandom, /dev/urandom)
- - [ ] Proper implementation (CBC/GCM, unique IVs)
- 1. Check for key material:
- ```
- run_strings("{filename}", min_length=16)
- ```
- Look for: Base64 keys, hex strings (32/64 chars)
- 2. Analyze key generation:
- ```
- analyze_xrefs("{filename}", "CryptGenKey")
- r2_decompile("{filename}", "<keygen_function>")
- ```
- [PHASE 4: FILE TARGETING ANALYSIS]
- =================================
- 1. What files are targeted?
- - File extensions (docs, images, databases)
- - Directory exclusions (Windows, Program Files)
- 2. Encryption scope:
- - Full file encryption
- - Partial (first N bytes)
- - Alternating blocks
- [REPORT FORMAT]
- ===============
- ## 🔐 Ransomware Triage Report
- ### Executive Summary
- | Attribute | Value |
- |-----------|-------|
- | Family | [known family or "Unknown"] |
- | Recovery Possible | ✅ YES / ⚠️ MAYBE / ❌ NO |
- | Encryption | [algorithm] |
- | Key Type | [symmetric/asymmetric/hybrid] |
- ### Encryption Details
- - Algorithm: AES-256-CBC / RSA-2048 / ChaCha20 / etc.
- - Mode: ECB / CBC / GCM / CTR
- - Key Generation: [method]
- - IV/Nonce: [handling]
- ### Recovery Assessment
- **Confidence: [HIGH/MEDIUM/LOW]**
- Weaknesses Found:
- - [ ] [weakness 1 with evidence]
- - [ ] [weakness 2 with evidence]
- Recovery Steps (if possible):
- 1. [step 1]
- 2. [step 2]
- ### IOCs
- - Ransom note: [filename]
- - Extension: [.xxx]
- - Mutex: [name]
- - Registry: [keys]
- ### Recommendations
- 1. **Immediate**: [containment steps]
- 2. **Recovery**: [decryption options]
- 3. **Prevention**: [future protection]
- Begin ransomware triage now. TIME IS CRITICAL!
- """
- def code_similarity_mode(filename: str = "target_binary") -> str:
- """Binary similarity analysis for variant detection and clustering."""
- return f"""
- You are a Binary Similarity Analyst specializing in malware variant identification.
- Your mission: Analyze '{filename}' to identify code similarities with known families.
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- [PHASE 1: SIGNATURE GENERATION]
- ==============================
- 1. Generate unique signatures:
- ```
- generate_signature("{filename}", "entry0")
- parse_binary_with_lief("{filename}")
- ```
- 2. Extract identifying features:
- - Import hash (imphash)
- - Section hashes
- - Rich header hash
- - TLSH (Trend Micro Locality Sensitive Hash)
- 3. Get function-level hashes:
- ```
- run_radare2("{filename}", "afl")
- ```
- [PHASE 2: LIBRARY IDENTIFICATION]
- ================================
- 1. Match against known libraries:
- ```
- match_libraries("{filename}")
- ```
- 2. Calculate custom code percentage:
- - High custom % = likely unique malware
- - Low custom % = mostly standard code
- [PHASE 3: VARIANT COMPARISON]
- ============================
- If comparing with another sample:
- ```
- diff_binaries("{filename}", "<comparison_file>")
- analyze_variant_changes("{filename}", "<comparison_file>")
- ```
- Look for:
- - Function additions/removals
- - String changes (C2, versions)
- - Behavior modifications
- - Packer changes
- [PHASE 4: FAMILY ATTRIBUTION]
- ============================
- Based on collected signatures:
- 1. Compare with known families:
- | Feature | This Sample | Known Family |
- |---------|-------------|--------------|
- | Imphash | xxx | yyy |
- | Strings | [list] | [list] |
- | APIs | [list] | [list] |
- 2. Similarity scoring:
- - > 90%: Same family/variant
- - 70-90%: Related/modified
- - 50-70%: Possible connection
- - < 50%: Unlikely related
- [PHASE 5: CLUSTERING INDICATORS]
- ===============================
- Generate indicators for clustering:
- 1. Unique code patterns
- 2. String constants (mutex, paths)
- 3. Network patterns (domains, ports)
- 4. Behavioral signatures
- [REPORT FORMAT]
- ===============
- ## 🔍 Code Similarity Analysis Report
- ### Sample Identification
- | Attribute | Value |
- |-----------|-------|
- | SHA256 | [hash] |
- | Imphash | [hash] |
- | SSDEEP | [hash] |
- | File Type | [type] |
- ### Signature Summary
- - Custom Code: [X]%
- - Library Code: [Y]%
- - Unique Functions: [count]
- ### Family Attribution
- | Family | Similarity | Confidence | Evidence |
- |--------|------------|------------|----------|
- | [name] | XX% | HIGH/MED | [evidence] |
- ### Variant Analysis (if applicable)
- Changes from baseline:
- - Added: [functions/strings]
- - Removed: [functions/strings]
- - Modified: [behaviors]
- ### Clustering Indicators
- ```yara
- // YARA rule for clustering
- rule Similar_Family {{
- strings:
- $s1 = "[unique string]"
- condition:
- all of them
- }}
- ```
- ### Related Samples
- | Hash | Similarity | Notes |
- |------|------------|-------|
- | [hash] | XX% | [notes] |
- Begin similarity analysis now.
- """
reversecore_mcp/prompts/report.py · Bundled script · 113 lines · 1 finding marked
- """Prompts for report generation."""
- from reversecore_mcp.prompts.common import DOCKER_PATH_RULE, LANGUAGE_RULE
- def report_generation_mode(filename: str = "target_binary") -> str:
- """Generate professional malware analysis reports with accurate timestamps and IOC tracking."""
- return f"""
- You are a Security Report Specialist generating professional malware analysis documentation.
- Your task is to analyze '{filename}' and create a comprehensive, shareable report using the actual report session tools.
- {LANGUAGE_RULE}
- {DOCKER_PATH_RULE}
- ═══════════════════════════════════════════════════════════════════════════
- ██ REPORT GENERATION WORKFLOW ██
- ═══════════════════════════════════════════════════════════════════════════
- [STEP 1] Initialize Analysis Session
- First, get accurate system time and start a tracking session:
- ```
- get_system_time() # Get server timestamp (prevents date hallucination)
- start_report_session(
- binary_name="{filename}"
- )
- ```
- [STEP 2] Perform Analysis & Collect Evidence
- Conduct your analysis using appropriate tools (e.g., dormant_detector, run_strings, r2_decompile, etc.).
- [STEP 3] Collect IOCs During Analysis
- As you find indicators, add them to the session:
- ```
- add_ioc(ioc_type="hash", value="SHA256:abc123...", confidence="high")
- add_ioc(ioc_type="ip", value="192.168.1.100", confidence="high")
- add_ioc(ioc_type="domain", value="malware-c2.com", confidence="medium")
- add_ioc(ioc_type="url", value="http://evil.com/payload.exe", confidence="high")
- Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
- Line 40 on GitHub
- ```
- Valid ioc_types: hash, ip, domain, url, file, registry, mutex, email, other
- Valid confidences: low, medium, high
- [STEP 4] Document MITRE ATT&CK Techniques
- Map behaviors to MITRE framework:
- ```
- add_mitre_technique(technique_id="T1059.001", technique_name="PowerShell", tactic="Execution")
- add_mitre_technique(technique_id="T1547.001", technique_name="Registry Run Keys", tactic="Persistence")
- add_mitre_technique(technique_id="T1071.001", technique_name="Web Protocols", tactic="Command and Control")
- ```
- [STEP 5] Add Analysis Notes
- Document important findings:
- ```
- add_analysis_note(note="Found encrypted config at 0x401000", category="finding")
- add_analysis_note(note="Sample connects to C2 on port 443", category="behavior")
- add_analysis_note(note="Anti-VM checks detected", category="warning")
- ```
- Note categories: general, finding, warning, important, behavior
- **Tip: Label each note with evidence level!**
- ```
- add_analysis_note(note="[🔍 OBSERVED] Procmon captured registry write to Run key", category="finding")
- add_analysis_note(note="[🔎 INFERRED] CryptEncrypt import suggests encryption capability", category="finding")
- add_analysis_note(note="[❓ POSSIBLE] SMB functions may enable lateral movement", category="warning")
- ```
- [STEP 6] Set Severity and Tags
- ```
- set_severity("high")
- ```
- Valid severities: low, medium, high, critical
- [STEP 7] End Session and Generate Report
- ```
- end_report_session(summary="Brief summary of findings...")
- create_analysis_report(
- template_type="full_analysis", # full_analysis, quick_triage, ioc_summary, executive_brief
- classification="TLP:AMBER"
- )
- ```
- [CRITICAL: Evidence Summary in Report]
- The final report MUST include an evidence summary:
- ## Confidence Assessment
- | Evidence Level | Count | Key Findings |
- |----------------|-------|---------------|
- | 🔍 OBSERVED | X | (sandbox, logs, traces) |
- | 🔎 INFERRED | Y | (static analysis) |
- | ❓ POSSIBLE | Z | (needs verification) |
- **Overall Confidence**: [✅ CONFIRMED / 🟢 HIGH / 🟡 MEDIUM / 🔴 LOW]
- ═══════════════════════════════════════════════════════════════════════════
- ██ AVAILABLE REPORT TEMPLATES ██
- ═══════════════════════════════════════════════════════════════════════════
- | Template | Purpose |
- |----------|---------|
- | `full_analysis` | Complete technical report with all details |
- | `quick_triage` | Rapid assessment summary |
- | `ioc_summary` | IOC-focused export |
- | `executive_brief` | Non-technical summary for management |
- Begin report generation workflow now.
- """
reversecore_mcp/tools/analysis/vt_lookup.py · Bundled script · 312 lines · 1 finding marked
- """VirusTotal IOC reputation lookup tool.
- Queries the VirusTotal API v3 for IP addresses, domain names, URLs,
- and file hashes extracted from binary analysis (e.g. from extract_iocs).
- Requires: REVERSECORE_VT_API_KEY environment variable.
- Available tools (MCP-registered):
- vt_lookup — Bulk IOC reputation check via VirusTotal API v3
- """
- from __future__ import annotations
- import asyncio
- import ipaddress
- import re
- from typing import Any
- from reversecore_mcp.core.config import get_config
- from reversecore_mcp.core.decorators import log_execution
- from reversecore_mcp.core.error_handling import handle_tool_errors
- from reversecore_mcp.core.logging_config import get_logger
- from reversecore_mcp.core.metrics import track_metrics
- from reversecore_mcp.core.result import ToolResult, failure, success
- logger = get_logger(__name__)
- # ---------------------------------------------------------------------------
- # IOC type detection
- # ---------------------------------------------------------------------------
- _IPV4_RE = re.compile(r"^(\d{1,3}\.){3}\d{1,3}$")
- _HASH_RE = re.compile(r"^[0-9a-fA-F]{32}$|^[0-9a-fA-F]{40}$|^[0-9a-fA-F]{64}$")
- _URL_RE = re.compile(r"^https?://", re.IGNORECASE)
- _DOMAIN_RE = re.compile(
- r"^(?=.{1,253}\.?$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}\.?$"
- )
- def _classify_ioc(ioc: str) -> str:
- """Classify a single IOC string into: ip, domain, url, hash, or unknown."""
- ioc = ioc.strip()
- if _HASH_RE.match(ioc):
- return "hash"
- if _URL_RE.match(ioc):
- return "url"
- try:
- ipaddress.ip_address(ioc)
- return "ip"
- except ValueError:
- pass
- # Require valid DNS labels and a non-numeric top-level domain.
- if _DOMAIN_RE.fullmatch(ioc):
- return "domain"
- return "unknown"
- def _vt_url_for(ioc_type: str, ioc: str) -> str:
- """Return the VT API v3 endpoint URL for the given IOC."""
- import base64
- if ioc_type == "ip":
- return f"https://www.virustotal.com/api/v3/ip_addresses/{ioc}"
- elif ioc_type == "domain":
- return f"https://www.virustotal.com/api/v3/domains/{ioc}"
- elif ioc_type == "hash":
- return f"https://www.virustotal.com/api/v3/files/{ioc.lower()}"
- elif ioc_type == "url":
- # VT URL lookups require base64url-encoded URL (without padding)
- encoded = base64.urlsafe_b64encode(ioc.encode()).rstrip(b"=").decode()
- return f"https://www.virustotal.com/api/v3/urls/{encoded}"
- return ""
- def _extract_verdict(data: dict[str, Any], ioc_type: str) -> dict[str, Any]:
- """Extract the key reputation fields from a VT API v3 response."""
- attrs = data.get("attributes", {})
- last_analysis = attrs.get("last_analysis_stats", {})
- malicious = last_analysis.get("malicious", 0)
- suspicious = last_analysis.get("suspicious", 0)
- total = sum(last_analysis.values()) if last_analysis else 0
- # Determine verdict
- if malicious >= 5:
- verdict = "malicious"
- elif malicious >= 1 or suspicious >= 3:
- verdict = "suspicious"
- elif total > 0:
- verdict = "clean"
- else:
- verdict = "no_data"
- result: dict[str, Any] = {
- "verdict": verdict,
- "malicious_detections": malicious,
- "suspicious_detections": suspicious,
- "total_engines": total,
- "reputation": attrs.get("reputation", None),
- }
- # Type-specific enrichment
- if ioc_type == "hash":
- result["meaningful_name"] = attrs.get("meaningful_name") or attrs.get("name")
- result["file_type"] = attrs.get("type_description") or attrs.get("magic")
- result["size"] = attrs.get("size")
- result["first_seen"] = attrs.get("first_submission_date")
- result["last_seen"] = attrs.get("last_analysis_date")
- # Extract top malware family tags
- popular_tags = attrs.get("popular_threat_classification", {})
- result["threat_labels"] = [
- lbl.get("value") for lbl in popular_tags.get("popular_threat_name", [])
- ][:5]
- elif ioc_type in ("ip", "domain"):
- result["country"] = attrs.get("country")
- result["as_owner"] = attrs.get("as_owner")
- result["network"] = attrs.get("network")
- result["last_https_certificate_date"] = attrs.get("last_https_certificate_date")
- elif ioc_type == "url":
- result["final_url"] = attrs.get("last_final_url") or attrs.get("url")
- result["title"] = attrs.get("title")
- result["last_analysis_date"] = attrs.get("last_analysis_date")
- return result
- # ---------------------------------------------------------------------------
- # Main tool
- # ---------------------------------------------------------------------------
- @log_execution(tool_name="vt_lookup")
- @track_metrics("vt_lookup")
- @handle_tool_errors
- async def vt_lookup(
- iocs: list[str],
- api_key: str | None = None,
- ) -> ToolResult:
- """Look up IOC reputation using the VirusTotal API v3.
- Accepts a list of file hashes (MD5/SHA1/SHA256), IP addresses, domain
- names, and URLs. Returns per-IOC verdict, detection counts, and
- enrichment data from VirusTotal's 70+ security vendors.
- **API key required**: Set ``REVERSECORE_VT_API_KEY`` environment variable,
- or pass the key directly via the ``api_key`` parameter.
- Args:
- iocs: List of IOCs to look up (max 20 per call). Supported types:
- - File hashes: MD5 (32 chars), SHA1 (40), SHA256 (64)
- - IP addresses: IPv4 (e.g. ``8.8.8.8``)
- - Domain names: (e.g. ``evil.example.com``)
- - URLs: (e.g. ``https://evil.example.com/payload.exe``)
- Dismissed after review: Links to a Windows program from code, which is how droppers fetch their payload
- Line 155 on GitHub
- api_key: VirusTotal API key. If omitted, uses ``REVERSECORE_VT_API_KEY``
- environment variable.
- Returns:
- ToolResult with per-IOC verdict dicts on success:
- .. code-block:: json
- {
- "results": [
- {
- "ioc": "44d88612fea8a8f36de82e1278abb02f",
- "type": "hash",
- "verdict": "malicious",
- "malicious_detections": 67,
- "total_engines": 72,
- "threat_labels": ["eicar.test"]
- }
- ],
- "summary": {"malicious": 1, "suspicious": 0, "clean": 0, "no_data": 0}
- }
- Example:
- >>> result = await vt_lookup(["44d88612fea8a8f36de82e1278abb02f", "1.2.3.4"])
- """
- if not iocs:
- return failure("VALIDATION_ERROR", "No IOCs provided. Pass a non-empty list.")
- # Limit to 20 IOCs per call to avoid rate limits
- if len(iocs) > 20:
- iocs = iocs[:20]
- logger.warning("vt_lookup: truncated IOC list to 20 entries")
- # Resolve API key
- cfg = get_config()
- resolved_key = api_key or cfg.vt_api_key
- if not resolved_key:
- return failure(
- "MISSING_API_KEY",
- "VirusTotal API key not configured.",
- hint=(
- "Set the REVERSECORE_VT_API_KEY environment variable, "
- "or pass api_key= directly to vt_lookup()."
- ),
- )
- timeout = cfg.vt_request_timeout
- # Classify IOCs
- classified: list[tuple[str, str]] = [] # (ioc, type)
- skipped: list[str] = []
- for ioc in iocs:
- ioc = ioc.strip()
- if not ioc:
- continue
- ioc_type = _classify_ioc(ioc)
- if ioc_type == "unknown":
- skipped.append(ioc)
- else:
- classified.append((ioc, ioc_type))
- if not classified:
- return failure(
- "VALIDATION_ERROR",
- "None of the provided IOCs could be classified (expected hash, IP, domain, or URL).",
- hint=f"Unclassifiable IOCs: {skipped[:5]}",
- )
- # --- HTTP client ---
- try:
- import httpx
- except ImportError:
- return failure(
- "DEPENDENCY_ERROR",
- "httpx is required for vt_lookup. Install it: pip install httpx",
- )
- headers = {"x-apikey": resolved_key, "Accept": "application/json"}
- results: list[dict[str, Any]] = []
- errors: list[dict[str, str]] = []
- async with httpx.AsyncClient(timeout=timeout, headers=headers) as client:
- semaphore = asyncio.Semaphore(4) # max 4 concurrent VT requests
- async def _fetch(ioc: str, ioc_type: str) -> None:
- url = _vt_url_for(ioc_type, ioc)
- if not url:
- errors.append({"ioc": ioc, "error": "Could not build VT URL"})
- return
- async with semaphore:
- try:
- resp = await client.get(url)
- if resp.status_code == 200:
- body = resp.json()
- verdict = _extract_verdict(body.get("data", {}), ioc_type)
- verdict["ioc"] = ioc
- verdict["type"] = ioc_type
- results.append(verdict)
- elif resp.status_code == 404:
- results.append(
- {
- "ioc": ioc,
- "type": ioc_type,
- "verdict": "not_found",
- "malicious_detections": 0,
- "total_engines": 0,
- }
- )
- elif resp.status_code == 401:
- errors.append({"ioc": ioc, "error": "Invalid API key (HTTP 401)"})
- elif resp.status_code == 429:
- errors.append(
- {
- "ioc": ioc,
- "error": "VirusTotal rate limit exceeded (HTTP 429)",
- }
- )
- else:
- errors.append(
- {
- "ioc": ioc,
- "error": f"VT API returned HTTP {resp.status_code}",
- }
- )
- except httpx.TimeoutException:
- errors.append({"ioc": ioc, "error": f"Request timed out after {timeout}s"})
- except Exception as exc:
- err_msg = str(exc)
- if resolved_key:
- err_msg = err_msg.replace(resolved_key, "[REDACTED]")
- errors.append({"ioc": ioc, "error": err_msg})
- await asyncio.gather(*[_fetch(ioc, ioc_type) for ioc, ioc_type in classified])
- # Build summary
- summary: dict[str, int] = {
- "malicious": 0,
- "suspicious": 0,
- "clean": 0,
- "no_data": 0,
- "not_found": 0,
- }
- for r in results:
- v = r.get("verdict", "no_data")
- summary[v] = summary.get(v, 0) + 1
- return success(
- {
- "results": results,
- "summary": summary,
- "skipped_unclassifiable": skipped,
- "errors": errors,
- "queried": len(classified),
- },
- total_malicious=summary["malicious"],
- total_suspicious=summary["suspicious"],
- )
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.