Skip to content
Back to search

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.

Checked today

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
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/sjkim1127--reversecore-mcp/badge.svg)](/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

i

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.

  1. {
  2. "name": "reversecore-mcp",
  3. "version": "1.0.0",
  4. "description": "Enterprise-grade AI reverse engineering MCP server: Radare2, r2ghidra, ESIL emulation, Go/Rust, Electron ASAR, Unity IL2CPP, and feature code reconstruction.",
  5. "author": {
  6. "name": "Reversecore Team",
  7. "url": "https://github.com/sjkim1127/Reversecore_MCP"
  8. },
  9. "repository": "https://github.com/sjkim1127/Reversecore_MCP",
  10. "license": "MIT",
  11. "keywords": [
  12. "reverse-engineering",
  13. "binary-analysis",
  14. "decompiler",
  15. "radare2",
  16. "ghidra",
  17. "malware-analysis",
  18. "mcp-server"
  19. ],
  20. "skills": "./.agents/skills",
  21. "mcpServers": {
  22. "reversecore": {
  23. "command": "python3",
  24. "args": [
  25. "-m",
  26. "reversecore_mcp"
  27. ],
  28. "env": {
  29. "REVERSECORE_TIERED_MODE": "true",
  30. "REVERSECORE_SCHEMA_PROFILE": "compact"
  31. }
  32. }
  33. }
  34. }
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.

  1. <div align="center">
  2. **English** · [한국어](README.ko.md) · [日本語](README.ja.md) · [简体中文](README.zh-CN.md)
  3. <br />
  4. <img src="icon.png" alt="Reversecore MCP" width="440" />
  5. # Reversecore MCP
  6. ### AI-Powered Binary Reverse Engineering, Malware Analysis & Vulnerability Research via MCP
  7. **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.**
  8. ---
  9. [![CI/CD](https://github.com/sjkim1127/Reversecore_MCP/actions/workflows/main.yml/badge.svg)](https://github.com/sjkim1127/Reversecore_MCP/actions/workflows/main.yml)
  10. [![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12-blue)](https://www.python.org/)
  11. [![License: MIT](https://img.shields.io/badge/license-MIT-yellow.svg)](LICENSE)
  12. [![Tests](https://img.shields.io/badge/tests-3086%20passed-brightgreen)](#testing)
  13. [![Coverage](https://img.shields.io/badge/coverage-88%25-green)](#testing)
  14. [![FastMCP](https://img.shields.io/badge/FastMCP-3.4.11-purple)](https://github.com/jlowin/fastmcp)
  15. [![PyPI](https://img.shields.io/pypi/v/reversecore-mcp)](https://pypi.org/project/reversecore-mcp/)
  16. [![Docker](https://img.shields.io/badge/docker-ghcr.io-blue)](https://github.com/sjkim1127/Reversecore_MCP/pkgs/container/reversecore_mcp)
  17. [![skills.sh](https://img.shields.io/badge/skills.sh-reversecore--mcp-5c4ee5)](https://skills.sh)
  18. [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/sjkim1127/Reversecore_MCP/badge)](https://scorecard.dev/viewer/?uri=github.com/sjkim1127/Reversecore_MCP)
  19. [![HVTrust](https://hvtracker.net/badge/reversecore-mcp.svg)](https://hvtracker.net/agents/reversecore-mcp)
  20. [![Watch the Demo](https://img.shields.io/badge/▶_Watch_Demo-FF0000?style=for-the-badge&logo=youtube&logoColor=white)](https://youtu.be/wJGW2bp3c5A)
  21. [![SafeSkill Verified](https://img.shields.io/badge/SafeSkill-93%2F100_Verified_Safe-brightgreen?style=for-the-badge)](https://safeskill.dev/scan/sjkim1127-reversecore-mcp)
  22. <br />
  23. **[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)**
  24. </div>
  25. ### ⚡ Instant One-Line Setup
  26. 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:
  27. ```bash
  28. # Option 1: Zero-install CLI setup (Recommended)
  29. pipx run reversecore-mcp setup
  30. # Option 2: One-line shell installer (macOS / Linux)
  31. curl -fsSL https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.sh | bash
  32. # Option 3: Install Agent Skill (skills.sh / Cursor / Claude Code / Codex)
  33. npx skills add sjkim1127/Reversecore_MCP
  34. ```
  35. > 💡 **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.
  36. ---
  37. ## Table of Contents
  38. - [What is Reversecore MCP?](#what-is-reversecore-mcp)
  39. - [🛡️ Security Analysis Workflows](#-security-analysis-workflows)
  40. - [What You Can Analyze](#what-you-can-analyze)
  41. - [⚡ Context Efficiency: Tiered Router, Compact Schema & Paging](#-context-efficiency-tiered-router-compact-schema--paging)
  42. - [Architecture](#architecture)
  43. - [Tool Catalog (194 Tools)](#tool-catalog-194-tools)
  44. - [Guided Analysis Prompts (34 Modes)](#guided-analysis-prompts-34-modes)
  45. - [MCP Resources (11 URIs)](#mcp-resources-11-uris)
  46. - [Quick Start](#quick-start)
  47. - [Connect to Your AI Client](#connect-to-your-ai-client)
  48. - [Configuration](#configuration)
  49. - [Security Model](#security-model)
  50. - [Development](#development)
  51. - [CI/CD Pipeline](#cicd-pipeline)
  52. - [Docker Build Architecture](#docker-build-architecture)
  53. - [System Requirements](#system-requirements)
  54. - [Project Structure](#project-structure)
  55. - [Error Handling](#error-handling)
  56. - [Adding New Tools](#adding-new-tools)
  57. - [Contributing](#contributing)
  58. - [Documentation](#documentation)
  59. - [License](#license)
  60. ---
  61. ## What is Reversecore MCP?
  62. 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.
  63. Instead of manually switching between disassemblers, decompilers, YARA scanners, and forensics utilities, you describe your investigation goal in natural language:
  64. ```text
  65. "Decompile the main payload of this suspicious sample, recover its custom string decryption
  66. routine, extract all C2 IOCs, map behaviors to MITRE ATT&CK, and generate a triage report."
  67. ```
  68. 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.
  69. ---
  70. ## 🛡️ Security Analysis Workflows
  71. ### Workflow 1: Malware Cryptor / DGA Recovery & Safe Emulation Verification
  72. 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.
  73. **Prompt:**
  74. ```text
  75. "Analyze the config decryption function at 0x401180 in sample.bin, write a safe Python
  76. decryptor script, and verify with ESIL emulation that its output matches the binary."
  77. ```
  78. **Agent Tool Chain & Verified Output:**
  79. ```
  80. 1. r2_decompile("sample.bin", "0x401180", detail="summary")
  81. └─ Returns compact complexity/API summary + cache handle: evidence_id="ev_9a4c102f8b11"
  82. 2. inspect_analysis_view(evidence_id="ev_9a4c102f8b11", facet="lines", offset=0, limit=40)
  83. └─ Streams exact pseudo-C lines on demand without exhausting context window
  84. 3. reconstruct_feature_code(
  85. file_path="sample.bin",
  86. address_or_symbol="sym.decrypt_word",
  87. target_language="python",
  88. test_inputs=["0x0", "0xff", "0xffff"]
  89. )
  90. ├─ Decompilation & Synthesis: r2ghidra -> clean Python function (decrypt_word)
  91. ├─ Binary Emulation: Radare2 ESIL VM (isolated register/memory state, zero host execution)
  92. ├─ Equivalence Verdict: VERIFIED (branch_parity: true, test_vectors_evaluated: 3, emulation_successful: true)
  93. └─ Reconstructed Code:
  94. def decrypt_word(param_1: Any = 0, param_2: Any = 0, *args: Any, **kwargs: Any) -> Any:
  95. uVar1 = (param_1 ^ param_2) * 0x45d9f3b
  96. return uVar1 >> 0x10 ^ uVar1
  97. ```
  98. ---
  99. ### Workflow 2: Modern Runtime Threat & Supply-Chain Auditing (Go/Rust, Electron ASAR, Unity)
  100. 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:
  101. **Prompt:**
  102. ```text
  103. "Audit this suspicious installer's app.asar for insecure BrowserWindow settings and
  104. suspicious IPC handlers, and recover function symbols from its bundled stripped Go helper."
  105. ```
  106. **Agent Tool Chain & Verified Output:**
  107. ```
  108. 1. inspect_electron_asar("app.asar", search_pattern="ipcMain|child_process|shell")
  109. ├─ Format: Chromium Pickle ASAR (header_size: 48,210 bytes, 642 files)
  110. ├─ Exposed IPC Handlers: 14 channels mapped across main and preload scripts
  111. └─ Security Audit Findings:
  112. • [HIGH] nodeIntegration: true detected in BrowserWindow configuration
  113. • [MEDIUM] sandbox: false detected in renderer window options
  114. 2. inspect_go_rust_binary("helper_daemon.elf")
  115. ├─ Runtime Detected: Go (gopclntab magic 0xfffffff1, Go 1.22)
  116. ├─ Symbol Recovery: 148 stripped package/function names recovered from .gopclntab
  117. └─ Suspicious Packages Identified:
  118. • main.establishBeaconLoop @ 0x48a200
  119. • main.encryptLocalVolume @ 0x48b940
  120. ```
  121. ---
  122. ### Workflow 3: Zero-Day Crash Triage, Taint Analysis & Adaptive YARA/Vaccine Generation
  123. 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.
  124. **Prompt:**
  125. ```text
  126. "Triage this ASan crash log on daemon.bin, verify whether untrusted network input reaches
  127. the vulnerable memcpy sink, scan for dormant backdoors, and generate a YARA rule."
  128. ```
  129. **Agent Tool Chain & Verified Output:**
  130. ```
  131. 1. cve_triage_crash(crash_log_or_text=asan_log)
  132. └─ Bug Class: heap-buffer-overflow (READ) | CWE-125 | Faulting Function: parse_packet+0x84
  133. 2. taint_trace("daemon.bin", function_name="parse_packet", verify_with_angr=True)
  134. └─ Source→Sink Confirmed: recv() → memcpy() at 0x402190 (unbounded length field)
  135. 3. dormant_detector("daemon.bin")
  136. └─ Discovered 1 orphan function (0x404800) with time-bomb trigger (cmp eax, 0x67758ac0)
  137. 4. adaptive_vaccine(threat_report={...}, action="both")
  138. ├─ Generated YARA detection rule with wildcarded address displacement masking
  139. └─ Synthesized binary mitigation patch neutralizing the vulnerable/malicious branch
  140. ```
  141. ---
  142. ## What You Can Analyze
  143. | Target Category | Security & Reverse Engineering Capabilities | Engine / Requirement |
  144. |---|---|---|
  145. | **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) |
  146. | **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** |
  147. | **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 |
  148. | **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 |
  149. | **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 |
  150. | **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`) |
  151. | **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** |
  152. | **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** |
  153. ---
  154. ## ⚡ Context Efficiency: Tiered Router, Compact Schema & Paging
  155. 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:
  156. | Optimization Layer | How to Enable | Context Savings & Behavior |
  157. |---|---|---|
  158. | **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`). |
  159. | **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. |
  160. | **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. |
  161. | **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. |
  162. ---
  163. ## Architecture
  164. ```
  165. AI Client (Claude / Cursor / any MCP-compatible client)
  166. │ MCP Protocol (stdio or HTTP/SSE)
  167. ▼
  168. ┌──────────────────────────────────────────────────────┐
  169. │ FastMCP 3.4.11 Server │
  170. │ 194 registered tools · Fully async │
  171. │ Python 3.10–3.12 │
  172. ├────────────────────┬─────────────────────────────────┤
  173. │ Guided Prompts │ Dynamic Resources │
  174. │ (22 analysis │ (11 URI-based: per-binary │
  175. │ modes) │ strings, IOCs, ASM, CFG, …) │
  176. ├────────────────────┴─────────────────────────────────┤
  177. │ Core Infrastructure │
  178. │ Config · Security · Validators · Exceptions (17) │
  179. │ R2 Pool · Metrics · Memory (SQLite) · Task Queue │
  180. │ MITRE Mapper · Evidence Engine · Resilience Layer │
  181. │ Arch Registry (x86/ARM/MIPS/RISC-V/PPC) │
  182. │ Result Cache (SHA256) · Analysis Cache (Redis+SQL) │
  183. │ SAST (Python AST + C/C++ Regex) · Plugin System │
  184. ├──────────────────────────────────────────────────────┤
  185. │ Analysis Engines │
  186. │ Radare2 6.0.4 │ YARA 4.3.1 · LIEF · Capstone │
  187. │ r2ghidra │ CAPA · angr · Qiling │
  188. │ Volatility3 · Scapy│ DIE · Binwalk · Sleuth Kit │
  189. │ pwntools · ROPgadget│ Keystone (assembler) │
  190. └──────────────────────────────────────────────────────┘
  191. ```
  192. The server supports Python 3.10–3.12. The optional `angr` symbolic execution
  193. engine is installed on Python 3.12 and newer, where a secure compatible release
  194. is available; Python 3.10 and 3.11 installs omit `angr`.
  195. ### Core Infrastructure (37 modules)
  196. The `reversecore_mcp/core/` directory contains the shared infrastructure that all tools build on:
  197. | Module | Purpose |
  198. |---|---|
  199. | `config.py` | Pydantic BaseSettings with 34+ environment variables |
  200. | `security.py` | Input sanitization, command argument validation |
  201. | `validators.py` | File and binary path validation with TOCTOU mitigation, symlink resolution |
  202. | `r2_pool.py` | Thread-safe Radare2 connection pool with configurable size |
  203. | `r2_helpers.py` | Structured Radare2 output parsing |
  204. | `metrics.py` | Per-tool execution times, call counts, error rates, cache statistics |
  205. | `memory.py` | Async SQLite-backed AI memory store for persisting analysis findings across sessions |
  206. | `mitre_mapper.py` | MITRE ATT&CK technique ID mapping engine |
  207. | `evidence.py` | Evidence classification system: `OBSERVED`, `INFERRED`, `POSSIBLE` |
  208. | `resilience.py` | Retry, circuit-breaker, and timeout decorator patterns |
  209. | `task_queue.py` | Background task queue via Redis + arq |
  210. | `extension_registry.py` | Plugin registration and lifecycle management |
  211. | `arch_registry.py` | Multi-architecture mapping (x86, x86_64, ARM32, ARM64, MIPS, RISC-V, PPC → r2 arch/bits/registers) |
  212. | `result_cache.py` | SHA256-based tool result caching decorator (`@cache_tool_result`) |
  213. | `analysis_cache.py` | Multi-level decompilation cache (L1: Redis, L2: SQLite) |
  214. | `result.py` | `ToolSuccess` / `ToolError` Pydantic models |
  215. | `exceptions.py` | 17 exception classes with `RCMCP-E*` error codes |
  216. | `decorators.py` | `@log_execution`, `@track_metrics` |
  217. | `error_handling.py` | `@handle_tool_errors` decorator |
  218. | `error_formatting.py` | Structured error response formatting |
  219. | `execution.py` | Safe subprocess execution with timeout and output limits |
  220. | `command_spec.py` | Command specification for subprocess calls |
  221. | `loader.py` | Dynamic tool module loader |
  222. | `plugin.py` | Plugin base class |
  223. | `extension.py` | Extension base class |
  224. | `container.py` | Container/sandbox execution support |
  225. | `audit.py` | Audit logging |
  226. | `binary_cache.py` | Binary file caching |
  227. | `json_utils.py` | JSON serialization via orjson (3-5x faster than stdlib json) |
  228. | `logging_config.py` | Loguru-based structured logging |
  229. | `report_generator.py` | Report rendering engine (Markdown, PDF via xhtml2pdf) |
  230. | `resource_manager.py` | MCP resource lifecycle management |
  231. | `sast/python_ast_scanner.py` | Python AST-based vulnerability scanner |
  232. | `sast/regex_scanner.py` | C/C++ regex-based vulnerability scanner |
  233. | `sast/rule_manager.py` | SAST rule loading and management |
  234. ---
  235. ## Tool Catalog (194 Tools)
  236. > 📖 **[Authoritative Tool Catalog & Parameter Reference (186 Tools)](docs/TOOLS.md)**
  237. > 📊 **[Tool Profile Footprint & Context Benchmark Matrix](docs/benchmarks/profile_footprint.md)**
  238. 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`):
  239. | Profile | Registered Tools | Schema Size | LLM Context Saving vs Full | Recommended Domain |
  240. |---|:---:|:---:|:---:|---|
  241. | `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) |
  242. | `full` | **186** | 144.2 KB | Baseline (0%) | Complete enterprise reverse engineering suite |
  243. | `vuln-research` | **138** | 96.4 KB | **-33.1%** (~10,000 tokens) | Fuzzing, ASan crash triage, CVE hunting, exploit research |
  244. | `static` | **132** | 91.2 KB | **-36.8%** (~11,100 tokens) | Disassembly, decompilation (r2ghidra), LIEF, modern runtimes, static triage |
  245. | `malware` | **100** | 76.5 KB | **-46.9%** (~14,100 tokens) | Threat triage, YARA scanning, deobfuscation, anti-analysis |
  246. | `forensics` | **81** | 51.8 KB | **-64.1%** (~19,300 tokens) | Memory forensics (Volatility3), network PCAP (Scapy), disk |
  247. ### ⚡ Tiered Tools & Multi-Agent Architecture (`REVERSECORE_PROFILE=tiered`)
  248. 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:
  249. 1. **Tier-1: Daily Core Tools (12 tools)**:
  250. - `run_file`, `parse_binary_with_lief`, `get_server_health`
  251. - `Radare2_open_file`, `Radare2_close_file`, `Radare2_list_functions`, `Radare2_list_strings`, `Radare2_disassemble_function`, `Radare2_decompile_function`
  252. - `extract_iocs`, `run_yara`, `create_analysis_report`
  253. 2. **Tier-2: Domain Expert Sub-Agents & Universal Router (3 tools)**:
  254. - `call_expert_agent`: Dispatches high-level multi-step domain tasks to specialized Sub-Agents:
  255. - `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`)
  256. - `vulnerability_hunter`: CVE scanning, dangerous API auditing, ROP gadget collection, heap analysis, crash triage
  257. - `forensics`: Network PCAP analysis, C2 extraction, Volatility3 memory dumps, SleuthKit disk carving
  258. - `malware_analyst`: IOC extraction, dormant backdoors, CAPA capability mapping, adaptive vaccines
  259. - `deobfuscator`: DIE packer detection, string decryption, API hash resolution, dead-code elimination
  260. - `symbolic_engine`: angr symbolic path reachability, constraint solving, dataflow taint tracing
  261. - `diff_analyst`: Semantic binary diffing, 1-day patch review, cross-binary annotation transfer
  262. - `source_auditor`: AST vulnerability scanning (Python) and regex pattern auditing (C/C++)
  263. - `search_tools`: Dynamic keyword and domain search across all 186 tools with parameter schemas and example invocations.
  264. - `execute_domain_tool`: Universal execution gateway to invoke any of the 186 specialized tools on demand with custom arguments.
  265. Enable tiered mode via `reversecore-mcp setup --tiered` or `export REVERSECORE_PROFILE=tiered`.
  266. ---
  267. ### 🔍 Static Analysis Plugin (24 tools)
  268. | # | Tool | Backend | Description |
  269. |---|---|---|---|
  270. | 1 | `run_strings` | `strings` CLI | ASCII/Unicode string extraction with configurable min-length |
  271. | 2 | `run_binwalk` | Binwalk | Firmware deep-scan for embedded signatures and filesystems |
  272. | 3 | `run_binwalk_extract` | Binwalk | Extract embedded files discovered by binwalk |
  273. | 4 | `parse_binary_with_lief` | LIEF | Full PE/ELF/Mach-O header, section, import/export, TLS parsing |
  274. | 5 | `detect_packer` | DIE | Quick packer/compiler detection |
  275. | 6 | `detect_packer_deep` | DIE (`diec`) | Deep packer/protector analysis via Detect It Easy |
  276. | 7 | `run_capa` | CAPA (Mandiant FLARE) | Capability detection — "encrypts data", "creates persistence", etc. |
  277. | 8 | `run_capa_quick` | CAPA | Quick capability scan with a rule subset |
  278. | 9 | `generate_signature` | Radare2 | Generate binary signatures for identification |
  279. | 10 | `generate_yara_rule` | Radare2 + YARA | Generate YARA detection rules from binary patterns |
  280. | 11 | `generate_advanced_yara_rule` | Radare2 + YARA | Advanced YARA rules with behavioral indicators |
  281. | 12 | `scan_for_versions` | LIEF + strings | Scan binary for embedded version strings |
  282. | 13 | `extract_rtti_info` | Radare2 | Extract C++ RTTI (Run-Time Type Information) |
  283. | 14 | `diff_binaries` | Radare2 | Semantic binary diff between two file versions |
  284. | 15 | `analyze_variant_changes` | Radare2 | Analyze changes between binary variants |
  285. | 16 | `match_libraries` | Radare2 | Identify statically linked libraries by function fingerprint |
  286. | 17 | `patch_diff_1day` | Radare2 + heuristics | Automated patch diff analysis for 1-day vulnerability research |
  287. | 18 | `analyze_patch_diff_auto` | Radare2 + inference | Automated patch vulnerability inference |
  288. | 19 | `emulate_binary` | Radare2 ESIL | Register/memory-traced code emulation |
  289. | 20 | `generate_fuzzing_harness` | Qiling + AFL++ | Generate a fuzzing harness targeting a specific function |
  290. | 21 | `run_fuzzing_campaign` | AFL++ | Run a full fuzzing campaign with crash collection |
  291. | 22 | `triage_crash` | GDB | Crash parsing and exploitability assessment |
  292. | 23 | `verify_path_and_get_args` | angr | Symbolic execution — prove path reachability and compute concrete inputs |
  293. | 24 | `taint_trace` | Radare2 + angr | Data-flow taint analysis from sources to sinks |
  294. ---
  295. ### 🔐 Source Code Audit Plugin (1 tool)
  296. | # | Tool | Backend | Description |
  297. |---|---|---|---|
  298. | 25 | `audit_source_code` | AST + Regex | Python AST scanning + C/C++ regex scanning for dangerous patterns |
  299. ---
  300. ### 🛠️ Common Utilities Plugin (20 tools)
  301. **File Operations (5 tools)**
  302. | # | Tool | Description |
  303. |---|---|---|
  304. | 26 | `run_file` | File type, architecture, and compiler fingerprinting |
  305. | 27 | `copy_to_workspace` | Copy a file into the analysis workspace |
  306. | 28 | `create_directory` | Create a directory in the workspace |
  307. | 29 | `list_workspace` | List all files in the workspace |
  308. | 30 | `scan_workspace` | Full workspace scan with file metadata |
  309. **Patch Explanation (1 tool)**
  310. | # | Tool | Description |
  311. |---|---|---|
  312. | 31 | `explain_patch` | Explain a binary patch in natural language |
  313. **Assembler (1 tool)**
  314. | # | Tool | Backend | Description |
  315. |---|---|---|---|
  316. | 32 | `assemble_instructions` | Keystone | Assemble instructions to machine code (x86, ARM, MIPS, etc.) |
  317. **AI Memory Management (11 tools)**
  318. These tools let the AI persist and recall findings across analysis sessions using an async SQLite database:
  319. | # | Tool | Description |
  320. |---|---|---|
  321. | 33 | `create_memory_session` | Start a new memory session for an analysis |
  322. | 34 | `store_analysis_finding` | Persist an analysis finding with tags |
  323. | 35 | `query_analysis_memories` | Search past findings by query |
  324. | 36 | `get_binary_analysis_context` | Retrieve all context for a specific binary |
  325. | 37 | `tag_analysis_session` | Add tags to a session for organization |
  326. | 38 | `search_memories_by_tag` | Find sessions/findings by tag |
  327. | 39 | `delete_analysis_session` | Remove a session and its findings |
  328. | 40 | `cleanup_expired_sessions` | Remove sessions older than a threshold |
  329. | 41 | `list_analysis_sessions` | List all active sessions |
  330. | 42 | `export_memory_store` | Export all memories to a portable format |
  331. | 43 | `import_memory_store` | Import memories from an export file |
  332. **Server Monitoring (2 tools)**
  333. | # | Tool | Description |
  334. |---|---|---|
  335. | 44 | `get_server_health` | Uptime, memory usage, loaded tools, Python version |
  336. | 45 | `get_tool_metrics` | Per-tool call counts, mean execution times, error rates, cache hit/miss |
  337. ---
  338. ### ⚙️ Radare2 & r2ghidra Plugin (30 tools)
  339. All Radare2 tools use a thread-safe connection pool (`r2_pool.py`) that automatically manages r2pipe sessions.
  340. | # | Tool | Description |
  341. |---|---|---|
  342. | 46 | `Radare2_open_file` | Open a binary file in Radare2 |
  343. | 47 | `Radare2_close_file` | Close a Radare2 session |
  344. | 48 | `Radare2_list_open_files` | List currently open files |
  345. | 49 | `Radare2_analyze_binary` | Run full auto-analysis (`aaa`) |
  346. | 50 | `Radare2_list_functions` | List all detected functions |
  347. | 51 | `Radare2_disassemble_function` | Disassemble a specific function |
  348. | 52 | `Radare2_disassemble_address` | Disassemble at a specific address |
  349. | 53 | `Radare2_decompile_function` | Decompile via r2ghidra (Ghidra engine embedded in r2, no JVM needed) |
  350. | 54 | `Radare2_list_exports` | List exported symbols |
  351. | 55 | `Radare2_list_imports` | List imported functions |
  352. | 56 | `Radare2_list_sections` | List binary sections with entropy |
  353. | 57 | `Radare2_list_strings` | List strings found in the binary |
  354. | 58 | `Radare2_find_cross_references` | Track function calls and data references |
  355. | 59 | `Radare2_search_bytes` | Search for byte patterns in the binary |
  356. | 60 | `Radare2_get_binary_info` | Get binary metadata (arch, format, endianness) |
  357. | 61 | `Radare2_execute_command` | Execute a raw Radare2 command |
  358. | 62 | `Radare2_esil_emulate` | ESIL emulation at a specific address |
  359. | 63 | `Radare2_get_hexdump` | Hex dump at a virtual address |
  360. | 64 | `Radare2_get_cfg_data` | Extract control flow graph data |
  361. | 65 | `Radare2_generate_cfg_png` | Generate CFG as PNG image |
  362. | 66 | `Radare2_generate_callgraph` | Generate function call graph |
  363. | 67 | `Radare2_recover_structures` | Auto-recover C structs and persist to annotation database |
  364. | 68 | `Radare2_decompile_with_r2ghidra` | High-quality C decompilation with caching |
  365. | 69 | `Radare2_annotate_binary` | Add annotations to the binary |
  366. | 70 | `Radare2_get_annotations` | Retrieve annotations |
  367. | 71 | `Radare2_export_annotations` | Export annotations to file |
  368. | 72 | `Radare2_import_annotations` | Import annotations from file |
  369. | 73 | `Radare2_detect_crypto_constants` | Detect cryptographic constants (AES S-box, etc.) |
  370. | 74 | `Radare2_find_gadgets` | Find ROP/JOP gadgets |
  371. | 75 | `Radare2_calculate_entropy` | Calculate per-section entropy |
  372. ---
  373. ### 🦠 Malware Analysis Plugin (9 tools)
  374. | # | Tool | Backend | Description |
  375. |---|---|---|---|
  376. | 76 | `dormant_detector` | Radare2 + heuristics | Find hidden backdoors, orphan functions, time-bombs, logic bombs |
  377. | 77 | `adaptive_vaccine` | YARA + Radare2 | Generate detection YARA rules + binary patches to neutralize threats |
  378. | 78 | `vulnerability_hunter` | Radare2 + analysis | Detect dangerous API patterns (strcpy, sprintf) and ROP gadget chains |
  379. | 79 | `extract_iocs` | Regex + LIEF | Extract IPs, URLs, domains, hashes, registry keys, crypto addresses |
  380. | 80 | `run_yara` | YARA | Scan with custom rule files and built-in rulesets |
  381. | 81 | `generate_poc_exploit` | pwntools | Generate proof-of-concept exploit code |
  382. | 82 | `build_rop_chain` | ROPgadget + pwntools | Automated ROP chain construction |
  383. | 83 | `autonomous_vuln_hunt` | Radare2 + angr | Autonomous vulnerability hunting pipeline |
  384. | 84 | `analyze_heap_exploit` | Radare2 + heuristics | Heap exploitation analysis (UAF, double-free, overflow) |
  385. ---
  386. ### 🕵️ Digital Forensics Plugin (22 tools)
  387. **Memory Forensics (6 tools)**
  388. | # | Tool | Backend | Description |
  389. |---|---|---|---|
  390. | 85 | `memory_analyze` | Volatility3 | Full memory dump analysis |
  391. | 86 | `memory_list_processes` | Volatility3 | List running processes from memory dump |
  392. | 87 | `memory_detect_injections` | Volatility3 | Detect code injection in process memory |
  393. | 88 | `memory_extract_strings` | Volatility3 | Extract strings from process memory |
  394. | 89 | `memory_dump_module` | Volatility3 | Dump a loaded module from memory |
  395. | 90 | `memory_list_symbols` | Volatility3 | List symbols from memory |
  396. **Disk Forensics (6 tools)**
  397. | # | Tool | Backend | Description |
  398. |---|---|---|---|
  399. | 91 | `disk_list_partition` | Sleuth Kit | List disk partitions |
  400. | 92 | `disk_list_files` | Sleuth Kit | List files in a disk image |
  401. | 93 | `disk_recover_deleted` | Sleuth Kit | Recover deleted files |
  402. | 94 | `disk_analyze_mft` | Sleuth Kit | Analyze NTFS Master File Table |
  403. | 95 | `disk_extract_file` | Sleuth Kit | Extract a file from disk image |
  404. | 96 | `disk_hash_verify` | Sleuth Kit | Verify file integrity via hash |
  405. **Network Forensics (5 tools)**
  406. | # | Tool | Backend | Description |
  407. |---|---|---|---|
  408. | 97 | `pcap_analyze` | Scapy | PCAP analysis: protocol breakdown, anomalies |
  409. | 98 | `pcap_list_connections` | Scapy | List all network connections |
  410. | 99 | `pcap_extract_dns` | Scapy | Extract DNS queries and responses |
  411. | 100 | `pcap_extract_c2` | Scapy | Identify potential C2 communication |
  412. | 101 | `pcap_reconstruct_stream` | Scapy | Reconstruct TCP streams |
  413. **Artifact Analysis (5 tools)**
  414. | # | Tool | Backend | Description |
  415. |---|---|---|---|
  416. | 102 | `artifact_collect` | Custom parsers | Collect browser history, registry hives, event logs, prefetch |
  417. | 103 | `artifact_correlate_ioc` | Custom parsers | Correlate artifacts with known IOCs |
  418. | 104 | `artifact_generate_yara` | YARA | Generate YARA rules from artifact patterns |
  419. | 105 | `artifact_timeline` | Custom parsers | Build timeline from multiple artifact sources |
  420. | 106 | `artifact_report` | Custom parsers | Generate artifact analysis report |
  421. ---
  422. ### 📝 Report Generation Plugin (14 tools)
  423. | # | Tool | Description |
  424. |---|---|---|
  425. | 107 | `get_system_time` | Get server timestamp (prevents AI from hallucinating dates) |
  426. | 108 | `set_timezone` | Set the reporting timezone |
  427. | 109 | `get_timezone_info` | Get current timezone information |
  428. | 110 | `start_report_session` | Start a timed analysis session with unique ID |
  429. | 111 | `end_report_session` | Finalize session: compute duration, lock IOC/ATT&CK lists |
  430. | 112 | `get_report_session_status` | Check session status |
  431. | 113 | `list_report_sessions` | List all active/completed sessions |
  432. | 114 | `add_ioc` | Collect and tag IOCs during a live session |
  433. | 115 | `add_analysis_note` | Add categorized notes (finding, warning, behavior) |
  434. | 116 | `add_mitre_technique` | Document MITRE ATT&CK technique IDs |
  435. | 117 | `set_severity` | Set session severity (low/medium/high/critical) |
  436. | 118 | `create_analysis_report` | Render report in 4 modes: `full_analysis`, `quick_triage`, `ioc_summary`, `executive_brief` |
  437. | 119 | `generate_vex_report` | Generate a VEX (Vulnerability Exploitability eXchange) report |
  438. | 120 | `generate_sigma_rule` | Generate SIGMA detection rules |
  439. ---
  440. ## Guided Analysis Prompts (22 Modes)
  441. 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.
  442. ### Malware Analysis (9 prompts)
  443. | Prompt | Use Case |
  444. |---|---|
  445. | `full_analysis_mode` | 6-phase comprehensive analysis: triage → disassembly → behavior → network → persistence → report |
  446. | `malware_analysis_mode` | Focused malware analysis with threat classification |
  447. | `basic_analysis_mode` | Rapid triage for initial assessment and quick verdicts |
  448. | `apt_hunting_mode` | APT-specific hunting: lateral movement, persistence, data exfiltration |
  449. | `malware_defense_mode` | Defense-oriented: generate detection rules and mitigations |
  450. | `unpacking_mode` | Analyze and bypass packing/obfuscation (Themida, VMProtect, UPX) |
  451. | `c2_extraction_mode` | Extract and analyze C2 communication infrastructure |
  452. | `ransomware_triage_mode` | Ransomware-specific triage: encryption analysis, key recovery assessment |
  453. | `code_similarity_mode` | Compare binaries for code similarity and shared lineage |
  454. ### Security Research (6 prompts)
  455. | Prompt | Use Case |
  456. |---|---|
  457. | `vulnerability_research_mode` | Bug hunting: buffer overflows, UAF, command injection |
  458. | `crypto_analysis_mode` | Cryptographic implementation analysis and weakness detection |
  459. | `firmware_analysis_mode` | IoT/embedded firmware: binwalk extraction, UART strings, hardcoded credentials |
  460. | `patch_analysis_mode` | Security patch analysis and regression testing |
  461. | `source_code_audit_mode` | Source code security audit (Python, C, C++) |
  462. | `autonomous_vuln_hunt_mode` | Autonomous vulnerability hunting pipeline |
  463. ### CVE Research & Exploit Development (5 prompts)
  464. | Prompt | Use Case |
  465. |---|---|
  466. | `taint_analysis_mode` | Data-flow taint analysis: automated source→sink path discovery |
  467. | `heap_exploit_mode` | Heap exploitation analysis and PoC generation |
  468. | `fuzzing_mode` | Fuzzing campaign setup and crash triage |
  469. | `patch_diff_auto_mode` | Automated patch diff for 1-day vulnerability research |
  470. | `cve_discovery_pipeline_mode` | Full CVE discovery pipeline: from patch diff to working exploit |
  471. ### Other (2 prompts)
  472. | Prompt | Use Case |
  473. |---|---|
  474. | `game_analysis_mode` | Game client analysis: anti-cheat detection, protocol RE, memory inspection |
  475. | `report_generation_mode` | Structured session workflow with MITRE ATT&CK technique mapping |
  476. > **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).
  477. ---
  478. ## MCP Resources (11 URIs)
  479. 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.
  480. ### Static Resources
  481. | URI | Description |
  482. |---|---|
  483. | `reversecore://guide` | Tool usage guide with file path rules and best practices |
  484. | `reversecore://guide/structures` | Structure recovery and cross-reference analysis technical guide |
  485. | `reversecore://tools` | Complete documentation for all 194 registered tools |
  486. | `reversecore://logs` | Application logs (last 100 lines) |
  487. ### Dynamic Resources (Per-Binary Virtual Filesystem)
  488. These URIs resolve per-binary and invoke the corresponding analysis tools on demand:
  489. | URI Template | Description |
  490. |---|---|
  491. | `reversecore://{filename}/strings` | Extract all strings from a binary |
  492. | `reversecore://{filename}/iocs` | Extract IOCs (IPs, URLs, emails, hashes) |
  493. | `reversecore://{filename}/func/{address}/code` | Decompiled pseudo-C code for a function |
  494. | `reversecore://{filename}/func/{address}/asm` | Disassembly for a function |
  495. | `reversecore://{filename}/func/{address}/cfg` | Control flow graph in Mermaid format |
  496. | `reversecore://{filename}/functions` | List of all functions in the binary |
  497. | `reversecore://{filename}/dormant_detector` | Dormant detector analysis results |
  498. ---
  499. ## Quick Start
  500. ### ⚡ One-Line Automated Setup (Recommended)
  501. 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:
  502. ```bash
  503. # macOS / Linux
  504. curl -fsSL https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.sh | bash
  505. # Or via uvx (zero installation required)
  506. uvx --from reversecore-mcp reversecore-setup
  507. # Or via pipx
  508. pipx run reversecore-mcp setup
  509. # Windows (PowerShell)
  510. irm https://raw.githubusercontent.com/sjkim1127/Reversecore_MCP/main/install.ps1 | iex
  511. ```
  512. **Common Setup Options:**
  513. ```bash
  514. reversecore-mcp setup --tiered # Tiered Mode: 15 essential tools (>90% context token reduction)
  515. reversecore-mcp setup --docker # Configure Docker container execution
  516. reversecore-mcp setup --dry-run # Preview configuration changes without writing
  517. reversecore-mcp setup --list # Inspect detected clients and config paths
  518. reversecore-mcp setup --remove # Unregister Reversecore from all clients
  519. ```
  520. ---
  521. ### Manual Installation Options
  522. #### Option 1 — PyPI (Simplest)
  523. ```bash
  524. pip install reversecore-mcp
  525. reversecore-mcp
  526. ```
  527. > **Prerequisites:** Radare2 must be installed on your system (`r2 --version`). YARA is installed automatically via `yara-python`.
  528. ### Option 2 — Docker (Recommended for Full Functionality)
  529. All analysis engines (Radare2, r2ghidra, YARA, Binwalk, Sleuth Kit, GDB, etc.) come pre-installed:
  530. ```bash
  531. docker run -i --rm \
  532. -v /path/to/your/samples:/app/workspace \
  533. -e REVERSECORE_WORKSPACE=/app/workspace \
  534. -e MCP_TRANSPORT=stdio \
  535. ghcr.io/sjkim1127/reversecore_mcp:latest
  536. ```
  537. ### Option 3 — Build from Source (Docker Compose)
  538. ```bash
  539. git clone https://github.com/sjkim1127/Reversecore_MCP.git
  540. cd Reversecore_MCP
  541. ./scripts/run-docker.sh # auto-detects Intel / Apple Silicon
  542. ```
  543. Or manually:
  544. ```bash
  545. docker compose --profile x86 up -d # Intel/AMD
  546. docker compose --profile arm64 up -d # Apple Silicon (M1/M2/M3)
  547. ```
  548. ### Option 4 — Python (Local Development)
  549. ```bash
  550. git clone https://github.com/sjkim1127/Reversecore_MCP.git
  551. cd Reversecore_MCP
  552. python -m venv venv && source venv/bin/activate
  553. pip install -r requirements.txt
  554. python -m reversecore_mcp.server
  555. ```
  556. > **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.
  557. ---
  558. ## Connect to Your AI Client
  559. Add the server configuration to your IDE client settings (e.g., `~/.cursor/mcp.json` or `claude_desktop_config.json`).
  560. ### ⚡ Option 1: Docker Exec Mode (Recommended)
  561. 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.
  562. ```json
  563. {
  564. "mcpServers": {
  565. "Reversecore_MCP": {
  566. "command": "docker",
  567. "args": [
  568. "exec",
  569. "-i",
  570. "-e",
  571. "MCP_TRANSPORT=stdio",
  572. "reversecore-mcp-arm64",
  573. "python",
  574. "-m",
  575. "reversecore_mcp.server"
  576. ]
  577. }
  578. }
  579. }
  580. ```
  581. > Replace `reversecore-mcp-arm64` with `reversecore-mcp` if you are on Intel/AMD.
  582. ---
  583. ### 🌐 Option 2: SSE HTTP Mode
  584. For network-based streaming (Server-Sent Events):
  585. ```json
  586. {
  587. "mcpServers": {
  588. "Reversecore_MCP": {
  589. "url": "http://localhost:8000/mcp/sse"
  590. }
  591. }
  592. }
  593. ```
  594. ---
  595. ### 📦 Option 3: Stdio Mode (Docker-on-Demand)
  596. Runs a fresh, isolated container for every session:
  597. <details>
  598. <summary>🍎 macOS</summary>
  599. ```json
  600. {
  601. "mcpServers": {
  602. "reversecore": {
  603. "command": "docker",
  604. "args": [
  605. "run", "-i", "--rm",
  606. "-v", "/Users/YOUR_USERNAME/samples:/app/workspace",
  607. "-e", "REVERSECORE_WORKSPACE=/app/workspace",
  608. "-e", "MCP_TRANSPORT=stdio",
  609. "ghcr.io/sjkim1127/reversecore_mcp:latest"
  610. ]
  611. }
  612. }
  613. }
  614. ```
  615. </details>
  616. <details>
  617. <summary>🐧 Linux</summary>
  618. ```json
  619. {
  620. "mcpServers": {
  621. "reversecore": {
  622. "command": "docker",
  623. "args": [
  624. "run", "-i", "--rm",
  625. "-v", "/home/YOUR_USERNAME/samples:/app/workspace",
  626. "-e", "REVERSECORE_WORKSPACE=/app/workspace",
  627. "-e", "MCP_TRANSPORT=stdio",
  628. "ghcr.io/sjkim1127/reversecore_mcp:latest"
  629. ]
  630. }
  631. }
  632. }
  633. ```
  634. </details>
  635. <details>
  636. <summary>🪟 Windows</summary>
  637. ```json
  638. {
  639. "mcpServers": {
  640. "reversecore": {
  641. "command": "docker",
  642. "args": [
  643. "run", "-i", "--rm",
  644. "-v", "C:/samples:/app/workspace",
  645. "-e", "REVERSECORE_WORKSPACE=/app/workspace",
  646. "-e", "MCP_TRANSPORT=stdio",
  647. "ghcr.io/sjkim1127/reversecore_mcp:latest"
  648. ]
  649. }
  650. }
  651. }
  652. ```
  653. </details>
  654. > **⚠️ Important — File Paths Inside Docker**
  655. >
  656. > Your local folder is mounted to `/app/workspace` inside the container.
  657. > Always reference files by **filename only**, not by your local full path.
  658. >
  659. > | ❌ Wrong | ✅ Correct |
  660. > |---|---|
  661. > | `r2_decompile("/Users/john/samples/mal.exe")` | `r2_decompile("mal.exe")` |
  662. ---
  663. ## Configuration
  664. 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.
  665. ### Core Settings
  666. | Variable | Default | Description |
  667. |---|---|---|
  668. | `MCP_TRANSPORT` | `stdio` | Transport mode: `stdio` or `http` |
  669. | `REVERSECORE_WORKSPACE` | `./` (cwd) | Analysis workspace directory |
  670. | `REVERSECORE_READ_DIRS` | `""` | Comma-separated list of additional read-only directories |
  671. | `REVERSECORE_STRICT_PATHS` | `false` | Raise errors for missing paths instead of warnings |
  672. | `REVERSECORE_STRUCTURED_ERRORS` | `false` | Enable structured error responses with error codes |
  673. | `REVERSECORE_DEFAULT_TOOL_TIMEOUT` | `120` | Default tool execution timeout in seconds |
  674. | `REVERSECORE_MAX_OUTPUT_SIZE` | `10000000` | Maximum output size for tools (bytes) |
  675. | `REVERSECORE_FORENSICS_MAX_RECOVERED_BYTES` | `500000000` | Maximum bytes recovered from one disk inode |
  676. ### HTTP Mode Settings
  677. | Variable | Default | Description |
  678. |---|---|---|
  679. | `MCP_HOST` | `0.0.0.0` | Host interface to bind (auto-overrides to `127.0.0.1` if no API key) |
  680. | `MCP_PORT` | `8000` | Port for HTTP server |
  681. | `MCP_API_KEY` | *(unset)* | API key for HTTP authentication (`X-API-Key` or `Authorization: Bearer`) |
  682. | `REVERSECORE_RATE_LIMIT` | `60` | Max requests per minute (HTTP mode only, via slowapi) |
  683. | `MAX_UPLOAD_SIZE` | `100000000` | Maximum upload size (100 MB default) |
  684. | `FILE_RETENTION_MINUTES` | `1440` | Retention period for uploaded files (24h default) |
  685. ### Radare2 Settings
  686. | Variable | Default | Description |
  687. |---|---|---|
  688. | `REVERSECORE_R2_POOL_SIZE` | `3` | Number of Radare2 connections in the pool |
  689. | `REVERSECORE_R2_POOL_TIMEOUT` | `30` | Timeout for acquiring a connection from the pool |
  690. | `REVERSECORE_R2_EXTENSIONS` | `""` | Comma-separated list of r2 extension classes (`module:ClassName`) |
  691. | `REVERSECORE_GHIDRA_MAX_PROJECTS` | `3` | Max cached r2ghidra decompiler projects |
  692. | `REVERSECORE_GHIDRA_EXTENSIONS` | `""` | Comma-separated list of Ghidra extension classes |
  693. | `MAX_EMULATION_INSTRUCTIONS` | `1000` | Maximum ESIL emulation instructions |
  694. ### Sandbox Settings
  695. | Variable | Default | Description |
  696. |---|---|---|
  697. | `REVERSECORE_SANDBOX_ENABLED` | `false` | Enable sandbox execution for dynamic analysis tools |
  698. | `REVERSECORE_SANDBOX_MODE` | `auto` | Sandbox mode: `auto`, `host`, `container`, `disabled` |
  699. | `REVERSECORE_SANDBOX_DOCKER_IMAGE` | `reversecore-sandbox:latest` | Docker image for sandbox execution |
  700. | `REVERSECORE_SANDBOX_CPU_LIMIT` | `1.0` | CPU core limit for sandbox containers |
  701. | `REVERSECORE_SANDBOX_MEMORY_LIMIT` | `512m` | Memory limit for sandbox containers |
  702. | `REVERSECORE_SANDBOX_PIDS_LIMIT` | `100` | PID limit for sandbox containers |
  703. | `REVERSECORE_SANDBOX_USER` | `nobody` | Non-root user for sandbox execution |
  704. ### Storage & Queue
  705. | Variable | Default | Description |
  706. |---|---|---|
  707. | `REDIS_URL` | `redis://localhost:6379/0` | Redis URL for task queue and result caching |
  708. | `MEMORY_DB_PATH` | `~/.reversecore_mcp/memory.db` | Path to AI memory SQLite database |
  709. | `REVERSECORE_LIEF_MAX_FILE_SIZE` | `1000000000` | Maximum file size for LIEF parsing (1 GB) |
  710. ### Logging
  711. | Variable | Default | Description |
  712. |---|---|---|
  713. | `LOG_LEVEL` | `INFO` | Logging verbosity: `DEBUG`, `INFO`, `WARNING`, `ERROR` |
  714. | `LOG_FILE` | `<tempdir>/reversecore/app.log` | Path to log file |
  715. | `LOG_FORMAT` | `human` | Log format: `human` (readable) or `json` (structured) |
  716. ### Plugins & SAST
  717. | Variable | Default | Description |
  718. |---|---|---|
  719. | `REVERSECORE_PLUGIN_DIRS` | `""` | Comma-separated directories to scan for extension plugins |
  720. | `REVERSECORE_SAST_RULES_PATH` | `""` | Path to custom YAML SAST rules file |
  721. ---
  722. ## Security Model
  723. Security is implemented as defense-in-depth, with protections at multiple layers:
  724. ### Input & Path Safety
  725. | Control | Implementation |
  726. |---|---|
  727. | **No shell injection** | All subprocess calls use list arguments, never shell strings (`execution.py`) |
  728. | **Path traversal prevention** | `validate_file_path()` and `validate_binary_path()` resolve symlinks and confine access to the workspace (`validators.py`) |
  729. | **TOCTOU mitigation** | `bypass_cache=True` flag re-validates paths to prevent race conditions |
  730. | **Input sanitization** | All parameters sanitized before execution (`security.py`) |
  731. | **CSRF protection** | Dashboard forms require token-based CSRF validation (`dashboard/__init__.py`) |
  732. ### Network & Authentication
  733. | Control | Implementation |
  734. |---|---|
  735. | **Timing-attack-safe auth** | `secrets.compare_digest()` for API key comparison (`web/auth.py`) |
  736. | **Restricted auth vectors** | Only `X-API-Key` and `Authorization: Bearer` headers accepted; no query params or cookies |
  737. | **Loopback-only fallback** | Without `MCP_API_KEY`, HTTP access restricted to `127.0.0.1` (`web/middleware.py`) |
  738. | **Rate limiting** | Configurable per-minute limits via slowapi |
  739. | **Security headers** | HSTS, X-Content-Type-Options, X-Frame-Options, CSP on all HTTP responses (`web/middleware.py`) |
  740. | **Minimized `/health`** | Public endpoint returns only `{"status": "alive"}`; details behind authentication (`web/endpoints.py`) |
  741. ### Container & Runtime
  742. | Control | Implementation |
  743. |---|---|
  744. | **Non-root execution** | Runs as `appuser` (UID 1000) with minimal capabilities |
  745. | **Resource limits** | Docker Compose enforces CPU (2.0) and memory (4 GB) limits |
  746. | **Sandbox isolation** | Optional container-based sandboxing for dynamic analysis tools |
  747. ### CI/CD Security Gates
  748. | Control | Implementation |
  749. |---|---|
  750. | **Secrets scanning** | Gitleaks runs on every commit (pre-commit hook + CI) |
  751. | **SAST** | Bandit scans all Python code on every commit |
  752. | **CodeQL** | GitHub CodeQL static analysis on every push to `main` |
  753. | **Dependency auditing** | pip-audit on every push — no unreviewed CVEs |
  754. | **Container scanning** | Trivy scans Docker images for vulnerabilities (LOW through CRITICAL) |
  755. | **Exploit safety gate** | POC templates scanned with Bandit; Hypothesis DAST fuzzing; container isolation verified |
  756. ### Structured Error Handling
  757. All 17 exception classes carry `RCMCP-E*` error codes for programmatic handling. See [Error Handling](#error-handling) for the full hierarchy.
  758. ---
  759. ## Development
  760. ### Setup
  761. ```bash
  762. git clone https://github.com/sjkim1127/Reversecore_MCP.git
  763. cd Reversecore_MCP
  764. python -m venv venv && source venv/bin/activate
  765. pip install -r requirements.txt
  766. pip install -r requirements-dev.txt
  767. pre-commit install # installs Ruff, Bandit, Gitleaks hooks
  768. ```
  769. ### Testing
  770. ```bash
  771. # Full test suite with coverage report
  772. pytest tests/ -v
  773. # Unit tests only (fast, no external dependencies)
  774. pytest tests/unit/ -v
  775. # Integration tests (requires Docker)
  776. pytest tests/integration/ -v
  777. # Run with coverage threshold enforcement
  778. pytest tests/unit/ --cov=reversecore_mcp --cov-fail-under=80
  779. # Run a specific test
  780. pytest tests/unit/test_cli_tools.py::TestRunFile::test_success -v
  781. # Security boundary tests
  782. pytest tests/ -m security -v
  783. # Benchmarks
  784. pytest tests/ -m benchmark -v
  785. ```
  786. **Test status:**
  787. - ✅ **1,957 unit tests** passing across Python 3.10 / 3.11 / 3.12
  788. - 📊 **87% code coverage** (80% minimum enforced in CI)
  789. - 🔒 Zero Bandit findings
  790. - ⚡ Fully async test suite via `pytest-asyncio`
  791. **Test markers:**
  792. | Marker | Purpose |
  793. |---|---|
  794. | `@pytest.mark.unit` | Fast unit tests |
  795. | `@pytest.mark.integration` | Tests requiring Docker or external tools |
  796. | `@pytest.mark.slow` | Long-running tests |
  797. | `@pytest.mark.benchmark` | Performance benchmarks |
  798. | `@pytest.mark.security` | Security boundary validation tests |
  799. ### Code Quality
  800. ```bash
  801. ruff check reversecore_mcp/ # Lint (E, W, F, I, B, C4, UP rules)
  802. ruff format reversecore_mcp/ # Format
  803. mypy reversecore_mcp/ # Type check (0 errors across 108 files)
  804. bandit -r reversecore_mcp/ # Security scan (all severities)
  805. pip-audit # Dependency CVE scan
  806. ```
  807. ### Pre-commit Hooks
  808. The following hooks run automatically on every commit:
  809. 1. **Ruff** — lint with auto-fix + format check
  810. 2. **trailing-whitespace** — remove trailing whitespace
  811. 3. **end-of-file-fixer** — ensure files end with newline
  812. 4. **check-yaml / check-json** — validate YAML/JSON syntax
  813. 5. **check-added-large-files** — block files > 1 MB
  814. 6. **check-merge-conflict** — detect unresolved merge markers
  815. 7. **detect-private-key** — prevent accidental key commits
  816. 8. **Bandit** — Python security scanning
  817. ---
  818. ## CI/CD Pipeline
  819. Every push to `main` triggers 11 pipeline jobs. All must pass before deployment.
  820. ```
  821. Lint & Security Gate Unit Tests (Python Matrix)
  822. ├─ Gitleaks (secret scan) ├─ pytest 3.10 --cov-fail-under=80
  823. ├─ Hadolint (Dockerfile lint) ├─ pytest 3.11 --cov-fail-under=80
  824. ├─ Ruff check + format └─ pytest 3.12 --cov-fail-under=80
  825. ├─ Mypy type check (108 files)
  826. ├─ Bandit (all severities) Wheel Smoke Test
  827. ├─ pip-audit (no CVEs) └─ Build wheel → install in /tmp
  828. └─ Security boundary tests → verify plugin discovery
  829. → assert __file__ under sys.prefix
  830. CodeQL Analysis
  831. └─ Python SAST Docker Verification
  832. ├─ Build reversecore-mcp:ci
  833. Exploit Safety Gate ├─ Trivy container scan
  834. ├─ Bandit on POC templates ├─ Image size check (< 5 GB)
  835. ├─ Hypothesis DAST fuzzing ├─ CLI tool verification
  836. ├─ Performance benchmarks ├─ Integration tests in container
  837. └─ Container isolation test └─ E2E tool invocation
  838. In-Container Smoke Test Build Base Image (amd64 + arm64)
  839. ├─ Copy test ELF into container ├─ Compile YARA 4.3.1
  840. └─ Run scripts/smoke_test.py ├─ Compile Radare2 6.0.4
  841. ├─ Compile r2ghidra
  842. Deploy (amd64 + arm64) └─ Push to GHCR
  843. ├─ Build app image
  844. ├─ Push to GHCR Merge Manifests
  845. └─ Trivy rescan on published └─ Multi-arch manifest → :latest
  846. ```
  847. > **Zero-bypass policy:** CI/CD failures are never resolved by modifying pipeline configuration. Root causes are always fixed directly in source code or dependencies.
  848. ---
  849. ## Docker Build Architecture
  850. The Docker build uses a two-layer approach to keep build times manageable:
  851. ### Layer 1: Base Image (`Dockerfile.base`)
  852. A multi-stage build that compiles all slow-to-build, rarely-changing dependencies from source:
  853. ```
  854. compiler-toolchain (python:3.12-slim-bookworm + build tools)
  855. ├── compiler-yara (YARA 4.3.1 from source) [parallel]
  856. ├── compiler-r2 (Radare2 6.0.4 from source) [parallel]
  857. │ └── compiler-r2ghidra (r2ghidra plugin) [sequential]
  858. └── compiler-pip (pip install into /opt/venv) [parallel]
  859. base (final runtime: python:3.12-slim-bookworm)
  860. ├── Runtime packages: file, binutils, gdb, binwalk, graphviz, nasm, sleuthkit
  861. ├── /opt/yara (compiled YARA)
  862. ├── /opt/radare2 (compiled r2 + r2ghidra)
  863. ├── /opt/venv (Python packages)
  864. └── Non-root user: appuser (UID 1000)
  865. ```
  866. This image is rebuilt only when tool versions change. Build time: ~12 minutes.
  867. ### Layer 2: Application Image (`Dockerfile`)
  868. Inherits from the base image and copies application code:
  869. ```
  870. FROM base image
  871. ├── COPY reversecore_mcp/ (application code)
  872. ├── COPY scripts/ (smoke test, benchmarks)
  873. ├── pip install any new requirements
  874. ├── Security package upgrades
  875. └── CMD ["python", "-m", "reversecore_mcp.server"]
  876. ```
  877. Build time: ~60 seconds.
  878. ### Docker Compose
  879. Three services with architecture-specific profiles:
  880. | Service | Profile | Description |
  881. |---|---|---|
  882. | `reversecore-mcp` | `default`, `x86` | Intel/AMD x86_64 |
  883. | `reversecore-mcp-arm64` | `arm64`, `macos` | Apple Silicon ARM64 |
  884. | `redis` | all profiles | Redis 7 Alpine for task queue and caching |
  885. Resource limits: 2.0 CPU cores, 4 GB memory per container.
  886. ---
  887. ## System Requirements
  888. | Component | Minimum | Recommended |
  889. |---|---|---|
  890. | CPU | 4 cores | 8+ cores |
  891. | RAM | 8 GB | 16 GB |
  892. | Storage | 20 GB | 50 GB SSD |
  893. | OS | Linux / macOS | Docker environment (any OS) |
  894. | Docker | 20.10+ | 24.0+ |
  895. | Python (local mode) | 3.10 | 3.11 or 3.12 |
  896. ---
  897. ## Project Structure
  898. ```
  899. reversecore_mcp/
  900. ├── core/ # Infrastructure layer (37 modules)
  901. │ ├── config.py # Pydantic BaseSettings (34+ env vars)
  902. │ ├── exceptions.py # Exception hierarchy (17 classes, RCMCP-E* codes)
  903. │ ├── security.py # Input sanitization & command arg validation
  904. │ ├── validators.py # Path validators (TOCTOU-hardened, symlink-safe)
  905. │ ├── r2_pool.py # Thread-safe Radare2 connection pool
  906. │ ├── r2_helpers.py # Structured Radare2 output parsing
  907. │ ├── metrics.py # Per-tool timing, counts, error rates, cache stats
  908. │ ├── decorators.py # @log_execution, @track_metrics
  909. │ ├── error_handling.py # @handle_tool_errors decorator
  910. │ ├── error_formatting.py # Structured error formatting
  911. │ ├── execution.py # Safe subprocess with timeout/output limits
  912. │ ├── command_spec.py # Command specifications
  913. │ ├── memory.py # Async SQLite AI memory store
  914. │ ├── mitre_mapper.py # MITRE ATT&CK mapping engine
  915. │ ├── evidence.py # Evidence classification (OBSERVED/INFERRED/POSSIBLE)
  916. │ ├── resilience.py # Retry, circuit-breaker, timeout patterns
  917. │ ├── task_queue.py # Background task queue (Redis + arq)
  918. │ ├── extension_registry.py # Plugin registration system
  919. │ ├── arch_registry.py # Multi-arch mapping (x86/ARM/MIPS/RISC-V/PPC)
  920. │ ├── result_cache.py # SHA256-based tool result caching
  921. │ ├── analysis_cache.py # Multi-level decompilation cache (Redis + SQLite)
  922. │ ├── result.py # ToolSuccess / ToolError Pydantic models
  923. │ ├── loader.py # Dynamic tool module loader
  924. │ ├── plugin.py # Plugin base class
  925. │ ├── extension.py # Extension base class
  926. │ ├── container.py # Container/sandbox execution
  927. │ ├── audit.py # Audit logging
  928. │ ├── binary_cache.py # Binary file caching
  929. │ ├── json_utils.py # orjson-backed JSON (3-5x faster)
  930. │ ├── logging_config.py # Loguru logging configuration
  931. │ ├── report_generator.py # Report rendering (Markdown, PDF)
  932. │ ├── resource_manager.py # MCP resource lifecycle
  933. │ └── sast/ # Source code scanners
  934. │ ├── python_ast_scanner.py # Python AST vulnerability scanner
  935. │ ├── regex_scanner.py # C/C++ regex vulnerability scanner
  936. │ ├── rule_manager.py # SAST rule loader
  937. │ └── default_rules.yaml # Default scanning rules
  938. │
  939. ├── tools/ # MCP tool implementations (194 tools)
  940. │ ├── analysis/ # Static analysis (24 tools)
  941. │ │ ├── static_analysis.py # file, strings, binwalk
  942. │ │ ├── lief_tools.py # LIEF binary parser
  943. │ │ ├── capa_tools.py # CAPA capability detection
  944. │ │ ├── die_tools.py # Detect It Easy packer detection
  945. │ │ ├── diff_tools.py # Binary diffing
  946. │ │ ├── emulation_tools.py # ESIL emulation
  947. │ │ ├── fuzz_tools.py # Fuzzing harness generator
  948. │ │ ├── fuzzing_campaign.py # Full fuzzing campaign runner
  949. │ │ ├── symbolic_analysis.py # angr symbolic execution
  950. │ │ ├── signature_tools.py # Library signature matching
  951. │ │ ├── source_auditor.py # SAST (Python + C/C++)
  952. │ │ ├── crash_triage.py # GDB crash triage
  953. │ │ ├── taint_analysis.py # Source→sink taint tracing
  954. │ │ ├── advanced_yara.py # Advanced YARA generation
  955. │ │ ├── patch_vuln_inference.py # Patch vulnerability inference
  956. │ │ └── cache_tools.py # Analysis cache management
  957. │ │
  958. │ ├── radare2/ # Disassembly & decompilation (30 tools)
  959. │ │ ├── radare2_mcp_tools.py # Core Radare2 tool set
  960. │ │ ├── r2ghidra_tools.py # r2ghidra decompiler (cached)
  961. │ │ ├── r2_analysis.py # Deep function analysis
  962. │ │ ├── r2_db.py # SQLite annotation + cache DB
  963. │ │ ├── r2_esil_simulator.py # Multi-arch ESIL simulator
  964. │ │ └── r2_session.py # Stateful analysis sessions
  965. │ │
  966. │ ├── malware/ # Threat detection (9 tools)
  967. │ │ ├── dormant_detector.py # Backdoor/logic bomb detection
  968. │ │ ├── ioc_tools.py # IOC extraction
  969. │ │ ├── yara_tools.py # YARA scanning
  970. │ │ ├── adaptive_vaccine.py # YARA rule + patch generation
  971. │ │ ├── vulnerability_hunter.py # Dangerous API detection
  972. │ │ ├── autonomous_hunter.py # Autonomous vuln hunting pipeline
  973. │ │ ├── heap_exploit.py # Heap exploitation analysis
  974. │ │ ├── poc_generator.py # PoC exploit generation
  975. │ │ └── rop_builder.py # ROP chain construction
  976. │ │
  977. │ ├── forensics/ # Digital forensics (22 tools)
  978. │ │ ├── memory.py # Volatility3 memory forensics
  979. │ │ ├── network.py # Scapy PCAP analysis
  980. │ │ ├── disk.py # Sleuth Kit disk forensics
  981. │ │ └── artifact.py # Browser/registry/event log analysis
  982. │ │
  983. │ ├── report/ # Report generation (14 tools)
  984. │ │ ├── report_mcp_tools.py # MCP-registered report tools
  985. │ │ ├── report_tools.py # Report rendering logic
  986. │ │ ├── session.py # Session state management
  987. │ │ ├── converter.py # Format conversion (Markdown → PDF/HTML)
  988. │ │ ├── email.py # SMTP report delivery
  989. │ │ ├── sigma_generator.py # SIGMA rule generation
  990. │ │ └── vex_generator.py # VEX report generation
  991. │ │
  992. │ └── common/ # Shared utilities (20 tools)
  993. │ ├── file_operations.py # File ops, workspace management
  994. │ ├── server_tools.py # Server health, tool metrics
  995. │ ├── memory_tools.py # AI memory management (11 tools)
  996. │ ├── patch_explainer.py # Binary patch explanation
  997. │ └── assembler.py # Keystone assembler
  998. │
  999. ├── prompts/ # AI reasoning prompts (22 modes)
  1000. │ ├── malware.py # 9 malware analysis prompts
  1001. │ ├── security.py # 6 security research prompts
  1002. │ ├── cve_research.py # 5 CVE/exploit research prompts
  1003. │ ├── game.py # Game client analysis prompt
  1004. │ ├── report.py # Report generation prompt
  1005. │ ├── server_health.py # Server inspection prompts
  1006. │ └── common.py # Shared constants (DOCKER_PATH_RULE, LANGUAGE_RULE)
  1007. │
  1008. ├── dashboard/ # Web dashboard (FastAPI + HTMX)
  1009. │ ├── templates/ # Jinja2 templates with HTMX fragments
  1010. │ └── static/ # htmx.min.js (local, CSP-compliant)
  1011. │
  1012. ├── web/ # HTTP transport layer
  1013. │ ├── auth.py # API key authentication middleware
  1014. │ ├── middleware.py # Security headers, loopback restriction
  1015. │ └── endpoints.py # /health, file upload, dashboard routes
  1016. │
  1017. ├── resources.py # 11 MCP resources (static + dynamic per-binary)
  1018. └── server.py # FastMCP server entry point
  1019. ```
  1020. **Other directories:**
  1021. ```
  1022. tests/
  1023. ├── unit/ # 1,957 unit tests
  1024. ├── integration/ # Docker-based integration tests
  1025. ├── fixtures/ # Test binaries, YARA rules, sample data
  1026. └── conftest.py # Shared pytest fixtures
  1027. scripts/
  1028. ├── smoke_test.py # Multi-layer in-container smoke test
  1029. ├── check_release_metadata.py # Version consistency validation
  1030. ├── fetch_test_binaries.py # Download test fixtures
  1031. ├── run-docker.sh # Auto-detect architecture and start
  1032. └── ... # Benchmarks, analysis scripts
  1033. docs/
  1034. ├── getting-started/ # Installation guide
  1035. ├── development/ # Architecture, contributing, testing guides
  1036. ├── api/ # Tool and module reference
  1037. └── user-guide/ # Analysis workflows
  1038. ```
  1039. ---
  1040. ## Error Handling
  1041. All custom exceptions inherit from `ReversecoreError` and carry structured error codes:
  1042. | Exception | Code | Type | When |
  1043. |---|---|---|---|
  1044. | `ReversecoreError` | `RCMCP-E000` | `UNKNOWN_ERROR` | Base class for all errors |
  1045. | `ValidationError` | `RCMCP-E001` | `VALIDATION_ERROR` | Invalid input, bad parameters |
  1046. | `ExecutionTimeoutError` | `RCMCP-E002` | `TIMEOUT_ERROR` | Tool exceeded timeout |
  1047. | `ToolNotFoundError` | `RCMCP-E003` | `TOOL_ERROR` | Required CLI tool not installed |
  1048. | `OutputLimitExceededError` | `RCMCP-E004` | `OUTPUT_ERROR` | Output exceeded max size |
  1049. | `ToolExecutionError` | `RCMCP-E005` | `EXECUTION_ERROR` | Subprocess returned non-zero |
  1050. | `BinaryAnalysisError` | `RCMCP-E100` | `BINARY_ANALYSIS_ERROR` | General binary analysis failure |
  1051. | `DecompilationError` | `RCMCP-E101` | `DECOMPILATION_ERROR` | r2ghidra decompilation failed |
  1052. | `DisassemblyError` | `RCMCP-E102` | `DISASSEMBLY_ERROR` | Radare2 disassembly failed |
  1053. | `StructureRecoveryError` | `RCMCP-E103` | `STRUCTURE_RECOVERY_ERROR` | C struct recovery failed |
  1054. | `SignatureGenerationError` | `RCMCP-E104` | `SIGNATURE_GENERATION_ERROR` | YARA/signature generation failed |
  1055. | `EmulationError` | `RCMCP-E105` | `EMULATION_ERROR` | ESIL emulation failed |
  1056. | `ToolTimeoutError` | `RCMCP-E200` | `TOOL_TIMEOUT_ERROR` | External tool timed out |
  1057. | `GhidraConnectionError` | `RCMCP-E201` | `GHIDRA_CONNECTION_ERROR` | r2ghidra connection issue |
  1058. | `Radare2Error` | `RCMCP-E202` | `RADARE2_ERROR` | Radare2 command failed |
  1059. | `WorkspaceError` | `RCMCP-E300` | `WORKSPACE_ERROR` | Workspace file access error |
  1060. | `SecurityViolationError` | `RCMCP-E301` | `SECURITY_VIOLATION` | Security policy violation |
  1061. | `PathTraversalError` | `RCMCP-E302` | `PATH_TRAVERSAL` | Path traversal attempt detected |
  1062. 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.
  1063. ---
  1064. ## Adding New Tools
  1065. Follow this pattern to add a new MCP tool:
  1066. ```python
  1067. # reversecore_mcp/tools/analysis/my_tool.py
  1068. from reversecore_mcp.core.decorators import log_execution
  1069. from reversecore_mcp.core.result import ToolResult, success, failure
  1070. from reversecore_mcp.core.security import validate_file_path
  1071. @log_execution()
  1072. async def my_analysis_tool(
  1073. file_path: str,
  1074. option: str | None = None,
  1075. ) -> ToolResult:
  1076. """Analyze a binary for X.
  1077. Args:
  1078. file_path: Path to the binary file (relative to workspace).
  1079. option: Optional analysis option.
  1080. Returns:
  1081. ToolResult with status='success' and structured content.
  1082. """
  1083. try:
  1084. safe_path = validate_file_path(file_path)
  1085. result = await perform_analysis(safe_path)
  1086. return success({"result": result})
  1087. except Exception as e:
  1088. return failure(
  1089. error_code="RCMCP-E100",
  1090. message=str(e),
  1091. hint="Check that the file exists and is a valid binary.",
  1092. )
  1093. ```
  1094. Then register it in the appropriate plugin's `__init__.py` and add tests in `tests/unit/`.
  1095. ---
  1096. ## Contributing
  1097. 1. Fork the repository
  1098. 2. Create a feature branch: `git checkout -b feat/my-feature`
  1099. 3. Write tests alongside your code — coverage must not drop below 80%
  1100. 4. Ensure all gates pass: `pytest`, `ruff check`, `mypy`, `bandit`
  1101. 5. Open a pull request with a clear description
  1102. Please read the [Contributing Guide](docs/development/contributing.md) for code standards, docstring conventions (Google-style), and the pull request checklist.
  1103. ---
  1104. ## Documentation
  1105. | Document | Description |
  1106. |---|---|
  1107. | [Installation Guide](docs/getting-started/installation.md) | Detailed setup for all environments |
  1108. | [Architecture Guide](docs/development/architecture.md) | System design & component details |
  1109. | [Contributing Guide](docs/development/contributing.md) | Code standards, docstrings, PR workflow |
  1110. | [Testing Guide](docs/development/testing.md) | Test patterns, fixtures, and coverage |
  1111. | [API Reference](docs/api/) | Tool and module reference |
  1112. | [User Guide](docs/user-guide/) | Analysis workflows |
  1113. ---
  1114. ## Usage Examples
  1115. ### Example 1: Basic Malware Triage
  1116. ```
  1117. User: "Analyze this suspicious file sample.exe"
  1118. AI calls:
  1119. 1. run_file("sample.exe") → PE32 executable, x86, MSVC
  1120. 2. detect_packer("sample.exe") → Not packed
  1121. 3. extract_iocs("sample.exe") → 3 IPs, 2 URLs, 1 mutex
  1122. 4. run_capa("sample.exe") → "creates persistence", "encrypts data"
  1123. 5. dormant_detector("sample.exe") → 2 orphan functions with network calls
  1124. 6. generate_yara_rule("sample.exe") → Detection rule generated
  1125. AI response: "This PE32 binary shows ransomware-like behavior. CAPA detected
  1126. encryption and persistence capabilities. I found 2 hidden network functions
  1127. that may serve as a backup C2 channel. Here's a YARA rule for detection..."
  1128. ```
  1129. ### Example 2: Vulnerability Research with Taint Analysis
  1130. ```
  1131. User: "Find exploitable bugs in this network daemon"
  1132. AI activates: taint_analysis_mode
  1133. AI calls:
  1134. 1. taint_trace("daemon", verify_with_angr=True)
  1135. → Found 3 source→sink paths:
  1136. recv() → strcpy() [CWE-120, CONFIRMED by angr]
  1137. read() → sprintf() [CWE-134, LIKELY]
  1138. getenv() → system() [CWE-78, POSSIBLE]
  1139. 2. vulnerability_hunter("daemon")
  1140. → 12 dangerous API calls, 4 exploitable patterns
  1141. 3. generate_poc_exploit(target="daemon", vuln_type="bof", offset=128)
  1142. → Python exploit script generated
  1143. AI response: "I found a confirmed stack buffer overflow where recv() data
  1144. flows directly into strcpy() at 0x40123C. angr proved the path is reachable.
  1145. Here's a working PoC..."
  1146. ```
  1147. ### Example 3: Digital Forensics Investigation
  1148. ```
  1149. User: "Analyze this memory dump from a compromised server"
  1150. AI calls:
  1151. 1. memory_list_processes("memdump.raw")
  1152. → 47 processes, 2 with suspicious names
  1153. 2. memory_detect_injections("memdump.raw")
  1154. → Code injection detected in PID 1842 (svchost.exe)
  1155. 3. memory_extract_strings("memdump.raw", pid=1842)
  1156. → C2 domain strings extracted
  1157. 4. artifact_correlate_ioc(artifacts={"domains": ["evil-c2.com"]})
  1158. → Matches known APT group IOCs
  1159. 5. create_analysis_report(template_type="full_analysis")
  1160. → PDF report with timeline and MITRE ATT&CK mapping
  1161. ```
  1162. ### Example 4: Patch Diffing for 1-day Research
  1163. ```
  1164. User: "Compare the patched and unpatched versions to find what was fixed"
  1165. AI activates: patch_diff_auto_mode
  1166. AI calls:
  1167. 1. diff_binaries("libfoo-1.0.so", "libfoo-1.1.so")
  1168. → 3 functions changed, 1 new function
  1169. 2. patch_diff_1day("libfoo-1.0.so", "libfoo-1.1.so")
  1170. → Automated analysis: bounds check added at parse_header()
  1171. 3. r2_decompile("libfoo-1.0.so", "parse_header")
  1172. → Decompiled vulnerable version (no bounds check)
  1173. 4. r2_decompile("libfoo-1.1.so", "parse_header")
  1174. → Decompiled patched version (memcpy size limited)
  1175. AI response: "The patch adds a bounds check in parse_header() at 0x12340.
  1176. The old version copies user-controlled length bytes via memcpy without
  1177. validation, creating a heap buffer overflow (CWE-122)."
  1178. ```
  1179. ---
  1180. ## Multi-Architecture Support
  1181. The `arch_registry.py` module maps architecture names to Radare2 configuration parameters, enabling tools to work across different CPU architectures without manual configuration:
  1182. | Architecture | Key | r2 Arch | Bit Widths | PC Register | SP Register |
  1183. |---|---|---|---|---|---|
  1184. | Intel 32-bit | `x86` | `x86` | 32 | `eip` | `esp` |
  1185. | Intel/AMD 64-bit | `x86_64` | `x86` | 64 | `rip` | `rsp` |
  1186. | ARM 32-bit / Thumb | `arm32` | `arm` | 16, 32 | `r15` | `r13` |
  1187. | ARM 64-bit (AArch64) | `arm64` | `arm` | 64 | `pc` | `sp` |
  1188. | MIPS | `mips` | `mips` | 32, 64 | `pc` | `sp` |
  1189. | RISC-V | `riscv` | `riscv` | 32, 64 | `pc` | `sp` |
  1190. | PowerPC | `ppc` | `ppc` | 32, 64 | `pc` | `r1` |
  1191. **Alias resolution** is handled automatically:
  1192. - `amd64` → `x86_64`
  1193. - `aarch64` → `arm64`
  1194. - `arm` with `bits=64` → `arm64`
  1195. - `arm` with `bits=16` or `bits=32` → `arm32`
  1196. Tools like `Radare2_esil_emulate`, `assemble_instructions`, and `r2_simulate_patch` use this registry to configure the analysis environment correctly for any target binary.
  1197. ---
  1198. ## Result Cache System
  1199. Two caching layers minimize redundant computation:
  1200. ### Tool Result Cache (`result_cache.py`)
  1201. 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:
  1202. ```
  1203. Cache key = SHA256( "<tool_name>::{sorted_json_kwargs}" )
  1204. ```
  1205. **Storage backend:** SQLite database via `r2_db.py`, accessible through `get_cached_result()` and `set_cached_result()` tools.
  1206. **Metrics:** Cache hits and misses are tracked via `metrics_collector.record_cache_hit()` and `record_cache_miss()`, visible through the `get_tool_metrics` tool.
  1207. ### Analysis Cache (`analysis_cache.py`)
  1208. A multi-level cache specifically for decompilation results (which are expensive to compute):
  1209. | Level | Backend | Key Format | TTL | Purpose |
  1210. |---|---|---|---|---|
  1211. | L1 | Redis | `ghidra:decompile:{file_hash}:{function_address}:{decompiler}` | 1 hour (3600s) | Fast, shared across sessions |
  1212. | L2 | SQLite | Table `decompilation_cache` | Persistent | Survives Redis restarts |
  1213. **Import/Export:** The `export_analysis_cache` and `import_analysis_cache` tools allow saving cache state to/from `rcpack` files for sharing between environments.
  1214. ---
  1215. ## AI Memory System
  1216. The AI memory system (`memory_tools.py` + `core/memory.py`) provides persistent, queryable storage for analysis findings across sessions. This allows the AI to:
  1217. - **Remember** what it previously found about a binary
  1218. - **Cross-reference** findings between different samples
  1219. - **Tag** and **search** sessions by topic, malware family, or technique
  1220. ### How It Works
  1221. ```
  1222. create_memory_session("analysis of ransomware sample")
  1223. │
  1224. ├── store_analysis_finding("Found AES-256 encryption at 0x401000", tags=["crypto", "ransomware"])
  1225. ├── store_analysis_finding("C2 beacon interval: 30 seconds", tags=["c2", "network"])
  1226. └── tag_analysis_session(tags=["ransomware", "financial-sector"])
  1227. # Later, in a different session:
  1228. query_analysis_memories("ransomware encryption")
  1229. → Returns previous findings about ransomware encryption patterns
  1230. get_binary_analysis_context("sample.exe")
  1231. → Returns all findings ever recorded for this binary
  1232. ```
  1233. **Storage:** Async SQLite database at the path configured by `MEMORY_DB_PATH` (default: `~/.reversecore_mcp/memory.db`).
  1234. **Portability:** Use `export_memory_store` and `import_memory_store` to transfer the entire memory database between environments.
  1235. ---
  1236. ## Web Dashboard
  1237. When running in HTTP mode (`MCP_TRANSPORT=http`), a web dashboard is available at `http://localhost:8000/dashboard`. It provides:
  1238. - Binary upload with drag-and-drop
  1239. - Real-time analysis status
  1240. - Interactive function list and disassembly view
  1241. - IOC extraction results
  1242. - Server health monitoring
  1243. **Tech stack:** FastAPI + Jinja2 templates + HTMX (loaded locally from `dashboard/static/`, no CDN dependency for CSP compliance).
  1244. **Security features:**
  1245. - CSRF tokens on all state-changing forms
  1246. - Jinja2 auto-escaping enabled
  1247. - All user input sanitized via `html.escape()` before display
  1248. - Path traversal protection via `validate_file_path()`
  1249. ---
  1250. ## Deployment
  1251. ### Production Checklist
  1252. Before deploying to production:
  1253. | Item | How |
  1254. |---|---|
  1255. | Set API key | `MCP_API_KEY=<strong-random-key>` |
  1256. | Use non-root user | Built-in: container runs as `appuser` (UID 1000) |
  1257. | Set resource limits | Default: 2 CPU / 4 GB RAM in `docker-compose.yml` |
  1258. | Enable structured logging | `LOG_FORMAT=json` for log aggregation |
  1259. | Configure Redis | `REDIS_URL=redis://<host>:6379/0` for task queue and caching |
  1260. | Set workspace path | `REVERSECORE_WORKSPACE=/path/to/isolated/directory` |
  1261. | Review rate limits | `REVERSECORE_RATE_LIMIT=60` (requests/min, adjust as needed) |
  1262. | Enable sandbox | `REVERSECORE_SANDBOX_ENABLED=true` for dynamic analysis isolation |
  1263. ### Health Checks
  1264. The server provides HTTP health check endpoints for orchestration:
  1265. ```bash
  1266. # Liveness (always 200 if process is running)
  1267. curl http://localhost:8000/health/live
  1268. # Readiness (checks tool availability)
  1269. curl http://localhost:8000/health/ready
  1270. # Full health (requires API key if configured)
  1271. curl -H "X-API-Key: <key>" http://localhost:8000/health
  1272. ```
  1273. These endpoints are exempted from API key authentication so load balancers and container orchestrators can probe them.
  1274. ### Container Healthcheck
  1275. 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.
  1276. ---
  1277. ## Troubleshooting
  1278. ### Common Issues
  1279. <details>
  1280. <summary><b>Tool returns RCMCP-E003: Tool not found</b></summary>
  1281. The required CLI tool is not installed in the environment.
  1282. **Solution:** If using Docker, verify the tool is in the base image:
  1283. ```bash
  1284. docker exec reversecore-mcp-arm64 which r2 yara binwalk tsk_recover gdb
  1285. ```
  1286. If using local Python installation, install the missing tool:
  1287. ```bash
  1288. # macOS
  1289. brew install radare2 yara binwalk sleuthkit
  1290. # Ubuntu/Debian
  1291. apt install radare2 yara binwalk sleuthkit
  1292. ```
  1293. </details>
  1294. <details>
  1295. <summary><b>Timeout error (RCMCP-E002 / RCMCP-E200)</b></summary>
  1296. Analysis exceeded the configured timeout.
  1297. **Solution:** Increase the timeout:
  1298. ```bash
  1299. export REVERSECORE_DEFAULT_TOOL_TIMEOUT=300 # 5 minutes
  1300. ```
  1301. For large binaries (>100 MB), consider using quick-scan variants:
  1302. - `run_capa_quick` instead of `run_capa`
  1303. - `detect_packer` instead of `detect_packer_deep`
  1304. </details>
  1305. <details>
  1306. <summary><b>Path traversal error (RCMCP-E302)</b></summary>
  1307. You referenced a file outside the workspace directory.
  1308. **Solution:** Copy the file into the workspace first:
  1309. ```
  1310. copy_to_workspace("/path/to/file.exe")
  1311. ```
  1312. Or mount additional directories as read-only:
  1313. ```bash
  1314. export REVERSECORE_READ_DIRS=/opt/samples,/mnt/evidence
  1315. ```
  1316. </details>
  1317. <details>
  1318. <summary><b>Docker container won't start on Apple Silicon</b></summary>
  1319. Make sure you're using the ARM64 profile:
  1320. ```bash
  1321. docker compose --profile arm64 up -d
  1322. ```
  1323. Or use the auto-detection script:
  1324. ```bash
  1325. ./scripts/run-docker.sh
  1326. ```
  1327. </details>
  1328. <details>
  1329. <summary><b>Redis connection refused</b></summary>
  1330. The task queue requires a running Redis instance.
  1331. **Solution:** Start Redis alongside the main service:
  1332. ```bash
  1333. docker compose --profile arm64 up -d # Starts both reversecore and redis
  1334. ```
  1335. Or disable Redis-dependent features by not setting `REDIS_URL`.
  1336. </details>
  1337. <details>
  1338. <summary><b>r2ghidra decompilation produces empty output</b></summary>
  1339. This usually means the function wasn't analyzed first.
  1340. **Solution:** Run analysis before decompilation:
  1341. ```
  1342. Radare2_analyze_binary("sample.exe")
  1343. Radare2_decompile_function("sample.exe", "main")
  1344. ```
  1345. </details>
  1346. ---
  1347. ## FAQ
  1348. <details>
  1349. <summary><b>Does this replace Ghidra or IDA Pro?</b></summary>
  1350. 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.
  1351. </details>
  1352. <details>
  1353. <summary><b>Is a separate Ghidra or JDK installation needed?</b></summary>
  1354. 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.
  1355. </details>
  1356. <details>
  1357. <summary><b>What MCP clients are supported?</b></summary>
  1358. 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.
  1359. </details>
  1360. <details>
  1361. <summary><b>Can I analyze Windows PE files on Linux/macOS?</b></summary>
  1362. 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.
  1363. </details>
  1364. <details>
  1365. <summary><b>How safe is it to analyze malware with this tool?</b></summary>
  1366. 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.
  1367. </details>
  1368. <details>
  1369. <summary><b>What's the maximum file size?</b></summary>
  1370. Default limits:
  1371. - Upload: 100 MB (`MAX_UPLOAD_SIZE`)
  1372. - LIEF parsing: 1 GB (`REVERSECORE_LIEF_MAX_FILE_SIZE`)
  1373. - Tool output: 10 MB (`REVERSECORE_MAX_OUTPUT_SIZE`)
  1374. All limits are configurable via environment variables.
  1375. </details>
  1376. ---
  1377. ## Acknowledgments
  1378. This project is built on the work of many open-source projects:
  1379. | Project | Role in Reversecore MCP |
  1380. |---|---|
  1381. | [Radare2](https://radare.org/) | Disassembly, emulation, binary analysis |
  1382. | [r2ghidra](https://github.com/radareorg/r2ghidra) | Ghidra decompiler engine for Radare2 |
  1383. | [FastMCP](https://github.com/jlowin/fastmcp) | MCP server framework |
  1384. | [YARA](https://virustotal.github.io/yara/) | Pattern matching for malware detection |
  1385. | [LIEF](https://lief-project.github.io/) | Binary format parsing (PE, ELF, Mach-O) |
  1386. | [CAPA](https://github.com/mandiant/capa) | Mandiant FLARE capability detection |
  1387. | [angr](https://angr.io/) | Symbolic execution engine |
  1388. | [Capstone](https://www.capstone-engine.org/) | Disassembly framework |
  1389. | [Keystone](https://www.keystone-engine.org/) | Assembly framework |
  1390. | [pwntools](https://github.com/Gallopsled/pwntools) | Exploit development toolkit |
  1391. | [ROPgadget](https://github.com/JonathanSalwan/ROPgadget) | ROP gadget finder |
  1392. | [Volatility3](https://github.com/volatilityfoundation/volatility3) | Memory forensics framework |
  1393. | [Scapy](https://scapy.net/) | Network packet analysis |
  1394. | [Sleuth Kit](https://sleuthkit.org/) | Disk forensics toolkit |
  1395. | [Binwalk](https://github.com/ReFirmLabs/binwalk) | Firmware analysis |
  1396. | [Detect It Easy](https://github.com/horsicq/DIE-engine) | Packer/compiler detection |
  1397. ---
  1398. ## License
  1399. MIT — see [LICENSE](LICENSE) for details.
  1400. ---
  1401. <div align="center">
  1402. **[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/)**
  1403. </div>
install.ps1 · Bundled script · 124 lines · 1 finding marked
  1. # ==============================================================================
  2. # Reversecore_MCP One-line Installer & Setup Wizard (Windows PowerShell)
  3. #
  4. # Usage:
  5. # 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
  6. # .\install.ps1 [options]
  7. # ==============================================================================
  8. [CmdletBinding()]
  9. param(
  10. [switch]$All,
  11. [string]$Clients,
  12. [string]$Mode = "auto",
  13. [switch]$Docker,
  14. [switch]$Uvx,
  15. [switch]$Pipx,
  16. [string]$Command,
  17. [string[]]$Args,
  18. [switch]$DryRun,
  19. [switch]$Remove,
  20. [switch]$List,
  21. [switch]$Tiered
  22. )
  23. $ErrorActionPreference = "Stop"
  24. function Find-Python {
  25. $candidates = @("python", "py -3.12", "py -3.11", "py -3.10", "py")
  26. foreach ($cmd in $candidates) {
  27. try {
  28. $parts = $cmd.Split(" ")
  29. $exe = $parts[0]
  30. $cmdArgs = @()
  31. if ($parts.Length -gt 1) {
  32. $cmdArgs = $parts[1..($parts.Length - 1)]
  33. }
  34. $testArgs = $cmdArgs + @("-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')")
  35. $ver = & $exe $testArgs 2>$null
  36. if ($ver -and [version]$ver -ge [version]"3.10") {
  37. return $cmd
  38. }
  39. } catch {}
  40. }
  41. return $null
  42. }
  43. # Pass-through arguments to python setup script
  44. $passArgs = @($args)
  45. if ($All) { $passArgs += "--all" }
  46. if ($Clients) { $passArgs += @("--clients", $Clients) }
  47. if ($Docker) { $passArgs += "--docker" }
  48. if ($Uvx) { $passArgs += "--uvx" }
  49. if ($Pipx) { $passArgs += "--pipx" }
  50. if ($Command) { $passArgs += @("--command", $Command) }
  51. if ($DryRun) { $passArgs += "--dry-run" }
  52. if ($Remove) { $passArgs += "--remove" }
  53. if ($List) { $passArgs += "--list" }
  54. if ($Tiered) { $passArgs += "--tiered" }
  55. # If inside local repository clone
  56. if (Test-Path "reversecore_mcp\setup.py") {
  57. if (Test-Path "venv\Scripts\python.exe") {
  58. & "venv\Scripts\python.exe" -m reversecore_mcp.setup @passArgs
  59. exit $LASTEXITCODE
  60. }
  61. $py = Find-Python
  62. if ($py) {
  63. $parts = $py.Split(" ")
  64. $exe = $parts[0]
  65. $cmdArgs = @()
  66. if ($parts.Length -gt 1) {
  67. $cmdArgs = $parts[1..($parts.Length - 1)]
  68. }
  69. & $exe ($cmdArgs + @("-m", "reversecore_mcp.setup") + $passArgs)
  70. exit $LASTEXITCODE
  71. }
  72. }
  73. # If reversecore-mcp is in PATH
  74. if (Get-Command "reversecore-mcp" -ErrorAction SilentlyContinue) {
  75. & reversecore-mcp setup @passArgs
  76. exit $LASTEXITCODE
  77. }
  78. # If uvx is available
  79. if (Get-Command "uvx" -ErrorAction SilentlyContinue) {
  80. Write-Host "🚀 Running Reversecore setup via uvx..." -ForegroundColor Cyan
  81. & uvx --from reversecore-mcp reversecore-setup @passArgs
  82. exit $LASTEXITCODE
  83. }
  84. # If pipx is available
  85. if (Get-Command "pipx" -ErrorAction SilentlyContinue) {
  86. Write-Host "🚀 Running Reversecore setup via pipx..." -ForegroundColor Cyan
  87. & pipx run reversecore-mcp setup @passArgs
  88. exit $LASTEXITCODE
  89. }
  90. # Fallback: install in isolated virtualenv
  91. $py = Find-Python
  92. if ($py) {
  93. $installDir = Join-Path $env:USERPROFILE ".reversecore-mcp"
  94. $venvDir = Join-Path $installDir "venv"
  95. $venvPython = Join-Path $venvDir "Scripts\python.exe"
  96. Write-Host "📦 Installing Reversecore_MCP into isolated environment: $venvDir" -ForegroundColor Cyan
  97. if (-not (Test-Path $venvDir)) {
  98. $parts = $py.Split(" ")
  99. $exe = $parts[0]
  100. $cmdArgs = @()
  101. if ($parts.Length -gt 1) {
  102. $cmdArgs = $parts[1..($parts.Length - 1)]
  103. }
  104. & $exe ($cmdArgs + @("-m", "venv", $venvDir))
  105. }
  106. Write-Host "⬇️ Fetching reversecore-mcp package..." -ForegroundColor Cyan
  107. & $venvPython -m pip install --upgrade --quiet pip reversecore-mcp
  108. & $venvPython -m reversecore_mcp.setup @passArgs
  109. exit $LASTEXITCODE
  110. }
  111. Write-Error "Python 3.10+ or uv / pipx is required to install Reversecore_MCP."
  112. exit 1
install.sh · Bundled script · 135 lines · 2 findings marked
  1. #!/usr/bin/env bash
  2. # ==============================================================================
  3. # Reversecore_MCP One-line Installer & Setup Wizard
  4. #
  5. # Usage:
  6. # 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
  7. # 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
  8. # ./install.sh [options]
  9. #
  10. # Supported Options:
  11. # --all Configure all detected clients automatically
  12. # --clients Comma-separated client list (cursor, claude_code, windsurf, etc.)
  13. # --docker Use Docker container mode
  14. # --uvx Use uvx runner mode
  15. # --pipx Use pipx runner mode
  16. # --tiered Enable Tiered Tools / Agents Mode (15 tools, >90% lower LLM context tokens)
  17. # --dry-run Preview configuration changes without writing
  18. # --remove Unregister Reversecore_MCP from clients
  19. # --list List detected clients and exit
  20. # ==============================================================================
  21. set -euo pipefail
  22. # Print banner
  23. print_banner() {
  24. cat << 'EOF'
  25. ========================================================================
  26. ____ __ __ ____ ____
  27. / __ \___ _ _____ _____________ _________ ________ / |/ // ___// __ \
  28. / /_/ / _ \ | / / _ \/ ___/ ___/ _ \/ ___/ __ \/ ___/ _ \/ /|_/ / / / / /_/ /
  29. / _, _/ __/ |/ / __/ / (__ ) __/ /__/ /_/ / / / __/ / / / / /___/ ____/
  30. /_/ |_|\___/|___/\___/_/ /____/\___/\___/\____/_/ \___/_/ /_/ \____/_/
  31. Reversecore_MCP One-line Installer & Setup Wizard
  32. ========================================================================
  33. EOF
  34. }
  35. # Restore standard input from controlling terminal when script is piped (curl | bash)
  36. restore_tty() {
  37. if [ ! -t 0 ] && [ -e /dev/tty ]; then
  38. exec 0< /dev/tty
  39. fi
  40. }
  41. # Find suitable Python 3.10+ executable
  42. find_python() {
  43. local candidate
  44. for candidate in python3 python python3.12 python3.11 python3.10; do
  45. if command -v "$candidate" >/dev/null 2>&1; then
  46. if "$candidate" -c "import sys; exit(0 if sys.version_info >= (3, 10) else 1)" 2>/dev/null; then
  47. command -v "$candidate"
  48. return 0
  49. fi
  50. fi
  51. done
  52. return 1
  53. }
  54. main() {
  55. restore_tty
  56. # If running inside a local git clone with reversecore_mcp available
  57. if [ -f "reversecore_mcp/setup.py" ]; then
  58. if [ -x "venv/bin/python" ]; then
  59. exec venv/bin/python -m reversecore_mcp.setup "$@"
  60. elif [ -x ".venv/bin/python" ]; then
  61. exec .venv/bin/python -m reversecore_mcp.setup "$@"
  62. else
  63. local local_py
  64. if local_py="$(find_python)"; then
  65. exec "$local_py" -m reversecore_mcp.setup "$@"
  66. fi
  67. fi
  68. fi
  69. # If reversecore-mcp binary is already installed and in PATH
  70. if command -v reversecore-mcp >/dev/null 2>&1; then
  71. exec reversecore-mcp setup "$@"
  72. fi
  73. # If uvx is available
  74. if command -v uvx >/dev/null 2>&1; then
  75. echo "🚀 Running Reversecore setup via uvx..."
  76. exec uvx --from reversecore-mcp reversecore-setup "$@"
  77. fi
  78. # If pipx is available
  79. if command -v pipx >/dev/null 2>&1; then
  80. echo "🚀 Running Reversecore setup via pipx..."
  81. exec pipx run reversecore-mcp setup "$@"
  82. fi
  83. # Fallback: check for Python 3.10+ and install in an isolated user environment
  84. local py_bin
  85. if py_bin="$(find_python)"; then
  86. local install_dir="$HOME/.reversecore-mcp"
  87. local venv_dir="$install_dir/venv"
  88. echo "📦 Installing Reversecore_MCP into isolated environment: $venv_dir"
  89. mkdir -p "$install_dir"
  90. if [ ! -d "$venv_dir" ]; then
  91. "$py_bin" -m venv "$venv_dir"
  92. fi
  93. echo "⬇️ Fetching reversecore-mcp package..."
  94. "$venv_dir/bin/pip" install --upgrade --quiet pip reversecore-mcp
  95. # Try to symlink executable to ~/.local/bin if directory exists or is in PATH
  96. if [ -d "$HOME/.local/bin" ]; then
  97. ln -sf "$venv_dir/bin/reversecore-mcp" "$HOME/.local/bin/reversecore-mcp" || true
  98. ln -sf "$venv_dir/bin/reversecore-setup" "$HOME/.local/bin/reversecore-setup" || true
  99. fi
  100. exec "$venv_dir/bin/python" -m reversecore_mcp.setup "$@"
  101. fi
  102. # If Docker is available and user wants Docker mode
  103. for arg in "$@"; do
  104. if [ "$arg" = "--docker" ] && command -v docker >/dev/null 2>&1; then
  105. echo "🐳 Running setup via Docker container..."
  106. exec docker run --rm -it \
  107. -v "$HOME:$HOME" \
  108. -e "HOME=$HOME" \
  109. ghcr.io/sjkim1127/reversecore-mcp:latest \
  110. python -m reversecore_mcp.setup "$@"
  111. fi
  112. done
  113. print_banner
  114. echo "❌ Error: Python 3.10+ or uv / pipx is required to install Reversecore_MCP." >&2
  115. echo "Please install Python 3.10+ (https://www.python.org/) or uv (https://astral.sh/uv)." >&2
  116. exit 1
  117. }
  118. main "$@"
reversecore_mcp/prompts/malware.py · Bundled script · 1,219 lines · 1 finding marked
  1. """Prompts for malware analysis modes."""
  2. from reversecore_mcp.prompts.common import DOCKER_PATH_RULE, LANGUAGE_RULE
  3. def full_analysis_mode(filename: str = "target_binary") -> str:
  4. """Expert mode that analyzes a file completely from A to Z with maximum AI reasoning."""
  5. return f"""
  6. You are an Elite Reverse Engineering Expert with 20+ years of experience in:
  7. - Malware analysis and threat intelligence (APT, Ransomware, RAT, Rootkits)
  8. - Binary exploitation and vulnerability research (0-day hunting)
  9. - Anti-analysis bypass and advanced evasion techniques
  10. - Cryptographic analysis and protocol reverse engineering
  11. - Firmware and embedded systems security
  12. - Code deobfuscation and unpacking (Themida, VMProtect, custom packers)
  13. Your mission: Perform a COMPREHENSIVE security analysis of '{filename}'
  14. that leaves no stone unturned. You will identify ALL threats, understand
  15. their purpose, and generate actionable intelligence.
  16. {LANGUAGE_RULE}
  17. {DOCKER_PATH_RULE}
  18. [CRITICAL: Evidence-Based Analysis Rule]
  19. ==========================================
  20. **Every finding MUST be labeled with an evidence level:**
  21. 🔍 [OBSERVED] - Directly observed through dynamic analysis, logs, or traces
  22. Example: "Procmon captured CreateMutexA('WNcry@2ol7') call"
  23. Confidence: 100%
  24. 🔎 [INFERRED] - Logically inferred from static analysis (high confidence)
  25. Example: "CryptEncrypt import suggests encryption capability"
  26. Confidence: 70-85%
  27. ❓ [POSSIBLE] - Possible based on patterns, requires verification
  28. Example: "SMB functions present, may attempt lateral movement"
  29. Confidence: 40-60%
  30. **NEVER state 'confirmed' or 'detected' for inferred/possible findings!**
  31. Use language like:
  32. - OBSERVED: "확인됨", "detected", "observed"
  33. - INFERRED: "추정됨", "likely", "suggests"
  34. - POSSIBLE: "가능성 있음", "may", "could"
  35. ═══════════════════════════════════════════════════════════════════════════
  36. ██ PHASE 1: INITIAL TRIAGE & THREAT CLASSIFICATION ██
  37. ═══════════════════════════════════════════════════════════════════════════
  38. [STEP 1.1] File Intelligence Gathering
  39. Build your initial mental model with these foundational tools:
  40. ```
  41. detect_packer("{filename}") # FIRST: Packer/Compiler/Protector detection
  42. run_file("{filename}") # File type, architecture, compiler
  43. parse_binary_with_lief("{filename}") # PE/ELF structure, sections, entropy
  44. run_strings("{filename}", min_length=5) # Extract all meaningful strings
  45. extract_iocs("{filename}") # IP, URL, Email, Bitcoin, Hashes
  46. ```
  47. **Why detect_packer First?**
  48. - If packed (UPX, Themida, VMProtect), skip deep analysis until unpacked
  49. - Compiler info helps understand the binary's origin
  50. - Protector detection guides anti-analysis strategy
  51. [REASONING CHECKPOINT 1 - THREAT HYPOTHESIS]
  52. Before proceeding, form initial hypotheses by answering:
  53. **File Characteristics:**
  54. Q1: What is the exact file format? (PE32/PE64/ELF/Mach-O/Script?)
  55. Q2: What compiler/language produced this? (MSVC/GCC/Go/Rust/Python?)
  56. Q3: Is it packed? (Section entropy > 7.0? Suspicious section names?)
  57. Q4: What's the apparent purpose? (Installer/DLL/Service/Standalone?)
  58. **Initial Threat Assessment:**
  59. Q5: Based on strings, what capabilities might this have?
  60. - Network? (socket, http, connect, send, recv)
  61. - File System? (CreateFile, DeleteFile, encrypt, ransom)
  62. - Persistence? (Registry, Service, Scheduled Task)
  63. - Credential Theft? (chrome, firefox, password, vault)
  64. - Evasion? (IsDebugger, Sleep, VM, sandbox)
  65. Q6: What malware family does this MOST LIKELY belong to?
  66. Form a hypothesis: "This appears to be [type] because [evidence]"
  67. **Threat Score (0-100):**
  68. Calculate preliminary threat score based on IOCs and strings found.
  69. ═══════════════════════════════════════════════════════════════════════════
  70. ██ PHASE 2: HIDDEN THREAT DISCOVERY ██
  71. ═══════════════════════════════════════════════════════════════════════════
  72. [STEP 2.1] Dormant Detector Analysis (Critical for APT/Backdoors)
  73. ```
  74. dormant_detector("{filename}")
  75. ```
  76. This is your PRIMARY tool for finding hidden threats. Analyze results carefully:
  77. **Orphan Functions (No Cross-References):**
  78. - Why would legitimate code have unreferenced functions?
  79. - Possible explanations: Dead code, conditional activation, backdoor
  80. - Size matters: Small orphans (<50 bytes) = likely dead code
  81. Large orphans (>100 bytes) = SUSPICIOUS, investigate!
  82. **Magic Value Triggers:**
  83. - Date/Time checks = Time bombs (activates on specific date)
  84. - Environment checks = Targeted attacks (specific hostname/user)
  85. - Network triggers = C2 activation conditions
  86. [STEP 2.2] Library Identification & Filtering
  87. ```
  88. match_libraries("{filename}")
  89. ```
  90. **Why This Matters:**
  91. - Standard library code is NOT interesting - filter it out!
  92. - Focus only on CUSTOM code that's unique to this binary
  93. - Low match percentage (< 50%) = Heavy custom code = More suspicious
  94. [REASONING CHECKPOINT 2 - THREAT CONFIRMATION]
  95. Update your hypothesis based on Phase 2 findings:
  96. **Hidden Threat Assessment:**
  97. Q7: Were orphan functions found? What do they appear to do?
  98. Q8: Were magic value triggers found? What conditions activate them?
  99. Q9: What percentage is standard library vs custom code?
  100. Q10: Does this change your initial threat hypothesis? How?
  101. **Confidence Level:**
  102. - HIGH: Clear malicious indicators found
  103. - MEDIUM: Suspicious but needs deeper analysis
  104. - LOW: Appears benign but continue analysis
  105. ═══════════════════════════════════════════════════════════════════════════
  106. ██ PHASE 3: DEEP BEHAVIORAL ANALYSIS ██
  107. ═══════════════════════════════════════════════════════════════════════════
  108. [STEP 3.1] Import Analysis - Capability Mapping
  109. ```
  110. run_radare2("{filename}", "iij")
  111. ```
  112. Map imports to MITRE ATT&CK techniques:
  113. | Import Pattern | Capability | MITRE Technique |
  114. |---------------|------------|-----------------|
  115. | CreateProcess, ShellExecute | Execution | T1059 |
  116. | RegSetValue, RegCreateKey | Persistence | T1547 |
  117. | socket, connect, send | C2 Communication | T1071 |
  118. | CryptEncrypt, CryptDecrypt | Data Encryption | T1486 |
  119. | CreateToolhelp32Snapshot | Process Discovery | T1057 |
  120. | VirtualAlloc, WriteProcessMemory | Process Injection | T1055 |
  121. | IsDebuggerPresent, CheckRemoteDebugger | Anti-Analysis | T1622 |
  122. [STEP 3.2] Cross-Reference Analysis for Suspicious APIs
  123. For each dangerous API found, trace backwards:
  124. ```
  125. analyze_xrefs("{filename}", "CreateProcessW")
  126. analyze_xrefs("{filename}", "VirtualAlloc")
  127. analyze_xrefs("{filename}", "InternetOpenW")
  128. ```
  129. **Think Like an Analyst:**
  130. - WHO calls this dangerous function?
  131. - WHAT data is passed to it?
  132. - WHEN is it called? (startup, trigger, always?)
  133. - HOW can this be weaponized?
  134. [STEP 3.3] Execution Path Tracing (Sink Analysis)
  135. ```
  136. trace_execution_path("{filename}", "system", max_depth=3)
  137. trace_execution_path("{filename}", "connect", max_depth=3)
  138. trace_execution_path("{filename}", "CryptEncrypt", max_depth=3)
  139. ```
  140. **Key Question:** Can untrusted input reach these dangerous sinks?
  141. - If YES → Potential vulnerability or intentional malicious path
  142. - If NO → Function may be used legitimately
  143. [REASONING CHECKPOINT 3 - BEHAVIORAL PROFILE]
  144. Build a complete behavioral profile:
  145. **Capabilities Confirmed:**
  146. Q11: What execution capabilities does this have?
  147. Q12: What persistence mechanisms are implemented?
  148. Q13: What data exfiltration methods exist?
  149. Q14: What evasion techniques are present?
  150. **Kill Chain Position:**
  151. Where does this fit in the cyber kill chain?
  152. [ ] Reconnaissance → [ ] Weaponization → [ ] Delivery →
  153. [ ] Exploitation → [ ] Installation → [ ] C2 → [ ] Actions
  154. ═══════════════════════════════════════════════════════════════════════════
  155. ██ PHASE 4: CODE-LEVEL DEEP DIVE ██
  156. ═══════════════════════════════════════════════════════════════════════════
  157. [STEP 4.1] Decompilation of Critical Functions
  158. For each suspicious function identified in Phases 2-3:
  159. ```
  160. r2_decompile("{filename}", "<suspicious_function_address>")
  161. ```
  162. If the code is obfuscated or complex:
  163. ```
  164. r2_decompile("{filename}", "<address>")
  165. ```
  166. **Code Analysis Framework:**
  167. When reading decompiled code, look for:
  168. 1. **String Decryption Routines:**
  169. - XOR loops, Base64, custom encoding
  170. - Key material (hardcoded or derived)
  171. 2. **Network Communication:**
  172. - C2 server addresses (IP, domain)
  173. - Protocol structure (HTTP, custom binary)
  174. - Encryption/authentication
  175. 3. **Anti-Analysis Tricks:**
  176. - Timing checks (GetTickCount differences)
  177. - Environment detection (VM, sandbox, debugger)
  178. - Self-modification (unpacking, decryption)
  179. 4. **Payload Delivery:**
  180. - Download and execute patterns
  181. - Process injection techniques
  182. - Fileless execution methods
  183. [STEP 4.2] Structure Recovery
  184. For data-heavy malware (credential stealers, etc.):
  185. ```
  186. r2_recover_structures("{filename}", "<data_handling_function>")
  187. ```
  188. **Look For:**
  189. - Credential structures (username, password, url)
  190. - Configuration structures (C2 list, encryption keys)
  191. - Exfiltration buffers
  192. [STEP 4.3] Emulation for Dynamic Behavior (If Needed)
  193. If code appears to unpack or decrypt at runtime:
  194. ```
  195. emulate_machine_code("{filename}", "<unpacking_function>", max_steps=1000)
  196. ```
  197. **Caution:** Only emulate small, contained routines.
  198. [REASONING CHECKPOINT 4 - INTENT DETERMINATION]
  199. Determine the TRUE PURPOSE of this binary:
  200. Q15: What is the PRIMARY malicious function?
  201. Q16: What is the SECONDARY function (if any)?
  202. Q17: Is this a:
  203. [ ] Dropper/Downloader → Delivers next stage
  204. [ ] RAT/Backdoor → Persistent access
  205. [ ] Stealer → Data theft
  206. [ ] Ransomware → Encryption/extortion
  207. [ ] Wiper → Destruction
  208. [ ] Loader → Executes in-memory payloads
  209. [ ] Rootkit → Stealth/persistence
  210. [ ] Cryptominer → Resource theft
  211. Q18: What's the sophistication level? (1-10)
  212. 1-3: Script kiddie / commodity malware
  213. 4-6: Professional cybercrime
  214. 7-9: Advanced threat actor / APT
  215. 10: Nation-state level
  216. ═══════════════════════════════════════════════════════════════════════════
  217. ██ PHASE 5: DEFENSE ARTIFACT GENERATION ██
  218. ═══════════════════════════════════════════════════════════════════════════
  219. [STEP 5.1] Enhanced YARA Rule Generation (Low False Positive)
  220. **IMPORTANT: Use enhanced YARA generator with structural conditions!**
  221. Simple string-only rules have HIGH false positive rates.
  222. Use `generate_enhanced_yara_rule` with structural conditions:
  223. ```python
  224. generate_enhanced_yara_rule(
  225. "{filename}",
  226. rule_name="Sample_Detection",
  227. strings=["unique_string1", "unique_string2", "unique_string3"],
  228. imports=["CryptEncrypt", "CreateServiceA"], # Optional but reduces FP
  229. file_type="PE",
  230. min_filesize=100000, # Minimum file size
  231. max_filesize=5000000, # Maximum file size
  232. section_names=[".rsrc"], # Required section names (optional)
  233. )
  234. ```
  235. **Good Enhanced YARA Signatures Include:**
  236. - Unique strings (C2 domains, mutex names, registry keys)
  237. - Structural conditions (PE header, file size range)
  238. - Import table checks (at least 1-2 dangerous APIs)
  239. - Minimum string match threshold (default: 2/3 of strings)
  240. [STEP 5.2] MITRE ATT&CK Mapping with Confidence Levels
  241. **CRITICAL: Every MITRE technique MUST have a confidence level!**
  242. Use this format in your report:
  243. | Technique ID | Name | Tactic | Confidence | Evidence |
  244. |-------------|------|--------|------------|----------|
  245. | T1486 | Data Encrypted for Impact | Impact | ✅ CONFIRMED | CryptEncrypt + ransom note strings |
  246. | T1055 | Process Injection | Defense Evasion | 🟢 HIGH | VirtualAllocEx + WriteProcessMemory imports |
  247. | T1570 | Lateral Tool Transfer | Lateral Movement | 🟡 MEDIUM | SMB API imports (no observed network activity) |
  248. | T1021 | Remote Services | Lateral Movement | 🔴 LOW | Possible based on port 445 reference |
  249. **Confidence Levels:**
  250. - ✅ CONFIRMED: Multiple independent evidence sources
  251. - 🟢 HIGH: Strong single evidence (observed or high-confidence inferred)
  252. - 🟡 MEDIUM: Inferred from API/patterns (needs verification)
  253. - 🔴 LOW: Possible based on weak indicators
  254. [STEP 5.3] Vulnerability Hunter Report (Automated)
  255. For comprehensive defense artifacts:
  256. ```
  257. vulnerability_hunter("{filename}", mode="full")
  258. ```
  259. This generates:
  260. - Detection rules (YARA)
  261. - Behavioral indicators
  262. - Remediation recommendations
  263. ═══════════════════════════════════════════════════════════════════════════
  264. ██ PHASE 6: FINAL SYNTHESIS & INTELLIGENCE REPORT ██
  265. ═══════════════════════════════════════════════════════════════════════════
  266. Synthesize ALL findings into a comprehensive intelligence report:
  267. ```markdown
  268. # 🔬 Binary Analysis Intelligence Report
  269. ## Executive Summary
  270. | Attribute | Value |
  271. |-----------|-------|
  272. | **File** | {filename} |
  273. | **SHA256** | [hash] |
  274. | **Verdict** | MALICIOUS / SUSPICIOUS / CLEAN |
  275. | **Threat Type** | [Ransomware/RAT/Stealer/etc.] |
  276. | **Sophistication** | [1-10] |
  277. | **Confidence** | [HIGH/MEDIUM/LOW] |
  278. ## Threat Overview
  279. **One-Line Summary:** [What this malware does in plain language]
  280. **Detailed Description:**
  281. [2-3 paragraphs explaining the malware's purpose, behavior, and impact]
  282. ## Technical Analysis
  283. ### File Characteristics
  284. | Property | Value |
  285. |----------|-------|
  286. | Type | PE32/PE64/ELF |
  287. | Compiler | MSVC/GCC/etc |
  288. | Packed | Yes/No (packer name) |
  289. | Size | X bytes |
  290. | Entropy | X.XX |
  291. ### Capabilities (MITRE ATT&CK Mapping with Confidence)
  292. | Technique ID | Technique Name | Tactic | Confidence | Evidence |
  293. |-------------|----------------|--------|------------|----------|
  294. | T1486 | Data Encrypted for Impact | Impact | ✅ CONFIRMED | [specific finding + source] |
  295. | T1055 | Process Injection | Defense Evasion | 🟢 HIGH | [specific finding] |
  296. | ... | ... | ... | ... | ... |
  297. ### Indicators of Compromise (IOCs)
  298. **Network:**
  299. - C2: [IP/domain]
  300. - User-Agent: [string]
  301. - URI Pattern: [path]
  302. **Host:**
  303. - Mutex: [name]
  304. - Registry: [key]
  305. - Files: [paths]
  306. **Hashes:**
  307. - SHA256: [hash]
  308. - Imphash: [hash]
  309. - SSDEEP: [hash]
  310. ### Hidden Threats Discovered
  311. | Function | Address | Purpose | Trigger |
  312. |----------|---------|---------|---------|
  313. | [name] | 0x... | [purpose] | [condition] |
  314. ### Decompiled Code Highlights
  315. ```c
  316. // Key malicious function
  317. [relevant code snippet with comments]
  318. ```
  319. ## Detection & Response
  320. ### YARA Rules
  321. ```yara
  322. [generated YARA rule]
  323. ```
  324. ### Detection Opportunities
  325. 1. **Network:** [specific signatures]
  326. 2. **Endpoint:** [behavioral indicators]
  327. 3. **Memory:** [patterns to scan for]
  328. ### Remediation Steps
  329. 1. **Immediate:** [containment actions]
  330. 2. **Short-term:** [eradication steps]
  331. 3. **Long-term:** [prevention measures]
  332. ## Analyst Notes
  333. - **Confidence Assessment:** [Detailed breakdown: X observed, Y inferred, Z possible]
  334. - **Evidence Summary:**
  335. - 🔍 Observed findings: [count] (highest confidence)
  336. - 🔎 Inferred findings: [count] (medium-high confidence)
  337. - ❓ Possible findings: [count] (requires verification)
  338. - **Gaps in Analysis:** [what couldn't be determined and why]
  339. - **Recommended Next Steps:** [additional analysis or dynamic analysis needed]
  340. - **Recommended Next Steps:** [additional analysis needed]
  341. ## Appendix
  342. - Full IOC list
  343. - All function addresses analyzed
  344. - Raw tool outputs (summarized)
  345. ```
  346. ═══════════════════════════════════════════════════════════════════════════
  347. ██ EXECUTION INSTRUCTIONS ██
  348. ═══════════════════════════════════════════════════════════════════════════
  349. BEGIN ANALYSIS NOW.
  350. **Critical Guidelines:**
  351. 1. Execute Phase 1 tools first to build your initial hypothesis
  352. 2. At each REASONING CHECKPOINT, explicitly state your thinking
  353. 3. Update your hypothesis as new evidence emerges
  354. 4. Don't skip phases - each builds on the previous
  355. 5. Show confidence levels for each major conclusion
  356. 6. If you hit a dead end, explain why and adjust approach
  357. **Quality Standards:**
  358. - Every claim must have supporting evidence
  359. - Every tool call must have a clear purpose
  360. - Every finding must map to a threat or be explicitly ruled out
  361. - The final report must be actionable for defenders
  362. Remember: You are not just running tools - you are THINKING like an expert
  363. malware analyst. Each finding should trigger new questions and hypotheses.
  364. The goal is UNDERSTANDING, not just detection.
  365. START PHASE 1 NOW.
  366. """
  367. def malware_analysis_mode(filename: str = "target_binary") -> str:
  368. """Focused analysis on Malware behaviors (Ransomware, Stealer, Backdoor)."""
  369. return f"""
  370. You are a Malware Analyst.
  371. Analyze the file '{filename}' focusing on malicious behaviors and indicators of compromise (IOCs).
  372. {LANGUAGE_RULE}
  373. {DOCKER_PATH_RULE}
  374. [CRITICAL: Evidence-Based Analysis]
  375. ==========================================
  376. **Every finding MUST be labeled with an evidence level:**
  377. 🔍 [OBSERVED] - Directly observed (sandbox, Procmon, API trace)
  378. Confidence: 100% - Use "detected", "confirmed", "확인됨"
  379. 🔎 [INFERRED] - Inferred from static analysis (imports, strings)
  380. Confidence: 70-85% - Use "likely", "suggests", "추정됨"
  381. ❓ [POSSIBLE] - Possible based on patterns (needs verification)
  382. Confidence: 40-60% - Use "may", "could", "가능성 있음"
  383. [Analysis SOP]
  384. 1. Behavioral Triage:
  385. - Check for Ransomware indicators (crypto constants, file enumeration) using `run_yara` and `run_strings`.
  386. - Check for Stealer behaviors (browser paths, credential vaults) using `run_strings`.
  387. - Check for Backdoor/C2 (socket APIs, connect, listen) using `run_radare2` imports.
  388. → Label each finding: [🔍 OBSERVED] or [🔎 INFERRED]
  389. 2. Evasion Detection:
  390. - Use `dormant_detector` to find anti-analysis tricks (IsDebuggerPresent, sleep loops, time checks).
  391. - Check for packing using `parse_binary_with_lief`.
  392. → Orphan functions = [❓ POSSIBLE] hidden behavior
  393. 3. Persistence Mechanism:
  394. - Look for Registry keys (Run, RunOnce), Service creation, or Scheduled Tasks in strings or imports.
  395. → API import only = [🔎 INFERRED], Registry log = [🔍 OBSERVED]
  396. 4. Payload Analysis:
  397. - Decompile suspicious functions using `r2_decompile` to understand the payload logic.
  398. 5. Reporting:
  399. - Map behaviors to MITRE ATT&CK framework with confidence levels:
  400. | Technique | Confidence | Evidence |
  401. |-----------|------------|----------|
  402. | T1486 | ✅ CONFIRMED | CryptEncrypt + ransom note |
  403. | T1055 | 🟢 HIGH | VirtualAllocEx import |
  404. - Extract all IOCs (C2, Hashes, Mutexes).
  405. - Generate enhanced YARA rule: `generate_enhanced_yara_rule()` with structural conditions.
  406. """
  407. def basic_analysis_mode(filename: str = "target_binary") -> str:
  408. """Rapid analysis mode that quickly identifies basic static analysis and threat elements."""
  409. return f"""
  410. You are a Reverse Engineering Security Analyst.
  411. Perform 'Rapid Static Analysis' on the file '{filename}' to identify initial threats.
  412. {LANGUAGE_RULE}
  413. {DOCKER_PATH_RULE}
  414. [Analysis SOP (Standard Operating Procedure)]
  415. Never use time-consuming deep analysis tools (Ghidra, Decompile, Emulation).
  416. Use only the following lightweight tools to get results quickly:
  417. 0. Packer Detection (FIRST!):
  418. - `detect_packer("{filename}")`: Check for packer/compiler/protector.
  419. - If packed → Note packer name and consider unpacking before deep analysis.
  420. 1. Identification:
  421. - `run_file("{filename}")`: Identify the exact file type.
  422. - `parse_binary_with_lief("{filename}")`: Check binary structure, entropy, and section information to determine packing status.
  423. 2. Strings & IOCs Analysis:
  424. - `run_strings("{filename}", min_length=5)`: Extract meaningful strings.
  425. - Based on the results, run `extract_iocs` to identify C2 IPs, URLs, emails, Bitcoin addresses, etc.
  426. 3. API & Capabilities Summary:
  427. - `run_radare2("{filename}", "ii")`: Quickly list import functions to infer the file's main behavior (network connection, file manipulation, etc.).
  428. 4. Quick Triage Report:
  429. - Summarize the file's identity, major IOCs found, and suspicious API behaviors.
  430. - Estimate the probability of the file being malicious (High/Medium/Low).
  431. - Advise the next step:
  432. * General Malware -> `malware_analysis_mode`
  433. * Complex/Hidden Threats -> `full_analysis_mode` or `apt_hunting_mode`
  434. * Game/Firmware -> Specialized modes
  435. """
  436. def apt_hunting_mode(filename: str = "target_binary") -> str:
  437. """Advanced Persistent Threat (APT) detection using Dormant Detector and Smart Decompiler."""
  438. return f"""
  439. You are an APT Hunter - specialized in detecting sophisticated, state-sponsored malware.
  440. Analyze '{filename}' for APT indicators using advanced signature technologies.
  441. {LANGUAGE_RULE}
  442. {DOCKER_PATH_RULE}
  443. [CRITICAL: Evidence-Based Analysis]
  444. ==========================================
  445. APT hunting requires RIGOROUS evidence standards. Never speculate without evidence.
  446. 🔍 [OBSERVED] - Dynamic analysis confirmed (sandbox, memory forensics)
  447. Example: "Network capture shows C2 beacon to 1.2.3.4:443"
  448. 🔎 [INFERRED] - High-confidence static analysis
  449. Example: "Custom XOR encryption routine at 0x401000"
  450. ❓ [POSSIBLE] - Pattern matching, needs verification
  451. Example: "Code similarity with APT29 tooling"
  452. **Attribution requires MULTIPLE [🔍 OBSERVED] + [🔎 INFERRED] findings!**
  453. [APT Hunting SOP]
  454. 1. Dormant Detector Analysis (Primary Detection):
  455. Use `dormant_detector("{filename}")` to find APT characteristics:
  456. - Orphan Functions: APTs often hide backdoors in unused code paths [❓ POSSIBLE]
  457. - Magic Value Triggers: Look for date/time bombs or environment checks [🔎 INFERRED]
  458. - Conditional Execution: APT malware activates only in specific conditions
  459. 2. Smart Decompiler Refinement:
  460. For each suspicious function from Dormant Detector:
  461. - Run `r2_decompile("{filename}", address)`
  462. - Analyze refined code for APT patterns
  463. 3. MITRE ATT&CK with Confidence Levels:
  464. | Technique ID | Name | Confidence | Evidence Source |
  465. |-------------|------|------------|------------------|
  466. | T1055 | Process Injection | 🟢 HIGH | [🔎 INFERRED] VirtualAllocEx+WriteProcessMemory |
  467. | T1071.001 | HTTPS C2 | ✅ CONFIRMED | [🔍 OBSERVED] PCAP + [🔎 INFERRED] imports |
  468. | T1070.006 | Timestomping | 🟡 MEDIUM | [🔎 INFERRED] SetFileTime import |
  469. 4. APT Attribution Standards:
  470. - NEVER attribute without multiple independent evidence sources
  471. - Use "Code similarities suggest" not "This is APT29"
  472. - List evidence explicitly for any attribution claim
  473. 5. Defense Generation:
  474. If APT confirmed:
  475. - Use `generate_enhanced_yara_rule()` with structural conditions
  476. - Document TTPs with evidence levels
  477. - Create IOC list with confidence ratings
  478. [Report Format]
  479. ## 🎯 APT Hunting Report
  480. ### Evidence Summary
  481. | Level | Count | Examples |
  482. |-------|-------|----------|
  483. | 🔍 OBSERVED | X | (list key findings) |
  484. | 🔎 INFERRED | Y | (list key findings) |
  485. | ❓ POSSIBLE | Z | (list hypotheses) |
  486. ### Dormant Detector Findings
  487. - Orphan Functions: [count] [❓ POSSIBLE hidden functionality]
  488. - Logic Bombs: [triggers found] [🔎 INFERRED/🔍 OBSERVED]
  489. - Emulation Results: [ESIL verification] [🔍 OBSERVED]
  490. ### APT Assessment
  491. - Sophistication Level: [1-10] (evidence-based)
  492. - Attribution: ["Possible APT29" or "Unknown - insufficient evidence"]
  493. - Confidence: [✅ CONFIRMED / 🟢 HIGH / 🟡 MEDIUM / 🔴 LOW]
  494. - Key Evidence: [list of evidence supporting attribution]
  495. Begin APT analysis now.
  496. """
  497. def malware_defense_mode(filename: str = "target_binary") -> str:
  498. """Automated 3-phase threat detection and defense generation (DISCOVER → UNDERSTAND → NEUTRALIZE)."""
  499. return f"""
  500. You are a Malware Defense Specialist - an elite automated threat hunter.
  501. Execute a complete defense automation workflow on '{filename}' using the Malware Defense System.
  502. {LANGUAGE_RULE}
  503. {DOCKER_PATH_RULE}
  504. [Malware Defense SOP - 3 Phase Pipeline]
  505. OPTION 1: Full Automation (Recommended)
  506. ----------------------------------------
  507. Use `vulnerability_hunter("{filename}", mode="full")` for complete automation:
  508. - Phase 1 (DISCOVER): Dormant Detector finds hidden threats
  509. - Phase 2 (UNDERSTAND): Smart Decompiler analyzes intent
  510. - Phase 3 (NEUTRALIZE): Adaptive Vaccine generates defenses
  511. This single command will:
  512. 1. Scan for orphan functions and logic bombs
  513. 2. Analyze suspicious code with AI-powered decompilation
  514. 3. Generate YARA rules and provide actionable recommendations
  515. 4. Return a comprehensive threat report with confidence scores
  516. OPTION 2: Step-by-Step (For Complex Analysis)
  517. ----------------------------------------------
  518. If you need granular control, execute phases manually:
  519. Phase 1 - DISCOVER:
  520. - `dormant_detector("{filename}")` → Find hidden threats
  521. - Review orphan_functions and suspicious_logic in results
  522. - Identify high-priority targets for Phase 2
  523. Phase 2 - UNDERSTAND:
  524. For each threat found in Phase 1:
  525. - `r2_decompile("{filename}", address)` → Get readable code
  526. - Analyze the refined_code to understand intent
  527. - Look for patterns: backdoor, time_bomb, data_exfiltration
  528. Phase 3 - NEUTRALIZE:
  529. For confirmed threats:
  530. - `adaptive_vaccine(threat_report, action="yara")` → Generate detection rule
  531. - Deploy YARA rules to endpoints
  532. - Follow recommendations from Malware Defense report
  533. [Output Requirements]
  534. Present results in this format:
  535. ## 🛡️ Malware Defense Analysis Report
  536. ### Phase 1: Discovery Results
  537. - Threats Discovered: [count]
  538. - Orphan Functions: [list]
  539. - Suspicious Logic: [list]
  540. ### Phase 2: Threat Understanding
  541. For each threat:
  542. - Function: [name @ address]
  543. - Intent: [backdoor/time_bomb/etc.]
  544. - Confidence: [0.0-1.0]
  545. - Key Code Snippet: [refined code]
  546. ### Phase 3: Defense Measures
  547. - YARA Rules Generated: [count]
  548. - Recommendations:
  549. * Immediate Actions
  550. * Investigation Steps
  551. * Remediation Plan
  552. ### Final Verdict
  553. - Overall Risk: CRITICAL/HIGH/MEDIUM/LOW
  554. - Recommended Actions: [priority list]
  555. Start Malware Defense System now.
  556. """
  557. def unpacking_mode(filename: str = "target_binary") -> str:
  558. """Guide for unpacking packed binaries (UPX, Themida, VMProtect, custom packers)."""
  559. return f"""
  560. You are an Expert Binary Unpacker with deep knowledge of packing techniques.
  561. Your mission: Analyze and unpack '{filename}' to reveal the original code.
  562. {LANGUAGE_RULE}
  563. {DOCKER_PATH_RULE}
  564. ═══════════════════════════════════════════════════════════════════════════
  565. ██ PHASE 1: PACKER IDENTIFICATION & ENTROPY QUANTIFICATION ██
  566. ═══════════════════════════════════════════════════════════════════════════
  567. 1. Automated Packer Signature Scan:
  568. ```
  569. detect_packer("{filename}")
  570. detect_packer_deep("{filename}")
  571. ```
  572. 2. Quantitative Section Entropy & Header Analysis:
  573. Run LIEF analysis to inspect sections:
  574. ```
  575. parse_binary_with_lief("{filename}")
  576. ```
  577. Identify packing indicator thresholds:
  578. - **High Entropy**: Check the `entropy` field of each section. Any section with `entropy > 7.0` indicates encryption or high compression (packed).
  579. - **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.
  580. - **Suspicious Section Names**: Keep an eye out for standard packer section names (e.g., `.UPX0`, `.UPX1`, `.themida`, `.vmp0`, `PESpin`).
  581. 3. Heuristic Manual Fallback:
  582. If automated scanners return no packer detection but entropy is high, scan strings for packer/protector signatures:
  583. ```
  584. run_strings("{filename}", min_length=4)
  585. ```
  586. Filter output for keyword signatures: `UPX!`, `Themida`, `VMProtect`, `ASPack`, `PESpin`, `MEW`, `Upack`.
  587. ═══════════════════════════════════════════════════════════════════════════
  588. ██ PHASE 2: UNPACKING STRATEGY & STATIC DEOBFUSCATION ██
  589. ═══════════════════════════════════════════════════════════════════════════
  590. Choose your strategy based on packer characteristics:
  591. **UPX / Compressed (Simple)**
  592. - Try standard CLI unpacking: run `upx -d {filename}` (if upx CLI is installed).
  593. - If modified UPX headers block CLI decompression, locate the tail jump manually.
  594. **Virtualized/Virtual VMs (Themida/VMProtect)**
  595. - Static analysis is extremely difficult due to VM handlers.
  596. - 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.
  597. **Custom Packer Stub Analysis**
  598. - Find the entrypoint stub:
  599. ```
  600. r2_decompile("{filename}", "entry0")
  601. ```
  602. Look for:
  603. - Large memory allocation APIs: `VirtualAlloc`, `VirtualProtect`.
  604. - Dynamic API loaders: `LoadLibraryA`, `GetProcAddress`.
  605. - Decryption loop structures: XOR/ADD loops over a byte array.
  606. ═══════════════════════════════════════════════════════════════════════════
  607. ██ PHASE 3: ORIGINAL ENTRY POINT (OEP) DISCOVERY ██
  608. ═══════════════════════════════════════════════════════════════════════════
  609. To locate the Original Entry Point (OEP) where control transitions from packer stub to original executable:
  610. 1. Disassemble around the packer entrypoint:
  611. ```
  612. Radare2_run_command("{filename}", "pdf @ entry0")
  613. ```
  614. 2. Identify OEP Transition Patterns:
  615. - **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.
  616. - **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).
  617. 3. Verify OEP Header Signatures:
  618. Decompile the target address to check if it matches compiler startup entry sequences:
  619. - MSVC: `call __security_init_cookie` or `jmp __tmainCRTStartup`
  620. - GCC: `xor ebp, ebp` followed by `pop rsi` or `mov rdx, rsp`
  621. ═══════════════════════════════════════════════════════════════════════════
  622. ██ REPORT FORMAT ██
  623. ═══════════════════════════════════════════════════════════════════════════
  624. ## 📦 Unpacking Analysis Report
  625. ### 1. Packer Profile
  626. - **Identified Packer**: [e.g., UPX / Themida / Custom / None]
  627. - **Section Entropy**: [List sections with entropy > 7.0]
  628. - **Header Anomalies**: [e.g., RawSize vs VirtualSize differences]
  629. ### 2. Stub Analysis
  630. - **Unpacking Logic**: [e.g., VirtualAlloc + XOR Decryption loop detected]
  631. - **Dynamic API Resolvers**: [e.g., LoadLibrary/GetProcAddress xrefs]
  632. ### 3. Entry Point Transitions
  633. - **Stub Entry Address**: `0x...`
  634. - **Tail Jump Address**: `0x...`
  635. - **Suspected OEP**: `0x...`
  636. ### 4. Next Steps
  637. - Recommended unpacking procedure and OEP patching instructions.
  638. """
  639. def c2_extraction_mode(filename: str = "target_binary") -> str:
  640. """Specialized analysis for extracting C2 (Command & Control) server information."""
  641. return f"""
  642. You are a C2 Infrastructure Analyst specializing in extracting command and control details.
  643. Your mission: Extract ALL C2 communication details from '{filename}' using data-flow tracing.
  644. {LANGUAGE_RULE}
  645. {DOCKER_PATH_RULE}
  646. ═══════════════════════════════════════════════════════════════════════════
  647. ██ PHASE 1: AUTOMATED IOC & ENCODED STRING SCANNING ██
  648. ═══════════════════════════════════════════════════════════════════════════
  649. 1. Extract Config & Direct Network Indicators:
  650. ```
  651. extract_iocs("{filename}")
  652. run_strings("{filename}", min_length=5)
  653. ```
  654. 2. Identify Encoded Config blocks:
  655. Look for base64 strings (`=`, `==` padding), high-entropy byte blobs (potential XOR encrypted data), or registry string targets.
  656. ═══════════════════════════════════════════════════════════════════════════
  657. ██ PHASE 2: API CROSS-REFERENCE & ARGUMENT TRACING (SOP) ██
  658. ═══════════════════════════════════════════════════════════════════════════
  659. Follow this systematic procedure to trace where C2 endpoints are stored in memory and loaded at runtime:
  660. 1. Find Network API Imports:
  661. ```
  662. Radare2_list_imports("{filename}")
  663. ```
  664. Look for: `connect`, `InternetConnectA`, `InternetConnectW`, `getaddrinfo`, `WSAConnect`, `InternetOpenUrlA`, `HttpOpenRequestA`.
  665. 2. Query Cross-References (Xrefs) to Connections:
  666. For every network API found, check who calls it. Example:
  667. ```
  668. Radare2_xrefs_to("{filename}", "connect")
  669. ```
  670. 3. Trace Register/Stack Loading Arguments:
  671. For each xref calling address, decompile or disassemble the calling context:
  672. ```
  673. r2_decompile("{filename}", "<calling_function_address_or_symbol>")
  674. ```
  675. If decompilation is partial, dump raw assembly surrounding the call site:
  676. ```
  677. Radare2_run_command("{filename}", "pd 20 @ <xref_call_offset-0x30>")
  678. ```
  679. - **Analyze Parameter Loading**:
  680. - In x64 calling conventions: Check registers `rcx` (1st arg), `rdx` (2nd arg - socket address struct containing IP/Port), `r8` (3rd arg), `r9` (4th arg).
  681. - In x86 calling conventions: Look at the `push` instructions preceding the `call` instruction.
  682. - **Identify Static Buffer Offsets**:
  683. Look for instructions like `lea rdx, [0x40a000]` or `mov dword [esp+4], 0x40a000`. This address `0x40a000` is the static C2 config buffer.
  684. 4. Extract Hardcoded Memory Buffers:
  685. Dump the strings or raw bytes directly from the static buffer address found in the previous step:
  686. ```
  687. Radare2_run_command("{filename}", "ps @ <buffer_address_e.g._0x40a000>")
  688. Radare2_run_command("{filename}", "px 128 @ <buffer_address_e.g._0x40a000>")
  689. ```
  690. If bytes look obfuscated, check for a preceding decryption loop (e.g. XOR with a key byte) in the calling function.
  691. ═══════════════════════════════════════════════════════════════════════════
  692. ██ PHASE 3: PROTOCOL & COMMAND STRUCTURE ANALYSIS ██
  693. ═══════════════════════════════════════════════════════════════════════════
  694. 1. Decompile Packet Formatting logic:
  695. Locate the functions sending data (`send`, `sendto`, `WSASend`, `InternetWriteFile`) and trace backwards to see how the buffer is populated:
  696. ```
  697. r2_decompile("{filename}", "<send_function_caller>")
  698. ```
  699. 2. Extract C2 Configuration Structs:
  700. If the binary parses structured config files (e.g., custom JSON or binary blobs), recover the structural layout:
  701. ```
  702. r2_recover_structures("{filename}", "<config_parsing_function>")
  703. ```
  704. 3. Document C2 Commands:
  705. 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).
  706. ═══════════════════════════════════════════════════════════════════════════
  707. ██ REPORT FORMAT ██
  708. ═══════════════════════════════════════════════════════════════════════════
  709. ## 🌐 C2 Extraction Report
  710. ### 1. C2 Servers Identified
  711. | Role | Endpoint (IP/Domain) | Port | Transport | Confidence |
  712. |------|----------------------|------|-----------|------------|
  713. | Primary | [value] | [port] | [e.g. TCP/HTTPS] | [HIGH/MED] |
  714. | Backup | [value] | [port] | [e.g. DNS] | [LOW] |
  715. ### 2. Argument Tracing Path
  716. - **Target Network API**: `[e.g., InternetConnectA]`
  717. - **Call Site Offset**: `0x...`
  718. - **Parameter Register/Stack Offset**: `[e.g. RDX / push 0x40a080]`
  719. - **Static Configuration Buffer**: `0x...`
  720. - **Obfuscation**: [e.g. Plaintext / XOR 0x5A Key / Base64]
  721. ### 3. C2 Protocol Specs
  722. - **User-Agent / Headers**: [Captured strings]
  723. - **Beacon Interval**: [Pattern / Hardcoded seconds]
  724. - **Opcode Command Table**:
  725. | Command Opcode | Handler Function | Action / Purpose |
  726. |----------------|------------------|------------------|
  727. | `0x...` | `sym.func_...` | [e.g., Execute shell command] |
  728. ### 4. Extracted IOCs for Network Defense
  729. ```
  730. # Domain Blocks
  731. [Domain List]
  732. # IP Blocks
  733. [IP List]
  734. ```
  735. Begin C2 extraction now.
  736. """
  737. def ransomware_triage_mode(filename: str = "target_binary") -> str:
  738. """Specialized analysis for ransomware - encryption, keys, recovery potential."""
  739. return f"""
  740. You are a Ransomware Response Specialist.
  741. Your mission: Analyze '{filename}' to assess encryption strength and recovery possibility.
  742. {LANGUAGE_RULE}
  743. {DOCKER_PATH_RULE}
  744. ⚠️ CRITICAL: This is time-sensitive incident response!
  745. Focus on: Can victims recover their files WITHOUT paying?
  746. [PHASE 1: RANSOMWARE IDENTIFICATION]
  747. ===================================
  748. 1. Initial Triage:
  749. ```
  750. detect_packer("{filename}")
  751. run_file("{filename}")
  752. run_strings("{filename}", min_length=5)
  753. ```
  754. 2. Look for ransomware indicators:
  755. - Ransom note text ("Your files are encrypted", "Bitcoin", "decrypt")
  756. - File extension patterns (.encrypted, .locked, .cry)
  757. - Known ransomware family signatures
  758. 3. Check YARA rules:
  759. ```
  760. run_yara("{filename}", "ransomware_rules.yar")
  761. ```
  762. [PHASE 2: ENCRYPTION ANALYSIS]
  763. =============================
  764. 1. Identify crypto imports:
  765. ```
  766. run_radare2("{filename}", "iij")
  767. ```
  768. Key APIs:
  769. | API | Implication |
  770. |-----|-------------|
  771. | CryptEncrypt | Windows Crypto API |
  772. | CryptGenKey | Key generation |
  773. | CryptAcquireContext | Crypto provider |
  774. | BCryptEncrypt | Modern crypto |
  775. | OpenSSL functions | OpenSSL crypto |
  776. 2. Look for crypto constants:
  777. - AES S-boxes
  778. - RSA public exponents (0x10001)
  779. - ChaCha20 constants
  780. - Salsa20 sigma
  781. 3. Analyze encryption routine:
  782. ```
  783. r2_decompile("{filename}", "<crypto_function>")
  784. ```
  785. [PHASE 3: KEY RECOVERY ASSESSMENT]
  786. =================================
  787. **Recovery Possibility Checklist:**
  788. ✅ POSSIBLE RECOVERY if:
  789. - [ ] Key derived from predictable seed (time, hostname)
  790. - [ ] Key hardcoded in binary
  791. - [ ] Weak RNG used (CRT rand(), GetTickCount)
  792. - [ ] Key stored locally before C2 contact
  793. - [ ] Implementation bugs (ECB mode, key reuse)
  794. ❌ UNLIKELY RECOVERY if:
  795. - [ ] RSA + AES hybrid with online key
  796. - [ ] Keys sent to C2 before encryption
  797. - [ ] Strong RNG (CryptGenRandom, /dev/urandom)
  798. - [ ] Proper implementation (CBC/GCM, unique IVs)
  799. 1. Check for key material:
  800. ```
  801. run_strings("{filename}", min_length=16)
  802. ```
  803. Look for: Base64 keys, hex strings (32/64 chars)
  804. 2. Analyze key generation:
  805. ```
  806. analyze_xrefs("{filename}", "CryptGenKey")
  807. r2_decompile("{filename}", "<keygen_function>")
  808. ```
  809. [PHASE 4: FILE TARGETING ANALYSIS]
  810. =================================
  811. 1. What files are targeted?
  812. - File extensions (docs, images, databases)
  813. - Directory exclusions (Windows, Program Files)
  814. 2. Encryption scope:
  815. - Full file encryption
  816. - Partial (first N bytes)
  817. - Alternating blocks
  818. [REPORT FORMAT]
  819. ===============
  820. ## 🔐 Ransomware Triage Report
  821. ### Executive Summary
  822. | Attribute | Value |
  823. |-----------|-------|
  824. | Family | [known family or "Unknown"] |
  825. | Recovery Possible | ✅ YES / ⚠️ MAYBE / ❌ NO |
  826. | Encryption | [algorithm] |
  827. | Key Type | [symmetric/asymmetric/hybrid] |
  828. ### Encryption Details
  829. - Algorithm: AES-256-CBC / RSA-2048 / ChaCha20 / etc.
  830. - Mode: ECB / CBC / GCM / CTR
  831. - Key Generation: [method]
  832. - IV/Nonce: [handling]
  833. ### Recovery Assessment
  834. **Confidence: [HIGH/MEDIUM/LOW]**
  835. Weaknesses Found:
  836. - [ ] [weakness 1 with evidence]
  837. - [ ] [weakness 2 with evidence]
  838. Recovery Steps (if possible):
  839. 1. [step 1]
  840. 2. [step 2]
  841. ### IOCs
  842. - Ransom note: [filename]
  843. - Extension: [.xxx]
  844. - Mutex: [name]
  845. - Registry: [keys]
  846. ### Recommendations
  847. 1. **Immediate**: [containment steps]
  848. 2. **Recovery**: [decryption options]
  849. 3. **Prevention**: [future protection]
  850. Begin ransomware triage now. TIME IS CRITICAL!
  851. """
  852. def code_similarity_mode(filename: str = "target_binary") -> str:
  853. """Binary similarity analysis for variant detection and clustering."""
  854. return f"""
  855. You are a Binary Similarity Analyst specializing in malware variant identification.
  856. Your mission: Analyze '{filename}' to identify code similarities with known families.
  857. {LANGUAGE_RULE}
  858. {DOCKER_PATH_RULE}
  859. [PHASE 1: SIGNATURE GENERATION]
  860. ==============================
  861. 1. Generate unique signatures:
  862. ```
  863. generate_signature("{filename}", "entry0")
  864. parse_binary_with_lief("{filename}")
  865. ```
  866. 2. Extract identifying features:
  867. - Import hash (imphash)
  868. - Section hashes
  869. - Rich header hash
  870. - TLSH (Trend Micro Locality Sensitive Hash)
  871. 3. Get function-level hashes:
  872. ```
  873. run_radare2("{filename}", "afl")
  874. ```
  875. [PHASE 2: LIBRARY IDENTIFICATION]
  876. ================================
  877. 1. Match against known libraries:
  878. ```
  879. match_libraries("{filename}")
  880. ```
  881. 2. Calculate custom code percentage:
  882. - High custom % = likely unique malware
  883. - Low custom % = mostly standard code
  884. [PHASE 3: VARIANT COMPARISON]
  885. ============================
  886. If comparing with another sample:
  887. ```
  888. diff_binaries("{filename}", "<comparison_file>")
  889. analyze_variant_changes("{filename}", "<comparison_file>")
  890. ```
  891. Look for:
  892. - Function additions/removals
  893. - String changes (C2, versions)
  894. - Behavior modifications
  895. - Packer changes
  896. [PHASE 4: FAMILY ATTRIBUTION]
  897. ============================
  898. Based on collected signatures:
  899. 1. Compare with known families:
  900. | Feature | This Sample | Known Family |
  901. |---------|-------------|--------------|
  902. | Imphash | xxx | yyy |
  903. | Strings | [list] | [list] |
  904. | APIs | [list] | [list] |
  905. 2. Similarity scoring:
  906. - > 90%: Same family/variant
  907. - 70-90%: Related/modified
  908. - 50-70%: Possible connection
  909. - < 50%: Unlikely related
  910. [PHASE 5: CLUSTERING INDICATORS]
  911. ===============================
  912. Generate indicators for clustering:
  913. 1. Unique code patterns
  914. 2. String constants (mutex, paths)
  915. 3. Network patterns (domains, ports)
  916. 4. Behavioral signatures
  917. [REPORT FORMAT]
  918. ===============
  919. ## 🔍 Code Similarity Analysis Report
  920. ### Sample Identification
  921. | Attribute | Value |
  922. |-----------|-------|
  923. | SHA256 | [hash] |
  924. | Imphash | [hash] |
  925. | SSDEEP | [hash] |
  926. | File Type | [type] |
  927. ### Signature Summary
  928. - Custom Code: [X]%
  929. - Library Code: [Y]%
  930. - Unique Functions: [count]
  931. ### Family Attribution
  932. | Family | Similarity | Confidence | Evidence |
  933. |--------|------------|------------|----------|
  934. | [name] | XX% | HIGH/MED | [evidence] |
  935. ### Variant Analysis (if applicable)
  936. Changes from baseline:
  937. - Added: [functions/strings]
  938. - Removed: [functions/strings]
  939. - Modified: [behaviors]
  940. ### Clustering Indicators
  941. ```yara
  942. // YARA rule for clustering
  943. rule Similar_Family {{
  944. strings:
  945. $s1 = "[unique string]"
  946. condition:
  947. all of them
  948. }}
  949. ```
  950. ### Related Samples
  951. | Hash | Similarity | Notes |
  952. |------|------------|-------|
  953. | [hash] | XX% | [notes] |
  954. Begin similarity analysis now.
  955. """
reversecore_mcp/prompts/report.py · Bundled script · 113 lines · 1 finding marked
  1. """Prompts for report generation."""
  2. from reversecore_mcp.prompts.common import DOCKER_PATH_RULE, LANGUAGE_RULE
  3. def report_generation_mode(filename: str = "target_binary") -> str:
  4. """Generate professional malware analysis reports with accurate timestamps and IOC tracking."""
  5. return f"""
  6. You are a Security Report Specialist generating professional malware analysis documentation.
  7. Your task is to analyze '{filename}' and create a comprehensive, shareable report using the actual report session tools.
  8. {LANGUAGE_RULE}
  9. {DOCKER_PATH_RULE}
  10. ═══════════════════════════════════════════════════════════════════════════
  11. ██ REPORT GENERATION WORKFLOW ██
  12. ═══════════════════════════════════════════════════════════════════════════
  13. [STEP 1] Initialize Analysis Session
  14. First, get accurate system time and start a tracking session:
  15. ```
  16. get_system_time() # Get server timestamp (prevents date hallucination)
  17. start_report_session(
  18. binary_name="{filename}"
  19. )
  20. ```
  21. [STEP 2] Perform Analysis & Collect Evidence
  22. Conduct your analysis using appropriate tools (e.g., dormant_detector, run_strings, r2_decompile, etc.).
  23. [STEP 3] Collect IOCs During Analysis
  24. As you find indicators, add them to the session:
  25. ```
  26. add_ioc(ioc_type="hash", value="SHA256:abc123...", confidence="high")
  27. add_ioc(ioc_type="ip", value="192.168.1.100", confidence="high")
  28. add_ioc(ioc_type="domain", value="malware-c2.com", confidence="medium")
  29. 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
  30. ```
  31. Valid ioc_types: hash, ip, domain, url, file, registry, mutex, email, other
  32. Valid confidences: low, medium, high
  33. [STEP 4] Document MITRE ATT&CK Techniques
  34. Map behaviors to MITRE framework:
  35. ```
  36. add_mitre_technique(technique_id="T1059.001", technique_name="PowerShell", tactic="Execution")
  37. add_mitre_technique(technique_id="T1547.001", technique_name="Registry Run Keys", tactic="Persistence")
  38. add_mitre_technique(technique_id="T1071.001", technique_name="Web Protocols", tactic="Command and Control")
  39. ```
  40. [STEP 5] Add Analysis Notes
  41. Document important findings:
  42. ```
  43. add_analysis_note(note="Found encrypted config at 0x401000", category="finding")
  44. add_analysis_note(note="Sample connects to C2 on port 443", category="behavior")
  45. add_analysis_note(note="Anti-VM checks detected", category="warning")
  46. ```
  47. Note categories: general, finding, warning, important, behavior
  48. **Tip: Label each note with evidence level!**
  49. ```
  50. add_analysis_note(note="[🔍 OBSERVED] Procmon captured registry write to Run key", category="finding")
  51. add_analysis_note(note="[🔎 INFERRED] CryptEncrypt import suggests encryption capability", category="finding")
  52. add_analysis_note(note="[❓ POSSIBLE] SMB functions may enable lateral movement", category="warning")
  53. ```
  54. [STEP 6] Set Severity and Tags
  55. ```
  56. set_severity("high")
  57. ```
  58. Valid severities: low, medium, high, critical
  59. [STEP 7] End Session and Generate Report
  60. ```
  61. end_report_session(summary="Brief summary of findings...")
  62. create_analysis_report(
  63. template_type="full_analysis", # full_analysis, quick_triage, ioc_summary, executive_brief
  64. classification="TLP:AMBER"
  65. )
  66. ```
  67. [CRITICAL: Evidence Summary in Report]
  68. The final report MUST include an evidence summary:
  69. ## Confidence Assessment
  70. | Evidence Level | Count | Key Findings |
  71. |----------------|-------|---------------|
  72. | 🔍 OBSERVED | X | (sandbox, logs, traces) |
  73. | 🔎 INFERRED | Y | (static analysis) |
  74. | ❓ POSSIBLE | Z | (needs verification) |
  75. **Overall Confidence**: [✅ CONFIRMED / 🟢 HIGH / 🟡 MEDIUM / 🔴 LOW]
  76. ═══════════════════════════════════════════════════════════════════════════
  77. ██ AVAILABLE REPORT TEMPLATES ██
  78. ═══════════════════════════════════════════════════════════════════════════
  79. | Template | Purpose |
  80. |----------|---------|
  81. | `full_analysis` | Complete technical report with all details |
  82. | `quick_triage` | Rapid assessment summary |
  83. | `ioc_summary` | IOC-focused export |
  84. | `executive_brief` | Non-technical summary for management |
  85. Begin report generation workflow now.
  86. """
reversecore_mcp/tools/analysis/vt_lookup.py · Bundled script · 312 lines · 1 finding marked
  1. """VirusTotal IOC reputation lookup tool.
  2. Queries the VirusTotal API v3 for IP addresses, domain names, URLs,
  3. and file hashes extracted from binary analysis (e.g. from extract_iocs).
  4. Requires: REVERSECORE_VT_API_KEY environment variable.
  5. Available tools (MCP-registered):
  6. vt_lookup — Bulk IOC reputation check via VirusTotal API v3
  7. """
  8. from __future__ import annotations
  9. import asyncio
  10. import ipaddress
  11. import re
  12. from typing import Any
  13. from reversecore_mcp.core.config import get_config
  14. from reversecore_mcp.core.decorators import log_execution
  15. from reversecore_mcp.core.error_handling import handle_tool_errors
  16. from reversecore_mcp.core.logging_config import get_logger
  17. from reversecore_mcp.core.metrics import track_metrics
  18. from reversecore_mcp.core.result import ToolResult, failure, success
  19. logger = get_logger(__name__)
  20. # ---------------------------------------------------------------------------
  21. # IOC type detection
  22. # ---------------------------------------------------------------------------
  23. _IPV4_RE = re.compile(r"^(\d{1,3}\.){3}\d{1,3}$")
  24. _HASH_RE = re.compile(r"^[0-9a-fA-F]{32}$|^[0-9a-fA-F]{40}$|^[0-9a-fA-F]{64}$")
  25. _URL_RE = re.compile(r"^https?://", re.IGNORECASE)
  26. _DOMAIN_RE = re.compile(
  27. r"^(?=.{1,253}\.?$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}\.?$"
  28. )
  29. def _classify_ioc(ioc: str) -> str:
  30. """Classify a single IOC string into: ip, domain, url, hash, or unknown."""
  31. ioc = ioc.strip()
  32. if _HASH_RE.match(ioc):
  33. return "hash"
  34. if _URL_RE.match(ioc):
  35. return "url"
  36. try:
  37. ipaddress.ip_address(ioc)
  38. return "ip"
  39. except ValueError:
  40. pass
  41. # Require valid DNS labels and a non-numeric top-level domain.
  42. if _DOMAIN_RE.fullmatch(ioc):
  43. return "domain"
  44. return "unknown"
  45. def _vt_url_for(ioc_type: str, ioc: str) -> str:
  46. """Return the VT API v3 endpoint URL for the given IOC."""
  47. import base64
  48. if ioc_type == "ip":
  49. return f"https://www.virustotal.com/api/v3/ip_addresses/{ioc}"
  50. elif ioc_type == "domain":
  51. return f"https://www.virustotal.com/api/v3/domains/{ioc}"
  52. elif ioc_type == "hash":
  53. return f"https://www.virustotal.com/api/v3/files/{ioc.lower()}"
  54. elif ioc_type == "url":
  55. # VT URL lookups require base64url-encoded URL (without padding)
  56. encoded = base64.urlsafe_b64encode(ioc.encode()).rstrip(b"=").decode()
  57. return f"https://www.virustotal.com/api/v3/urls/{encoded}"
  58. return ""
  59. def _extract_verdict(data: dict[str, Any], ioc_type: str) -> dict[str, Any]:
  60. """Extract the key reputation fields from a VT API v3 response."""
  61. attrs = data.get("attributes", {})
  62. last_analysis = attrs.get("last_analysis_stats", {})
  63. malicious = last_analysis.get("malicious", 0)
  64. suspicious = last_analysis.get("suspicious", 0)
  65. total = sum(last_analysis.values()) if last_analysis else 0
  66. # Determine verdict
  67. if malicious >= 5:
  68. verdict = "malicious"
  69. elif malicious >= 1 or suspicious >= 3:
  70. verdict = "suspicious"
  71. elif total > 0:
  72. verdict = "clean"
  73. else:
  74. verdict = "no_data"
  75. result: dict[str, Any] = {
  76. "verdict": verdict,
  77. "malicious_detections": malicious,
  78. "suspicious_detections": suspicious,
  79. "total_engines": total,
  80. "reputation": attrs.get("reputation", None),
  81. }
  82. # Type-specific enrichment
  83. if ioc_type == "hash":
  84. result["meaningful_name"] = attrs.get("meaningful_name") or attrs.get("name")
  85. result["file_type"] = attrs.get("type_description") or attrs.get("magic")
  86. result["size"] = attrs.get("size")
  87. result["first_seen"] = attrs.get("first_submission_date")
  88. result["last_seen"] = attrs.get("last_analysis_date")
  89. # Extract top malware family tags
  90. popular_tags = attrs.get("popular_threat_classification", {})
  91. result["threat_labels"] = [
  92. lbl.get("value") for lbl in popular_tags.get("popular_threat_name", [])
  93. ][:5]
  94. elif ioc_type in ("ip", "domain"):
  95. result["country"] = attrs.get("country")
  96. result["as_owner"] = attrs.get("as_owner")
  97. result["network"] = attrs.get("network")
  98. result["last_https_certificate_date"] = attrs.get("last_https_certificate_date")
  99. elif ioc_type == "url":
  100. result["final_url"] = attrs.get("last_final_url") or attrs.get("url")
  101. result["title"] = attrs.get("title")
  102. result["last_analysis_date"] = attrs.get("last_analysis_date")
  103. return result
  104. # ---------------------------------------------------------------------------
  105. # Main tool
  106. # ---------------------------------------------------------------------------
  107. @log_execution(tool_name="vt_lookup")
  108. @track_metrics("vt_lookup")
  109. @handle_tool_errors
  110. async def vt_lookup(
  111. iocs: list[str],
  112. api_key: str | None = None,
  113. ) -> ToolResult:
  114. """Look up IOC reputation using the VirusTotal API v3.
  115. Accepts a list of file hashes (MD5/SHA1/SHA256), IP addresses, domain
  116. names, and URLs. Returns per-IOC verdict, detection counts, and
  117. enrichment data from VirusTotal's 70+ security vendors.
  118. **API key required**: Set ``REVERSECORE_VT_API_KEY`` environment variable,
  119. or pass the key directly via the ``api_key`` parameter.
  120. Args:
  121. iocs: List of IOCs to look up (max 20 per call). Supported types:
  122. - File hashes: MD5 (32 chars), SHA1 (40), SHA256 (64)
  123. - IP addresses: IPv4 (e.g. ``8.8.8.8``)
  124. - Domain names: (e.g. ``evil.example.com``)
  125. - 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
  126. api_key: VirusTotal API key. If omitted, uses ``REVERSECORE_VT_API_KEY``
  127. environment variable.
  128. Returns:
  129. ToolResult with per-IOC verdict dicts on success:
  130. .. code-block:: json
  131. {
  132. "results": [
  133. {
  134. "ioc": "44d88612fea8a8f36de82e1278abb02f",
  135. "type": "hash",
  136. "verdict": "malicious",
  137. "malicious_detections": 67,
  138. "total_engines": 72,
  139. "threat_labels": ["eicar.test"]
  140. }
  141. ],
  142. "summary": {"malicious": 1, "suspicious": 0, "clean": 0, "no_data": 0}
  143. }
  144. Example:
  145. >>> result = await vt_lookup(["44d88612fea8a8f36de82e1278abb02f", "1.2.3.4"])
  146. """
  147. if not iocs:
  148. return failure("VALIDATION_ERROR", "No IOCs provided. Pass a non-empty list.")
  149. # Limit to 20 IOCs per call to avoid rate limits
  150. if len(iocs) > 20:
  151. iocs = iocs[:20]
  152. logger.warning("vt_lookup: truncated IOC list to 20 entries")
  153. # Resolve API key
  154. cfg = get_config()
  155. resolved_key = api_key or cfg.vt_api_key
  156. if not resolved_key:
  157. return failure(
  158. "MISSING_API_KEY",
  159. "VirusTotal API key not configured.",
  160. hint=(
  161. "Set the REVERSECORE_VT_API_KEY environment variable, "
  162. "or pass api_key= directly to vt_lookup()."
  163. ),
  164. )
  165. timeout = cfg.vt_request_timeout
  166. # Classify IOCs
  167. classified: list[tuple[str, str]] = [] # (ioc, type)
  168. skipped: list[str] = []
  169. for ioc in iocs:
  170. ioc = ioc.strip()
  171. if not ioc:
  172. continue
  173. ioc_type = _classify_ioc(ioc)
  174. if ioc_type == "unknown":
  175. skipped.append(ioc)
  176. else:
  177. classified.append((ioc, ioc_type))
  178. if not classified:
  179. return failure(
  180. "VALIDATION_ERROR",
  181. "None of the provided IOCs could be classified (expected hash, IP, domain, or URL).",
  182. hint=f"Unclassifiable IOCs: {skipped[:5]}",
  183. )
  184. # --- HTTP client ---
  185. try:
  186. import httpx
  187. except ImportError:
  188. return failure(
  189. "DEPENDENCY_ERROR",
  190. "httpx is required for vt_lookup. Install it: pip install httpx",
  191. )
  192. headers = {"x-apikey": resolved_key, "Accept": "application/json"}
  193. results: list[dict[str, Any]] = []
  194. errors: list[dict[str, str]] = []
  195. async with httpx.AsyncClient(timeout=timeout, headers=headers) as client:
  196. semaphore = asyncio.Semaphore(4) # max 4 concurrent VT requests
  197. async def _fetch(ioc: str, ioc_type: str) -> None:
  198. url = _vt_url_for(ioc_type, ioc)
  199. if not url:
  200. errors.append({"ioc": ioc, "error": "Could not build VT URL"})
  201. return
  202. async with semaphore:
  203. try:
  204. resp = await client.get(url)
  205. if resp.status_code == 200:
  206. body = resp.json()
  207. verdict = _extract_verdict(body.get("data", {}), ioc_type)
  208. verdict["ioc"] = ioc
  209. verdict["type"] = ioc_type
  210. results.append(verdict)
  211. elif resp.status_code == 404:
  212. results.append(
  213. {
  214. "ioc": ioc,
  215. "type": ioc_type,
  216. "verdict": "not_found",
  217. "malicious_detections": 0,
  218. "total_engines": 0,
  219. }
  220. )
  221. elif resp.status_code == 401:
  222. errors.append({"ioc": ioc, "error": "Invalid API key (HTTP 401)"})
  223. elif resp.status_code == 429:
  224. errors.append(
  225. {
  226. "ioc": ioc,
  227. "error": "VirusTotal rate limit exceeded (HTTP 429)",
  228. }
  229. )
  230. else:
  231. errors.append(
  232. {
  233. "ioc": ioc,
  234. "error": f"VT API returned HTTP {resp.status_code}",
  235. }
  236. )
  237. except httpx.TimeoutException:
  238. errors.append({"ioc": ioc, "error": f"Request timed out after {timeout}s"})
  239. except Exception as exc:
  240. err_msg = str(exc)
  241. if resolved_key:
  242. err_msg = err_msg.replace(resolved_key, "[REDACTED]")
  243. errors.append({"ioc": ioc, "error": err_msg})
  244. await asyncio.gather(*[_fetch(ioc, ioc_type) for ioc, ioc_type in classified])
  245. # Build summary
  246. summary: dict[str, int] = {
  247. "malicious": 0,
  248. "suspicious": 0,
  249. "clean": 0,
  250. "no_data": 0,
  251. "not_found": 0,
  252. }
  253. for r in results:
  254. v = r.get("verdict", "no_data")
  255. summary[v] = summary.get(v, 0) + 1
  256. return success(
  257. {
  258. "results": results,
  259. "summary": summary,
  260. "skipped_unclassifiable": skipped,
  261. "errors": errors,
  262. "queried": len(classified),
  263. },
  264. total_malicious=summary["malicious"],
  265. total_suspicious=summary["suspicious"],
  266. )

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.