Metadata-Version: 2.4
Name: jnisleuth-mcp
Version: 0.4.0
Summary: Automated Android JNI RegisterNatives Recovery, Stripped ARM64 .so Emulation & Type Reconstruction, OLLVM Deobfuscation, JNISleuth Studio UI, and Unified MCP Server.
Author: Aman Kumar (@nighthawkk)
License: Apache-2.0
Project-URL: Homepage, https://github.com/nighthawkk/JNISleuth-MCP
Project-URL: Repository, https://github.com/nighthawkk/JNISleuth-MCP
Project-URL: Issues, https://github.com/nighthawkk/JNISleuth-MCP/issues
Project-URL: Changelog, https://github.com/nighthawkk/JNISleuth-MCP/releases
Keywords: android,jni,reverse-engineering,ghidra,ida-pro,jadx,mcp,arm64,ollvm,unicorn,dobby
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Disassemblers
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: emulate
Requires-Dist: unicorn>=2.0.1; extra == "emulate"
Provides-Extra: full
Requires-Dist: unicorn>=2.0.1; extra == "full"
Requires-Dist: fastmcp>=0.4.0; extra == "full"
Requires-Dist: lief>=0.14.0; extra == "full"
Requires-Dist: capstone>=5.0.0; extra == "full"
Requires-Dist: rich>=13.7.0; extra == "full"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: build>=1.2.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Dynamic: license-file

<div align="center">

# 🕵️‍♂️ JNISleuth-MCP

**Bridge the Java-to-Native Chasm in Android Reverse Engineering.**  
*Automated `RegisterNatives` Recovery, Stripped ARM64 `.so` Type Reconstruction, OLLVM `BR X8` Deobfuscation, and a Unified Jadx + Ghidra / IDA Pro 9.0 MCP Server for AI-Assisted Malware Analysis.*

