Metadata-Version: 2.4
Name: frida-mcp-re
Version: 0.3.10
Summary: Model Context Protocol implementation for Frida
License: MIT
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: frida>=17.9.11
Requires-Dist: mcp>=1.27.1
Provides-Extra: dev
Requires-Dist: black; extra == 'dev'
Requires-Dist: mypy; extra == 'dev'
Description-Content-Type: text/markdown

# Frida MCP

A Model Context Protocol (MCP) implementation for Frida dynamic instrumentation toolkit.

## Overview

This package provides an MCP-compliant server for Frida, enabling AI systems to interact with mobile and desktop applications through Frida's dynamic instrumentation capabilities. It uses the official [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) to enable seamless integration with AI applications like Claude Desktop.

## Demo

https://github.com/user-attachments/assets/5dc0e8f5-5011-4cf2-be77-6a77ec960501

## What's New in 0.3.10

> **Same code as 0.3.9 — only the README was expanded with full documentation of the 35 new VMP tools.**

## What's New in 0.3.9 🔥 35 new VMProtect tools (4 new modules)

This release adds **3 brand-new VMProtect modules** (`vmp_dumper_v3.py`, `vmp_dumper_v4.py`,
`vmp_dumper_v5.py`) bringing the total to **42 VMP tools** (up from 7) and **~111 MCP tools** overall.

