mirror of
https://codeberg.org/dabao1955/apk-reverse.git
synced 2026-11-28 11:50:22 +08:00
Extension pass: module route, extraction shells, emulation/RPC, DBI, kernel layer, protocols
Closes the six coverage gaps named in an external review of this skill, and moves the deliverable-form decision out of the single assumption it rested on. New references (7): - lsposed-and-modules.md deliver a hook module when a repack is refused - advanced-unpacking.md extraction shells, FART-style recovery, the root-side dump - emulation-and-rpc.md call the routine instead of reading it - native-dbi-and-deobfuscation.md OLLVM, Stalker traces, two measured boundaries - protocol-reverse.md protobuf/gRPC/QUIC and native-side pinning - kernel-and-environment-hardening.md when userspace hooking cannot reach the check - on-device-tooling.md MT Manager, its APK MCP, working from the phone New scripts (8): dex_dump_validate.py (+ --trim for page-aligned captures), dex_mem_scan.py, lsposed_scaffold.py, frida_rpc_serve.py + rpc_template.js, stalker_trace.js + stalker_report.py, mt_mcp_probe.py SKILL.md: - G1 carries a four-form deliverable table (rebuilt APK / module / RPC service / report) with the evidence that says when to leave the repack column, plus a matching hand-off section on how "verified" moves with the form - Coverage gains a documented-routes tier carrying its own strength note; Not-covered loses the now-inaccurate "general unpacker" line and gains the limits that do apply - 13 new symptom rows, 7 reference rows, 8 script rows, a fifth tooling obligation - the pid-drift symptom is stated with its competing causes, not a single attribution toolchain.md gains measured ASC/ddc cards; README gains the structure, capability and scope entries for everything above; .gitignore stops tracking the local workspace. Evidence: docs/tool-verification/EXTENSION-*.md (7 files), same three labels as the rest of the record. Measured: the gradle-free module build chain (5.27 s end to end), a successful injection confirmed through the LSPosed file channel (9 rounds) after three logcat queries came back empty on a ROM with a broken logd, 17 dex images recovered by root-side /proc/<pid>/mem dumping, the trivial-body metric separating a shell skeleton from real bodies, ASC/ddc on a hardened APK, and Stalker's zero-event and crash boundaries. The pid-drift attribution was corrected twice against better measurements.
This commit is contained in:
1 parent
5fa80a5bea
commit
ce2e4f98e1
27 files changed
+6602
-9
No files matched your search
@@ -0,0 +1,357 @@
|
||||
# Advanced Unpacking — Extraction Shells, Active Invocation, and the VMP Boundary
|
||||
|
||||
Load this when a memory dump of a packed app has already landed on your desk and the
|
||||
dump itself is the problem: the image parses, the classes are there, and the method
|
||||
bodies are empty. The neighbouring files each own one stage — `packers.md` owns
|
||||
*identifying* a shell and mapping what it validates, `recon.md` §Unpacking a dex-level
|
||||
packer owns the whole-image memory dump and its first-pass filtering, and
|
||||
`dynamic-frida.md` owns the runtime environment those dumps need. This file owns what
|
||||
comes after: recognizing that a "successful" dump is only a skeleton, recovering the
|
||||
missing code, and knowing where that recovery honestly stops.
|
||||
|
||||
**Strength note, read this first:** the repository's verification target carried no
|
||||
extraction shell and no VMP, so nothing here was exercised end to end against a live
|
||||
hardened sample by this skill's own verification pass. The FART/Youpk mechanisms and
|
||||
the Android 12-16 failure analysis are **inferred** from public work (FART/Youpk
|
||||
release notes and a 2026-08 Kanxue thread, `thread-292312`, on why classic
|
||||
active-invocation hooks die on modern ART). The one **measured** element is the
|
||||
detection metric: the trivial-body statistic was exercised by
|
||||
`scripts/dex_dump_validate.py` against a surgical fixture derived from a real hardened
|
||||
sample (see `docs/tool-verification/EXTENSION-unpacking.md`). Label your own results
|
||||
the same way.
|
||||
|
||||
Two parts of this file have since been exercised against live hardened targets on a
|
||||
rooted device. The **root-side memory route** (§Dumping when frida is refused) was run
|
||||
end to end: 17 ART dex mappings exported from `/proc/<pid>/mem`, page-alignment trim
|
||||
included, validated with `scripts/dex_dump_validate.py`; the evidence, the device-shell
|
||||
traps and the throughput numbers are recorded in
|
||||
`docs/tool-verification/EXTENSION-rootdump.md`. The `frida-dexdump` refusal that
|
||||
motivates that section is in `docs/tool-verification/EXTENSION-device-run.md`. The
|
||||
FART/active-invocation half of the file is still **inferred** — no extraction-shell
|
||||
target has been spliced end to end here.
|
||||
|
||||
## The four shapes a dump can be
|
||||
|
||||
Diagnose before choosing a route. Run `scripts/dex_dump_validate.py` over the dump
|
||||
directory and read the `stub%` column — the four shapes separate on it.
|
||||
|
||||
| The dumped image | `stub%` | Diagnosis | Route |
|
||||
|---|---|---|---|
|
||||
| Parses, many classes, real bodies | near-baseline | First-generation landing shell; the whole-dex dump **is** the original | Done — filter (`recon.md` §Unpacking a dex-level packer) and proceed to patching |
|
||||
| Parses, many classes, most bodies are `return-void` stubs or nop fills | high | **Extraction shell skeleton** — bodies are decrypted only on invocation | FART loop, this file |
|
||||
| Whole classes appear as bare `native` declarations | n/a | dex2c / JNI sink — the code left the dex entirely | `code-virtualization-and-custom-linkers.md` |
|
||||
| Parses, bodies present but instruction streams are nonsense to a dalvik disassembler | baseline | **Real Dex VMP** — private opcodes behind a native interpreter | Last section of this file, and be honest about the cost |
|
||||
|
||||
Two supporting signals worth recording while you are here (the second is measured on
|
||||
this repo's hardened sample): a shipped shell `classes.dex` can be megabytes in size
|
||||
yet define only a handful of classes — the bytes are payload, not code, so class count
|
||||
and file size move independently under a packer. And a dump whose signature field
|
||||
disagrees with its own contents while the checksum agrees is not necessarily corrupt;
|
||||
a shell that never verifies its own header can ship it that way, so treat
|
||||
checksum/signature results from `verify_dex_header` as evidence about *who touched the
|
||||
image*, not as a pass/fail gate on usability.
|
||||
|
||||
## Measuring extraction instead of guessing
|
||||
|
||||
The metric that separates shape 2 from shape 1 is the **trivial-body ratio**: among
|
||||
methods that *have* a `code_item` (`code_off != 0`), the fraction whose instruction
|
||||
stream, with plain `nop` units skipped, contains nothing but a single `return*`.
|
||||
`code_off == 0` methods are abstract or native declarations — that absence is normal
|
||||
and is excluded from the ratio. A method with a `code_item`, real `insns_size`, and a
|
||||
lone `return-void` inside is what an extraction shell leaves behind.
|
||||
|
||||
```bash
|
||||
python scripts/dex_dump_validate.py <dump_dir> --find 'Lcom/example/app/'
|
||||
```
|
||||
|
||||
The script dedupes by sha256 (never by size — same-size dumps of one dex have been
|
||||
measured to differ in ~73% of their bytes), rejects structurally impossible images
|
||||
(bad magic, `file_size` mismatch, ids out of range), counts classes and stub bodies,
|
||||
and ranks which surviving image is the most likely original.
|
||||
|
||||
Calibration, **inferred** from field reports rather than measured across a population:
|
||||
ordinary app code carries a few percent of genuinely trivial bodies (constructors that
|
||||
do nothing, interface stubs); a ratio in the tens of percent or higher is a skeleton,
|
||||
not code. A ratio that is high *and* the image parses is the extraction-shell
|
||||
signature — a first-generation dump of the same app would show the same classes with
|
||||
real bodies.
|
||||
|
||||
## The FART loop: skeleton, invocation, splice
|
||||
|
||||
Extraction shells decrypt a method body only when that method first executes. A dump
|
||||
taken at any fixed moment therefore holds whatever the app happened to invoke before
|
||||
you dumped — mostly stubs. Waiting for the UI to wander into every method is not a
|
||||
plan (thousands of methods, many on paths a user never triggers). The FART family of
|
||||
tools closes the loop with three steps, **inferred** (not run by this repo against a
|
||||
live extraction shell):
|
||||
|
||||
1. **Dump the whole image.** Class definitions, field and method signatures, string
|
||||
tables — the skeleton is complete even when every body is a stub. This is the
|
||||
ordinary `recon.md` dump; it gives you the address map for step 3.
|
||||
2. **Actively invoke every method.** Walk the dumped class list reflectively and call
|
||||
each method (dummy arguments; most will throw, which is fine — the point is that
|
||||
the *shell* decrypts and installs the body as the method is entered). Hook inside
|
||||
ART at the interpreter's entry so that, as each method begins executing, the
|
||||
method's `code_item` — now holding the decrypted body — is written to disk,
|
||||
tagged with its `method_idx`. These per-method records are the "bin" files of a
|
||||
FART dump.
|
||||
3. **Splice the bodies back into the skeleton.** For each record, overwrite the
|
||||
stub body in the whole-dex image at the offset the skeleton gives you, fix the
|
||||
header (`scripts/dexutil.py` `fix_dex_header` — signature first, checksum last),
|
||||
and **accept nothing until jadx or baksmali parses the result** and the method
|
||||
count matches the skeleton. "It assembled" is not "it repaired".
|
||||
|
||||
## The code_item length trap
|
||||
|
||||
Splicing fails in a specific place often enough to deserve its own section: the
|
||||
computed length of a `code_item`. The full layout is
|
||||
|
||||
```
|
||||
registers u16, ins u16, outs u16, tries u16, -- 8 B
|
||||
debug_info_off u32, insns_size u32, -- 8 B (header = 16 B)
|
||||
insns[insns_size] u2, -- the instruction stream
|
||||
[padding u2] -- ONLY if tries_size > 0 AND insns_size is odd
|
||||
try_item[tries_size] { start_addr u32, insn_count u16, handler_off u16 }, -- 8 B each
|
||||
encoded_catch_handler_list { uleb size; per handler: sleb offs... } -- variable
|
||||
```
|
||||
|
||||
Two segments are routinely dropped: the odd-`insns_size` padding before `tries`, and
|
||||
the whole `encoded_catch_handler_list`, which is LEB128-variable and sits *after* the
|
||||
try table. Drop either and the splice boundary slides — the rebuilt method swallows
|
||||
bytes from its neighbour or leaves the handler table pointing past the image, and the
|
||||
failure surfaces later as a dex that half-parses. Walk the handler list with
|
||||
`read_uleb` to its true end (`scripts/dexutil.py`); do not estimate it. This trap is
|
||||
**inferred** from repair-tool post-mortems, and it is the first place to look when a
|
||||
spliced dex parses worse than the skeleton did.
|
||||
|
||||
## Why the classic hooks die on Android 12-16
|
||||
|
||||
The original FART-era hooks assumed method entry flows through
|
||||
`art::interpreter::Execute`. On Android 12-16 that assumption fails for five
|
||||
independent reasons (**inferred**, from the Kanxue `thread-292312` analysis, 2026-08).
|
||||
Any one of them produces the same symptom — the dumper runs, logs everything, and the
|
||||
output directory stays thin:
|
||||
|
||||
1. **Invoke dispatch splits away from `Execute`.** A quick-entry call goes to Nterp,
|
||||
AOT or JIT code, or a bridge — none of them pass through the old `Execute` hook.
|
||||
Forcing the interpreter is not a fix either: the entry point then switches to
|
||||
Nterp, which *also* bypasses it. *Repair:* move the dump point up to
|
||||
`EnterInterpreterFromInvoke`, which sits ahead of the Nterp/interpreter split, and
|
||||
keep fallback points (special invoke branches, ClassLinker load paths, DexFile
|
||||
open, Frida ClassLoader enumeration) for the methods that still slip through.
|
||||
2. **`ArtMethod` layout drift.** Field offsets and pointer-sized members changed
|
||||
across releases; a hardcoded offset reads the wrong field and the dump silently
|
||||
mislabels everything after it. *Repair:* derive offsets at runtime (probe
|
||||
`access_flags` / `quickCode` / `jniCode` on a known method) instead of compiling
|
||||
them in.
|
||||
3. **Scoped Storage breaks the output quietly.** Writes to `/sdcard` fail, the log
|
||||
reads like a completed run, and the directory is empty. *Repair:* write under
|
||||
`/sdcard/Android/data/<pkg>/files/` (or app-private storage) and **check the
|
||||
`open()` return value** — the silent variant of this failure wastes a whole round.
|
||||
4. **The shell fights back.** Junk classes that exit inside their initializer,
|
||||
detection of reflective enumeration, deliberate dex-header corruption in memory,
|
||||
decryption deferred to the true execution point, fingerprinting of known dumper
|
||||
thread names and paths. *Repair:* randomize your thread names and output paths,
|
||||
filter junk classes (few methods, throwaway names) before invoking, and expect the
|
||||
counter-measure list to differ per vendor.
|
||||
5. **Compilation policy shifts the entry under you.** A just-installed app and one
|
||||
that has run for a while present different entry mixes (profile-guided
|
||||
compilation, Mainline module updates). *Repair:* re-probe the entry type every
|
||||
run; never cache yesterday's hook decision.
|
||||
|
||||
The debugging order that isolates all five in the fewest rounds: print the entry and
|
||||
flags for a known method → force the interpreter → observe what the entry became →
|
||||
place the dump point accordingly → force only the target package (`ignore` lists for
|
||||
`androidx.*`, `com.google.*`, `kotlin.*` — forcing the framework too freezes or kills
|
||||
the app) → compare a method's `code_item` before and after invocation → splice →
|
||||
verify with jadx/baksmali.
|
||||
|
||||
## Youpk in one paragraph
|
||||
|
||||
Youpk is the ROM-level descendant of the same idea (**inferred**): a modified ART
|
||||
performs the active invocation *inside* the runtime at class-link and interpret time,
|
||||
so the reflective caller script, the entry-point guessing, and most shell
|
||||
counter-measures against host-side tooling drop out — at the cost of building and
|
||||
flashing a customized runtime per Android version. Choose it when the target's
|
||||
anti-instrumentation defeats host-side loops entirely, and you control the device.
|
||||
|
||||
## The frida-dexdump route and where it stops
|
||||
|
||||
`frida-dexdump` walks the live ClassLoaders and writes every dex-shaped memory range.
|
||||
Environment setup and its two time sinks (the `-o` directory must pre-exist, and
|
||||
`-D` does not take remote devices) are recorded in `recon.md` §Unpacking a dex-level
|
||||
packer; the Frida environment itself is `dynamic-frida.md`. What it hands you is a
|
||||
pile of images of the four shapes above — dedupe, reject and rank them with
|
||||
`scripts/dex_dump_validate.py` before touching any by hand. Its hard limit: against
|
||||
an extraction shell it can only ever produce the **skeleton**, because the missing
|
||||
bodies exist nowhere in memory until invoked. No amount of re-dumping fixes that;
|
||||
only the invocation loop recovers them.
|
||||
|
||||
## Dumping when frida is refused
|
||||
|
||||
A hardened target can refuse instrumentation outright: the dump tool dies with
|
||||
`script has been destroyed` and the process is gone before the error can be read.
|
||||
That is a *protocol* refusal, not a timeout, and re-running the same attach with a
|
||||
different flag is the wrong response — twice-identical failure on one variable is a
|
||||
stop signal, not a hint to try a third flag. What remains is the route that never
|
||||
touches the process's instrumentation interface at all: **root reads the target's own
|
||||
memory** through `/proc/<pid>/maps` and `/proc/<pid>/mem`. No agent, no ptrace
|
||||
attach, no server process for the shell to find.
|
||||
|
||||
**Read the signals carefully, because one of them lies.** The refusal presents as
|
||||
(a) the dump tool's attach failing with `script has been destroyed` while the app is
|
||||
otherwise healthy, and (b) pid churn. But **pid churn alone is not evidence that
|
||||
frida was detected.** A 360-jiagu sample on this repository's test device was
|
||||
measured exiting every 7-18 s and being restarted by the platform, with *no*
|
||||
instrumentation process anywhere on the device, logging
|
||||
`Process <pkg> (pid N) has died: fg TOP` and no crash, tombstone or ANR record — a
|
||||
clean self-exit, i.e. the packer's own environment check. Attribution needs the
|
||||
control run, and the control run needs a window longer than one restart period: a
|
||||
12-second observation lands inside a 17-second cycle and reports "stable" about a
|
||||
process that is not. If the sample self-exits on that cadence, every step below must
|
||||
fit inside a single lifetime.
|
||||
|
||||
### Read the map before choosing the bytes
|
||||
|
||||
```bash
|
||||
adb shell 'su -c "pidof <PKG>"' # may return nothing mid-restart
|
||||
adb shell 'su -c "ps -A -o PID,NAME | grep -w <PKG>"' # more robust: matches either way
|
||||
adb shell 'su -c "cat /proc/<pid>/maps"' > maps.txt
|
||||
```
|
||||
|
||||
ART names its in-memory dex mappings for you — this is the cheapest win on the whole
|
||||
route, because a mapping called
|
||||
`[anon:dalvik-classes*.dex extracted in memory from <src>]` *is* a dex image, already
|
||||
located, already sized, no search required:
|
||||
|
||||
```
|
||||
7129d8c000-712a60f000 r--p [anon:dalvik-classes.dex extracted in memory from /data/app/~~…/base.apk]
|
||||
```
|
||||
|
||||
Copy those ranges first. Everything else — anonymous `rw-p`, `libc_malloc`, `.bss` —
|
||||
is a *search* target, and searching is the expensive half.
|
||||
|
||||
### Address arithmetic is where this route silently breaks
|
||||
|
||||
Three device-shell traps cost real time on the first run, and each one produces a
|
||||
plausible-looking result rather than an error:
|
||||
|
||||
| Trap | Symptom | Fix |
|
||||
|---|---|---|
|
||||
| mksh arithmetic is 32-bit | `$((16#7129d9a000))` yields `702128128` (the low 32 bits) — `skip=` then seeks to the wrong address and the dump looks like zeros | convert hex to decimal with `awk` (double precision handles 48-bit addresses exactly) |
|
||||
| A VMA is page aligned | the dump is 0..4095 bytes longer than the image; a validator rejects it with `file_size=8923752 actual=8925184` (17 of 17 files on the measured run) | trim to the `file_size` at dex header offset 32 before validating |
|
||||
| `grep` is line oriented | the magic contains a `0A`, so no line-oriented pattern can ever match `dex\n035\0`; `-F` with a real newline in the pattern fails too | `grep -z -a -o -b -E 'dex.035'` — with `-z`, records are NUL separated and `.` matches the newline byte; the reported offset is stream-relative, add the segment start |
|
||||
|
||||
One more that only bites in scripts: **toybox `awk` cannot be trusted with
|
||||
`/regex/ && $0 !~ /…/`** — a filter written that way selected all 808 map lines,
|
||||
including `r--p` system libraries. Filter the map with `grep` and keep `awk` for
|
||||
arithmetic only.
|
||||
|
||||
### Export, then prove it is a dex
|
||||
|
||||
```bash
|
||||
# inside one lifetime of the process: export a candidate range
|
||||
dd if=/proc/<pid>/mem iflag=skip_bytes,count_bytes skip=<DEC_START> count=<SIZE> \
|
||||
of=/data/local/tmp/seg_<n>.bin bs=256k
|
||||
adb pull /data/local/tmp/seg_<n>.bin <dumpdir>/<n>.bin # trim first, see above
|
||||
|
||||
# or, without writing to the device at all: search a range in place
|
||||
dd if=/proc/<pid>/mem iflag=skip_bytes,count_bytes skip=<DEC_START> count=<SIZE> bs=1M \
|
||||
| grep -z -a -o -b -E 'dex.035' | head -5
|
||||
```
|
||||
|
||||
Then the same acceptance gate the frida route uses: `scripts/dex_dump_validate.py`
|
||||
over the dump directory — sha256 dedupe, header and `file_size` validation, class
|
||||
counts, `stub%`, ranking. Rename to `*.dex` first; the validator selects on extension.
|
||||
Pass `--trim` when the captures come straight from VMAs: a page-aligned region is always
|
||||
longer than the image it holds, so without it every file is rejected on
|
||||
`file_size=… actual=…` — 17 of 17 on the measured run, all of them recoverable.
|
||||
|
||||
When you do **not** already know which region holds the payload —
|
||||
`scripts/dex_mem_scan.py <region_dir> --dump <out_dir>` does the search and the cut in one
|
||||
step: it scans the captures for the magic in bounded chunks, reads each hit's own header,
|
||||
and writes exactly `file_size` bytes from there. That is the anonymous-mapping case, where
|
||||
no `maps` entry names the buffer. The division of labour matches the rest of this kit:
|
||||
that script **finds and cuts**, `dex_dump_validate.py` **judges**. On the measured device
|
||||
the scan of 142 anonymous regions returned zero hits while the named ART mappings returned
|
||||
17 images — a negative from a cheap scan is worth having before committing to a heap sweep.
|
||||
|
||||
Measured on the test device, this route **works**: 17 ART dex mappings exported in
|
||||
one pass, all 17 parsing after the page-alignment trim, `stub%` 0.9-3.2 % (real
|
||||
bodies, SDK plugins), and one of them — the mapping that came from the app's own
|
||||
`base.apk` — defining exactly **4 classes** on 8.9 MB. That last image is the landing
|
||||
shell skeleton, and the class count is what says so; the size says nothing. Note what
|
||||
the route did *not* produce: no second application dex ever appeared in the map
|
||||
across 22 s of sampling, so the packer's real payload was not sitting in memory as a
|
||||
loaded ART dex while the observer watched — which is the honest boundary of every
|
||||
`/proc/<pid>/mem` dump, not a defect of the tooling.
|
||||
|
||||
### Limits to budget for
|
||||
|
||||
- **The process must stay alive and keep the same pid.** A VMA map and a page table
|
||||
both belong to a live process, and every `dd` after the restart reads the wrong
|
||||
address space or nothing. On a sample that self-exits every 7-18 s, a dump routine
|
||||
must be atomic within one window and re-entrant (re-read `maps` after every
|
||||
restart) rather than a long batch.
|
||||
- **Throughput is the binding constraint, not correctness.** Reading
|
||||
`/proc/<pid>/mem` through `grep -z -E` measured about **10 MB/s** on this device.
|
||||
A 1 GB ART heap is therefore a ~100 s scan — several lifetimes — so scanning the
|
||||
Java heap for a decrypted buffer is the *last* resort, not the first. Named ART dex
|
||||
mappings are free; a heap sweep is not.
|
||||
- **`/proc/<pid>/map_files/` is not a shortcut on this ROM.** The directory exists
|
||||
and is root-owned, but its entries are absent/unreadable, so `dd
|
||||
if=/proc/<pid>/map_files/<start>-<end>` returns a few dozen bytes of error text.
|
||||
Use the `mem` + decimal-offset form.
|
||||
- **Memcpy dumps of `.so` files are not the `.so` files.** A range lifted from
|
||||
`/proc/<pid>/mem` usually carries `PT_LOAD` contents and no section header table;
|
||||
a real ELF on disk has both. That difference is how to tell a *disk copy* of a
|
||||
library from a *memory-extracted* one — and it is why a leftover `.so` in a work
|
||||
directory must be matched against the APK it claims to come from before it is used
|
||||
as evidence.
|
||||
- **In-memory dex bodies can be non-contiguous.** A decrypted image stitched across
|
||||
two VMAs (or a payload the packer splits) will not be recovered by dumping ranges
|
||||
independently; the `code_off` cross-check and the class-count sanity check in
|
||||
§Measuring extraction are what catch that, not the magic search.
|
||||
|
||||
## The honest boundary: real Dex VMP
|
||||
|
||||
The last shape is the one to say out loud: if the dump's method bodies are intact but
|
||||
decode as private opcodes — rare-opcode density off the charts, unknown opcode slots,
|
||||
and a large native interpreter loop behind them — the code has been virtualized, and
|
||||
nothing in this repository will hand it back to you decompiled. Distinguish it from
|
||||
the JNI sink first (`code-virtualization-and-custom-linkers.md`): there the methods
|
||||
are `native` stubs and the logic lives as native code; here the bodies are present
|
||||
and *re-encoded*.
|
||||
|
||||
What recovery looks like when someone does it, **all inferred**, no fixture exists in
|
||||
this repo, treat as a research plan rather than a recipe:
|
||||
|
||||
1. **Differential hardening as a black-box oracle.** Build sample APKs containing
|
||||
every dalvik opcode in known, labeled sequences; submit them to the *same*
|
||||
hardening platform as the target; dump the returned dexes; align each original
|
||||
method with its hardened counterpart and read off the opcode substitution table.
|
||||
2. **Handler map recovery.** Locate the native interpreter's dispatch table; each
|
||||
handler implements one virtual opcode; the differential table names them.
|
||||
3. **A private disassembler.** Feed the substitution table into an existing dalvik
|
||||
decode layer (`scripts/dexutil.py`'s format table is the shape of the thing) and
|
||||
re-disassemble the bodies; decompilation is then ordinary tooling on the output.
|
||||
|
||||
Budget honestly: this is weeks, not an afternoon, and it redone per vendor per
|
||||
version. The cheaper question is usually whether the behaviour you need survives
|
||||
outside the virtualized island — a hook at the method's Java boundary
|
||||
(`dynamic-frida.md`) or a server-side answer often reaches the goal without paying
|
||||
for the island itself.
|
||||
|
||||
## Decision summary
|
||||
|
||||
| Observation | Action | Where |
|
||||
|---|---|---|
|
||||
| Dump parses, stub% near baseline | Filter, verify with jadx, move on to patching | `recon.md` |
|
||||
| stub% high, image parses | FART loop: skeleton + active invocation + splice | this file |
|
||||
| Splice produces a half-parsing dex | Re-check code_item length (padding, handler list) | §The code_item length trap |
|
||||
| Dumper runs, output dir empty | Storage path + `open()` check, then entry-type probe | §Why the classic hooks die on Android 12-16 |
|
||||
| App dies under the invoker | Shell counter-measures; narrow the force list | §Why the classic hooks die on Android 12-16, and `detection-and-anti-analysis.md` |
|
||||
| frida attach refused (`script has been destroyed`) | Root-side `/proc/<pid>/mem` dump, atomic inside one process lifetime | §Dumping when frida is refused |
|
||||
| Sample self-exits and restarts with no instrumenter present | The packer's own check, not your hook; shorten every step to one lifetime | §Dumping when frida is refused |
|
||||
| Methods are `native` stubs | dex2c / JNI sink | `code-virtualization-and-custom-linkers.md` |
|
||||
| Bodies present, decode as nonsense | Real VMP — differential oracle or walk away | §The honest boundary: real Dex VMP |
|
||||
@@ -0,0 +1,309 @@
|
||||
# Emulation and RPC — running the target's code on your terms
|
||||
|
||||
There is a class of target where neither reading nor patching is the bottleneck: the code you need
|
||||
is *inside* a hardened `.so`, statically unreadable (OLLVM, string encryption, VMP) or only
|
||||
decrypted in memory, and what you actually want is its **output** — the signature it computes, the
|
||||
blob it decrypts, the token it mints — not its source. Two routes give you that without winning the
|
||||
unpacking war first:
|
||||
|
||||
- **Unidbg** — emulate the `.so` on your PC, feed it inputs, read outputs. Offline, batch, no
|
||||
device, no detector. You pay in *environment*: everything the library touches must be faked.
|
||||
- **Frida RPC** — let the real process run its own hardened code, and call it from Python through a
|
||||
resident session. High fidelity (it is the real environment), no faking required. You pay in
|
||||
*stability*: the process must tolerate injection, and the session must survive.
|
||||
|
||||
This file is about choosing between them and driving both. The unpacking itself is
|
||||
`references/packers.md` and `references/advanced-unpacking.md`; the hooking mechanics live in
|
||||
`references/dynamic-frida.md`. What is new here is treating the target's own crypto as a **callable
|
||||
function** instead of a thing to understand.
|
||||
|
||||
## When emulation or RPC is the right move
|
||||
|
||||
Reach for this file when any of these holds:
|
||||
|
||||
- The algorithm you need lives in a hardened `.so` and reverse-engineering it (weeks against OLLVM
|
||||
or VMP) costs more than *calling* it (hours of environment work).
|
||||
- You need **many** calls — fuzzing an input format, brute-forcing a key schedule, generating
|
||||
signed request batches — where hand-driving a device per call is hopeless.
|
||||
- The function's output depends on environment state (files, system properties, other libraries)
|
||||
that a static read cannot evaluate.
|
||||
- The gate you care about is a *computed value* (sign header, encrypted body) rather than a branch
|
||||
— `references/server-api.md` told you the server checks it, and the client computes it in native
|
||||
code (`references/signature-derived-keys.md`).
|
||||
|
||||
Do **not** reach for it when a two-byte dex patch or an LSPosed module solves the problem —
|
||||
`references/dex-patching.md` and `references/lsposed-and-modules.md` are cheaper and more durable.
|
||||
Emulation and RPC are for when the code that matters must keep *running*.
|
||||
|
||||
## The decision table
|
||||
|
||||
| | Unidbg (offline emulation) | Frida RPC (live process) |
|
||||
|---|---|---|
|
||||
| Environment fidelity | fake — you build it | real — the device provides it |
|
||||
| Works without a device | yes | no (device or emulator required) |
|
||||
| Works against anti-injection | **yes** — the code never knows | **no** — injection is the entry ticket |
|
||||
| Batch throughput | thousands of calls/min | tens of calls/sec, process-bound |
|
||||
| Setup cost | Java + maven + per-library env work | frida already installed, minutes |
|
||||
| Maintenance cost | every missing JNI/syscall is a new stub | reconnect logic, process lifecycle |
|
||||
| Reproducibility | deterministic (you control time/random) | real time, real randomness |
|
||||
| Best for | signing algorithms, crypto, parsers | anything entangled with live app state |
|
||||
|
||||
The two-strike rule applies across the table: if a library refuses to run under unidbg after two
|
||||
focused rounds of `DalvikVM` patching, stop emulating and move to RPC (or the reverse) instead of a
|
||||
third round — a library that checks its own loading path or decrypts itself against device state
|
||||
may simply not be worth emulating, and that is a finding, not a failure (`SKILL.md`
|
||||
§Stop conditions).
|
||||
|
||||
## Part A — Unidbg
|
||||
|
||||
### What it is
|
||||
|
||||
Unidbg ([zhkl0228/unidbg](https://github.com/zhkl0228/unidbg), Java, Apache-2.0) emulates an
|
||||
Android process on your PC:
|
||||
|
||||
- **CPU** — a `backend` layer over Unicorn (default) or Dynarmic/Hypervisor, executing the real
|
||||
arm/arm64 code of your `.so`.
|
||||
- **Memory & linker** — it maps the ELF, resolves `DT_NEEDED` dependencies from a bundled Android
|
||||
system-library set (`AndroidResolver(apiLevel)`), and runs relocations.
|
||||
- **JNI environment** — a Dalvik VM emulation (`emulator.createDalvikVM(apk)`) that answers the
|
||||
library's `FindClass`/`GetMethodInfo`/`CallObjectMethod` calls against either real classes from
|
||||
the APK's dex or **stubs you write in Java**.
|
||||
- **Syscalls** — file IO, `mmap`, `pthread` primitives, system properties, `/proc` reads are
|
||||
emulated or redirected.
|
||||
|
||||
You write a Java main that wires those together, calls `JNI_OnLoad` (many hardened libraries do
|
||||
their initialization there), then calls the target function with your inputs. The library's real
|
||||
arm code executes; its output comes back as a Java value.
|
||||
|
||||
**This repository does not bundle unidbg** — it is a Java/maven project, not a script. To use it:
|
||||
|
||||
```bash
|
||||
git clone --depth 1 https://github.com/zhkl0228/unidbg.git
|
||||
cd unidbg
|
||||
# Windows + JDK 17 (measured): the shipped pom pins -source/-target 8, and on JDK 9+
|
||||
# the compiler resolves against the current API where `Module` is ambiguous
|
||||
# (java.lang.Module vs com.github.unidbg.Module) — unidbg-api fails to compile.
|
||||
# <release>8</release> selects the JDK 8 API and fixes it; the bundled Maven wrapper
|
||||
# is 3.5.4, which rejects maven-compiler-plugin 3.13, so 3.8.1 is the version that
|
||||
# both supports <release> and runs on that wrapper.
|
||||
set JAVA_HOME=C:\Program Files\Java\jdk-17.0.4.1
|
||||
mvnw.cmd -B -pl unidbg-android -am -DskipTests compile # BUILD SUCCESS, ~48 s
|
||||
# tests are skipped by <maven.test.skip>true</maven.test.skip> in the pom — override it:
|
||||
mvnw.cmd -B -pl unidbg-android -am -Dmaven.test.skip=false \
|
||||
-Dtest=MemoryTrackerTest -DfailIfNoTests=false test # Tests run: 3, Failures: 0
|
||||
# first run downloads maven itself plus dependencies — minutes
|
||||
```
|
||||
|
||||
Then pick the demo closest to your target under `unidbg-android/src/test/java` and adapt it; the
|
||||
bundled demos (`TTEncrypt`, `SignUtil`, `QDReaderJni`, …) each need the `.so`/APK they reference
|
||||
placed where the test expects it.
|
||||
|
||||
A library project that already uses maven/gradle can instead depend on the published artifacts
|
||||
(group `com.github.zhkl0228`, artifacts `unidbg-android` + `unidbg-api`, on Maven Central) — the
|
||||
clone-above route avoids version drift and gives you the test-suite demos to copy from.
|
||||
|
||||
### The minimal call template
|
||||
|
||||
Adapt this to your target — it is the shape every unidbg driver has (measured against the
|
||||
0.9.x API; class names move rarely but do move, check a current test under
|
||||
`unidbg-android/src/test/java` when something fails to resolve):
|
||||
|
||||
```java
|
||||
import com.github.unidbg.AndroidEmulator;
|
||||
import com.github.unidbg.LibraryLoader;
|
||||
import com.github.unidbg.linux.android.AndroidEmulatorBuilder;
|
||||
import com.github.unidbg.linux.android.AndroidResolver;
|
||||
import com.github.unidbg.linux.android.dvm.*;
|
||||
import com.github.unidbg.memory.Memory;
|
||||
import java.io.File;
|
||||
|
||||
public class CallTarget {
|
||||
public static void main(String[] args) {
|
||||
// 64-bit or 32-bit must match the .so, not the PC.
|
||||
AndroidEmulator emulator = AndroidEmulatorBuilder.for64Bit()
|
||||
.setProcessName("com.example.app") // some libraries check this
|
||||
.build();
|
||||
Memory memory = emulator.getMemory();
|
||||
memory.setLibraryResolver(new AndroidResolver(23)); // bundled system .so set
|
||||
|
||||
// The APK gives the VM real classes for JNI calls; null is allowed if
|
||||
// you intend to stub everything yourself.
|
||||
VM vm = emulator.createDalvikVM(new File("target.apk"));
|
||||
vm.setVerbose(true);
|
||||
vm.setJni(new AbstractJni() { // your JNI callbacks — see below
|
||||
// override methods as the target demands them
|
||||
});
|
||||
|
||||
DalvikModule dm = vm.loadLibrary(new File("libtarget.so"), false);
|
||||
dm.callJNI_OnLoad(emulator); // init: decrypts, registers natives
|
||||
|
||||
// Calling a *statically exported* symbol:
|
||||
// DvmObject<?> ret = dm.callFunction(...)
|
||||
// Calling a *JNI-registered* method by its Java name (most common for hardened SDKs):
|
||||
DvmClass<?> c = vm.resolveClass("com/example/NativeApi");
|
||||
DvmObject<?> result = c.callStaticJniMethodObject(emulator,
|
||||
"sign(Ljava/lang/String;)Ljava/lang/String;", "input");
|
||||
|
||||
System.out.println(result.getValue());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Filling the environment — "supply what is missing"
|
||||
|
||||
A hardened library does not just compute; it *checks*. Every unidbg session converges on the same
|
||||
loop: run, read the first unsupported callback or mapping fault, implement exactly that, repeat.
|
||||
In order of frequency:
|
||||
|
||||
| The library wants | You supply |
|
||||
|---|---|
|
||||
| `JNI_OnLoad` → `FindClass`/`GetMethodID` on app classes | `AbstractJni` overrides (`callStaticObjectMethodV`, `getStaticObjectField`, …) returning canned values; or real classes from the APK via `createDalvikVM(apk)` |
|
||||
| `Context` methods (`getPackageName`, `getFilesDir`, `getPackageManager` → signature!) | stubs — `vm.resolveClass("android/content/Context")` + your `AbstractJni` answers; a signature check wants the *original* APK's signature bytes, which `createDalvikVM(apk)` serves from that very file |
|
||||
| file reads (`/proc/self/maps`, `/data/data/...`, config files) | `emulator.getSyscallHandler().addIOResolver(...)` redirecting to host files, or `virtualFileSystem` mounts; a `/proc/self/maps` check that looks for frida/xposed is satisfied by a clean canned maps file |
|
||||
| other `.so` (cocos, tls, crypto) | `vm.loadLibrary` them first, in dependency order, or drop them beside the target so the resolver finds them |
|
||||
| time / randomness | `emulator.getSyscallHandler` clock override; unidbg's deterministic RNG unless the target seeds from `/dev/urandom` (redirect it) |
|
||||
|
||||
Two structural rules that save hours:
|
||||
|
||||
- **Load order is init order.** `JNI_OnLoad` of the shell often registers natives and decrypts;
|
||||
calling a function before the init that populates it yields a null deref that looks like a bug
|
||||
in unidbg. Always `callJNI_OnLoad` first, and if the library has an explicit init/exported
|
||||
setup entry, call that next.
|
||||
- **32 vs 64 must match the `.so`,** not your PC and not the device's preference
|
||||
(`references/native-and-so.md` §Cross-architecture applies here too: `for32Bit()`/`for64Bit()`
|
||||
mirror the ABI you extracted from `lib/`).
|
||||
|
||||
### Failure modes you will meet
|
||||
|
||||
| Symptom | Meaning | Move |
|
||||
|---|---|---|
|
||||
| `unsupported syscall` / `signal 11 (SIGSEGV)` at a stable address | the library touched something unidbg does not fake yet | read the unidbg log line above the fault — it names the syscall/JNI call; stub it |
|
||||
| `JNI_OnLoad` returns non-zero or throws | self-check failed inside init | enable `vm.setVerbose(true)`, read which check it ran (often signature, path, or a system property), satisfy it via stub |
|
||||
| works, but output differs from device | environment input differs (time, random, files, another lib's state) | diff the inputs: redirect and pin them; on-device RPC (Part B) is the ground truth to compare against |
|
||||
| crashes deep in the library, no unsupported call logged | the code path is genuinely wrong (wrong calling convention, wrong args) — or the library decrypted itself against device state it cannot have here | recheck the prototype (arg types/order) against the dex `native` declaration; then consider RPC instead |
|
||||
| library refuses to load: dependency not found | a `DT_NEEDED` `.so` you did not provide | `readelf -d` the target, load missing libs first |
|
||||
|
||||
Know when to stop: a library that validates its own decrypt key against server data, or that
|
||||
refuses any environment it did not boot in, is **not worth emulating** — that is exactly the shape
|
||||
where the decision table sends you to Part B. (Which anti-emulation checks exist and how common
|
||||
each is: inferred from community experience, not measured here.)
|
||||
|
||||
### Measured here
|
||||
|
||||
See `docs/tool-verification/EXTENSION-emulation-rpc.md` for the exact commands and outputs behind
|
||||
every label in this section. Measured in that pass: the repository builds on Windows/JDK 17 once
|
||||
the compiler plugin is pointed at the JDK 8 API, the emulator boots, and one bundled test suite
|
||||
passes on the Dynarmic backend. **No target `.so` was emulated yet** — every per-library claim above
|
||||
(which JNI callbacks a hardened library asks for, which syscalls it hits, how many rounds of stubbing
|
||||
it costs) is **inferred** from the library's shape and from community practice, not from a run
|
||||
against this sample.
|
||||
|
||||
## Part B — Frida RPC
|
||||
|
||||
### The mechanism
|
||||
|
||||
A Frida script can export functions to its host: assign to `rpc.exports`, and every property
|
||||
becomes callable from Python (`script.exports_sync.name(...)` after frida 16) with JSON-serializable
|
||||
arguments and return values, synchronously, from outside the process. That is the whole trick:
|
||||
|
||||
```javascript
|
||||
rpc.exports = {
|
||||
add: function (a, b) { return a + b; },
|
||||
};
|
||||
```
|
||||
|
||||
```python
|
||||
script = session.create_script(code); script.load()
|
||||
print(script.exports_sync.add(40, 2)) # -> 42
|
||||
```
|
||||
|
||||
Everything else is packaging: keeping the session alive, finding the function address, converting
|
||||
types across the NativeFunction boundary. The pattern for the case that matters — a hardened
|
||||
library's signing function, exported or `RegisterNatives`-bound:
|
||||
|
||||
```javascript
|
||||
// 1) exported symbol:
|
||||
const addr = Module.findExportByName('libtarget.so', 'Java_..._sign');
|
||||
// 2) dynamically registered (no export — the usual shape for hardened SDKs):
|
||||
// hook RegisterNatives once at startup, note the fnPtr for the name you care about
|
||||
const sign = new NativeFunction(addr, 'pointer', ['pointer', 'pointer']);
|
||||
rpc.exports = { sign: function (s) { return sign(env, jstring(s)); } };
|
||||
```
|
||||
|
||||
Java-side functions are equally callable (`Java.perform` wraps the call), which is how the
|
||||
harmless connectivity probe — `getPackageName` over RPC — works in the template below.
|
||||
|
||||
### The kit's tooling
|
||||
|
||||
`scripts/frida_rpc_serve.py` + `scripts/rpc_template.js` implement the full loop:
|
||||
|
||||
- three front ends: one-shot `--mode call`, interactive `--mode repl`, and a resident
|
||||
`--mode http` endpoint (`POST /call {"export": "...", "args": [...]}`, `GET /exports`,
|
||||
`POST /reload`);
|
||||
- spawn or attach (by name or by pid — attach-by-name fails on incomplete process enumeration,
|
||||
`references/dynamic-frida.md` §Attach by PID);
|
||||
- automatic reconnect: a detached session (app restart, killed server, ROM reaping the server)
|
||||
re-attaches, reloads the script and retries the call, with per-request retry cycles and
|
||||
exponential backoff; a killed-and-restarted device server is recovered by dropping the cached
|
||||
remote device before reconnecting;
|
||||
- the template exports `add` (transport sanity), `getpackagename` (Java probe),
|
||||
`callnative(module, export, retType, argTypes, args)` and `callnativeaddr(module, offset, ...)`
|
||||
for wrapping any native symbol, with a frida-16/17-compatible export resolver.
|
||||
|
||||
Typical session (device server already running and forwarded, `references/dynamic-frida.md`
|
||||
§Setup):
|
||||
|
||||
```bash
|
||||
adb -s <serial> forward tcp:27043 tcp:27043
|
||||
python scripts/frida_rpc_serve.py --remote 127.0.0.1:27043 --package com.example.app \
|
||||
--script scripts/rpc_template.js --mode repl
|
||||
rpc> list
|
||||
rpc> getpackagename
|
||||
rpc> callnative ["libtarget.so","Java_com_example_Native_sign","pointer",["pointer","pointer"],[...]]
|
||||
```
|
||||
|
||||
Then feed the recovered function into request generation the way `references/server-api.md`
|
||||
describes — the RPC service turns "the server checks a signed header" into "I can compute that
|
||||
header on demand", which is the whole reason this route exists.
|
||||
|
||||
### What the live route costs — measured failure modes
|
||||
|
||||
Every row below was hit against a real device during the verification pass behind this file
|
||||
(exact outputs in `docs/tool-verification/EXTENSION-emulation-rpc.md`):
|
||||
|
||||
| Failure | What it looks like | Handling |
|
||||
|---|---|---|
|
||||
| **Hardened target kills injection** | attach: `process either refused to load frida-agent, or terminated during injection`, logcat `CRASH ... IterateRegisters found fp`; spawn: script loads, then every call dies with `script has been destroyed` | the shell's anti-instrumentation won; do not retry the same attach — switch route (unidbg for the crypto, or `references/lsposed-and-modules.md` / static patching), or fight the detector deliberately (`references/detection-and-anti-analysis.md`) |
|
||||
| **ROM reaps the server** | `connection closed` mid-session, sometimes repeatedly | budget restarts, not re-analysis: the bridge reconnects once the server is back; check `pidof <server>` before every experiment block (`references/dynamic-frida.md`) |
|
||||
| **Attach by name fails for processes the device can see** | `unable to find process with name 'com.example.app'` while `frida-ps -Uai` and `ps -A` both list it alive; reproduced for a system app and for a Magisk-manager process, for every package name tried | resolve the pid yourself and attach with `--pid`: measured on the same ROM, `device.attach(pid)` loaded the script and returned RPC results for the very processes whose *name* lookup failed (`--pid 19938` → `com.android.settings`, `--pid 21493` → `com.android.email`). Take the pid from `frida-ps -U`, `ps -A`, or `adb shell pidof <pkg>` |
|
||||
| **The server comes back on a non-default port** | `frida.ServerNotRunningError: unable to connect to remote frida-server: closed` on attach even though `frida-ps -U` still works | the ROM or a watchdog reaped the visible server and a disguised copy returned elsewhere (measured: only `*.svc16` left alive, listening on 27043, nothing on 27042). Check the listening port, `adb forward tcp:27043 tcp:27043`, then `--remote 127.0.0.1:27043` — do not assume the default port |
|
||||
| **Attach by pid times out on a busy process** | `frida.TimedOutError: unexpectedly timed out while waiting for signal from process with PID X` during attach (raised by an ordinary third-party app); it is not a `TransportError` subclass and escaped every handler | nothing is wrong with the tooling — the process did not answer the agent handshake; use another process for the connectivity probe, or retry once the app settles (the bridge now treats `TimedOutError` as retryable and fails with one line instead of a traceback) |
|
||||
| **Short-lived processes** | the settings main activity process exits seconds after `am start` | pick a persistent process for connectivity tests; the business target only when it actually stays up |
|
||||
|
||||
The strategic point those rows make together: **on a hardened target, RPC is not guaranteed to be
|
||||
available at all** — the injection ticket can be revoked by the target itself. That is the single
|
||||
strongest argument for keeping the unidbg route warm, despite its environment cost: it is the one
|
||||
route that works when the process refuses to be instrumented.
|
||||
|
||||
### Combining the routes
|
||||
|
||||
The routes compose rather than compete:
|
||||
|
||||
1. **RPC as oracle, unidbg as student.** When an emulated function's output must be trusted, diff
|
||||
it against the live process's output for identical inputs; disagreement localizes the missing
|
||||
environment piece far faster than reading the library (`Part A` §failure modes, "output
|
||||
differs").
|
||||
2. **Dump via RPC, emulate after.** A live call that returns the decrypted key/table the library
|
||||
uses (`references/runtime-data.md`) can be replayed into the emulated run as a fixed stub.
|
||||
3. **Batch offload.** Use the device session to discover the calling convention and to capture
|
||||
sample inputs/outputs (few calls), then run the bulk of the work offline under unidbg.
|
||||
|
||||
## What to record
|
||||
|
||||
- which route was chosen and why (one line, against the decision table)
|
||||
- for unidbg: the API level resolver, the list of JNI stubs you had to write, what the library
|
||||
checked before it would compute (that list *is* the target's defense inventory)
|
||||
- for RPC: server version vs host version, attach vs spawn, reconnect behaviour observed, and —
|
||||
decisive for a hardened target — whether injection survived at all
|
||||
- inputs/outputs for at least one call verified against an independent source (device-side log,
|
||||
server response, or a known-answer test)
|
||||
@@ -0,0 +1,211 @@
|
||||
# Kernel-level and environment hardening — where to go when userspace hooking is not enough
|
||||
|
||||
Load this when you have already concluded, via `detection-and-anti-analysis.md`, that the target
|
||||
genuinely detects your instrumentation — and that the check cannot be neutralised from userspace
|
||||
because it runs before your hook, or bypasses the layers a userspace hook can reach. This file is
|
||||
the **escalation map**: what the next layer down actually is, what it costs, and when it is the
|
||||
wrong answer.
|
||||
|
||||
Division of labour, so the two files never duplicate:
|
||||
|
||||
- `detection-and-anti-analysis.md` owns **identifying** detection and the **cost decision**
|
||||
(work around / change route / accept and report). Read it first; its Step 0 still applies.
|
||||
- This file owns **the routes below userspace** — root-implementation hiding properties, kernel
|
||||
interception options, and the syscall-level realities that decide whether "just hook it" was
|
||||
ever going to work.
|
||||
|
||||
**This repository does not do kernel development.** Everything in the kernel section is a map of
|
||||
externally documented mechanisms with sources, labelled `inferred` — none of it was executed here.
|
||||
That is deliberate: the purpose is to stop you from spending a day rediscovering the version
|
||||
gate (§4) or the conflict (§5), not to teach kernel hacking.
|
||||
|
||||
## 1. The attack-surface timeline — why "just hook it" fails
|
||||
|
||||
An app process initializes in a fixed order, and every anti-analysis check you will meet lives at
|
||||
one of these stations:
|
||||
|
||||
```
|
||||
linker (ld-android/inker) -> relocations resolved, DT_INIT run
|
||||
.init_array of each loaded .so -> constructors: earliest native code that runs
|
||||
JNI_OnLoad -> packers and RASP SDKs hook here
|
||||
Application.onCreate -> first Java-level check
|
||||
first frame -> UI-visible checks (and the end of "early")
|
||||
```
|
||||
|
||||
The later your tool attaches, the more of this timeline has already executed and taken its
|
||||
decision. Frida in attach mode arrives after all of it; spawn mode arrives at zygote fork, which
|
||||
is why `dynamic-frida.md` prefers it — but a constructor in `.init_array` can still run before
|
||||
the Frida agent finishes injecting, and a check placed there fires once and stores its verdict.
|
||||
|
||||
What those checks actually look for, and why each one is out of reach of a naive userspace hook
|
||||
(the identification side belongs to `detection-and-anti-analysis.md`; this is the *mechanics* of
|
||||
why the hook does not land):
|
||||
|
||||
| Detection mechanism | Why a userspace hook misses it |
|
||||
|---|---|
|
||||
| Inline `svc #0` syscalls (bypassing libc) | PLT/GOT hooks only intercept calls that go through the PLT. Hand-written `svc` instructions in the target's own `.so` never touch libc, so there is no PLT entry to redirect. |
|
||||
| `/proc/self/maps` scan for foreign mappings | The read can be done with raw `openat`+`read` syscalls (same svc trick), and the thing being detected — your injected agent's mapping — exists in the process regardless of what you hook. |
|
||||
| Named pipes / thread-name probes for known agents | Frida's runtime creates identifiable threads (`gum-js-loop` etc.) and (older versions) a linjector pipe. Renaming helps only if you control the runtime's identity, not the probe. |
|
||||
| Code-page checksums of the target's own `.so` | An inline hook *is* a modification of the pages being checksummed. The check catches the hook by construction; the only userspace answer is to also neutralise the checksum, which recursively has the same problem if *that* code is checksummed too. |
|
||||
| `/proc/self/status` `TracerPid` read | The field is written by the kernel. A userspace hook on the reader works only until the reader uses raw syscalls (row 1). See §6. |
|
||||
|
||||
The structural lesson: **userspace hooking and userspace anti-hooking are the same layer.** A
|
||||
detection routine that lives in the same process as your hook, and that is willing to use raw
|
||||
syscalls and self-verification, can always in principle race you. The routes below win by moving
|
||||
to a layer the check cannot see from userspace — or by not being in the process at all.
|
||||
|
||||
## 2. Root implementations and what each one exposes
|
||||
|
||||
The root method you run decides which artefacts a detector can find *outside* the target process
|
||||
(manager app, daemon, mount layout, SELinux contexts). Facts below are from the projects' own
|
||||
documentation (sources at the end of the section); none were re-measured here — `inferred`.
|
||||
|
||||
| | **Magisk** | **KernelSU** | **APatch** |
|
||||
|---|---|---|---|
|
||||
| How su works | Patches the ramdisk/init; a `magiskd` runs in userspace; the manager app requests su through it | `su` handled **inside the kernel**; a manager app talks to the kernel via a driver/interface. Kernel modification. | Kernel modification via **KernelPatch**: patches the existing `boot.img` kernel — no kernel source needed (the difference from KernelSU) |
|
||||
| Kernel version gate | None (works on old kernels — this is why the 4.14 test device runs it) | Official support = GKI 2.0, kernel **5.10+** (in practice: shipped with Android 12). Backported to 4.14 but you must build the kernel yourself | Same GKI-era expectation; needs only the stock `boot.img` to patch |
|
||||
| Access control | Manager grants per-app; denylist for hiding | Manager + **App Profile** (constrain what a rooted app can do) | **SuperKey**: KPatch installs a new syscall (SuperCall); callers must present the SuperKey credential |
|
||||
| SELinux | Modifies contexts (magiskpolicy) | Kernel-side handling | Hooks/bypasses SELinux rather than rewriting contexts — threads can be rooted in app context without `libsu`/IPC |
|
||||
| Module format | Magisk modules (magic mount) | Magisk-compatible modules; `/system` modification needs a metamodule (overlayfs) | APM (Magisk-compatible) plus **KPM** — kernel-space modules with inline-hook and syscall-table-hook capability |
|
||||
| Zygisk | Built-in | None built-in; add ZygiskNext | None built-in; add ZygiskNext / ReZygisk / NeoZygisk |
|
||||
|
||||
**What this means for hiding** (`inferred`):
|
||||
|
||||
- **Manager identity is the shared weak point.** All three ship a manager app the detector can
|
||||
enumerate by package or by scanning for its UI. All three support "randomise/repackage the
|
||||
manager" — use it, and do not assume the default package name is safe.
|
||||
- **KernelSU/APatch remove the userspace su daemon** the detector could otherwise find as a
|
||||
process or a socket. But they add a kernel-level surface of their own; a detector cannot see it
|
||||
from an unprivileged app — which is the point.
|
||||
- **Magisk on an old kernel is not a disadvantage for hiding**; it is a constraint of the device.
|
||||
Do not switch root schemes to win a detection race — that is §7's stop signal.
|
||||
- **Module ecosystems interoperate but do not merge**: KernelSU's module system conflicts with
|
||||
Magisk magic mount (per KernelSU FAQ, running both means one stops working); su-only coexistence
|
||||
is possible because KernelSU patches the kernel while Magisk patches the ramdisk.
|
||||
|
||||
Sources: KernelSU README + FAQ (github.com/tiann/KernelSU), APatch FAQ (apatch.dev, project
|
||||
originally at github.com/bmax121/APatch), fetched 2026-09. Device facts (Magisk alpha on kernel
|
||||
4.14.186) are `observed` in `tools/_phone-modules/README-手机模块环境.md`.
|
||||
|
||||
## 3. Environment-hiding modules: Zygisk-Assistant vs Shamiko
|
||||
|
||||
Both are Zygisk modules that hide root + Zygisk from target apps. **Do not install both** — they
|
||||
overlap in function (mount-namespace handling, trace wiping) and interfere; this is documented in
|
||||
the module ecosystems and was the deciding fact on the reference device (`observed` in
|
||||
`tools/_phone-modules/README-手机模块环境.md`: Shamiko kept as a backup zip, uninstalled).
|
||||
|
||||
The practical difference is their **denylist dependency** (from each project's own README,
|
||||
`inferred`):
|
||||
|
||||
| | **Shamiko** | **Zygisk-Assistant** |
|
||||
|---|---|---|
|
||||
| Reads the Magisk denylist | Yes — but **requires DenyList enforcement to be OFF** (it takes over the handling itself) | Magisk: add the target to the denylist, **Enforce DenyList OFF**. KernelSU/APatch: enable the manager's "Umount modules/Exclude modifications" for the target app |
|
||||
| Extra modes | Whitelist mode via `/data/adb/shamiko/whitelist` (empty file); docs warn of performance/memory cost, test-only | — |
|
||||
| On APatch | Officially unsupported ("Shamiko is proprietary software, we cannot adapt it" — APatch FAQ) | Works via ZygiskNext |
|
||||
| Version gates | Newer Shamiko requires recent Magisk/KernelSU bases | Current |
|
||||
|
||||
Selection rule (`inferred`): on Magisk, either works alone — pick one, configure its denylist
|
||||
dependency correctly, and verify on the actual target. On KernelSU/APatch, Zygisk-Assistant (+
|
||||
ZygiskNext) is the supported path. The denylist/enforcement settings are the part people get
|
||||
wrong: **enforcement off, list populated** is the working combination for both.
|
||||
|
||||
Verification status: neither module's hiding effect was tested against a real detector on the
|
||||
reference device (`tools/_phone-modules/README-手机模块环境.md` §未覆盖的验证) — treat every
|
||||
"this hides X" claim above as documented-but-unproven here.
|
||||
|
||||
## 4. Kernel-level interception — the map, and the version gate
|
||||
|
||||
When you need to observe or alter what a target does *at syscall level* — e.g. it reads
|
||||
`/proc/self/status` via raw `svc`, and you want that read to return a spoofed page — userspace is
|
||||
structurally the wrong layer. The options below exist; **none of them were executed in this
|
||||
repository** (`unverified`), and each has a hard prerequisite worth checking before you read any
|
||||
further:
|
||||
|
||||
```
|
||||
uname -r # on the device. The gate for most of this section is 5.10+
|
||||
```
|
||||
|
||||
- **Why 5.10**: Android's GKI (Generic Kernel Image) programme starts at android12-5.10; the
|
||||
kernel-BPF ecosystem for tracing (bpftrace-class tools, kprobe/uprobe attachment as the tooling
|
||||
expects it) targets GKI kernels. Source: the Android kernel architecture documentation on
|
||||
source.android.com (GKI and eBPF pages). On the reference
|
||||
device (kernel **4.14.186**) this entire row is **closed** — `observed` (the version), with the
|
||||
consequence recorded in `tools/_phone-modules/README-MCP与网络环境.md`: eBPF-based tooling
|
||||
(stackplz, mcp-termux's tracing half) is unavailable there. Write the one-line environment fact
|
||||
per `detection-and-anti-analysis.md` Step 5 and do not revisit it.
|
||||
|
||||
| Route | What it gives you | Prereqs | Strength |
|
||||
|---|---|---|---|
|
||||
| **eBPF kprobes/uprobes** | Fire a BPF program on kernel or userspace function entry; observe syscall arguments/results system-wide, invisible to the target process | GKI 5.10+ kernel with the BTF/tracing config; root; toolchain (bpftrace or a custom loader) | `inferred` — documented upstream, not run here |
|
||||
| **seccomp-BPF filter** | Per-process syscall allow/deny — can make a syscall **fail**, and seccomp can be installed by the app on itself (no root needed for self-filtering) | Any modern kernel; but a filter you install into the target requires ptrace/zygisk injection first | `inferred`. **Key limitation**: seccomp can reject or error a syscall (SECCOMP_RET_ERRNO/TRAP); it cannot rewrite the *content* of what a successful read returns. It closes doors; it does not paint them. |
|
||||
| **Kernel module hooking** (KPM on APatch; out-of-tree LKM elsewhere) | Inline hooks and syscall-table hooks in kernel space — the layer that *can* rewrite what a `/proc` read returns | APatch (KPM) or a self-built kernel/LKM load path; kernel-dev skills | `inferred`. This is genuine kernel development — out of scope for this skill (§7) |
|
||||
| **Zygisk injection** (not kernel, but below the target's defences) | Run code in the target's process from zygote fork, before `.init_array` of the app's own libs | Magisk/KernelSU+ZygiskNext + a Zygisk module; no ptrace involved | `measured` as a framework (LSPosed runs this way on the reference device); a purpose-built module for a given target is `inferred` here |
|
||||
|
||||
The row that matters most in practice: **Zygisk is the cheap "below userspace" route** — it is in
|
||||
the process earlier than any userspace tool can be, needs no ptrace (so it does not trip
|
||||
`TracerPid`), and its ecosystem is maintained by other people. A custom kernel module that
|
||||
rewrites one `/proc` read is a research project; a Zygisk module that hooks the target's
|
||||
constructor is a build task.
|
||||
|
||||
## 5. The syscall-level realities that survive every hook
|
||||
|
||||
Two facts decide a lot of "unexplainable" behaviour, and both belong to the kernel's design
|
||||
rather than to any tool:
|
||||
|
||||
1. **`TracerPid` is written by the kernel, not by a library.** Anything that ptraces the target
|
||||
(classic Frida attach, debuggers) makes `/proc/self/status` show it, and the only readers that
|
||||
miss it are the ones you broke. Ways out, in escalating cost:
|
||||
- attach-free operation: **Zygisk** (injection at fork; no ptrace) or Frida **spawn** (still
|
||||
ptrace-based but only during injection — verify for your version) or a memory patch applied
|
||||
before detach (`scripts/spawn_patch_detach.py`, `measured`);
|
||||
- kernel-level hiding of the field (KPM/eBPF rewrite of the proc read) — §4, `unverified`;
|
||||
- **self-ptrace**: the target ptraces itself so nothing else can (classic anti-anti-debug);
|
||||
works because only one tracer is allowed — but it constrains your tooling to non-ptrace
|
||||
routes anyway. `inferred`.
|
||||
2. **A raw `svc` cannot be intercepted from userspace at all.** No PLT, no libc, no hookable
|
||||
symbol. Every plan that says "hook open/read and spoof the maps" silently assumes the target
|
||||
calls libc; a hardened target does not. Verify which one you have before building the spoof:
|
||||
disassemble the check's `.so` and look for `svc #0` (AArch64) / `int 0x80`-era equivalents in
|
||||
the check path (`inferred`; `scripts/native_crash.py`-style capstone disassembly applies).
|
||||
|
||||
## 6. What the reference environment chose (and why it generalises)
|
||||
|
||||
On the 4.14-kernel reference device, the escalation ladder terminates early — and that is the
|
||||
honest outcome (`observed`, from `tools/_phone-modules/README-*.md`):
|
||||
|
||||
| Layer | Status on a 4.14 Magisk device |
|
||||
|---|---|
|
||||
| LSPosed (Zygisk) module hooking | available — framework activation verified by log (`welcome to LSPosed!` lines, `lspd` daemon process) |
|
||||
| MT Manager on-device editing/repack/sign | available (`on-device-tooling.md`) |
|
||||
| eBPF tracing | closed (kernel gate) |
|
||||
| KPM / kernel module route | closed (no kernel source/build for the device; out of scope regardless) |
|
||||
| Frida with disguised server | available (a renamed server binary was present on the device from prior work) |
|
||||
|
||||
The generalisable rule: **enumerate the ladder for *your* device once, write the one-line
|
||||
environment facts, and stop re-deriving them mid-task.** A closed rung is a route decision, not a
|
||||
failure.
|
||||
|
||||
## 7. When to stop escalating — the decision table
|
||||
|
||||
This extends `detection-and-anti-analysis.md` Step 2 with the kernel rung. The repo's stance:
|
||||
R3 (never ship or claim an unverified artifact) outranks winning the arms race; a detector you
|
||||
defeated with a custom kernel module is not a deliverable anyone can install.
|
||||
|
||||
| Situation | Do this | Not this |
|
||||
|---|---|---|
|
||||
| Check is userspace, hookable, single-site | Neutralise at the site (`native-tamper-and-suicide.md` rules) | Building a hide stack |
|
||||
| Check runs before your userspace tool (init_array) | Zygisk-route module, or static patch of the check itself | Earlier userspace attach racing the constructor |
|
||||
| Check uses raw syscalls | Static patch of the check; or LSPosed/Zygisk module hooking the consuming code | "Hook libc open/read" (does nothing) |
|
||||
| Check detects the *environment* (root/emulator), not your patch | `detection-and-anti-analysis.md` A/B/C — usually a different device or route | Kernel work |
|
||||
| You are about to write a kernel module / patch a kernel | Stop. State what is blocked and the evidence; propose the static/module route | Kernel development (out of scope for this skill) |
|
||||
| Escalation effort exceeds the user's actual ask | `detection-and-anti-analysis.md` stop signal — switch to static | One more layer |
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] `detection-and-anti-analysis.md` read first; A/B/C chosen deliberately
|
||||
- [ ] Check located on the timeline (§1) before choosing a counter-layer
|
||||
- [ ] Root scheme's artefacts enumerated (manager/daemon/mounts) before blaming the target
|
||||
- [ ] Hiding module: exactly one of Shamiko / Zygisk-Assistant; denylist configured to its spec
|
||||
- [ ] Kernel rung checked against `uname -r` — one line recorded if closed
|
||||
- [ ] Raw-syscall vs libc-call distinction verified by disassembly before building any spoof
|
||||
- [ ] No kernel development undertaken as part of an APK deliverable
|
||||
@@ -0,0 +1,353 @@
|
||||
# LSPosed modules — when to deliver a hook instead of a patched APK
|
||||
|
||||
Load this when the honest answer to "patch the APK" is *no*: the target checks its own bytes, derives
|
||||
keys from its signature, re-downloads what you removed, or is simply cheaper to hook than to rebuild.
|
||||
A module is a different **deliverable**, not a different way to analyse — it changes what you ship, how
|
||||
it survives upgrades, and who has to install it.
|
||||
|
||||
This file covers the module route end to end: choosing it, the smallest project that works, the
|
||||
Gradle-free build chain, deployment and verification, what hides it from the target, and what it
|
||||
cannot reach at all.
|
||||
|
||||
**Route honesty first.** A module does not modify the APK, so it cannot be "the patched build". If the
|
||||
user asked for an installable standalone APK, a module is not that artifact, and this file will not
|
||||
make it one.
|
||||
|
||||
## Step 0 — pick the route deliberately
|
||||
|
||||
Three routes ship three different things. Choose on **who runs it and for how long**, not on which one
|
||||
you enjoy more.
|
||||
|
||||
| Route | Deliverable | Runs when | Survives target update | Cost |
|
||||
|---|---|---|---|---|
|
||||
| **Frida** (attach/spawn) | a script, driven by you | while a server process is alive on the device | it does not; you re-run it | lowest to start, highest per-session |
|
||||
| **LSPosed module** | an installable APK the user keeps | every process start, automatically, after the module is enabled and scoped | usually yes — the hook targets classes/methods, not offsets | mid: one project, no repackaging of the target |
|
||||
| **Repackaged APK** | a modified, re-signed APK | whenever the app runs | no — every update needs rework | highest: integrity, signature, packing, repack |
|
||||
|
||||
Reach for a module when **any** of these is true:
|
||||
|
||||
- the target verifies its own signature or APK digest, so a repackaged build dies on arrival
|
||||
(`references/signature-derived-keys.md`, `references/native-tamper-and-suicide.md`);
|
||||
- the change must persist across restarts without your laptop being attached;
|
||||
- attaching a debugger/injector is itself detected, but a startup-time hook is not
|
||||
(`references/detection-and-anti-analysis.md`);
|
||||
- you need a Java-level behaviour change only, and the target's own code is reachable from Java.
|
||||
|
||||
Do **not** reach for a module when the logic you need lives in native code or in an AOT-compiled
|
||||
runtime: see *What this route cannot reach* below.
|
||||
|
||||
## What the module can and cannot change
|
||||
|
||||
| Layer | Module can reach it? | Where to go instead |
|
||||
|---|---|---|
|
||||
| Java/Kotlin app code (incl. classes loaded late by a packer's ClassLoader) | yes, once you have the right `ClassLoader` | — |
|
||||
| `Application` / `Activity` / framework lifecycle | yes | — |
|
||||
| Java SDK internals (OkHttp, ad SDKs, HTTP clients) | yes | — |
|
||||
| Pure native logic inside a `.so` | no — Java hooks see only the JNI boundary | `references/native-and-so.md`, `references/native-dbi-and-deobfuscation.md` |
|
||||
| Extracted / virtualised dex (instruction-抽取, dex VMP) | no — the original method bodies may not exist as dex at all | `references/advanced-unpacking.md` |
|
||||
| Flutter / Dart AOT business logic | no — Dart is not Java; the Java layer only hosts the shell | `references/dart-aot.md` |
|
||||
| Behaviour that is *decided* server-side | irrelevant — a hook cannot remove a server rule | `references/server-api.md`, `references/server-config-and-updates.md` |
|
||||
|
||||
The Flutter row is the one that most often surprises: hooking every Java entry point in a Flutter app
|
||||
still leaves all business logic behind `libapp.so`. Confirm which layer owns your target before
|
||||
building a module for it (`references/dart-aot.md`).
|
||||
|
||||
## How injection actually works
|
||||
|
||||
The mechanism matters because every failure mode below is a consequence of it.
|
||||
|
||||
- LSPosed ships as a **Zygisk module** (`zygisk_lsposed`). Zygisk loads into `zygote`, so every app
|
||||
process forked from it is a candidate for injection. [inferred: standard Magisk/Zygisk design]
|
||||
- A module is **not** injected everywhere. For each forked process LSPosed asks its daemon (`lspd`)
|
||||
whether this package is in the module's **scope**, and only then loads the module. Scope is therefore
|
||||
the real gate; anything inside the module that filters on package name is a second, weaker gate.
|
||||
- Module code is loaded **from memory**, not from a file mapping — the module's dex is read out of the
|
||||
installed APK and handed to an in-memory ClassLoader. This is why a target scanning `/proc/self/maps`
|
||||
for path names finds nothing (`references` below, *What detects you anyway*).
|
||||
- The entry point is the class named in `assets/xposed_init`, and it receives
|
||||
`handleLoadPackage(XC_LoadPackage.LoadPackageParam)` **before the application's own `Application`
|
||||
object is attached** — the earliest Java-visible moment in the process. [measured: the injection
|
||||
point is why `Application.attach` and `Activity.onCreate` hooks installed from here fire even under a
|
||||
packer]
|
||||
- `LoadPackageParam.classLoader` is the **application's** loader (the packer's stub loader when the APK
|
||||
is packed). It is the handle you use to find classes the app loads later, and it is also the object
|
||||
anti-Xposed code counts — see *What detects you anyway*.
|
||||
|
||||
## Minimal module anatomy
|
||||
|
||||
Four files. Nothing else is required — no `res/`, no launcher Activity, no permissions.
|
||||
|
||||
| File | Why it is required |
|
||||
|---|---|
|
||||
| `AndroidManifest.xml` with `<meta-data android:name="xposedmodule" android:value="true"/>` | without this key the APK installs as an ordinary app and never appears in the module list |
|
||||
| same manifest: `xposeddescription`, `xposedminversion` (`82`) | shown in the manager UI; `82` is the classic XposedBridge API level and is accepted by LSPosed |
|
||||
| `assets/xposed_init` | one line: the fully qualified entry class. A typo here produces a module that loads and silently does nothing |
|
||||
| the entry class implementing `IXposedHookLoadPackage` | the only class LSPosed instantiates for you |
|
||||
|
||||
`scripts/lsposed_scaffold.py` writes exactly this set, plus a README containing the build chain below,
|
||||
so the project is reproducible without Gradle:
|
||||
|
||||
```sh
|
||||
lsposed_scaffold.py --package com.example.probe --name "Example probe" \
|
||||
--hook-target com.example.target --out ./module
|
||||
```
|
||||
|
||||
The generated entry class logs on **every** scoped process load before anything else, and hooks
|
||||
`Application.attach` / `Activity.onCreate`. Both are diagnostics first: the first line proves injection,
|
||||
the second names the real Activity classes (under a packer, these are the *unpacked* classes, not the
|
||||
manifest's stub).
|
||||
|
||||
## Building without Gradle
|
||||
|
||||
There is no resource to compile and no dependency resolution to do, so the whole toolchain is five
|
||||
commands. [measured on a Windows bench, JDK 17, build-tools 34.0.0, Android API 28 android.jar,
|
||||
Xposed api-82 stub jar; end-to-end 5.3 s for a one-class module]
|
||||
|
||||
```sh
|
||||
BT=/path/to/build-tools/34.0.0
|
||||
AJ=/path/to/android.jar # platforms/android-28/android.jar
|
||||
API=/path/to/api-82.jar # de.robv.android.xposed:api:82
|
||||
OUT=build
|
||||
|
||||
javac -encoding UTF-8 -source 8 -target 8 -nowarn -cp "$AJ:$API" \
|
||||
-d "$OUT/classes" src/com/example/probe/MainHook.java # 850 ms
|
||||
jar cf "$OUT/classes.jar" -C "$OUT/classes" . # 259 ms
|
||||
"$BT/d8" --min-api 24 --lib "$AJ" --output "$OUT" "$OUT/classes.jar" # 1143 ms -> classes.dex
|
||||
"$BT/aapt2" link -o "$OUT/base.apk" -I "$AJ" --manifest AndroidManifest.xml \
|
||||
--min-sdk-version 24 --target-sdk-version 28 -A assets # 126 ms
|
||||
cp "$OUT/base.apk" "$OUT/unsigned.apk"
|
||||
cp "$OUT/classes.dex" . # must sit next to the apk
|
||||
(cd "$OUT" && "$BT/aapt" add unsigned.apk classes.dex) # 97 ms
|
||||
"$BT/zipalign" -f -p 4 "$OUT/unsigned.apk" "$OUT/aligned.apk" # 76 ms
|
||||
"$BT/apksigner" sign --ks mod.keystore --ks-pass pass:android --key-pass pass:android \
|
||||
--v2-signing-enabled true --out "$OUT/module.apk" "$OUT/aligned.apk" # 1794 ms
|
||||
"$BT/apksigner" verify --print-certs "$OUT/module.apk" # 725 ms -> v2/v3 OK
|
||||
```
|
||||
|
||||
Four traps, all measured rather than guessed:
|
||||
|
||||
- **`d8` rejects a directory.** Pointing it at `build/classes/` fails with *Unsupported source file
|
||||
type*. Jar the classes first and pass the jar.
|
||||
- **`aapt add` resolves its argument relative to the current directory and stores the same name.** Run
|
||||
it from the output directory with `classes.dex` present there; a path like `dex/classes.dex` lands
|
||||
inside the APK as `dex/classes.dex` and the module never loads.
|
||||
- **`jar` and `keytool` are frequently not on `PATH` even when `javac` is.** Oracle's `javapath` shim
|
||||
exposes only `java`/`javac`; call the JDK's `bin` directory explicitly.
|
||||
- **`-bootclasspath` no longer exists on JDK 9+**, so the Android API comes from `-cp` together with the
|
||||
Xposed stub jar. `-source 8 -target 8` keeps the class-file version low enough for `d8`.
|
||||
|
||||
The generated README carries the same chain in copy-paste form, including the Windows variants
|
||||
(`.bat` wrappers, `;` classpath separator).
|
||||
|
||||
## Deploy, enable, and verify
|
||||
|
||||
**There are two independent switches.** Getting one right and not the other is the single most common
|
||||
"I built a module and nothing happens" report.
|
||||
|
||||
| Switch | Where | What it actually controls |
|
||||
|---|---|---|
|
||||
| package enabled state | `pm enable <module>` / `pm disable <module>` | whether Android allows the package's components to run at all |
|
||||
| module enabled | LSPosed Manager (module list) | whether LSPosed loads the module into scoped processes |
|
||||
| scope | LSPosed Manager (module → scope) | *which* packages the module is injected into |
|
||||
|
||||
[measured: a freshly installed module can be in the module database yet disabled — the package
|
||||
manager reported `enabled=0` for the module and `pm enable` flipped it to `enabled=1`, while the
|
||||
LSPosed-side enable flag was still 0 in its own database]
|
||||
|
||||
A third, device-level gate sits on vendor ROMs: the *install* itself can be intercepted by the ROM's
|
||||
security centre. The shape is a shell-identity `pm install` returning a bare `Failure [-99]` while the
|
||||
vendor security app takes the foreground, and the **same APK installing cleanly as root**
|
||||
(`su -c 'pm install -r <apk>'`). If a module APK "will not install" on a phone that is otherwise
|
||||
healthy, try root before suspecting the APK. [measured; the extension record has the transcript]
|
||||
|
||||
Verification has **two channels**, and on a device with a broken platform log only one of them works:
|
||||
|
||||
```sh
|
||||
# 1. the platform log — where the module's line normally appears
|
||||
adb logcat -s <TAG> # then start the target app; do NOT clear the buffer first
|
||||
# 2. LSPosed's own module log — where it appears when logd is broken
|
||||
adb shell "su -c 'cat /data/adb/lspd/log/modules_<timestamp>.log'"
|
||||
```
|
||||
|
||||
The expected first line in either channel is the one the scaffold writes on entry — it fires before
|
||||
any app code:
|
||||
|
||||
```
|
||||
<TAG> injected: <target.package>/<process> cl=<loader>@<hash>
|
||||
```
|
||||
|
||||
[measured] On a device whose `logd` route is broken, channel 1 is **completely empty** — not merely
|
||||
`logcat -s <TAG>`, but `logcat -s LSPosed-Bridge` and a full-buffer search for the tag as well — while
|
||||
channel 2 shows a complete, successful injection for every process start. A ROM whose LSPosed log
|
||||
opens with `Logd maybe crashed (err=Socket operation on non-socket)` is exactly this case, and it had
|
||||
nine successful injections in it while logcat showed nothing at all. Debugging with `logcat` alone
|
||||
there produces the confident and wrong conclusion "the module never ran".
|
||||
|
||||
Decision order when that line is missing — stop at the first hit:
|
||||
|
||||
1. module enabled in LSPosed Manager?
|
||||
2. target package present in the module's **scope**?
|
||||
3. module APK still installed (`pm path <module>`)?
|
||||
4. **was the target process started after the scope change?** Scope is read for newly forked
|
||||
processes; a process that was already running keeps the decision it got at fork time.
|
||||
[external, matches LSPosed behaviour reported independently: a scope change takes effect on the
|
||||
target's next start, no device reboot required — 看雪 thread-291750]
|
||||
|
||||
The LSPosed-side state is inspectable from a root shell:
|
||||
|
||||
| Path | Contents |
|
||||
|---|---|
|
||||
| `/data/adb/lspd/config/modules_config.db` | SQLite: `modules(mid, module_pkg_name, apk_path, enabled)`, `scope(mid, app_pkg_name, user_id)`, `configs(...)` [measured] |
|
||||
| `/data/adb/lspd/log/` | `modules_<timestamp>.log`, `verbose_<timestamp>.log`, `kmsg.log`, `props.txt` [measured] |
|
||||
| process `lspd` | the daemon that serves scope decisions; it is a separate process from the target [measured] |
|
||||
|
||||
Two measured caveats about that log directory, because both waste time:
|
||||
|
||||
- `modules_*.log` **is** the module log: it is the file LSPosed appends your `XposedBridge.log()` lines
|
||||
to. It may *also* contain `Logd maybe crashed (err=Socket operation on non-socket), retrying in 1s...`,
|
||||
which means the platform log channel is unavailable — not that your hook failed. Check this file
|
||||
**and** `logcat -s <TAG>`; a device can deliver one and not the other. [measured: nine successful
|
||||
injections were in this file while logcat showed nothing]
|
||||
- `verbose_*.log` is a *logcat snapshot* that includes the whole system, so it is useful for
|
||||
correlating a system-side event with your run, and useless as a module log.
|
||||
|
||||
**Do not kill `lspd` to force a configuration reload.** [measured] On the bench it is started by
|
||||
`/data/adb/modules/zygisk_lsposed/service.sh`, which runs `unshare -m sh -c "$MODDIR/daemon --from-service &"`;
|
||||
the `daemon` script ends in `exec /system/bin/app_process ... org.lsposed.lspd.Main`. Magisk runs
|
||||
`service.sh` once per boot, so an externally killed `lspd` is not restarted by anything you can see
|
||||
from a root shell. The consequence is worse than a dead daemon: newly forked processes stop getting
|
||||
scope decisions. Configure scope through the manager, which talks to the running daemon.
|
||||
|
||||
The same reasoning applies to editing `modules_config.db` by hand: the file is the daemon's
|
||||
**persisted** state, while the decisions actually served to `zygote` come from the daemon's live copy.
|
||||
A hand-edited row is not wrong — it is simply not read until the daemon reloads it, and there is no
|
||||
supported way to make it reload. [inferred from the storage layout and the daemon lifecycle; the
|
||||
manager path is the one that updates both]
|
||||
|
||||
## Hiding the framework from the target
|
||||
|
||||
Injecting a Java hook is trivial to detect **if the target is allowed to see the root/Zygisk
|
||||
environment at all**. On a rooted device the hiding layer is a separate module, and the two common
|
||||
choices differ in exactly one operational detail: how they learn which apps to hide from.
|
||||
|
||||
| | Zygisk Assistant | Shamiko |
|
||||
|---|---|---|
|
||||
| source | open | closed-source, LSPosed project |
|
||||
| target selection | Magisk **DenyList** entries (or KernelSU profiles); no UI of its own | also reads Magisk's DenyList, **but requires DenyList enforcement to be OFF** |
|
||||
| extra mode | — | creating `/data/adb/shamiko/whitelist` switches to whitelist mode without a reboot; documented as costly in memory/performance and test-only |
|
||||
| mechanism | unmounts root-related paths and masks Zygisk presence for the selected process | same family of process-level hiding, plus its own mount/`maps` handling |
|
||||
|
||||
[external: Zygisk Assistant module description and Shamiko README]
|
||||
|
||||
**The DenyList/enforcement distinction is where people lose afternoons.** Enforcement is Magisk's own
|
||||
feature that unmounts Magisk-provided files for listed processes; the *list* is shared, the *enforcement
|
||||
toggle* is not the same thing. Shamiko wants the list without enforcement; Zygisk Assistant is
|
||||
documented to work with the list as configured.
|
||||
|
||||
[measured on the bench: the DenyList was **enforced but empty** — `magisk --denylist status` reported
|
||||
`Denylist is enforced`, `magisk --denylist ls` printed nothing, `/data/adb/shamiko` did not exist, and
|
||||
Zygisk Assistant v2.1.4 was installed. So on that device nothing was being hidden from any app, while
|
||||
LSPosed and `lspd` were running normally. If a target seems to know it is on a rooted device, check
|
||||
this before blaming the module.]
|
||||
|
||||
Practical rules:
|
||||
|
||||
- **Keep the scope minimal.** Every extra scoped package is both an extra place your hook can break
|
||||
something and an extra ClassLoader in that process (next section).
|
||||
- Hiding and hooking are separate problems. A module that is perfectly hidden can still be detected by
|
||||
the ClassLoader count; a target that never checks cannot see either.
|
||||
- If the target is the *only* app you care about, scoping to it alone is both the smallest blast radius
|
||||
and the least observable configuration.
|
||||
|
||||
## What detects you anyway
|
||||
|
||||
Traditional Java-level anti-Xposed checks — `Class.forName("de.robv.android.xposed.XposedBridge")`,
|
||||
exception-stack scanning for Xposed frames, reflection on `findAndHookMethod`, enumerating
|
||||
in-memory-ClassLoader instances — are all **query interfaces**, and hiding layers exist precisely to
|
||||
falsify their answers. They are no longer a reliable signal that a module is present or absent.
|
||||
|
||||
The check that does not depend on a query interface is the **ClassLoader count**. [external: 看雪
|
||||
thread-291750, which reports a clean baseline of 3 versus 12 with a module injected, threshold ≥9; the
|
||||
original idea is traced there to thread-289567]
|
||||
|
||||
The reason it works, in one paragraph: ART's `ClassLinker` keeps a `class_loaders_` list of every live
|
||||
ClassLoader, and that list is part of GC reachability. A module's loader must stay on that list or the
|
||||
GC will collect the module's code and the hook dies. So a module cannot both remain alive and be absent
|
||||
from a structure the runtime itself walks. Hiding layers can fake lookups; they cannot remove a node
|
||||
from a GC-traversal list without unloading the module.
|
||||
|
||||
The same source reports two further native-side traces of the same injection, which are worth knowing
|
||||
because they are independent of ClassLoader counting: the module's dex shows up as **anonymous
|
||||
executable memory** (it is loaded from memory, so no file mapping exists), and Zygisk's patching of
|
||||
`libart` leaves **private-dirty pages** in the library's executable segments.
|
||||
|
||||
Engineering consequences for anyone choosing this route:
|
||||
|
||||
- **Scope discipline is detection hygiene.** Fewer scoped packages means fewer injected processes; a
|
||||
multi-module stack inflates the same count. The number is per-process, so a clean device elsewhere
|
||||
does not help this process.
|
||||
- **A count check needs a calibrated baseline.** On complex hosts (WebView, split APKs, plugin
|
||||
frameworks, other modules) the clean count is already high, and the threshold has to be measured per
|
||||
host, never copied. [external: same source]
|
||||
- **Detection of the framework is not the same as detection of your change.** If the target reacts to
|
||||
the count by refusing to run, that is an environment finding to report
|
||||
(`references/detection-and-anti-analysis.md`), not something to escalate against indefinitely.
|
||||
- If the target's check is native and inline-hooks *your* detector's counterpart, you are in DBI
|
||||
territory: `references/native-dbi-and-deobfuscation.md`.
|
||||
|
||||
## LSPosed vs Frida — the division of labour
|
||||
|
||||
They are not competitors; they are the two answers to "how long must this hook exist".
|
||||
|
||||
| Need | Frida | LSPosed module |
|
||||
|---|---|---|
|
||||
| Understand a flow once, now | **yes** — interactive, no build step | no: build + install + restart per iteration |
|
||||
| Ship something that works every launch, unattended | no: needs a server process | **yes** |
|
||||
| Hook a `.so` function directly | **yes** (`Interceptor`, Stalker) | no: Java hooks stop at JNI |
|
||||
| Survive a target that kills external injectors | weak: `ptrace`-based attach is the thing being detected | **stronger: no external process, no attach, no port** |
|
||||
| Replace a method's return value in app code | yes | yes |
|
||||
| Be re-runnable after a target update | yes (re-attach) | usually yes (class/method names auto-update far better than byte offsets) |
|
||||
| Need no root on the target device | no | no |
|
||||
|
||||
The productive pattern is to use **both in sequence**: Frida to discover which class and method matter
|
||||
and what the real call chain is (`references/dynamic-frida.md`), then a module to make that finding
|
||||
permanent without touching the APK. Rebuilding a module for every question is the expensive way to
|
||||
explore; exploring with an interactive script and only then writing the module is the cheap way.
|
||||
|
||||
A third option exists when the goal is *calling* target code rather than changing it — exporting a
|
||||
native function over RPC: `references/emulation-and-rpc.md`.
|
||||
|
||||
## Failure modes
|
||||
|
||||
| Symptom | Most likely cause | Check |
|
||||
|---|---|---|
|
||||
| module never appears in the manager | `xposedmodule` meta-data missing/mistyped after manifest merge | `aapt2 dump xmltree` the built APK, or re-read the manifest |
|
||||
| module listed, no `injected:` line in either channel | module disabled in manager, package not in scope, **target process not restarted** after the scope change, or you looked at only one channel | the four-step order above, then the two-channel check |
|
||||
| the platform log is empty but the module log is not | the ROM's `logd` route is broken; the module is working | the tell is `Logd maybe crashed (err=Socket operation on non-socket)` at the top of the module log |
|
||||
| `injected:` line present, but `TARGETS` gate skips the process | in-module gate, not the framework | read the module's own log line, then its gate |
|
||||
| hook installed, method never fires | wrong class/loader: packers and plugin frameworks hold several ClassLoaders | resolve the loader at runtime; enumerate `/proc/<pid>/maps`-independent evidence via `references/dex-patching.md` |
|
||||
| target dies right after injection | target side: ClassLoader counting or anonymous-memory heuristics (above); device side: ROM behaviour | instrument-free control run first (`references/detection-and-anti-analysis.md`) |
|
||||
| `pm enable` had no effect on injection | `pm` state and LSPosed state are different switches | the two-switch table above |
|
||||
| `d8` fails on a directory / `aapt add` cannot find the dex / `keytool` not found | build-chain traps, all three measured | the four traps above |
|
||||
|
||||
## Verification for the record
|
||||
|
||||
- which module APK, its hash, and what it was built from (scaffold output or hand-written);
|
||||
- the build commands and whether `apksigner verify` passed;
|
||||
- `pm path`/`dumpsys package` output for the module (installed, enabled state);
|
||||
- the scope list actually configured;
|
||||
- the target process start time relative to the scope change;
|
||||
- the module's logcat lines, in order, showing injection and any hook installs;
|
||||
- whether the target misbehaved, and the instrument-free control result for the same build.
|
||||
|
||||
## See also
|
||||
|
||||
- `references/dynamic-frida.md` — the exploration half of the workflow above
|
||||
- `references/detection-and-anti-analysis.md` — when the target fights back and when to stop
|
||||
- `references/native-and-so.md`, `references/native-dbi-and-deobfuscation.md` — the layer a Java hook stops at
|
||||
- `references/dart-aot.md` — the layer that owns a Flutter app's logic
|
||||
- `references/advanced-unpacking.md` — extracted dex and the VMP boundary
|
||||
- `references/repack-and-sign.md`, `references/signature-derived-keys.md` — what you are avoiding, and why it is sometimes unavoidable
|
||||
- `references/on-device-tooling.md` — MT Manager and the rest of the on-device kit
|
||||
- `references/verification.md` — what "done" means, including the control-build rule
|
||||
- `scripts/lsposed_scaffold.py` — generates the project skeleton described here
|
||||
@@ -0,0 +1,271 @@
|
||||
# Native DBI and deobfuscation
|
||||
|
||||
**Load this when static disassembly of a `.so` has stopped producing information** — an exported
|
||||
function decompiles into a dispatcher loop and arithmetic soup, a symbol you need has no name, or you
|
||||
must answer "what actually ran" instead of "what could run". This file covers instruction-level
|
||||
dynamic tracing: what a trace can and cannot decide, how to record one with the scripts in
|
||||
`scripts/`, and where it hands off to emulation and symbolic execution.
|
||||
|
||||
**Hand-off.** `native-and-so.md` owns the APK-side conclusions about a library — which `.so` is
|
||||
loaded, which ABI is executing, whether a hook can observe anything, how to neutralise a terminate
|
||||
path by returning. This file owns execution-level evidence. If the question is "did my patch cause
|
||||
the death", that is `native-and-so.md` and `native-tamper-and-suicide.md`; if it is "which blocks did
|
||||
this function really execute, and how often", it is here.
|
||||
|
||||
**Claim strength.** `measured` = an exact command and its output exist in
|
||||
`docs/tool-verification/EXTENSION-native-dbi.md`. `inferred` = it follows from measured behaviour or
|
||||
from documented behaviour of the tool. `unverified` = reported by someone else or reasoned from
|
||||
first principles without a run. The distinction matters more here than usual, because the honest
|
||||
result of this pass is that **the trace pipeline is unverified on the test device** — see §6.
|
||||
|
||||
## 1. Which obfuscation are you looking at
|
||||
|
||||
Obfuscator-LLVM ships three transforms, and one target usually carries all three. Identify by
|
||||
**which one made static reading fail**, because each is undone by a different observation.
|
||||
|
||||
| Transform | Static shape | Dynamic signature | What removes it |
|
||||
|---|---|---|---|
|
||||
| **Control-flow flattening** | One dominator block at the top of the function, reached from everywhere; a state variable (register or stack slot) assigned a constant before each jump back; a `switch`/jump table dispatch; the original block order is gone | The dispatcher block dominates the execution histogram by a wide margin; real blocks appear between dispatcher entries; execution sequence looks like `D R1 D R2 D R3 D` | Trace histogram + the state variable's constants: each dispatcher entry is preceded by a store of the next real block's id |
|
||||
| **Bogus control flow (opaque predicate)** | A branch whose condition is algebraically constant (`(x*x) >= 0`, `x*x % 2 == 0`), with a junk block on the impossible side; junk blocks reference unreachable names | The junk branch **never appears** in the trace at all: not once, at any input | Trace absence, and then dead-code deletion of the never-taken side. Absence in a trace is only evidence if the trace covers the input that would take it |
|
||||
| **Instruction substitution** | Arithmetic that is correct but unrecognisable: add chains with negated constants, `xor`/`and`/`or` rewrites of a comparison, MBA identities | The function's **result** is still correct at its boundary, and the single-step value at a known point (e.g. the return register) matches the un-obfuscated expectation | Symbolic execution or a brute-force input sweep; a trace alone does not simplify arithmetic |
|
||||
|
||||
Worked example of the distinction: a flattened function with substituted instructions produces a
|
||||
trace whose histogram has an obvious top, but the arithmetic between dispatcher entries still tells
|
||||
you nothing. Flattening is a **control**-flow problem and the trace answers it; substitution is a
|
||||
**data**-flow problem and needs §5.
|
||||
|
||||
**Reported, not verified here:** a community write-up of this exact pipeline — trace, aggregate,
|
||||
solve with a symbolic executor, patch the binary — is
|
||||
[基于动态指令追踪与符号执行对抗OLLVM控制流平坦化的工程化实践](https://cloud.tencent.com/developer/article/2721228)
|
||||
(cloud.tencent.com/developer/article/2721228, published 2026-08-05). It reports, on a 2,800-block
|
||||
x64 fixture: 15 s of tracing ≈ 220 MB of raw log, aggregation to 48 KB of block records, ~12 min of
|
||||
parallel symbolic execution resolving 67 dispatcher targets, and 1.2 s of binary patching over 147
|
||||
sites. **Those numbers are the author's, on a Windows x64 DLL, and were not reproduced here** —
|
||||
treat them as an order-of-magnitude sketch for the data-reduction ratio (raw log to block table is
|
||||
roughly 4000:1 there), not as a budget for an arm64 Android target. The article's code snippets are
|
||||
illustrative rather than runnable: its `onReceive` handler indexes parsed events by field name
|
||||
(`item.kind`, `item.start`), while `Stalker.parse(..., {stringify: false})` returns **positional
|
||||
arrays**. Take the method from that article; take the API shape from this repository and from the
|
||||
script header in `scripts/stalker_trace.js`.
|
||||
|
||||
## 2. Pick the observation before you pick the tool
|
||||
|
||||
| Question | Observation | Tool |
|
||||
|---|---|---|
|
||||
| Which blocks executed, and how often? | Block-level trace with execution counts | `scripts/stalker_trace.js` + `scripts/stalker_report.py` |
|
||||
| Which functions inside the module call each other? | Call edges from the same trace | same pair (`call` events) |
|
||||
| Which imported function does this stub reach? | Relocation table, not trace | `scripts/elf_plt.py` |
|
||||
| Where did the process die, and did it look arranged? | Crash record, signal, fault address, backtrace split by owner | `scripts/native_crash.py` |
|
||||
| What value must the state variable have to reach block X? | Constraint solving over the dispatcher | angr / Triton (§5) |
|
||||
| What is the value at a specific point for a specific input? | Deterministic per-instruction replay with memory operands | QBDI (§4) |
|
||||
| What does this code do with no device at all? | Emulation of the `.so` with a synthetic environment | unidbg / Unicorn / QEMU |
|
||||
|
||||
The first two rows are one run of one script — take both. `elf_plt.py` and `native_crash.py` are not
|
||||
competitors here: they answer a symbol and a death respectively, and both work when no trace can be
|
||||
taken at all.
|
||||
|
||||
## 3. Recording a trace with `scripts/stalker_trace.js`
|
||||
|
||||
Frida Stalker recompiles every basic block a followed thread executes and hands the events back to
|
||||
JavaScript. It needs no symbols, no source and no disassembler on the host, which is exactly why it
|
||||
works on stripped OLLVM output.
|
||||
|
||||
**Three rules, each one a failure mode if broken**
|
||||
|
||||
1. **Follow one trigger, not the whole process.** An unrestricted follow of a busy thread produces
|
||||
gigabytes and slows the target down until it dies.
|
||||
2. **Filter to one module.** `targetModule` is the only module whose blocks are reported; call edges
|
||||
report when either end is inside it. Filtering happens on the device, not in post-processing,
|
||||
which is what keeps the log usable.
|
||||
3. **Cap the volume.** `maxBlocks` stops the trace instead of letting the log eat the disk, and the
|
||||
`DONE` line records whether truncation happened.
|
||||
|
||||
**Configuration** (edit `CONFIG` in the script, or override at runtime through `rpc.exports.config`
|
||||
/ `script.post({type:'cfg', payload:{...}})`):
|
||||
|
||||
| Key | Meaning |
|
||||
|---|---|
|
||||
| `targetModule` | the one `.so` whose blocks are reported |
|
||||
| `trigger` | `{kind:'export', module, export}` — start on a named export (a JNI function is the classic); `{kind:'offset', module, offset}` — start at module-relative offset; `{kind:'java', cls, method}` — start at the Java→native boundary; `{kind:'main'}` — follow the thread right after load |
|
||||
| `followMs` | hard stop, so a forgotten trace cannot kill the process |
|
||||
| `maxBlocks` | event cap; the `DONE` line reports truncation |
|
||||
| `events.compile` | first translation of each block — deduplicated block set in first-visit order |
|
||||
| `events.block` | every executed block — the execution histogram |
|
||||
| `events.call` | call edges |
|
||||
| `events.exec` | **per instruction; enormous.** Enable only around a known point |
|
||||
| `events.ret` | return edges |
|
||||
|
||||
**Customising what gets translated (`transform`).** Event flags shape *what you are told*; the
|
||||
`transform` callback shapes *what runs*. It fires before a block is translated and receives the
|
||||
instruction iterator, so it can rewrite the code Stalker is about to execute — inline a counter at one
|
||||
call site, neutralise a logging call inside a hot loop, or substitute a value at the one address you
|
||||
care about. Reach for it when the question is "is this site reached, and how often" rather than "which
|
||||
blocks ran"; do not reach for it when the answer must be an observation, because a transform changes
|
||||
the process's behaviour and stops being passive measurement. Two properties to respect: it can run
|
||||
once per block per thread, so any rewrite must be idempotent, and the rewritten bytes are the DBI's
|
||||
copy, so a crash inside them will not point at a file offset. `inferred`: `scripts/stalker_trace.js`
|
||||
uses events and `onReceive` only; the transform route is documented here, not exercised by this
|
||||
repository's pass.
|
||||
|
||||
**Running it.** With the bundled injector, which writes every event to a log file *and* stdout:
|
||||
|
||||
```
|
||||
python scripts/run_probe.py scripts/stalker_trace.js 1 --pkg <pkg> --via usb --log trace.log
|
||||
```
|
||||
|
||||
With any driver that speaks Frida's rpc, so no file edit is needed:
|
||||
|
||||
```js
|
||||
script.exports.config({ targetModule: 'libapp.so',
|
||||
trigger: { kind: 'offset', module: 'libapp.so', offset: 0x9f6c0 },
|
||||
followMs: 3000, maxBlocks: 50000 });
|
||||
script.exports.start(<tid>); // follow this thread
|
||||
script.exports.status();
|
||||
script.exports.stop();
|
||||
```
|
||||
|
||||
Pass `start(tid)` explicitly rather than relying on the default. **`Process.getMainThreadId()` is
|
||||
not the Android main thread in practice**: on the measured run below, a process with pid `19938` was
|
||||
followed on tid `25606`, and an idle-looking thread produced zero events. On Android the main thread
|
||||
tid equals the pid, which is the value to start from.
|
||||
|
||||
**Output grammar** (one logical line per event; `scripts/stalker_report.py` parses it, including
|
||||
logs where each line is wrapped by `run_probe.py` as `[host ts] [dev ts] TRACE ...`):
|
||||
|
||||
```
|
||||
READY ... config echo and module status; nothing works before it
|
||||
MOD name base=0x.. size=.. path=..
|
||||
BB <seq> <mod>+0x<offset> block first translated (dedup'd skeleton)
|
||||
BLK <seq> <mod>+0x<offset> [size=n] block executed (histogram input)
|
||||
CALL <depth> <from> -> <to> call edge
|
||||
DONE reason=timeout|trigger-leave|maxBlocks|stop-rpc blocks=n blk=n calls=n truncated=0|1
|
||||
FATAL / TRIG-FAIL what did not install and why; the script keeps running
|
||||
```
|
||||
|
||||
**Reducing the log**
|
||||
|
||||
```
|
||||
python scripts/stalker_report.py trace.log --top 30 --skeleton 80 --edges 15 --json report.json
|
||||
```
|
||||
|
||||
Four reductions, each answering a different question: the **execution histogram** (top of the list =
|
||||
dispatcher candidate), the **first-visit order** (deduplicated block set ≈ CFG skeleton with the
|
||||
flattening state machine stripped out), the **call-edge table** (module-internal communication with
|
||||
no symbols), and the **collapsed execution sequence** (`block*N -> block -> ...`, which is where the
|
||||
`D -> R -> D -> R` flattening rhythm becomes visible).
|
||||
|
||||
Diagnostics the report prints, and what they mean:
|
||||
|
||||
- `DONE ... truncated=1` — the trace hit `maxBlocks`. Ratios remain useful; **absolute counts do
|
||||
not**, and a claim about a dispatcher's multiplicity must be re-measured with a higher cap.
|
||||
- `zero BLK with nonzero BB` — the thread was translated but executed nothing in-window: the window
|
||||
closed, or the trigger returned immediately.
|
||||
- `zero BB and zero BLK with DONE present` — the module never ran on the followed thread. Change the
|
||||
thread or the trigger; do not tune the follow time.
|
||||
- Everything zero **and no `DONE`** — the trace never started. Read the `READY` / `TRIG-FAIL` lines
|
||||
first; that is a plumbing problem, not an analysis result.
|
||||
|
||||
## 4. Stalker, QBDI, or emulation
|
||||
|
||||
| Situation | Choice | Why |
|
||||
|---|---|---|
|
||||
| Need block-level coverage and execution counts on a real device, no per-instruction semantics | **Stalker** | Cheapest to start, no host toolchain, works on code with no symbols |
|
||||
| Need per-instruction values, memory operands, or a deterministic replay that can be re-run at a recorded PC | **QBDI** (QuarkslaB Dynamic Binary Instrumentation), via its Frida binding | An independent DBI engine with its own register/memory API; the trace is a program, not a log. It instruments at a different layer than Stalker, which matters on ART: Stalker translates the code it sees, QBDI exposes the instruction stream and its operands directly |
|
||||
| Need to hurt the target as little as possible while instrumenting a hot path | **QBDI** | Deterministic, no reliance on the app's own JIT/AOT output |
|
||||
| Need a result with **no device and no app process** — a hardened sample refuses to run, or the algorithm must be called thousands of times | **Emulation** (unidbg, Unicorn, QEMU) | Runs the `.so` in a synthetic environment with JNI stubs; completely different trade-off (environment fidelity for scale) |
|
||||
| Need "what input reaches block X" rather than "what happened for input I" | **Symbolic execution** (§5) | A trace is one path; a solver enumerates the condition |
|
||||
|
||||
**Stalker and ART do not compose for free.** The followed thread's code can be recompiled by ART's
|
||||
JIT while Stalker has already translated it, and a block's address is only meaningful inside one
|
||||
process lifetime. Practical consequences: keys in a log are `module+offset` and stay comparable
|
||||
across runs only for code that is mapped from file; do not compare a `libart`-materialized block
|
||||
address between two runs; and never place a follow/unfollow pair on a hot function (measured failure
|
||||
in §6).
|
||||
|
||||
## 5. From a trace to a deobfuscated function (inferred)
|
||||
|
||||
This is the part the community write-up above also describes, and it is **inferred** here — the
|
||||
trace end was not reproducible on the test device, so the steps below are a method, not a record.
|
||||
|
||||
1. **Find the dispatcher.** Rank by execution count. In a flattened function the dispatcher runs
|
||||
once per real block; loops multiply it further. A block that is (a) at the top by a wide margin,
|
||||
(b) entered from many distinct predecessors, and (c) followed by many distinct successors, is the
|
||||
dispatcher. `stalker_report.py` prints exactly the three items needed to check that.
|
||||
2. **Find the state variable.** Disassemble the dispatcher entry window statically (the offset is in
|
||||
the trace, so no symbol is needed). Look for the register or stack slot written immediately
|
||||
before the indirect branch; in flattened output this is the value the dispatch table is indexed
|
||||
by. If more than one candidate exists, correlate: the state variable is the one whose written
|
||||
constants match the distinct block ids seen in the trace.
|
||||
3. **Recover the real CFG.** Convert the flat sequence into edges: `dispatcher → real block →
|
||||
dispatcher`. The real blocks' order and repetition come from the trace; the state constants come
|
||||
from step 2; the mapping `state value → real block` turns the dispatcher into a jump table you
|
||||
can then remove in the binary (the LIEF step in the write-up).
|
||||
4. **Solve what the trace did not cover.** A trace is one input's path. For a state value you never
|
||||
observed, symbolically execute the dispatcher **only** (a few tens of bytes: load the state,
|
||||
bounds-check it, index the table) rather than the whole function. This is where angr or Triton
|
||||
earns its cost: the entry point is the dispatcher offset the trace gave you, and the goal is the
|
||||
table index, not the program's semantics. Reported pitfall from the same write-up, worth repeating
|
||||
because it is structural: OLLVM inserts transitions that land outside the table, so prune states
|
||||
whose index exceeds the table bound instead of letting the solver chase them.
|
||||
5. **Only then patch the binary.** Direct-branch rewriting must respect instruction length: an
|
||||
absolute jump needs more bytes than the `mov; jmp` pair it replaces, so pad rather than move
|
||||
anything. `scripts/elf_plt.py` is the tool that tells you what a rewritten site actually reaches
|
||||
(by relocation, not by position), and a byte-diff of two builds is how you prove your patch set is
|
||||
what you think it is.
|
||||
|
||||
## 6. Failure modes
|
||||
|
||||
**Zero events, follow installed (measured, cause unverified).** With host frida 16.7.19 and a
|
||||
matching on-device frida-server 16.7.19 on Android 11 / arm64, `Stalker.follow` on a main thread for
|
||||
4 s produced `blocks=0 blk=0 calls=0` on two different system processes, and an `export`-triggered
|
||||
follow produced `reason=trigger-leave blocks=0` on every one of hundreds of firings. Every line
|
||||
before that was healthy: `READY`, `TRIG following tid=…`, `MOD libc.so base=0x…`. The conclusion to
|
||||
carry forward is narrow and should not be widened: **on that combination, follow installs but events
|
||||
do not arrive in `onReceive`.** It is not a licence to assume Stalker is broken everywhere, and not
|
||||
evidence about any other ROM, frida version or target. Validate the pipeline before trusting a zero
|
||||
result: follow a thread you control executing a known loop, and confirm nonzero `BLK` lines.
|
||||
|
||||
**High-frequency follow/unfollow crashes the target (measured).** Using a hot libc export as the
|
||||
trigger — every call starts a follow and every return ends it — a system UI process died with
|
||||
`SIGSEGV` after hundreds of cycles; the crash record's frame `#00` sat in an anonymous region (the
|
||||
DBI's code cache) and the return address led into `libart`. The process restarted under a new pid.
|
||||
The lesson is not "Stalker is unsafe"; it is **do not use a hot function as a follow trigger**, and
|
||||
do not build a follow/unfollow cycle per-call in a hot path. A single follow of a chosen thread for a
|
||||
bounded window is the shape that works.
|
||||
|
||||
**The device becomes the experiment (measured).** While this pipeline was running, the test device's
|
||||
`load average` reached `34.11` on an 8-core mid-range phone, and a co-running dynamic job on the same
|
||||
phone (a dex-dumping attach belonging to another task) was destroyed mid-flight. On a shared device
|
||||
these are not independent experiments: one heavy DBI run makes every other dynamic result
|
||||
unattributable. Announce the window, keep `followMs` in the low seconds, cap `maxBlocks`, never spawn
|
||||
when attach is enough, and treat a `script has been destroyed` in a *different* job as a signal that
|
||||
your load — not that job's code — is the variable. This is `long-task-discipline.md` §single-variable
|
||||
discipline applied to hardware.
|
||||
|
||||
**A trace of a VM is a trace of the interpreter.** If the target is a virtualized function (private
|
||||
bytecode executed by a handler loop), Stalker will happily report the interpreter's blocks: a huge,
|
||||
flat, repetitive histogram around one dispatch loop. That is a valid finding — it tells you the code
|
||||
is virtualized — but it is **not** the guest program's control flow. Recovering that needs handler
|
||||
identification and a private opcode table; see
|
||||
`code-virtualization-and-custom-linkers.md`, and do not present an interpreter trace as the
|
||||
deobfuscated function.
|
||||
|
||||
**Instrumentation was detected before you started.** If the process dies when you attach, refuses to
|
||||
run under root, or the module you want is never loaded while attached, the problem is upstream of
|
||||
this file: read the first section of `detection-and-anti-analysis.md` before escalating the trace,
|
||||
because the cheap answer is usually to switch to static analysis with `elf_plt.py` and
|
||||
`native_crash.py`, not to fight the detector.
|
||||
|
||||
## 7. Reporting what a trace proves
|
||||
|
||||
- A trace proves **what executed on the followed thread inside the followed window**. It does not
|
||||
prove absence: `BB` never appearing means it did not run *for that input, in that window* — which
|
||||
is meaningful for an opaque-predicate junk block only when the rest of the analysis says the input
|
||||
would have taken it.
|
||||
- Counts are evidence only when `truncated=0`. State the cap.
|
||||
- A dispatcher identification is a hypothesis about a block's role. Confirm it by disassembling the
|
||||
block and finding the table it indexes; a high count alone is also what a spin loop or a memory
|
||||
allocator's fast path looks like.
|
||||
- Write the product's before/after into `docs/tool-verification/`, with the exact command, the
|
||||
module, the offsets, and the strength label. The next person's first question is "was the pipeline
|
||||
known to work when you got that zero", and the answer belongs in that record, not in a footnote.
|
||||
@@ -0,0 +1,142 @@
|
||||
# On-device tooling — MT Manager, APK MCP, LSPosed, Termux
|
||||
|
||||
Sometimes the PC is the wrong place to work: the device already has the APK installed, the edit is
|
||||
one string, the target is a 38 MB repack you would otherwise push back and forth, or there simply
|
||||
is no laptop in the loop. This file covers the **on-device toolchain** and — more importantly —
|
||||
when each tool beats its PC counterpart and when it does not.
|
||||
|
||||
Evidence basis: the facts below come from a real configured environment (Android 11, Magisk +
|
||||
Zygisk, LSPosed v1.9.2, MT Manager 2.26.9), archived in `tools/_phone-modules/`. Framework
|
||||
activation and the module set are `observed` there; per-workflow usability notes are `measured`
|
||||
where marked, otherwise `inferred`. The MT MCP tool surface is from MT's official documentation
|
||||
(`observed` as a list; live invocation requires the service to be running — see §2).
|
||||
|
||||
## 1. MT Manager as a reverse-engineering workbench
|
||||
|
||||
MT Manager (`bin.mt.plus`) is a file manager plus APK editor. For this skill's purposes it is a
|
||||
**complete repack pipeline that runs on the phone**: view, edit, rebuild, sign.
|
||||
|
||||
What it covers, mapped to this skill's workflow stages:
|
||||
|
||||
| Skill stage | MT capability | Notes |
|
||||
|---|---|---|
|
||||
| Recon (manifest, SDKs) | APK viewer: manifest, entry list, string search across dex/resources | String search is the fast path; no full Java decompile in the editor workflow |
|
||||
| Dex reading/editing | Dex viewer + smali-level editing | Smali is the editing granularity — same discipline as `dex-patching.md` |
|
||||
| Removing signature verification | Built-in "去除签名校验" (signature-check killer) feature | Convenience feature; audit what it actually patched — a Java-layer signature killer can be a decoy while a native check still kills you (`code-virtualization-and-custom-linkers.md` §decoy) |
|
||||
| Extracting artifacts | Pull `classes.dex`, `.so`, `resources.arsc`, axml out of any APK/zip | Useful to move a single `.so` to the PC toolchain without a full unzip |
|
||||
| Repack + sign | Rebuild APK and sign it on device | Output lands in MT's working directory; verify with the same discipline as `repack-and-sign.md` (alignment, `resources.arsc` rules still apply — the platform enforces them regardless of which machine built the file) |
|
||||
|
||||
**When MT beats the PC pipeline:** quick single-file edits, on-the-spot verification on the same
|
||||
device the app is installed on, and sessions where shuffling 40 MB APKs over USB dominates the
|
||||
work. **When the PC wins:** anything scriptable/repeatable, dex-wide cross-referencing
|
||||
(`find_refs.py`), byte-precision patching with header recomputation, and anything needing a real
|
||||
decompiler. The honest split: MT for **breadth on device**, PC for **depth and repeatability**.
|
||||
`inferred`.
|
||||
|
||||
## 2. MT's built-in APK MCP server
|
||||
|
||||
MT 2.26.9+ ships an "APK MCP" service: it exposes MT's analysis and modification capabilities to
|
||||
an MCP (Model Context Protocol) client — which in practice means an AI agent drives MT's tooling
|
||||
over HTTP while the human sees the results on the phone. The official framing: AI understands the
|
||||
request and calls the tools; MT does the local read/modify/repack/sign.
|
||||
|
||||
**Transport and endpoint** (`measured` on the reference environment):
|
||||
|
||||
- Streamable HTTP MCP at `http://127.0.0.1:8787/mcp` from the PC, via `adb forward tcp:8787
|
||||
tcp:8787`; or directly `http://<phone-ip>:8787/mcp` on the LAN.
|
||||
- **The service must be started by hand in the MT UI** (side drawer → Tools → APK MCP → Start).
|
||||
adb cannot start it. Before it is started, the port is simply not listening — probe with
|
||||
`scripts/mt_mcp_probe.py`, which prints waiting instructions in that state.
|
||||
|
||||
**Tool surface** (official documentation; names observed from the published list):
|
||||
|
||||
| Category | Tools |
|
||||
|---|---|
|
||||
| Open/selection | `mt_apk_list_available_apks`, `mt_apk_open` |
|
||||
| Reading/search | `mt_apk_list`, `mt_apk_search`, `mt_apk_read_text`, `mt_apk_read_bytes`, `mt_apk_continue` |
|
||||
| Dex analysis | `mt_apk_dex_outline_class`, `mt_apk_dex_xref` |
|
||||
| Resources | `mt_apk_resource_read`, `mt_apk_resource_xref` |
|
||||
| Native static | `mt_apk_native_inspect`, `mt_apk_native_read_items`, `mt_apk_native_map_address`, `mt_apk_native_xref`, `mt_apk_native_disassemble`, `mt_apk_native_function_cfg` |
|
||||
| Modification | `mt_apk_edit_open`, `mt_apk_edit_text`, `mt_apk_edit_resource`, `mt_apk_patch_bytes`, `mt_apk_native_patch_instructions`, `mt_apk_native_patch_string`, `mt_apk_edit_check`, `mt_apk_build` |
|
||||
| Cleanup | `mt_apk_close` |
|
||||
|
||||
**Official constraints — budget your plans around these, not around hopes:**
|
||||
|
||||
1. **No Java decompilation.** The stated position: AI reads smali directly; decompiled Java of
|
||||
hardened/R8'd code misleads more than it helps. Cross-references (`dex_xref`) and class
|
||||
outlines are the structural view.
|
||||
2. **`resources.arsc`: existing entries only.** No new locales or new entries — edit what ships,
|
||||
do not plan feature-additions through arsc.
|
||||
3. **`.so` support is static analysis only.** No dynamic execution, no emulation, no C/C++
|
||||
pseudocode. Xrefs and CFG are "best-effort within a limited budget" — direct static results,
|
||||
**not** proof of a complete call chain or of runtime behaviour. For depth, the PC side (IDA/
|
||||
Ghidra-class, see `toolchain.md`) remains the answer.
|
||||
|
||||
**Handing an APK to the server** (three supported ways): open an APK in MT's file list and stay
|
||||
on its info dialog ("the current APK file"); open an installed app's info dialog the same way; or
|
||||
drop the APK into MT's configured MCP working directory and refer to it by filename/package. The
|
||||
working directory is also where rebuild output lands.
|
||||
|
||||
**Probing from the PC:** `python scripts/mt_mcp_probe.py` does the full JSON-RPC handshake
|
||||
(initialize → initialized → tools/list) with no MCP SDK dependency and prints a grouped tool
|
||||
inventory. If MT's MCP has not been started in the UI, it exits with waiting instructions and
|
||||
code 2 — usable as a loop check ("is it up yet") while you start it by hand. `measured`.
|
||||
|
||||
## 3. LSPosed Manager — the module route on device
|
||||
|
||||
LSPosed (via Zygisk) gives you a **Java-layer hook platform that needs no PC at runtime**: write/
|
||||
install a module once, and it applies to target apps at every launch.
|
||||
|
||||
Facts from the reference environment (`observed`, archived in `tools/_phone-modules/`):
|
||||
|
||||
- Activation is verifiable from logs: the `ZygiskCompanion: welcome to LSPosed!` banner, the
|
||||
version line, the `lspd` daemon process running as system.
|
||||
- Install discipline: `magisk --install-module` unpacks to `/data/adb/modules_update/` and only
|
||||
**merges after a reboot** — a module that "did not install" is usually one that has not merged
|
||||
yet. `ls /data/adb/modules/` is the truth; `modules_update/` non-empty means pending.
|
||||
- Zygisk itself needs one reboot after being enabled before its injection layer exists at all.
|
||||
|
||||
Limits that matter for this skill: LSPosed hooks **Java/ART** — it cannot hook inside a native
|
||||
`.so` (that is Frida/IDA territory, and the reason `framework-runtimes.md`'s runtime check
|
||||
exists), and it does nothing for Flutter/Dart AOT logic below the platform channel. Use it for
|
||||
the layer it owns: Java API interception, intent/telemetry rewriting, feature gates that live in
|
||||
Java. A hook module is also **not a deliverable** for a request that wants an installable APK —
|
||||
it is an environment change on your device (`detection-and-anti-analysis.md` Step 4 keeps these
|
||||
separate).
|
||||
|
||||
## 4. Termux + frida-server — device-side dynamic analysis
|
||||
|
||||
The phone can run the whole dynamic stack alone: Termux (or a plain root shell) hosts
|
||||
`frida-server`, and scripts run through Termux's own Python.
|
||||
|
||||
- **frida-server version must match the PC-side frida tooling** when the PC is also in the loop
|
||||
(`dynamic-frida.md` owns this). Device-only operation still needs a matching `frida` client in
|
||||
Termux.
|
||||
- **Disguise the server when the target hunts it**: a renamed binary and a non-default port are
|
||||
the minimum; a detection-savvy target scans process names and default ports. The reference
|
||||
environment carried renamed server copies from prior work — the technique is standard, and the
|
||||
detection mechanics are `kernel-and-environment-hardening.md` §1.
|
||||
- **32/64-bit**: a `zygote64_32` device runs both ABIs; make sure the frida-server architecture
|
||||
matches the process you are attaching to (`environment.md` §which architecture is actually
|
||||
executing).
|
||||
- Keep sessions simple: attach-mode on a hardened target inherits every §1 problem of
|
||||
`kernel-and-environment-hardening.md`; prefer spawn, and prefer `spawn_patch_detach.py`-style
|
||||
patch-then-detach when you only need a memory fix to stick.
|
||||
|
||||
## 5. On-device forensics — where the data is
|
||||
|
||||
Rooted-phone data inspection does not need a PC round-trip. The full layout, formats and
|
||||
ownership rules live in `runtime-data.md` (DataStore/MMKV/SQLite paths, `chown`/`restorecon`
|
||||
after restores, the "app rewrites your edit" decision tree) — on device, MT Manager's file
|
||||
browser with root covers the same reads, and Termux covers scripted pulls. The two on-device
|
||||
cautions that most often bite: edit files **only with the app force-stopped** (the in-memory
|
||||
copy wins otherwise), and re-check ownership after any reinstall (the uid increments).
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Chose the workbench deliberately: MT (on-device, fast) vs PC (scriptable, deep) — not by habit
|
||||
- [ ] MCP started in MT's UI and probed (`mt_mcp_probe.py` exits 0) before planning agent-driven edits
|
||||
- [ ] MCP plans respect the three official constraints (no Java decompile, arsc entries-only, `.so` static-only)
|
||||
- [ ] LSPosed modules verified merged (`/data/adb/modules/`, not `modules_update/`) before testing
|
||||
- [ ] frida-server architecture matches the target process; disguised if the target scans
|
||||
- [ ] Data edits done with the app stopped; ownership fixed after reinstalls
|
||||
@@ -0,0 +1,270 @@
|
||||
# Protocol reverse engineering
|
||||
|
||||
**Load this when the app's traffic is not readable by the usual means**: the body is protobuf with no
|
||||
schema, the transport is gRPC, the connection is QUIC rather than TCP, or the client refuses to trust
|
||||
your proxy because it validates the certificate inside a native library.
|
||||
|
||||
Everything in this file assumes you have already decided the traffic matters and that a proxy is
|
||||
allowed to see it. If a *feature-scoped* TLS failure has appeared while the rest of the app works,
|
||||
that is a different problem with its own file: read `tls-and-cert.md` first — it owns the trust-chain
|
||||
attribution and the permissive-defaults template, and this file deliberately does not repeat them.
|
||||
|
||||
**Claim strength.** `measured` = an exact command and output exist in
|
||||
`docs/tool-verification/EXTENSION-native-dbi.md`. `inferred` = documented behaviour or a step that
|
||||
follows directly from a measured one. `unverified` = reported by others, not reproduced here. The
|
||||
wire-format section is `measured` on a self-built fixture; every tool named below is `unverified`
|
||||
unless stated otherwise.
|
||||
|
||||
## 1. Protobuf on the wire (measured)
|
||||
|
||||
Protobuf has no field names on the wire and no header. A payload is a flat sequence of
|
||||
`tag, value` pairs, and a nested message is just a value of type "bytes whose content is another
|
||||
sequence". That is the whole format; the schema supplies meaning and nothing else.
|
||||
|
||||
| Element | Encoding |
|
||||
|---|---|
|
||||
| Varint | base-128, least-significant group first, high bit set on every byte but the last |
|
||||
| Tag | `(field_number << 3) \| wire_type`, itself a varint |
|
||||
| Wire type 0 | varint value (int32/int64/uint/bool/enum) |
|
||||
| Wire type 1 | fixed 8 bytes (fixed64/sfixed64/double) |
|
||||
| Wire type 2 | length-delimited: length varint, then that many bytes (string, bytes, nested message, packed repeated) |
|
||||
| Wire type 5 | fixed 4 bytes (fixed32/sfixed32/float) |
|
||||
| Wire types 3/4 | group start/end, legacy; treat as unsupported when walking a modern payload |
|
||||
|
||||
A host-side check of the rules, including the canonical `150 -> 96 01`, lives in
|
||||
`tools/_work/t4-dbi/pb_selftest.py` (workbench, not shipped with the skill). Measured output on the
|
||||
fixture built there:
|
||||
|
||||
```
|
||||
message (29 B): 089601120774657374696e671a0508011201782206038e029ea7052800
|
||||
field 1 varint 150
|
||||
field 2 len-delimited(7) 'testing'
|
||||
field 3 len-delimited(5) nested message:
|
||||
field 1 varint 1
|
||||
field 2 len-delimited(1) 'x'
|
||||
field 4 len-delimited(6) hex '038e029ea705'
|
||||
field 5 varint 0
|
||||
rebuild from the walked rows equals original: True
|
||||
```
|
||||
|
||||
Three consequences that decide how you interpret any decoded body:
|
||||
|
||||
1. **Field numbers are local to their message.** In the walk above, field 3 of the outer message is a
|
||||
nested message whose own field 1 exists independently. Nothing on the wire says which message a
|
||||
field number belongs to; only a schema does.
|
||||
2. **A packed repeated field is invisible without a schema.** Field 4 above is three varints
|
||||
(`3, 270, 86942`) packed into one length-delimited value. A schema-free decode can only report it
|
||||
as opaque bytes — the length is known, the element boundaries are not.
|
||||
3. **An explicit zero is byte-identical to an absent field** in proto3 (`28 00` versus no bytes at
|
||||
all). A decoded `0` is not evidence that the sender set the field, and "the server sent 0" is not
|
||||
a safe conclusion from a decode alone.
|
||||
|
||||
### Decoding without a schema
|
||||
|
||||
- `protoc --decode_raw < body.bin` — the reference implementation's own raw decode; prints field
|
||||
numbers and values in exactly the shape above. Note it prints strings and nested messages without
|
||||
distinguishing them, which is why the fallback order matters: try a nested walk first, then
|
||||
printable UTF-8, then hex.
|
||||
- `protobuf-inspector` and `blackboxprotobuf` are the pip-installable equivalents, and both add
|
||||
heuristics: guessing whether a length-delimited value is a string or a submessage, and (for
|
||||
`blackboxprotobuf`) inferring a candidate type set per field across many samples. Useful when you
|
||||
have traffic but no `protoc`; still unverified here.
|
||||
- Decode **many samples of the same message**, not one. The number of distinct field numbers in a
|
||||
large sample set is what tells you which fields are optional, which repeat, and which are enums
|
||||
whose value set you can then enumerate.
|
||||
- Anything the app stores locally is a sample source that needs no proxy at all: an OkHttp disk cache
|
||||
(the `journal` file plus its entries), a DataStore file, or a Room blob column. `runtime-data.md`
|
||||
covers reading these, and `datastore_inject.py` can re-encode an edited DataStore value once you
|
||||
know the message.
|
||||
|
||||
## 2. Recovering the schema from the APK
|
||||
|
||||
### What generated protobuf code looks like
|
||||
|
||||
| Marker in the decompiled output | What it tells you |
|
||||
|---|---|
|
||||
| `extends GeneratedMessageLite` / `GeneratedMessageV3` | protobuf class; `Lite` means the reflection/schema runtime, not the descriptor-based one |
|
||||
| `static final int FIELD_NUMBER = 3;` (or `int <name>_ = 3`) | the field number, usually right next to the field's getter |
|
||||
| `switch (tag >>> 3)` with `case` constants | the parse loop's field dispatch — each `case` is a field number, in declaration order |
|
||||
| `input.readInt32()`, `readInt64()`, `readBool()`, `readStringRequireUtf8()`, `readBytes()`, `readMessage(...)`, `readEnum()` | the field's wire type and semantic type, read *after* the tag |
|
||||
| `input.readTag()` returning 0 as the loop exit | the standard `parsePartialFrom` skeleton; the loop body is where all field knowledge lives |
|
||||
| `writeTo(CodedOutputStream)` / `getSerializedSize()` / `dynamicMethod(...)` | the class really is a generated message, not a hand-written DTO |
|
||||
| `newMessageInfo(instance, "<escaped string>", ...)` | protobuf-lite's compact schema blob (see below) |
|
||||
|
||||
The generator keeps those framework calls even after R8, so an obfuscated app usually still carries
|
||||
readable protobuf structure: class and field *names* are gone, field *numbers* and wire types are
|
||||
not.
|
||||
|
||||
### Two routes to a `.proto`
|
||||
|
||||
**Route A — read the field table out of the bytecode (inferred).** Decompile the class, walk
|
||||
`parsePartialFrom`, and record `case <n>` → the `read*` call that follows. Field name unknown? Name
|
||||
it `field_<n>`; a valid `.proto` does not need the original identifiers, and the app's own getter
|
||||
names often survive anyway. Then verify immediately against captured bytes with
|
||||
`protoc --decode=<message> <schema.proto>`: a decode that produces a coherent structure for **every**
|
||||
sample is the proof that your field table is right, and it costs seconds. A field that decodes into
|
||||
nonsense means a wrong wire type, not a wrong field number — check the `read*` call before moving on.
|
||||
|
||||
**Route B — read protobuf-lite's own schema blob (inferred).** protobuf-java-lite 3.x embeds a
|
||||
compact schema string (`rawMessageInfo`) per message class, consumed by `MessageSchema` at runtime.
|
||||
Recovering it means locating that blob and feeding it to a matching runtime build. It is a strictly
|
||||
larger win when it works — it carries field numbers, types, and labels in one place — and it is
|
||||
version-sensitive, so treat Route A as the default and Route B as the acceleration. `unverified`
|
||||
here: no target in this repository was analysed this way.
|
||||
|
||||
**Tooling that automates this (unverified):** `pbtk`/`protodump`-style scanners walk dex/JAR inputs
|
||||
looking for the generated-code shape above and emit `.proto` files, and a protobuf-aware decompiler
|
||||
plugin can do the same from a loaded APK. Use them to produce a first draft, then verify it with
|
||||
`protoc --decode` against real captured bytes — that verification is the step that turns a guess into
|
||||
a schema, and it is the step worth spending time on.
|
||||
|
||||
## 3. gRPC
|
||||
|
||||
gRPC is HTTP/2 with a message framing convention, so the first decision is whether you can see
|
||||
HTTP/2 at all.
|
||||
|
||||
- **Recognise it.** A request carries `:method: POST`, `content-type: application/grpc[+proto]` (also
|
||||
`+json`, `+thrift`), and `:path: /<package>.<Service>/<Method>` — that path shape is the reliable
|
||||
fingerprint; the package in it usually matches a package name visible in the APK, which is how you
|
||||
connect traffic to a client class.
|
||||
- **Message framing.** Each message is: one compression-flag byte, then a 4-byte **big-endian**
|
||||
length, then that many bytes of (possibly compressed) protobuf. Several messages can share one
|
||||
DATA frame and one message can span frames, so reassemble by length, not by frame. The call's
|
||||
outcome is in **trailers** (`grpc-status`, `grpc-message`), which many proxies display separately
|
||||
from the body — a `200` with no body and a nonzero `grpc-status` is a normal gRPC error.
|
||||
- **Read it after capture.** Extract the reassembled message bytes and hand them to
|
||||
`protoc --decode_raw` or your recovered schema. `grpcurl -plaintext -protoset file.protoset`
|
||||
replays against an endpoint once you have a schema, which is also the fastest way to confirm that
|
||||
a recovered `.proto` has the right shape.
|
||||
- **Capture it.** A transparent TCP proxy sees HTTP/2 fine; a tool that only understands HTTP/1.1 may
|
||||
show the tunnel without the frames, which looks like "the app is not making requests". Interception
|
||||
tooling for this comes in two shapes: a proxy add-on that understands the gRPC framing and prints
|
||||
messages (`grpc-dump` and similar mitmproxy add-ons, or a gRPC-Web decoder when the client is a
|
||||
browser-style stack), and a command-line client (`grpcurl`) for replay against a live endpoint. If
|
||||
the app uses TLS (gRPC-Java does by default), the certificate question comes first — see
|
||||
`tls-and-cert.md`, and the native-material trust chain below.
|
||||
|
||||
## 4. QUIC / HTTP/3
|
||||
|
||||
The failure to expect: a working HTTP proxy, a working CA, and **an empty capture**.
|
||||
|
||||
- **Why.** An HTTP proxy is a TCP endpoint, and a client reaches it with `CONNECT`. QUIC is a
|
||||
UDP-based transport with TLS 1.3 built into the handshake; there is no TCP connection for a
|
||||
`CONNECT` to carry and no separate TLS layer for a proxy to terminate.
|
||||
- **Recognise it before debugging anything else.** `Alt-Svc: h3=":443"` in an earlier HTTP response
|
||||
announced the upgrade; on the wire you see UDP traffic to port 443 whose first packets are QUIC
|
||||
Initials (long header, version field, and a TLS ClientHello inside), and the client's ALPN is `h3`.
|
||||
Check for UDP activity when a TCP proxy stays idle while the app plainly works.
|
||||
- **Options, in order of how little they change:**
|
||||
1. **Force a fallback to TCP.** Block or blackhole UDP 443 for the device. A client that cannot
|
||||
reach an origin over QUIC falls back to TCP/HTTP2 if the server also offers it, and then your
|
||||
existing proxy works unchanged. This is the cheapest option and the one to try first, but it is
|
||||
a **network-condition change**: state it in the report, because "the app failed to load over
|
||||
QUIC" and "the app failed" look identical in a screenshot.
|
||||
2. **Decrypt with keys, not with a proxy.** TLS 1.3 key logging (`SSLKEYLOGFILE`-style) works for
|
||||
QUIC exactly as it does for TLS-over-TCP, and a packet capture plus the key log can be
|
||||
decrypted in Wireshark. It requires the client to support a key-log callback — Chromium-based
|
||||
stacks and BoringSSL generally do, Java/OkHttp-based stacks generally do not — so this is a
|
||||
per-client property, not a general solution.
|
||||
3. **Turn HTTP/3 off in the client** by hooking whatever enables it (a library version check, a
|
||||
remote-config flag, or a build-time constant). This is a client-side patch and therefore
|
||||
belongs to the repack decision, not to the capture step.
|
||||
- Everything in this section is `inferred`/`unverified` here: no HTTP/3 target was exercised in this
|
||||
repository. Treat the ordering as a plan whose first step (block UDP 443) needs no tool support to
|
||||
test.
|
||||
|
||||
## 5. SSL pinning that lives inside a native library
|
||||
|
||||
Three different mechanisms are routinely called "pinning", and only the last one survives a system
|
||||
certificate module.
|
||||
|
||||
| Mechanism | Where it runs | What defeats it |
|
||||
|---|---|---|
|
||||
| OkHttp `CertificatePinner` (or a custom `TrustManager`) in Java/Kotlin | app's own client | Client-level, **not** the system path: `tls-and-cert.md` §Step 4 and §"If OkHttp is the failing path" own this case — do not apply the permissive-defaults template to it |
|
||||
| System trust decisions via `HttpsURLConnection` / platform stack | platform | System store policy — see `tls-and-cert.md` §Step 5 |
|
||||
| Verification performed by a **library the app ships**, e.g. a Flutter app's own BoringSSL, or a bundled `libcurl`/`mbedtls` | `libflutter.so`, `libapp.so`, another `.so` | Only an in-memory change to that library's verification path (below), because the library does not consult the platform trust manager you can influence from Java |
|
||||
|
||||
**Flutter, specifically.** A Flutter app's `dart:io` HTTP client runs on the engine's BoringSSL
|
||||
inside `libflutter.so`; the app's own Dart code can additionally supply a custom trusted-certificate
|
||||
context or a bad-certificate callback. Two consequences that decide which direction to work in:
|
||||
|
||||
- If the app is **not** pinning and simply fails to trust your CA, getting your CA into the **system**
|
||||
store is the normal fix. `MoveCertificate`-style Magisk modules exist precisely because Android 7+
|
||||
ignores user-store CAs for app traffic; moving the CA into the system store is a **device change**,
|
||||
not an artifact, and it must be labelled as a fallback rather than the deliverable. Its boundary is
|
||||
exactly this: it changes what the platform trust store contains, so it can only help a client that
|
||||
reads that store.
|
||||
- If the app **is** pinning, or supplies its own verification context, the system store is irrelevant
|
||||
and the change has to land on the library's verification function.
|
||||
|
||||
**Locating the verifier inside `libflutter.so` (unverified — reported method).** The published
|
||||
approach in
|
||||
[universal-flutter-ssl-pinning](https://github.com/vichhka-git/universal-flutter-ssl-pinning)
|
||||
(`github.com/vichhka-git/universal-flutter-ssl-pinning`) automates the anchor search with PyGhidra:
|
||||
|
||||
1. load `libflutter.so` headlessly in Ghidra and scan its defined strings for `ssl_client`;
|
||||
2. resolve cross-references from that string to the **containing functions**;
|
||||
3. decompile each candidate to count its parameters;
|
||||
4. take the **3-parameter** function — that is BoringSSL's
|
||||
`ssl_crypto_x509_session_verify_cert_chain`, the certificate-chain verification entry point;
|
||||
5. emit the discovered RVA into two ready-to-run artifacts: a Frida script that attaches to that
|
||||
address and replaces the return value with `1` (success), and a Renef script that patches the
|
||||
function entry with the ARM64 sequence `MOV X0, #1 ; RET`.
|
||||
|
||||
The repository reports it working on Google Flutter arm64-v8a and Shorebird-patched builds with
|
||||
Frida 16.x/17.x, and notes the RVA is identical across build types for the same engine version. The
|
||||
same project also ships an HTTP monitor that auto-locates BoringSSL's `SSL_write`/`SSL_read` in
|
||||
`libflutter.so` and prints reassembled, de-chunked plaintext — which is the route to take when the
|
||||
traffic cannot be proxied at all, because it never needs a certificate the app will accept.
|
||||
|
||||
**Two things to verify before trusting that recipe on your target.** First, the string anchor is a
|
||||
build artifact: a stripped or repacked engine can lose `ssl_client` while keeping the function, in
|
||||
which case fall back to the structural search — find the `X509_verify_cert`-shaped call sequence in
|
||||
the handshake code, or identify the function called with the handshake structure during
|
||||
`certificate_verify`. Second, the failure mode of a wrong anchor is a **silent** success: replacing a
|
||||
return value in a function that merely *looks* like the verifier makes the certificate check pass
|
||||
in a process that then fails somewhere else, which is easy to misread as "the app detected my hook".
|
||||
Always confirm the hook fires on a connection that would otherwise fail, and confirm it is
|
||||
`SSL_VERIFY`-shaped semantics (the same value the library itself uses for success), rather than
|
||||
assuming `1` is right.
|
||||
|
||||
**When the string anchor is gone (the `session_creator` route).** A second family of anchors does not
|
||||
depend on the `ssl_client` literal at all: instead of finding the verifier through a string it
|
||||
references, find it through the call chain that reaches it. BoringSSL's handshake creates the session
|
||||
and then verifies the peer certificate chain, so the target is the function invoked with the
|
||||
handshake/session structure on that path — this is the shape that Flutter-unpinning write-ups call the
|
||||
session-creator route. It survives string and symbol stripping, because the call graph survives, and
|
||||
it costs more: you must identify the handshake structure first, which is why the string anchor is the
|
||||
fast path and this is the fallback when an engine build has dropped the string. `unverified` here — no
|
||||
engine binary was analysed in this repository.
|
||||
|
||||
**When the system store is genuinely enough.** If the client is Java-side and non-pinning, moving the
|
||||
CA into the system store is the least invasive change and needs no per-library work. The decision is
|
||||
therefore: identify the client first (`tls-and-cert.md` §Step 4 attribution), then choose the
|
||||
mechanism. Patching a library that was never consulting the store is work with no effect; installing
|
||||
a system CA when a native verifier ignores it produces the same empty capture you started with.
|
||||
|
||||
## 6. Failure modes
|
||||
|
||||
**A decode that looks valid but is not.** protobuf is self-synchronising enough that random bytes
|
||||
often decode into a plausible-looking field list. Guard against it by (a) decoding several samples of
|
||||
the same message and expecting the same field set, (b) checking that nested lengths exactly consume
|
||||
their parents, and (c) when you have a schema, re-encoding the decoded structure and comparing bytes
|
||||
with the input — the same round-trip check used in §1, which caught a decoder bug in this
|
||||
repository's own fixture.
|
||||
|
||||
**Assuming the proxy sees everything.** The proxy sees what the client sends through it. An app that
|
||||
uses QUIC (§4), a raw socket, a native client bypassing Java's HTTP stack, or a certificate-pinned
|
||||
connection shows up as silence. Silence is evidence about the transport, not about the app: check
|
||||
UDP activity, check whether a native library is doing the I/O (`lib_map.py`, `dynamic-frida.md`),
|
||||
and only then conclude that a feature is client-side.
|
||||
|
||||
**Patching the wrong verifier.** Covered in §5: the failure is silent, and the resulting state is
|
||||
worse than a clean failure because it looks like progress. Verify the hook against a connection
|
||||
known to fail.
|
||||
|
||||
**Treating a recovered schema as ground truth for the server contract.** A schema recovered from the
|
||||
client tells you what the client expects to send and parse — it does not prove the server honours
|
||||
those fields, and it says nothing about authorization. `server-api.md` owns that question. The
|
||||
recurring expensive mistake is to assume that because a field exists and is settable client-side, the
|
||||
server will act on it.
|
||||
@@ -93,6 +93,23 @@ grepping a hand-exported smali tree.
|
||||
The division of labour is worth stating plainly: **ASC locates, `ddc` reads.** Running a full `ddc`
|
||||
export first, then grepping it, is the slow path this tool exists to replace.
|
||||
|
||||
**Measured in the extension pass** (droidasc `0.1.1.post1`, installed with `python -m pip install
|
||||
droidasc`; dependency is androguard only, no JVM, no SDK):
|
||||
|
||||
| Command | Result on a 38.7 MB hardened APK |
|
||||
|---|---|
|
||||
| `getmanifest` | 0.44 s → 32,345 B of complete XML |
|
||||
| `findrefs … string jiagu` | 0.42 s → hits inside the shell class's `<clinit>` and `attachBaseContext` |
|
||||
| `getclass com/stub/StubApp` | 0.33 s → 22,802 B of Java |
|
||||
| `listclass` (whole APK) | 0.18 s → **4 classes** |
|
||||
|
||||
Two facts from that run are worth carrying into any recon: the CLI name is **`droidasc`**, not `asc`
|
||||
(there is no `asc` binary, and `asc --version` is simply "command not found" — `python -m droidasc`
|
||||
also works), and on a packed APK a full `listclass` returning four classes is not a broken tool: the
|
||||
business dex is not in the file. Reaching for `getclass` on a class that is not there exits **1** with
|
||||
`Class … not found in APK.` — treat ASC as a manifest-and-shell inspector on hardened input, and take
|
||||
the business-logic question to a different layer.
|
||||
|
||||
### ddc — dex-to-Java with query subcommands (worth adopting)
|
||||
|
||||
A single-file Rust binary, no install, no JVM. Two things make it more useful than
|
||||
@@ -109,6 +126,22 @@ ddc app.apk -o out/ # full decompile, a few seconds for a norma
|
||||
Measured on a 4.7 MB APK (4,070 classes / 30k methods): `info` ~0.13 s, `findrefs`
|
||||
~0.11 s, one class ~0.25 s, full decompile ~2.8 s producing ~4,000 files.
|
||||
|
||||
**Measured in the extension pass** (ddc `0.1.8`, a single Rust binary — on Windows `bin/ddc.exe`,
|
||||
1,028,096 B, **not on PATH** and carrying no PE version resource, so `ddc -V` is the only way to read
|
||||
its version; source: the project's GitHub releases):
|
||||
|
||||
| Command | Result on a 38.7 MB hardened APK |
|
||||
|---|---|
|
||||
| `ddc info` | 0.24 s → label / package / version / application / launcher / sdk / size / md5, plus per-dex class, method, field and string counts |
|
||||
| `ddc findrefs <apk> string jiagu` | 0.13 s → tabulated `dex | kind | class | method | refs` |
|
||||
| `ddc strings -f jiagu --with-locations` | 0.14 s → strings mapped to the methods that hold them |
|
||||
|
||||
**The trap on this one is the exit code.** Asked for a class that is not present, `ddc` exits **2**
|
||||
*and still prints its help text to stdout* — so a wrapper that tests "did anything come back?" reads a
|
||||
usage error as an answer. Branch on the exit code, never on output emptiness. The same run also
|
||||
confirms the layered picture from the other direction: `info`'s per-dex counters report 4 classes and
|
||||
29 methods with code for the whole 8.9 MB shell dex.
|
||||
|
||||
Why the query subcommands matter more than the speed: **string cross-referencing
|
||||
becomes a lookup instead of a crawl.** Asking "which class mentions this config
|
||||
field name" is a sub-second command here and easily an hour of smali grepping by
|
||||
|
||||
Reference in new issue
Block a user