[![CI](https://github.com/nighthawkk/JNISleuth-MCP/actions/workflows/ci.yml/badge.svg)](https://github.com/nighthawkk/JNISleuth-MCP/actions/workflows/ci.yml)
[![Platform](https://img.shields.io/badge/Platform-Android%20ARM64%20%7C%20ARMv7%20%7C%20x86__64-3DDC84?logo=android&logoColor=white)](#)
[![Backends](https://img.shields.io/badge/Backends-Ghidra%2011%2B%20%7C%20IDA%20Pro%209.0-red)](#)
[![MCP](https://img.shields.io/badge/MCP-FastMCP%20Compatible-blueviolet)](#)
[![Native Engine](https://img.shields.io/badge/Dynamic%20Tracer-Dobby%20%7C%20Frida-orange)](#)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](./LICENSE)

[**Quickstart**](#-2-minute-quickstart) • [**How It Works**](#-architecture--how-it-works) • [**MCP Tools**](#-universal-llm--mcp-support-works-with-any-model) • [**Stealth Dobby Agent**](#-stealth-dobby-agent-anti-rasp--packer-mode) • [**Roadmap**](#-roadmap)

</div>

<p align="center">
  <img src="./docs/assets/jnisleuth_demo.gif" alt="JNISleuth-MCP Walkthrough: RegisterNatives Recovery, OLLVM BR X8 Patching, Ghidra/IDA Sync, and MCP Slice" width="100%" />
</p>

---

## ⚡ Why JNISleuth-MCP?

Modern Android malware, banking trojans, spyware, and commercial packers hide their core logic (C2 encryption, key derivation, environment checks, and exploit routines) inside **stripped C/C++ native libraries (`lib*.so`)**.

When reversing across the JNI boundary, analysts hit three walls:
1. **Broken Cross-References:** `native` methods declared in `classes.dex` do not use standard `Java_com_pkg_Class_method` symbols. Instead, they are dynamically bound at runtime inside an obfuscated `JNI_OnLoad` via `JNIEnv->RegisterNatives()`.
2. **Blind Decompilation:** Opening a stripped `.so` in Ghidra or IDA shows thousands of unnamed `sub_XXXX` functions where `JNIEnv*` vtable calls look like raw pointer arithmetic (`(**(code **)(*param_1 + 0x538))(param_1, param_2)`).
3. **Disconnected AI Context:** Existing Ghidra MCP and Jadx MCP servers live in silos—an LLM cannot trace data flow from an Android `BroadcastReceiver` in Java straight into an ARM64 encryption routine in `libnative-lib.so`.

**`JNISleuth-MCP` eliminates the context switch.** It automatically recovers static and dynamic `RegisterNatives` bindings, patches OLLVM `BR X8` dispatchers, re-types stripped ARM64 functions in Ghidra & IDA Pro 9.0, and exposes a single unified **Model Context Protocol (MCP)** server connecting DEX bytecode to native assembly.

| Capability | Standard Jadx / Ghidra MCPs | `JNISleuth-MCP` |
| :--- | :---: | :---: |
| Resolve standard `Java_*` exports | ✅ | ✅ |
| Recover stripped `RegisterNatives` struct arrays statically (`.rodata` / `.data.rel.ro` + `JNI_OnLoad` CFG) | ❌ | ✅ |
| Resolve & patch OLLVM `CSEL` + `BR X8` indirect branches in `JNI_OnLoad` | ❌ | ✅ |
| Stealth on-device `RegisterNatives` harvesting via **Dobby** (bypasses anti-Frida checks) | ❌ | ✅ |
| Auto-apply `JNIEnv*` vtable types & reconstruct `Call*Method` / `GetStringUTFChars` in Ghidra & IDA Pro 9.0 | ❌ | ✅ |
| Single-call cross-boundary dataflow (`Java Caller` ➔ `JNI Bridge` ➔ `Decompiled ARM64 C++`) | ❌ | ✅ |

---

## 🏗️ Architecture & How It Works

```mermaid
flowchart LR
    subgraph Input["📦 Target APK / Malware"]
        DEX["classes*.dex"]
        ELF["Stripped lib/*.so (ARM64)"]
    end

    subgraph Harvester["🔍 Stage 1: JNI Bridge Harvester"]
        StaticScan["Static ELF & DEX Scanner\n(LIEF + Capstone + Heuristic Triplets)"]
        DobbyAgent["Stealth Native Agent\n(C++ / NDK / Dobby Inline Hook)"]
    end

    subgraph GhidraEngine["⚙️ Stage 2: Ghidra & IDA 9.0 Reconstructor"]
        Renamer["Function Renamer & Signature Applier"]
        VTable["JNIEnv* VTable & Struct Propagator"]
    end

    subgraph MCPServer["🤖 Stage 3: Unified FastMCP Server"]
        CrossGraph["Cross-Boundary Callgraph\n(Jadx Java + Ghidra/IDA C/ARM64)"]
        CallbackTrace["Upcall Tracer\n(Native -> Java Reflection)"]
    end

    DEX --> StaticScan
    ELF --> StaticScan
    ELF -. "Packed / OLLVM?" .-> DobbyAgent
    StaticScan --> Renamer
    DobbyAgent -- "register_natives.json" --> Renamer
    Renamer --> VTable
    VTable --> CrossGraph
    VTable --> CallbackTrace
```

---

## 🎬 See It In Action

<p align="center">
  <img src="./docs/assets/jnisleuth_readme_demo.png" alt="JNISleuth-MCP CLI Recovery, OLLVM BR X8 Patch, and Before vs After Ghidra/IDA Pro 9.0 Decompilation" width="100%" />
</p>

### 1. CLI Static + Dynamic `RegisterNatives` Recovery
Run `jnisleuth scan` against an APK with stripped native libraries:

```text
$ jnisleuth scan --apk samples/banker_dropper.apk --trace examples/register_natives_trace.json

[*] Parsing 3 DEX files... Found 14 declared `native` methods across 4 classes.
[*] Inspecting lib/arm64-v8a/libcore-crypto.so (Stripped ELF, 0 exported Java_* symbols)
[*] Running static JNINativeMethod triplet scanner on .rodata / .data.rel.ro...
    [+] Resolved 11/14 methods via static struct table @ 0x0004d210
    [+] Resolved 2 OLLVM indirect branches (BR X8) in JNI_OnLoad
[!] 3 methods unresolved (constructed dynamically on stack in JNI_OnLoad).
[*] Launching headless Dobby collector on device (emulator-5554)...

┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┓
┃ Java Class & Method                      ┃ JNI Signature        ┃ .so Offset (ARM64)  ┃ Resolution Mode  ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━┩
│ com.dropper.Core#initEngine              │ (Landroid/content/.. │ libcore.so+0x001a40 │ Static (.rodata) │
│ com.dropper.Core#decryptPayload          │ ([BLjava/lang/Stri.. │ libcore.so+0x0023c8 │ Static (.rodata) │
│ com.dropper.Core#signC2Beacon            │ (Ljava/lang/String.. │ libcore.so+0x003f10 │ Dynamic (Dobby)  │
│ com.dropper.net.SocketBridge#connectRaw  │ (Ljava/lang/String.. │ libcore.so+0x004890 │ Dynamic (Dobby)  │
└──────────────────────────────────────────┴──────────────────────┴─────────────────────┴──────────────────┘
[+] Synced 14 function signatures and JNIEnv* types to Ghidra (banker_dropper.gpr) & IDA Pro 9.0 (banker_dropper.i64)
```

### 2. Before vs. After in Ghidra / IDA Pro 9.0

**Before `JNISleuth-MCP` (`FUN_000123c8`):**
```c
long FUN_000123c8(long *param_1, undefined8 param_2, undefined8 param_3, undefined8 param_4) {
  char *pcVar1;
  long lVar2;
  pcVar1 = (char *)(**(code **)(*param_1 + 0x548))(param_1, param_4, 0);
  lVar2 = (**(code **)(*param_1 + 0x5c0))(param_1, param_3, 0);
  sub_00014a00(lVar2, pcVar1);
  (**(code **)(*param_1 + 0x550))(param_1, param_4, pcVar1);
  return param_3;
}
```

**After `JNISleuth-MCP` (`Java_com_dropper_Core_decryptPayload`):**
```c
jbyteArray Java_com_dropper_Core_decryptPayload(
    JNIEnv *env, jobject thiz, jbyteArray encryptedData, jstring rc4KeyStr) 
{
  const char *key_utf = (*env)->GetStringUTFChars(env, rc4KeyStr, NULL);
  jbyte *payload_bytes = (*env)->GetByteArrayElements(env, encryptedData, NULL);
  rc4_crypt_buffer(payload_bytes, key_utf);
  (*env)->ReleaseStringUTFChars(env, rc4KeyStr, key_utf);
  return encryptedData;
}
```

---

## 🤖 Universal LLM & MCP Support (Works With Any Model)

`JNISleuth-MCP` is **100% model-agnostic**. You can connect it to **any cloud or local LLM** via the standard Model Context Protocol (`stdio` JSON-RPC 2.0) or export native **OpenAI / Gemini / Ollama function-calling schemas**:
* **Cloud LLMs & Agents:** Google **Gemini CLI**, **OpenAI / ChatGPT Desktop / Codex CLI**, **Cursor**, **Windsurf**, **Cline**, **Roo Code**, **Claude Desktop / Claude Code**
* **Local / Self-Hosted LLMs:** **Ollama**, **vLLM**, **LM Studio**, **OpenWebUI**, **Continue.dev** (DeepSeek-R1, Qwen-2.5-Coder, Llama-3.3)
* **Custom Python Agent SDKs:** Direct tool-schema export (`jnisleuth llm-tools --format openai|gemini|mcp`) for LangChain, LlamaIndex, LiteLLM, OpenAI SDK, or `google-genai`.

| Tool Name | Description |
| :--- | :--- |
| `resolve_apk_jni_map(apk_path)` | Extracts all `native` declarations from DEX and maps them to exact ELF file offsets in `lib/*.so` (via export symbols, static `.rodata` triplets, or dynamic trace import). |
| `get_cross_boundary_slice(java_method)` | Returns the decompiled Java caller (via Jadx) **and** the typed, decompiled C/ARM64 implementation (via Ghidra/IDA) in a single unified response. |
| `trace_jni_upcalls(so_name, fn_offset)` | Lists every Java reflection callback (`FindClass`, `GetMethodID`, `CallObjectMethod`, `SetByteArrayRegion`) invoked inside a native ARM64 function and its callees. |
| `sync_ghidra_jni_types(trace_json)` | Applies `JNIEnv*`, `JavaVM*`, `JNINativeMethod` structs, and recovered function signatures directly into an active or headless Ghidra project. |
| `sync_ida_jni_types(trace_json)` | Applies `JNIEnv*`, `JavaVM*`, `JNINativeMethod` C headers, recovered function prototypes, and OLLVM `fl_JN` code cross-references into IDA Pro 9.0 (`idalib` / `idapyswitch` / `idat64`). |
| `resolve_ollvm_indirect_branches(so_name, fn_offset)` | Resolves OLLVM `CSEL` + `BR X8` state-machine dispatchers and `.rodata` jump tables in `JNI_OnLoad`, and optionally patches the ELF binary with direct `B.<cond>` / `B` instructions. |
| `extract_jni_onload_strings(so_name)` | Dumps stack-constructed and XOR-decrypted strings inside `.init_array` and `JNI_OnLoad` (tagged as untrusted binary data for prompt-injection safety). |
| `emulate_jni_onload(so_name, entry_offset, engine)` | Micro-emulates ARM64 `.init_array` & `JNI_OnLoad` (via **Unicorn** or the built-in zero-dep **pure-ARM64** engine) under a synthetic `JavaVM*`/`JNIEnv*` ABI to harvest runtime-built `RegisterNatives` bindings & decrypted strings with zero Android device needed. |
| `generate_html_report(apk_path, output_html_path)` | Generates a zero-CDN, offline-capable interactive **JNISleuth Studio** HTML report for any APK, Split-APK (`.apks`/`.xapk`), or `.so`. |

> **Streamable HTTP MCP + Prompts:** Start a remote/container-friendly MCP endpoint over HTTP/SSE with `python3 -m jnisleuth mcp --transport http --port 8766` (exposes `POST /mcp`, `GET /mcp`, `GET /health`, MCP Resources, and 3 built-in RE prompt templates via `prompts/list`).

---

## 🖥️ JNISleuth Studio UI & Shareable HTML Reports

Want visual exploration instead of raw JSON or terminal tables? `JNISleuth-MCP` ships a **zero-dependency, offline-capable interactive workbench** in two modes:

<p align="center">
  <img src="./docs/assets/jnisleuth_studio_demo.gif" alt="JNISleuth Studio Walkthrough: Before/After C Typing, Interactive SVG Call Graph, OLLVM & IOC Lab, and YARA/IDA/Ghidra Exports" width="100%" />
</p>

<details>
<summary>📸 View Static High-Resolution Cross-Boundary Bridge Screenshot</summary>
<p align="center">
  <img src="./docs/assets/jnisleuth_studio_ui.png" alt="JNISleuth Studio Cross-Boundary Bridge View" width="100%" />
</p>
</details>

1. **Zero-Server Standalone HTML Report (`--html-report`):**
   ```bash
   # Zero-install (plain python3 — no uv/pip required):
   PYTHONPATH=src python3 -m jnisleuth scan --apk samples/banker_dropper.apk --html-report report.html
   # Or via uv:
   uv run jnisleuth scan --apk samples/banker_dropper.apk --html-report report.html
   ```
   Generates a single self-contained HTML file (no external CDN dependencies, safe for air-gapped analysis VMs) featuring:
   - **Cross-Boundary Bridge:** Searchable native method rail, clickable `JNIEnv*` upcall pills that highlight C lines, synchronized Java caller + Before/After C toggle, and inline `SVC #0` syscall alerts.
   - **Interactive SVG Call Graph:** Java Callers → DEX Native Declarations → Stripped ELF Offsets → Reflection Upcalls & Syscalls.
   - **OLLVM & String Lab:** Patched vs. obfuscated indirect-branch preview and IOC/JNI string table.
   - **Export Studio:** One-click copy for syntax-validated IDA Pro 9.0 `.h`, Ghidra 233-slot manifest, starter YARA rule, and MCP context JSON.

2. **Local Interactive Studio Server (`jnisleuth ui`):**
   ```bash
   PYTHONPATH=src python3 -m jnisleuth ui --apk samples/banker_dropper.apk --port 8765 --open
   ```
   Opens a local browser studio (`http://127.0.0.1:8765`) with drag-and-drop `.apk`/`.apks`/`.so` + `register_natives.json` upload, deep-linkable URLs (`?tab=ollvm`, `?method=decryptPayload&c=after`), live re-scanning, one-click `.deobf.so` OLLVM patch download, and HTML report export.

---

## 🥷 Stealth Dobby Agent (Anti-RASP & Packer Mode)

Many wild Android malware families and commercial protectors immediately crash or exit if they detect `frida-agent.so` in `/proc/self/maps`, `gum-js-loop` threads, or modified function prologues in `libc.so`.

`JNISleuth-MCP` includes an optional **zero-Frida native collector (`agent-native/`)** written in C++20 and ARM64 assembly using **Dobby**:
* **Mid-Function Hooking:** Places hooks inside the `ArtMethod::RegisterNative` / `JNIEnvExt::RegisterNatives` dispatch path rather than the first instruction of exported stubs, evading basic prologue integrity scanners.
* **Base-Address Normalization:** Uses `dladdr()` and linker `soinfo` traversal to automatically subtract ASLR slide and record deterministic file offsets (`libfoo.so + 0x23c8`), even if the packer unmaps ELF section headers after `JNI_OnLoad`.

---

## 🚀 2-Minute Quickstart

### Prerequisites
* **Python 3.10+** (zero required third-party dependencies — works with plain `python3` or `uv`)
* *(Optional)* Ghidra 11.0+ (`GHIDRA_INSTALL_DIR`) or IDA Pro 9.0+ (`IDA_INSTALL_DIR` / `idapyswitch`)
* *(Optional)* Jadx CLI installed in `$PATH` (automatically used for real Java caller decompilation)
* *(Optional)* Android NDK r26+ & ADB for dynamic Dobby collection

### Installation & Zero-Install Usage
```bash
git clone https://github.com/nighthawkk/JNISleuth-MCP.git
cd JNISleuth-MCP

# Zero-install (plain python3 — works on macOS/Linux without uv or pip):
PYTHONPATH=src python3 -m jnisleuth scan --apk examples/obfuscated_jni_sample.apk --html-report jnisleuth_report.html
PYTHONPATH=src python3 -m jnisleuth ui --apk examples/obfuscated_jni_sample.apk --port 8765 --open

# Or with uv:
uv sync
uv run jnisleuth scan --apk examples/obfuscated_jni_sample.apk --html-report jnisleuth_report.html
uv run jnisleuth ui --apk examples/obfuscated_jni_sample.apk --port 8765 --open

# Auto-discover, resolve & patch OLLVM CSEL + BR X8 indirect branches in JNI_OnLoad:
PYTHONPATH=src python3 -m jnisleuth deobfuscate --so examples/libcore-crypto.so --offset auto --patch-out examples/libcore-crypto.deobf.so

# Micro-emulate ARM64 .init_array + JNI_OnLoad (Unicorn or built-in zero-dep pure-ARM64):
PYTHONPATH=src python3 -m jnisleuth emulate --so examples/libcore-crypto.so --engine auto

# Or run the turnkey Docker container (bundles Python 3.12 + Unicorn + Jadx CLI + Studio UI + HTTP MCP):
docker compose up --build
# Studio UI -> http://127.0.0.1:8765  |  MCP Streamable HTTP -> http://127.0.0.1:8766/mcp
```

### Connect to Any LLM / IDE Agent (`mcp.json` / `settings.json`)
Works out of the box with **Gemini CLI (`~/.gemini/settings.json`)**, **Cursor (`.cursor/mcp.json`)**, **Windsurf**, **Cline**, **Continue.dev (Ollama)**, **ChatGPT Desktop**, and **Claude** (using either `python3` directly or `uv`):
```json
{
  "mcpServers": {
    "jnisleuth-mcp": {
      "command": "python3",
      "args": ["-m", "jnisleuth.mcp_server"],
      "env": {
        "PYTHONPATH": "/path/to/JNISleuth-MCP/src",
        "GHIDRA_INSTALL_DIR": "/opt/ghidra",
        "IDA_INSTALL_DIR": "/opt/idapro-9.0"
      }
    }
  }
}
```

### Use with OpenAI / Gemini / Ollama Python SDKs Directly (No MCP Client Needed)
```bash
# Export function-calling tool schemas for OpenAI / Ollama / vLLM or Google Gemini:
uv run jnisleuth llm-tools --format openai > openai_tools.json
uv run jnisleuth llm-tools --format gemini > gemini_tools.json
```

---

## 🗺️ Roadmap

- [x] Static DEX `native` method parser + ELF `.rodata` / `.data.rel.ro` `JNINativeMethod` triplet scanner
- [x] Headless Ghidra `JNIEnv*` vtable auto-typing script for ARM64 & x86_64
- [x] Unified FastMCP server bridging Jadx, Ghidra & IDA Pro 9.0
- [x] On-device Dobby mid-function `RegisterNatives` + `DexFile::OpenCommon` unpacker module
- [x] IDA Pro 9.0 (`idapyswitch` / `idalib` / headless `idat64`) backend support alongside Ghidra
- [x] Automated OLLVM indirect-branch (`BR X8`) resolver & ELF patcher for `JNI_OnLoad` state machines
- [x] Modern NDK `SHT_RELR` / `DT_RELR` & `PT_DYNAMIC` sectionless ELF decoding + Split-APK (`.apks`/`.xapk`) support + inline `SVC #0` syscall detection
- [x] Zero-dependency interactive **JNISleuth Studio** (`--html-report` & local `jnisleuth ui` web workbench)
- [x] Dual-engine ARM64 `.init_array` / `JNI_OnLoad` micro-emulator (**Unicorn** + built-in zero-dep **pure-ARM64** fallback) for runtime-decrypted `RegisterNatives` tables & strings
- [x] MCP **Streamable HTTP / SSE** transport, MCP Resources & RE Prompts, turnkey **Docker** image, and automated **PyPI** OIDC release workflow
- [ ] Binary Ninja HLIL / headless sync backend
- [ ] ARM64 opaque-predicate & MBA expression simplifier for heavily protected packers
- [ ] Automated multi-stage native unpacker diffing (`before` vs. `in-memory dumped .so`)

---

## ⚠️ Disclaimer

`JNISleuth-MCP` is developed for **defensive malware analysis, mobile application security assessments, and reverse-engineering research**. All sample binaries in `examples/` are synthetic crackmes created specifically for testing.