All techniques are derived from publicly available research. Full bibliography is in the
[Credits — VMProtect Research](#credits--vmprotect-research) section.

### Highlights

- 🚀 **High-speed dump** via `CreateFile`/`WriteFile` inside the target process — handles multi-GB modules in seconds
- 🕵️ **VMP version fingerprinter** — auto-detects 2.x / 3.0-3.4 / 3.5 / 3.6+ / 3.8+
- 🛡️ **Anti-debug bypass 3.6+/3.8+** — KUSER_SHARED_DATA patch, Heaven's Gate sysenter VEH, NTDLL fresh-map hook, Trap Flag normalizer, module-name scan defeat
- 🧩 **Dispatch classifier** — distinguishes `classic_pre_3_5` / `context_table_3_x` / `heap_dispatch_3_5+` / `veh_dispatch_3_5+`
- 🔍 **Hybrid function finder** — `.text → .vmp0` CALL site discovery
- 📜 **Canonical 34-opcode VM table** (NoVmpy + Rasetsuu research)
- 🧮 **MBA detector** — 6 byte-level patterns for Mixed Boolean-Arithmetic handlers
- 🔁 **Handler duplication detector** — verifies the documented 11× duplication scheme (Xyntia paper)
- 📚 **Curated toolchain catalog** — 18 external tools with version compatibility and "when to use" hints
- 🎯 **Recommendation engine** — given version + arch + goal, returns the optimal external toolchain
- 🏗️ **PE overlay reconstruction** — fuses per-section memory dumps onto an original PE
- 🧪 **OEP detector via r0da's `ZwProtectVirtualMemory` formula** — `((n+1)*2)+1` calls
- 🔓 **All-in-one anti-debug pipeline** — `vmp_apply_full_antidebug_v5` installs 5 bypasses in one call

## What's New in 0.3.2

- **7 new VMProtect Unpacker tools** — full runtime unpacking pipeline: OEP detection, PE dump, IAT reconstruction, section header fixing and all-in-one `vmp_full_unpack`
- **xrefs fixed** — rebuilt `.idata` section with proper `IMAGE_IMPORT_DESCRIPTOR` entries so IDA Pro and x64dbg resolve all API calls and string xrefs correctly
- **GetProcAddress hooking** — `vmp_resolve_imports` captures every import VMP resolves at runtime for 100% accurate IAT reconstruction

## What's New in 0.3.1

- **8 new VMProtect tools** — full VMProtect v2/v3 analysis: detection, section parsing, SDK hooking, anti-debug bypass, string decryption, handler AOB scan and dispatcher analysis
- **VMProtect integrated in `detect_embedded_vm`** — auto-detected alongside Mono, IL2CPP, Lua, Python, V8
- **Improved `publish.py`** — handles `400 File already exists` gracefully instead of crashing

## What's New in 0.3.0

- **7 new tools** — typed memory read/write, hex dump, pointer chain, address watcher, session list/close
- **Full async refactor** — all tools now use `threading.Event` instead of fixed `time.sleep` delays (up to 10× faster responses)
- **Central `_run_script` helper** — eliminates ~250 lines of duplicated boilerplate across all modules
- **Bug fix** — `read_memory` was missing its `@mcp.tool()` decorator and was never registered
- **Better error reporting** — all tools now return structured `timed_out` errors with clear messages

## Features

- Built with the official MCP Python SDK
- **76+ tools** covering all major Frida capabilities
- Full VM support: Java/Android, Mono, IL2CPP (Unity), Lua, Python embedded, V8/Node.js
- Full VMProtect v2/v3 analysis and bypass
- Game engine reverse engineering support
- Event-driven synchronization — no wasted wait time

## Tool Categories

### 🔧 Process & Device Management (10 tools)
| Tool | Description |
|------|-------------|
| `enumerate_processes` | List all running processes on device |
| `enumerate_devices` | List all connected devices (USB, remote) |
| `get_device` | Get a device by ID |
| `get_usb_device` | Get the connected USB device |
| `get_local_device` | Get the local device |
| `get_process_by_name` | Find a process by name (partial, case-insensitive) |
| `attach_to_process` | Attach to a process by PID |
| `spawn_process` | Spawn a new process or app |
| `resume_process` | Resume a suspended process |
| `kill_process` | Kill a process by PID |

### 💬 Interactive Sessions (3 tools)
| Tool | Description |
|------|-------------|
| `create_interactive_session` | Create a REPL-like Frida session with a process |
| `execute_in_session` | Execute JavaScript code in an active session |
| `get_session_messages` | Retrieve messages from persistent scripts |

### 🗂️ Session Management (2 tools) ⭐ New
| Tool | Description |
|------|-------------|
| `list_sessions` | List all active sessions with PID, timestamp and hook count |
| `close_session` | Detach, unload all scripts and clean up a session |

### 📦 Module & Symbol Analysis (6 tools)
| Tool | Description |
|------|-------------|
| `list_modules` | List all loaded modules/libraries |
| `find_module_by_name` | Find a module by name (partial match) |
| `list_exports` | List all exported symbols of a module |
| `list_imports` | List all imported symbols of a module |
| `resolve_symbol` | Resolve the absolute address of an export |
| `find_symbol_by_pattern` | Search exports by regex pattern |

### 💾 Memory Operations (11 tools)
| Tool | Description |
|------|-------------|
| `read_memory` | Read raw bytes from a memory address |
| `write_memory` | Write bytes to a memory address |
| `scan_memory_pattern` | AOB scan with wildcard support (`??`) |
| `read_pointer` | Read a pointer-sized value |
| `read_string_at` | Read null-terminated string (UTF-8/16/ANSI) |
| `enumerate_memory_ranges` | List all memory regions with permissions |
| `read_memory_typed` | Read a typed scalar value (int8…double…pointer) ⭐ New |
| `write_memory_typed` | Write a typed scalar value without encoding bytes ⭐ New |
| `dump_memory_region` | Hex editor-style dump: offset + hex + ASCII ⭐ New |
| `follow_pointer_chain` | Follow a multi-level pointer chain with all intermediate steps ⭐ New |
| `watch_address` | Poll a memory address and report value changes ⭐ New |

### 🪝 Hooking & Tracing (4 tools)
| Tool | Description |
|------|-------------|
| `hook_function` | Persistent Interceptor hook (args + retval) |
| `enumerate_threads` | List all threads with state and context |
| `get_thread_backtrace` | Get backtrace for a specific thread |
| `stalker_trace_thread` | Trace a thread's execution with Stalker |

### ⚙️ Native Calls (2 tools)
| Tool | Description |
|------|-------------|
| `call_native_function` | Call a native function at an address |
| `install_native_callback` | Replace a function with a NativeCallback |

### ☕ Java / Android Bridge (6 tools)
| Tool | Description |
|------|-------------|
| `java_list_classes` | List all loaded Java classes (with filter) |
| `java_list_methods` | List all methods of a Java class |
| `java_hook_method` | Hook a Java method (persistent) |
| `java_get_field_value` | Get a Java field value (static or instance) |
| `java_set_field_value` | Set a Java field value |
| `java_call_method` | Call a Java method directly |

### 🎮 VM & Game Engine Support (16 tools)
| Tool | Description |
|------|-------------|
| `detect_embedded_vm` | Auto-detect embedded VMs (Lua, LuaJIT, Python, Mono, IL2CPP, V8, JVM, Chakra) |
| `mono_list_assemblies` | Detect Mono/.NET runtime and assemblies |
| `il2cpp_find_class` | Find an IL2CPP class by namespace and name |
| `il2cpp_find_method` | Find a method in an IL2CPP class |
| `il2cpp_read_field` | Read a field from an IL2CPP object at offset |
| `il2cpp_hook_method` | Hook an IL2CPP native method |
| `lua_list_globals` | List Lua global variables |
| `lua_exec` | Execute Lua code in the embedded runtime |
| `python_detect` | Detect embedded CPython runtime |
| `python_exec` | Execute Python code in the embedded interpreter |
| `python_hook_function` | Hook PyEval_EvalCode to trace Python execution |
| `python_import_module` | Import a Python module in the embedded interpreter |
| `v8_detect` | Detect V8 / Node.js engine |
| `v8_list_scripts` | List JavaScript scripts loaded in V8 |
| `v8_hook_script_compile` | Hook Node.js script compilation entry points |
| `v8_enumerate_exports` | Enumerate V8/Node.js module exports |

### 🛡️ VMProtect Analysis (8 tools) ⭐ New in 0.3.1
| Tool | Description |
|------|-------------|
| `vmp_detect` | Detect VMProtect presence, version (v2/v3), confidence level, sections and SDK exports |
| `vmp_list_sections` | Parse PE headers in memory and list all .vmp0/.vmp1/.vmp2 sections with VA, size and flags |
| `vmp_list_sdk_functions` | Find all 22 known VMProtect SDK exports across loaded modules |
| `vmp_hook_antidebug` | Hook and bypass `IsDebuggerPresent`, `IsVirtualMachinePresent`, `IsValidImageCRC` |
| `vmp_decrypt_strings` | Hook `VMProtectDecryptStringA/W` to capture decrypted strings at runtime |
| `vmp_scan_handlers` | AOB scan .vmp sections for VM entry stubs, CPUID, RDTSC, indirect JMP patterns |
| `vmp_analyze_dispatcher` | Locate and analyze the VM dispatcher region with hex context |
| `vmp_hook_sdk` | Hook any VMProtect SDK function by name (license, HWID, activation tracing) |

### 🔓 VMProtect Unpacker (7 tools) ⭐ New in 0.3.2
| Tool | Description |
|------|-------------|
| `vmp_full_unpack` | **All-in-one**: OEP detect + PE dump + IAT rebuild + section fix → ready for IDA/x64dbg |
| `vmp_find_oep` | Find Original Entry Point via prolog scan + dispatcher exit hook |
| `vmp_dump_pe` | Dump decrypted PE from memory to disk with fixed section headers |
| `vmp_rebuild_iat` | Scan live IAT thunks, build `IMAGE_IMPORT_DESCRIPTOR` entries, append `.idata` section |
| `vmp_fix_section_headers` | Fix `PointerToRawData`/`SizeOfRawData` alignment for IDA Pro / x64dbg |
| `vmp_resolve_imports` | Hook `GetProcAddress` to capture every runtime import (most accurate IAT method) |
| `vmp_scan_iat_region` | Scan and map all IAT thunks with reverse API lookup |

### 🔥 VMProtect Standalone-Adapted (11 tools) ⭐ New in 0.3.9 — module `vmp_dumper_v3.py`
| Tool | Description |
|------|-------------|
| `vmp_analyze_protection_full` | Full PE analysis live (sections + EP section + IAT/TLS/Import directory RVAs + VMP markers + warnings) |
| `vmp_dump_pe_writefile` | **High-speed dump** via `CreateFile`+`WriteFile` inside target process (1 MB chunks, error-tolerant). Dramatically faster than base64 streaming for multi-GB modules |
| `vmp_fix_pe_headers_v3` | Fix `PointerToRawData=VA` + `SizeOfRawData=VSize`, rename `.vmp*` → `.secN`, redirect EP to `.text` |
| `vmp_deep_clean_vmp` | Zero ALL DataDirectories (except Export+Resource), disable ASLR (`DYNAMIC_BASE`), force standard section characteristics |
| `vmp_fix_pdata_entropy` | Compute Shannon entropy of `.pdata`; if ≥7.0 (encrypted), zero the entire section + DataDirectory[3] (Exception) + fix chars |
| `vmp_verify_strings` | Sanity check: count printable strings in `.rdata` + report UE markers (Engine/World/Player/Camera/Actor/...) |
| `vmp_scan_iat_real` | Chunked `.rdata` scan + per-pointer `DebugSymbol` resolution (PE64). Discovers REAL IAT pointers post-unpack |
| `vmp_save_iat_csv` | Persist resolved IAT to CSV (`rva,module,funcptr,name`), grouped by DLL with per-module counts |
| `vmp_rebuild_iat_v3` | Append `.idata` section with FULL `IMAGE_IMPORT_DESCRIPTOR` array + hint/name table + ILT + IAT + DataDirectory[1]/[12] updates |
| `vmp_clean_existing_dump` | **Offline** pipeline: parse PE → fix_headers → deep_clean → pdata_entropy → verify_strings. No Frida session needed |
| `vmp_dump_full_pipeline_v3` | **All-in-one**: analyze → writefile dump → fix headers → deep clean → pdata entropy → scan IAT → save CSV → rebuild IAT → verify strings |

### 🧬 VMProtect 3.5+ Dispatch Research (12 tools) ⭐ New in 0.3.9 — module `vmp_dumper_v4.py`
| Tool | Description |
|------|-------------|
| `vmp_get_opcode_table` | Canonical 34-opcode VM table (NoVmpy + Rasetsuu/vmprotect-research). NOP / PUSH_REG / POP_REG / PUSH_IMM / CALL / CRC / ADD / NOR / STORE / LOAD / NAND / RCL / RCR / ROL / ROR / SAL / SAR / SHL / SHR / SHLD / SHRD / MUL / IMUL / DIV / IDIV / RDTSC / CPUID / LOCK_XCHG / PUSH_CRX / POP_CRX / PUSH_SP / POP_SP / EXIT / POP_FLAG |
| `vmp_detect_no_access_vmp0` | Query LIVE page protection of every `.vmp*` (`r-x` / `rw-` / `---`). `.vmp0` PAGE_NOACCESS → VMP 3.5+ VEH dispatch indicator |
| `vmp_classify_dispatch` | Classify the dispatch model: **classic_pre_3_5** / **context_table_3_x** / **heap_dispatch_3_5+** / **veh_dispatch_3_5+** / none. Includes confidence + tailored next-step guidance |
| `vmp_hook_veh_register` | Hook `RtlAddVectoredExceptionHandler` + `RtlAddVectoredContinueHandler` → captures the actual VMP VEH handler address + module + caller |
| `vmp_find_hybrid_functions` | Scan `.text` for near-CALL (`E8`) into `.vmp0`/`.vmp1`. Reproduces the Memory.dll-style "hybrid function" architecture. Returns call site, target VA, target section |
| `vmp_scan_entry_stubs` | Scan `.vmp0` for VMP 3.5+ entry-stub patterns (`NOP; MOVSX ECX,R15B; POP RCX; JMP rel32`) with 3 variants. Returns jmp_target for each hit |
| `vmp_scan_context_table` | Scan `.vmp0` for heap pointers (non-module `rw-` ranges). Clusters of contiguous hits = VM_CONTEXT table start. Returns first 5 pointers of each cluster |
| `vmp_scan_heap_trampoline` | AOB scan for the heap dispatcher pattern `XCHG [RSP],RCX; PUSH RCX; MOVSXD RCX,EBX` + 32-byte snippet |
| `vmp_capture_bytecode_stream` | Read raw encrypted bytecode from a `.vmp0` address (configurable size). Optional binary file output for offline rolling-XOR decoders |
| `vmp_scan_decoder_candidates` | Scan `.vmp1` for rolling-XOR decoder x86 sequences (4 patterns). Each hit is a candidate per-handler decoder |
| `vmp_reconstruct_pe_overlay` | Overlay per-section memory dumps onto an original PE. Filename convention: `dump_.<section>_<VA_hex>.bin`. Uses pefile if available, else raw-struct fallback |
| `vmp_dispatch_report` | **One-call comprehensive report**: page_protection + classification + entry_stubs + context_table + heap_trampolines + hybrid_functions + summary + next_steps |

### 🛡️ VMProtect Version-Aware + Anti-Debug 3.6+/3.8+ (12 tools) ⭐ New in 0.3.9 — module `vmp_dumper_v5.py`
| Tool | Description |
|------|-------------|
| `vmp_fingerprint_version` | Heuristic version fingerprint: 2.x / 3.0-3.4 / 3.5 / 3.6+ / 3.8+. Uses section naming + `.vmp0` live protect + Heaven's Gate stub detection + VMProtectSDK presence |
| `vmp_recommend_toolchain` | Decision matrix: given (version, arch, goal=unpack/devirt/antidebug/iat_fix/dotnet_unmod/mba_clean) → returns optimal phased toolchain |
| `vmp_resources_external_tools` | Curated catalog of **18 external tools** with repo, type, supported VMP versions, tech stack, "when to use". Filter by type (devirt/unpacker/antidebug/mba/dotnet/detector) |
| `vmp_bypass_kuser_shared_data` | Patch `PEB.OsBuildNumber` + `KUSER_SHARED_DATA.NtBuildNumber` (via `VirtualProtect`) + hook `NtQuerySystemInformation(SystemKernelDebuggerInformation)`. Configurable fake build (default 9600 = Win8.1) |
| `vmp_bypass_heavens_gate` | Install VEH that catches `sysenter` (`0F 34`) and returns `EXCEPTION_CONTINUE_EXECUTION`. Defeats VMP 3.8+ WoW64 Heaven's Gate `jmp far 0x33` syscall escape |
| `vmp_bypass_ntdll_freshmap` | Hook `NtCreateSection` + `NtMapViewOfSection` + `NtOpenFile` + `NtQueryVirtualMemory`. Logs every NTDLL re-mapping attempt (VMP 3.6+ uses this to extract clean syscall numbers) |
| `vmp_bypass_module_name_scan` | Hook `NtQuerySystemInformation(SystemModuleInformation=11)` and rewrite matching driver names to `system.sys`. Default blocklist: 15 drivers (sice.sys, siwvid.sys, ntice.sys, iceext.sys, syser.sys, dbgv.sys, dbk64.sys, vboxdrv.sys, vmtools.sys, scyllahide, ...) |
| `vmp_bypass_trap_flag` | Install VEH for `STATUS_SINGLE_STEP` (`0x80000004`) that returns `EXCEPTION_CONTINUE_EXECUTION` — defeats Trap Flag RIP-delta detection |
| `vmp_count_zwprotect_unpack` | Hook `NtProtectVirtualMemory` and count calls hitting main module. r0da's classic formula: expect `((n_nonwritable_sections + 1) * 2) + 1` calls. When reached → unpacking complete → dump immediately |
| `vmp_scan_mba_handlers` | Scan `.vmp1` for 6 MBA byte patterns (NOT/OR/NOT XOR via De Morgan, OR+SUB ADD identity, AND/OR/SUB chain, NEG+XOR signed MBA, AND+OR ADD identity, XOR+AND XOR identity). Computes density per KB |
| `vmp_detect_handler_duplication` | Fingerprint handler prologues in `.vmp1` and count duplicates. Clusters of 9-13 hits = the documented "11× duplication" defense from the Xyntia paper |
| `vmp_apply_full_antidebug_v5` | **All-in-one**: kuser_shared_data + ntdll_freshmap + module_name_scan + trap_flag + heavens_gate. The recommended FIRST action after attaching to a VMP 3.6+/3.8+ process |

### 🖥️ Process Info (1 tool)
| Tool | Description |
|------|-------------|
| `get_process_architecture` | Get arch, platform, pointer size, page size |

## Installation

### Prerequisites

- Python 3.8 or later
- pip package manager
- Frida 16.0.0 or later

### Quick Install

```bash
pip install frida-mcp-re
```

### Development Install

```bash
git clone https://github.com/yourusername/frida-mcp.git
cd frida-mcp
pip install -e ".[dev]"
```

## Claude Desktop Integration

Add to your Claude Desktop config file:
- macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Windows: `%APPDATA%\Claude\claude_desktop_config.json`
- Linux: `~/.config/Claude/claude_desktop_config.json`

```json
{
  "mcpServers": {
    "frida": {
      "command": "frida-mcp"
    }
  }
}
```

## Game Reverse Engineering

Frida MCP is specifically designed for reverse engineering games that use embedded VMs or custom scripting engines:

### Supported Engines & VMs
- **Unity (Mono)** — Hook managed methods, read/write fields
- **Unity (IL2CPP)** — Native compiled code, class/method finder, field reader
- **Android (Java)** — Full Java bridge: class listing, method hooking, field access
- **Lua-based games** — Execute Lua code inside the game's Lua state
- **Python embedded** — Execute and trace CPython runtimes embedded in games/apps
- **V8 / Node.js** — Detect, enumerate and hook embedded V8 runtimes
- **Custom VM detection** — Auto-detects Lua, LuaJIT, Python, V8, Chakra, Mono, IL2CPP, JVM

### Typical Game RE Workflow

```
1. attach to game process     → attach_to_process
2. create session             → create_interactive_session
3. detect VM / engine         → detect_embedded_vm
4. map loaded modules         → list_modules
5. AOB scan                   → scan_memory_pattern  (ViewMatrix, EntityList…)
6. follow pointer chain       → follow_pointer_chain (static base → offsets)
7. read typed values          → read_memory_typed    (health, ammo, position)
8. watch address changes      → watch_address        (live monitoring)
9. hook game logic            → hook_function / java_hook_method / il2cpp_hook_method
10. dump struct layout        → dump_memory_region
11. patch values              → write_memory_typed
12. close when done           → close_session
```

### VMProtect Unpack Workflow (xrefs + IAT fixed)

```python
# One-liner: full unpack with OEP + IAT + xrefs
vmp_full_unpack(session_id, output_path="C:/dumps/unpacked.exe")

# Or step by step for maximum control:
vmp_find_oep(session_id)                                    # find real entry point
vmp_resolve_imports(session_id, duration_ms=15000)          # hook GetProcAddress
# ... interact with the game to trigger more imports ...
get_session_messages(session_id)                            # collect captured imports
vmp_dump_pe(session_id, output_path="C:/dumps/raw.exe")     # dump from memory
vmp_rebuild_iat(session_id, dump_path="C:/dumps/raw.exe",
                output_path="C:/dumps/unpacked.exe")        # fix imports + xrefs
# Load C:/dumps/unpacked.exe in IDA Pro → all xrefs, strings, API names work
```

### VMProtect RE Workflow

```
1. detect VMProtect           → vmp_detect           (version, confidence, sections)
2. list VMP sections          → vmp_list_sections    (VA, size, flags of .vmp0/.vmp1/.vmp2)
3. find SDK functions         → vmp_list_sdk_functions
4. bypass anti-debug          → vmp_hook_antidebug   (bypass=True)
5. capture strings            → vmp_decrypt_strings  + get_session_messages
6. scan VM handlers           → vmp_scan_handlers    (CPUID, RDTSC, indirect JMP…)
7. analyze dispatcher         → vmp_analyze_dispatcher
8. trace license validation   → vmp_hook_sdk("VMProtectSetSerialNumber")
9. capture HWID               → vmp_hook_sdk("VMProtectGetCurrentHWID")
```

### New Tools in Action

```python
# Read player health (float at known address)
read_memory_typed(session_id, "0x7FF12340", type="float")

# Follow pointer chain: base → +0x0 → +0x58 → +0x1A0 (player struct)
follow_pointer_chain(session_id, "0x14B8C2A0", offsets=[0x0, 0x58, 0x1A0])

# Watch ammo counter live (poll every 200ms for 10 seconds)
watch_address(session_id, "0x7FF12344", type="int32", interval_ms=200, duration_ms=10000)

# Hex dump 256 bytes of a struct
dump_memory_region(session_id, "0x7FF12300", size=256)

# Patch: set health to 9999
write_memory_typed(session_id, "0x7FF12340", type="float", value="9999.0")

# Clean up
close_session(session_id)
```

### VMProtect 0.3.9 Workflow (versión-aware, end-to-end)

The new modules turn VMP analysis into a structured 6-phase pipeline:

```
┌─────────────────────────────────────────────────────────────────────┐
│ PHASE 0 — Attach                                                     │
│   1. attach_to_process / spawn_process                               │
│   2. create_interactive_session                                      │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ PHASE 1 — Fingerprint + Recommend                                    │
│   3. vmp_fingerprint_version          → "3.6+" / "3.8+" / "3.0-3.4"  │
│   4. vmp_recommend_toolchain(...)     → list of external tools       │
│   5. vmp_resources_external_tools     → catalog reference            │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ PHASE 2 — Anti-debug bypass (CRITICAL for 3.6+/3.8+)                 │
│   6. vmp_apply_full_antidebug_v5      → installs 5 bypasses          │
│       ├─ vmp_bypass_kuser_shared_data                                │
│       ├─ vmp_bypass_ntdll_freshmap                                   │
│       ├─ vmp_bypass_module_name_scan                                 │
│       ├─ vmp_bypass_trap_flag                                        │
│       └─ vmp_bypass_heavens_gate                                     │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ PHASE 3 — Dispatch classification                                    │
│   7. vmp_dispatch_report              → one-call comprehensive       │
│       ├─ vmp_detect_no_access_vmp0    → PAGE_NOACCESS check          │
│       ├─ vmp_classify_dispatch        → classic / context_table /    │
│       │                                 heap_dispatch / veh_dispatch │
│       ├─ vmp_scan_entry_stubs                                        │
│       ├─ vmp_scan_context_table                                      │
│       ├─ vmp_scan_heap_trampoline                                    │
│       └─ vmp_find_hybrid_functions                                   │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ PHASE 4 — Wait for unpack completion                                 │
│   8. vmp_count_zwprotect_unpack       → installs counter             │
│   9. (poll get_session_messages until count = ((n+1)*2)+1)           │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ PHASE 5 — Dump + reconstruct (all-in-one)                            │
│  10. vmp_dump_full_pipeline_v3        → produces clean .exe + CSV    │
│       ├─ vmp_analyze_protection_full                                 │
│       ├─ vmp_dump_pe_writefile                                       │
│       ├─ vmp_fix_pe_headers_v3                                       │
│       ├─ vmp_deep_clean_vmp                                          │
│       ├─ vmp_fix_pdata_entropy                                       │
│       ├─ vmp_scan_iat_real                                           │
│       ├─ vmp_save_iat_csv                                            │
│       ├─ vmp_rebuild_iat_v3                                          │
│       └─ vmp_verify_strings                                          │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ PHASE 6 — Optional research / devirt                                 │
│  11. vmp_get_opcode_table             → 34-opcode reference          │
│  12. vmp_capture_bytecode_stream      → dump raw VMP bytecode        │
│  13. vmp_scan_decoder_candidates      → find rolling-XOR decoders    │
│  14. vmp_scan_mba_handlers            → MBA density                  │
│  15. vmp_detect_handler_duplication   → 11× duplication check        │
│  16. vmp_reconstruct_pe_overlay       → overlay dumps onto orig PE   │
│  17. (External) feed dump to NoVmp / VMPDump / JonathanSalwan        │
└─────────────────────────────────────────────────────────────────────┘
```

### One-liner quick start

```python
# After attach + create_interactive_session:
sid = "session-abc"

# 1) Identify the target
ver = vmp_fingerprint_version(session_id=sid)              # → "3.6+"
chain = vmp_recommend_toolchain(version="3.6+", arch="x64", goal="unpack")

# 2) Bypass everything anti-debug in one call
vmp_apply_full_antidebug_v5(session_id=sid)

# 3) Comprehensive dispatch report
report = vmp_dispatch_report(session_id=sid)

# 4) Wait for unpack (poll messages); when ready:
result = vmp_dump_full_pipeline_v3(
    session_id=sid,
    output_path=r"C:\dumps\game_unpacked.exe",
    scan_iat=True,
    save_iat_csv=True,
)
# → produces game_unpacked.exe + game_unpacked_iat.csv, ready for IDA Pro
```

### Choosing the right tool for the right VMP version

| VMP version | Primary tool path |
|---|---|
| **1.x – 1.9x** | Legacy unpacker toolkits (see `vmp_resources_external_tools`) |
| **2.x** | `vmp_full_unpack` (classic) or `vmp_dump_full_pipeline_v3` |
| **3.0 – 3.4** | `vmp_dump_full_pipeline_v3` → feed to **NoVmp** / **VMPDump** |
| **3.5** | `vmp_classify_dispatch` first; if `heap_dispatch_3_5+` → NoVmp fails |
| **3.6+** | `vmp_apply_full_antidebug_v5` + `vmp_dump_full_pipeline_v3`; devirt via Triton |
| **3.8+** | Add `vmp_bypass_heavens_gate` + TitanHide kernel-mode plugin |
| **.NET** | `VMUnprotect.Dumper` (external, see `vmp_recommend_toolchain` with `arch="dotnet"`) |

## Architecture

```
frida_mcp/
├── server.py          # FastMCP instance + shared state + _run_script helpers
├── cli.py             # STDIO entrypoint for Claude Desktop
└── tools/
    ├── processes.py   # Device & process management (10 tools)
    ├── sessions.py    # Interactive REPL sessions (3 tools)
    ├── modules.py     # Module & symbol analysis (4 tools)
    ├── memory.py      # Memory read/write/scan (9 tools)
    ├── hooks.py       # Hooking, tracing, Stalker (4 tools)
    ├── native.py      # NativeFunction / NativeCallback (2 tools)
    ├── java_bridge.py # Java/Android bridge (6 tools)
    ├── vm_support.py  # Mono, IL2CPP, Lua, Python, V8 (16 tools)
    ├── advanced.py    # Session mgmt + advanced memory (7 tools)
    ├── vmprotect.py   # VMProtect v2/v3 analysis and bypass (8 tools)
    └── vmp_dumper.py  # VMProtect runtime unpacker + IAT reconstruction (7 tools)
```

## Credits — VMProtect Research

The 35 new VMProtect tools added in **0.3.9** (modules `vmp_dumper_v3.py`, `vmp_dumper_v4.py`,
`vmp_dumper_v5.py`) are built entirely on top of publicly available research.
This section credits every primary source used.

### 🔬 Primary research repositories
| Source | Repo / URL | Contribution |
|---|---|---|
| **Rasetsuu / vmprotect-research** | https://github.com/Rasetsuu/vmprotect-research | VMP 3.5+ internal architecture (855-LOC `VMP_INTERNALS.md`): heap-dispatch, VEH dispatch, entry-stub patterns, context-table layout, rolling-XOR decoder, NoVmpy 34-opcode table. Inspired ALL of `vmp_dumper_v4.py`. |
| **can1357 / NoVmp** | https://github.com/can1357/NoVmp | Static devirtualizer for VMP x64 3.0-3.5 with VTIL+LLVM. Architecture reference (`architecture.hpp`, `il2vtil.cpp`). |
| **0xnobody / vmpdump** | https://github.com/0xnobody/vmpdump | Dynamic dumper + IAT fixer for VMP 3.x x64. Reference for IAT thunk resolution via VTIL. |
| **0xnobody / vmpattack** | https://github.com/0xnobody/vmpattack | Companion devirtualizer to vmpdump. |
| **JonathanSalwan / VMProtect-devirtualization** | https://github.com/JonathanSalwan/VMProtect-devirtualization | Triton + LLVM + Pin dynamic devirt for pure functions. Path-coverage flag-tracking heuristics. |
| **gmh5225 / titan** | https://github.com/gmh5225/titan-1 | Alternative static devirt with LLVM whitebox lifting. |
| **colby57 / VMP-Imports-Deobfuscator** | https://github.com/colby57/VMP-Imports-Deobfuscator | Pattern-based VMP import thunk resolver. |
| **void-stack / VMUnprotect.Dumper** | https://github.com/void-stack/VMUnprotect.Dumper | .NET-specific unpacker (VMP 3.4-3.7 .NET). |
| **DNLINYJ / DetectVMP3** | https://github.com/DNLINYJ/DetectVMP3 | Quick PE-only VMP 3.x version detector. |
| **dslee2022 / VMProtect-CRC-Bypass** | https://github.com/dslee2022/VMProtect-CRC-Bypass | Integrity-check (handler #6 CRC) bypass technique. |
| **x64dbg / ScyllaHide** | https://github.com/x64dbg/ScyllaHide | Reference for ALL anti-anti-debug techniques. Issue #156 (Heaven's Gate sysenter bypass). |
| **mrexodia / TitanHide** | https://github.com/mrexodia/TitanHide | Kernel-mode anti-debug bypass reference (for VMP 3.8+ where ScyllaHide alone fails). |
| **vtil-project / VTIL-Core** | https://github.com/vtil-project/VTIL-Core | IR + optimization passes used by NoVmp / VMPDump. |
| **Back Engineering Labs vmp3 suite** | https://git.back.engineering/vmp3 (`vmdevirt`, `vmemu`, `vmprofiler`) | Handler-level emulation/profiling. |
| **Back Engineering Labs VMP3-Unpacker** | Released May 2025 (free) | Community unpacker covering all VMP 3.x including latest. |
| **horsicq / Detect-It-Easy** | https://github.com/horsicq/Detect-It-Easy | First-step packer/protector identification. |
| **assarbad VMProtect resources Gist** | https://gist.github.com/assarbad/83e7def48a986727b12fcc644da1aa57 | Comprehensive index of VMP-related links. |

### 📝 Primary articles & blog posts
| Article | URL | Used for |
|---|---|---|
| **r0da — Quick look around VMP 3.x (Part 1: Unpacking)** | https://whereisr0da.github.io/blog/posts/2021-01-05-vmp-1/ | The `ZwProtectVirtualMemory` counting technique: `((n+1)*2)+1` calls → OEP detection. Implemented as `vmp_count_zwprotect_unpack`. Also section semantics (`.vmp0` = virtualized code, `.vmp1` = unpacking routine). |
| **r0da — Part 2 & Part 3 (Code Mutation & Virtualization)** | https://whereisr0da.github.io/blog/posts/2021-02-16-vmp-3/ | Rolling-key decryption chain (handle offset XOR), why static decryption is impossible without symbolic execution. |
| **cyber.wtf — Defeating VMProtect's Latest Tricks (Feb 2023)** | https://cyber.wtf/2023/02/09/defeating-vmprotects-latest-tricks/ | VMP 3.6+ tricks: KUSER_SHARED_DATA build number reads, NTDLL fresh-mapping (NtCreateSection SEC_IMAGE_NO_EXECUTE → NtMapViewOfSection → syscall extraction), Trap Flag detection (RIP delta), firmware RSMB checks. Implemented as `vmp_bypass_kuser_shared_data`, `vmp_bypass_ntdll_freshmap`, `vmp_bypass_trap_flag`. |
| **Tuts4you — VMProtect Heaven's Gate Anti-Debug Bypass to VectorHandler** | https://forum.tuts4you.com/topic/44425- | VMP 3.8.4+ uses `jmp far 0x33:offset` + `sysenter` to evade user-mode hooks. VEH-based proxy approach. Implemented as `vmp_bypass_heavens_gate`. |
| **Sachiel-archangel — Anti Debug techniques of VMProtect (Medium 2025)** | https://sachiel-archangel.medium.com/anti-debug-techniques-of-vmprotect-f1e343ee0fb2 | `NtQuerySystemInformation(SystemModuleInformation)` walks for debugger drivers (sice.sys, siwvid.sys, ntice.sys, iceext.sys, syser.sys). Implemented as `vmp_bypass_module_name_scan`. |
| **shhoya — VMProtect Bypass (Anti Debugging)** | https://shhoya.github.io/vmp_vmpantidebug.html | Cross-reference of user-mode VMP anti-debug techniques. |
| **hackyboiz — LLVM based VMProtect Devirtualization (Sept 2025)** | https://hackyboiz.github.io/2025/09/11/banda/LLVM_based_VMP/en/ | MBA expression patterns produced by VMP virtualization, white-box vs black-box lifting strategies. |
| **hackyboiz — VMProtect Devirtualization Part 2 (Dec 2025)** | https://hackyboiz.github.io/2025/12/11/banda/VMPpart2/en/ | Hands-on VMP 3.0.9 Virtualization mode reverse, Triton + custom VMPTrace-style toolchain. |
| **wwh1004 — Deobfuscating Mutation of VMProtect.NET** | https://wwh1004.com/en/deobfuscating-mutation-of-vmprotect_net/ | VMP.NET Mutation mode (constant encryption + obfuscated branching) emulation strategy. |
| **GuidedHacking forum threads** | https://guidedhacking.com (multiple VMP threads) | Practical guidance on Scylla, dump fixing, common pitfalls. |

### 📚 Academic papers
| Paper | Venue / Year | Used for |
|---|---|---|
| **MBA-Blast: Unveiling and Simplifying Mixed Boolean-Arithmetic Obfuscation** (Liu, Shen, Ming et al.) | USENIX Security 2021 | MBA detection patterns + statistics on VMP-protected malware. Used in `vmp_scan_mba_handlers`. |
| **Hardening Code Obfuscation Against Automated Attacks (LOKI)** (Schloegel et al., RUB-SysSec) | 2021, https://github.com/RUB-SysSec/loki | VM handler statistics table for VMProtect/Themida. Byte-level MBA pattern catalog. |
| **Search-based local black-box deobfuscation (Xyntia)** (Menguy, Bardin et al.) | CCS 2021 | Verified that VMP's arithmetic+Boolean handlers are replicated **11×** to fake handler diversity. Implemented as `vmp_detect_handler_duplication`. |
| **GAMBA: Simplification of General MBA Expressions** (Reichenwallner) | arXiv 2305.06763 (2023) | Extends SiMBA with algebraic rewriting; recommended downstream after VMP lifting. |
| **ProMBA: Simplifying MBA Obfuscation by Program Synthesis & Term Rewriting** | CCS 2023, ACM DOI 10.1145/3576915.3623186 | State-of-the-art MBA simplifier; cited in `vmp_resources_external_tools`. |
| **asmMBA: Robust Virtualization Obfuscation with Assembly-Level MBA** (Jin et al.) | ACM SAC 2025, DOI 10.1145/3672608.3707862 | Loki-Blast deobfuscation method and NEG-instruction transformations. |
| **Simplifying MBA Expression Using E-Graphs** | arXiv 2404.05431 (2024) | E-graph-based MBA simplification approach. |
| **x64Unpack: Hybrid Emulation Unpacker for 64-bit Windows** | ResearchGate (2020) | DBI-based hybrid pipeline tested against VMP 3.4. |

### 🛠️ Reference implementations
| Source | Used for |
|---|---|
| **NoVmpy** (Python reference for NoVmp) | Canonical 34-opcode VM table reproduced in `vmp_get_opcode_table`. |
| **Triton symbolic execution engine** | Reference for `triton_veh_handler.py` approach in Rasetsuu repo. |
| **Z3 SMT solver** | Standard tool for MBA simplification proofs. |
| **Intel Pin** | Dynamic binary instrumentation framework used by Salwan's devirt. |
| **Capstone** | Disassembler used in handler analysis. |
| **Unicorn Engine** | Used by Rasetsuu's `vmp_interp.py` for handler emulation. |

### 🙏 Special thanks
- Every contributor to the **r0da blog**, **cyber.wtf**, **Tuts4you forums** and **Back Engineering Labs**
  for the years of public knowledge sharing.
- **VMPSoft** for building VMProtect — without it none of this research would exist.
- The **anti-cheat / malware analysis** communities for keeping the knowledge alive despite DMCA campaigns.

> **Disclaimer**: This MCP is intended for **defensive malware analysis**, **authorized
> reverse-engineering research**, **CTF challenges**, and **personal-license
> software auditing**. Do NOT use it to bypass licensing of software you do not own.

---

## License

MIT
