mirror of
https://codeberg.org/dabao1955/apk-reverse.git
synced 2026-11-28 11:50:22 +08:00
Benchmark pass: measure the documented routes, close five tool gaps, correct four claims
Public targets under the existing routes, recorded per row in tests/benchmark.md with each row's own strength label: the MASTG crackmes (equal-length patch -> repack -> re-sign with a zero-change control, and the anti-debug race with its time-to-death baseline), DexPatcher's ezAndroid sample, two real split APK sets, and a self-built extraction-skeleton set. Hardening-shape discrimination now separates Java2C from an extraction shell, a VMP and JNI sinking. New: java2c_probe.py and java2c-and-jni-sinking.md; split-apk.md with repack.py growing set inventory, unified re-signing and merge; protobuf_decode_raw.py cross-checked against the official runtime; vmp_diff_harness.py and its cost table; kernelsu_syscall_mask.py with three kernel-side templates; stalker_trace.js gains Stalker.exclude() and a zero-event warning. Corrections, each because a measurement contradicted a recorded conclusion: the trivial-body ratio is bimodal rather than a threshold and the old threshold claim was deleted; a Dex-VMP verdict was withdrawn after dexdump contradicted a hand-written opcode table; the assumption that Stalker.exclude() fixes zero-event delivery is disproved (it keeps the process alive, nothing more); and a repack.py signing-path claim expired mid-pass when a second writer added one. Emulated and kernel-side routes are labelled unverified where no toolchain or device could run them; each evidence file states what was not run.
This commit is contained in:
1 parent
bea9955eb6
commit
6221a072ca
29 files changed
+10130
-97
No files matched your search
@@ -14,11 +14,13 @@ extraction shell and no VMP, so nothing here was exercised end to end against a
|
||||
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.
|
||||
active-invocation hooks die on modern ART). The detection metric has since been
|
||||
**measured against a purpose-built extraction-shell fixture set**, and that pass
|
||||
invalidated the threshold this file used to state — see the calibration table in
|
||||
§Measuring extraction instead of guessing and the commands behind it in
|
||||
`docs/tool-verification/EXTENSION-extraction-shell-bench.md`. The older surgical fixture
|
||||
that first exercised the script is in `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
|
||||
@@ -28,7 +30,9 @@ 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.
|
||||
target has been spliced end to end here, and the two candidate samples shipped in
|
||||
`repos/CyReverse` turned out not to be extraction shells at all (their two "shell"
|
||||
assets differ by six bytes; row B3 in the bench evidence file).
|
||||
|
||||
## The four shapes a dump can be
|
||||
|
||||
@@ -39,9 +43,18 @@ directory and read the `stub%` column — the four shapes separate on it.
|
||||
|---|---|---|---|
|
||||
| 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` |
|
||||
| Whole classes appear as bare `native` declarations, and the matching `Java_*` export exists | n/a | **JNI sinking** — the code left the dex for the `.so` | `java2c-and-jni-sinking.md` — read the function in the library, **not** this file |
|
||||
| Method bodies look like a thin forwarder to a native routine, or a single native island holds the app's own logic | n/a | **Java2C / native island** — the body is a compiled `J`/`.so` function, so re-reading the dex finds only the call | `java2c-and-jni-sinking.md` — the dex is the wrong instrument |
|
||||
| Whole classes appear as bare `native` declarations, and **no** `Java_*` export exists | n/a | Dynamic-registration native sink — the binding table is built at runtime | `java2c-and-jni-sinking.md` §the symbol search fails structurally |
|
||||
| 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 |
|
||||
|
||||
The two `native`-looking rows are **not** one row. They are separated because the
|
||||
correct next action differs: JNI sinking keeps the logic in a named, exported ARM64
|
||||
function that you read from the library, while a dynamic-registration sink has no
|
||||
symbol to find and needs the binding table read instead. Lumping them together sends an
|
||||
analyst to dump memory for code that is sitting in an ordinary `.so` — the misdiagnosis
|
||||
`java2c-and-jni-sinking.md` was written to stop.
|
||||
|
||||
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
|
||||
@@ -69,12 +82,67 @@ measured to differ in ~73% of their bytes), rejects structurally impossible imag
|
||||
(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.
|
||||
**Calibration — measured, and it is not a threshold.** Do not look for a `stub%` number
|
||||
to compare against. On a real 982 KB application dex (5,061 bodies) every emptying
|
||||
shape the shell family uses was built into a fixture and measured against a
|
||||
zero-change control (`docs/tool-verification/EXTENSION-extraction-shell-bench.md`,
|
||||
which carries the commands and the full matrix):
|
||||
|
||||
| What the shell left behind | `stub%` | vs. control (1.9 %) |
|
||||
|---|---|---|
|
||||
| bare `return-void` in every body | 100.0 % | sighted |
|
||||
| body cut to `const/4 v0,#0; return v0` | 93.2 % | sighted |
|
||||
| nop fill, no return — **the slot-clearing shape** | 0.0 % | **blind, and scores below the untouched original** |
|
||||
| `new RuntimeException; throw` stub — **the 360/legu shape** | 1.9 % | **blind, indistinguishable from the control** |
|
||||
| 25 / 50 / 75 % of bodies emptied | 1.7 / 1.7 / 2.1 % | blind |
|
||||
|
||||
The distribution is **bimodal**: `stub%` lands either at the app's own baseline
|
||||
(ordinary constructors and interface stubs, measured at 1.9 % here) or at ~100 %.
|
||||
Nothing sits in between, so there is no band a threshold could live in, and **partial
|
||||
extraction is invisible** — a dex with three quarters of its bodies removed reported
|
||||
0.2 points above its untouched control.
|
||||
|
||||
Two consequences the metric's name hides:
|
||||
|
||||
- **`stub%` high is dispositive; `stub%` low is not evidence of anything.** A low
|
||||
reading is compatible with a genuine dex, a fully nop-wiped skeleton, and a
|
||||
`throw`-stubbed skeleton alike.
|
||||
- **Read `emptied%`, not `stub%`, for the skeleton call.** `emptied%` unions the
|
||||
`return*`-stub and the nop-wiped classes, which is what lifts the nop-filled
|
||||
skeleton from 0.0 % to 100 %. A `throw`-stubbed skeleton still reads low; for that
|
||||
shape the ranking cannot help you and only per-body inspection can.
|
||||
|
||||
The trivial-body shapes `dex_dump_validate.py` counts, and which of them are skeleton
|
||||
evidence, are documented in the script itself (`classify_body`); the split between
|
||||
`stub` / `erased` / `minimal` exists because collapsing them produced a ranking that
|
||||
named a fully-wiped image the most likely original.
|
||||
|
||||
### The ranking's failure conditions — read these before trusting its winner
|
||||
|
||||
The `ranking` block names a "best-supported candidate for the original", and it is
|
||||
wrong in two measured situations. Both were reproduced, and both are the *opposite* of
|
||||
the obvious reading:
|
||||
|
||||
- **A partially extracted image outranks a heavily stubbed one.** Ranking on the
|
||||
emptied share alone put a dex with 25 % of its bodies removed *ahead of* its own
|
||||
untouched control — 1.7 % against 1.9 %, because replacing a body with
|
||||
`const/4 + return` lowers the `return-void` count. Measured before it was fixed;
|
||||
the current key uses the count of skeleton-shaped bodies first, which is monotone,
|
||||
and evicts anything over 50 % emptied.
|
||||
- **A `throw`-stub skeleton is invisible and ranks at the control's own baseline.**
|
||||
Every body replaced by `new RuntimeException; throw` measured 1.9 % — identical to
|
||||
the untouched image — and it still sorts third in the fixture set. No body statistic
|
||||
in this kit sees that shape. If the target family is 360/legu-like, **do not use the
|
||||
ranking to pick a baseline**; diff candidate images against each other by body hash
|
||||
instead.
|
||||
|
||||
The reason to state this in the reference file rather than only in the script: the
|
||||
ranking's output is a *sentence with a winner in it*, and a wrong winner is worse than
|
||||
no winner — an agent that adopts a modified image as its baseline builds every
|
||||
subsequent diff on the wrong artifact. When `emptied%` is at the app's own baseline and
|
||||
you cannot name a signal that separates the candidates, treat the ranking as
|
||||
uninformative for that set. Commands and full matrix:
|
||||
`docs/tool-verification/EXTENSION-extraction-shell-bench.md`.
|
||||
|
||||
## The FART loop: skeleton, invocation, splice
|
||||
|
||||
@@ -319,9 +387,46 @@ The last shape is the one to say out loud: if the dump's method bodies are intac
|
||||
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*.
|
||||
the JNI sink first (`code-virtualization-and-custom-linkers.md`,
|
||||
`java2c-and-jni-sinking.md`): there the methods are `native` stubs and the logic lives
|
||||
as native code; here the bodies are present and *re-encoded*.
|
||||
|
||||
### Establish "the bodies do not decode" with a decoder you did not write
|
||||
|
||||
This is the one measurement in this file that has already been got wrong here, so it
|
||||
gets its own rule. A hand-written opcode-width table silently desynchronises on large
|
||||
dex files — one arm64 branch opcode missing from the table is enough — and the
|
||||
desynchronisation is indistinguishable from the finding it fakes. Measured on the
|
||||
`ezAndroid` sample: a workbench table reported **1,393 of 22,424 bodies as
|
||||
non-decodable** and I read it as private opcodes; the platform decoder returned
|
||||
**943,223 lines, 34,566 instruction decodes, and zero structural errors** on the same
|
||||
file (`docs/tool-verification/EXTENSION-extraction-shell-bench.md` §3.4). The bodies
|
||||
were ordinary dalvik the whole time, and one of the "desync" methods disassembles into
|
||||
five clean instructions under `dexdump`.
|
||||
|
||||
So: **before any VMP verdict, decode the same file with `dexdump`,
|
||||
`baksmali`/`smali`, or `jadx`, and quote the failure count that came from *it*.** A
|
||||
rare-opcode histogram is a lead, not evidence. Never let a private table's desync
|
||||
inform a classification — "my decoder stopped" is a fact about the decoder.
|
||||
|
||||
### What a static dex probe can and cannot decide
|
||||
|
||||
Two different questions live in the same dump, and only the first one is answerable
|
||||
from the bytes on disk:
|
||||
|
||||
| Question | Statically decidable? | Why |
|
||||
|---|---|---|
|
||||
| Are the bodies real dalvik, or an encoded program? | **yes** | the platform decoder decodes them or reports a structural error |
|
||||
| Did the code leave the dex for native? | **yes** | `native` access flags, then `Java_*` exports / `JNI_OnLoad` in the matching `.so` |
|
||||
| Does a native island check signature, root or debugger? | **no** | the logic is ARM64 behind a vtable; the check may exist in no dex at all |
|
||||
| Are unlabelled `assets/` blobs live payload? | **no** | an unreferenced blob is dead until a runtime path constructs its name — measured: six such files in `ezAndroid`'s `assets/`, **zero** dex strings referencing them |
|
||||
|
||||
The trap is the asymmetry. A clean static reading licenses exactly one sentence —
|
||||
*"this is not dex-VMP"* — and it does **not** license *"this is not hardened"*. Those
|
||||
are different claims: the second one is the misdiagnosis that sends an analyst looking
|
||||
for an unpacker when the problem is a native island, or for a private disassembler when
|
||||
the code is ordinary ARM64 in a 206 KB `.so`. A static probe's silence about hardening
|
||||
is silence, not a clean bill of health.
|
||||
|
||||
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:
|
||||
@@ -348,10 +453,12 @@ for the island itself.
|
||||
|---|---|---|
|
||||
| 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 |
|
||||
| `emptied%` high but `stub%` low | nop-wiped skeleton; the old `stub%`-only reading called it the original | §Measuring extraction instead of guessing |
|
||||
| The ranking names a winner but `emptied%` sits at the app's baseline | Treat the ranking as uninformative for this set; do not adopt that image as a patch baseline | §The ranking's failure conditions |
|
||||
| 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 |
|
||||
| Methods are `native` stubs with a `Java_*` export | JNI sinking — read the function in the `.so` | `java2c-and-jni-sinking.md` |
|
||||
| Bodies present, decode as nonsense | Real VMP — **but confirm with `dexdump` first**, then differential oracle or walk away | §Establish "the bodies do not decode" with a decoder you did not write |
|
||||
@@ -47,6 +47,7 @@ Emulation and RPC are for when the code that matters must keep *running*.
|
||||
| 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 |
|
||||
| **Priority when either could work** | second — the environment bill below is real and routinely underestimated | **first** — the device already owns the environment |
|
||||
|
||||
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
|
||||
@@ -54,6 +55,33 @@ third round — a library that checks its own loading path or decrypts itself ag
|
||||
may simply not be worth emulating, and that is a finding, not a failure (`SKILL.md`
|
||||
§Stop conditions).
|
||||
|
||||
### The environment bill — budget days, not hours
|
||||
|
||||
"Filling the environment" reads like a checklist and behaves like a project. The mistake this
|
||||
section prevents is starting an emulation because the table says *works against anti-injection*, and
|
||||
then discovering that this library's environment includes everything emulation cannot fake: an
|
||||
Android `Context` backed by a real package manager, Binder round-trips into another process, a
|
||||
`KeyStore` attestation that only succeeds on real hardware, or a self-check against device state
|
||||
captured at install time. For a commercial native algorithm of that shape, "stub it until it runs"
|
||||
is measured in **days, not hours** — each missing piece is discovered one fault at a time, and the
|
||||
rounds do not get shorter.
|
||||
|
||||
Weigh it before starting:
|
||||
|
||||
| Question | If yes |
|
||||
|---|---|
|
||||
| Does it call through `Context` (package name, files dir, signature, `PackageManager`)? | a stub is often enough — cheap, keep going |
|
||||
| Does it talk to another process (Binder service, bound SDK, remote provider)? | the stub surface grows fast; **prefer RPC** |
|
||||
| Does it verify hardware (KeyStore, TEE, an attestation chain)? | emulation is likely a dead end — the value it wants cannot be produced here |
|
||||
| Does it check its own loading environment (paths, maps, root, debugger, installer)? | readable and patchable *inside* the emulator, but budget one round per check |
|
||||
| Must it be called thousands of times a minute? | the RPC throughput ceiling is real — this is the case that justifies the bill |
|
||||
|
||||
Default to **RPC first, emulation second**: the device already provides the environment, and
|
||||
per-call cost only starts to matter once you need volume. The two claims in this subsection
|
||||
(the day-scale cost of a Context/Binder/KeyStore-shaped library, and the RPC throughput ceiling)
|
||||
are **inferred** from the mechanism and from community practice — this repository has not emulated a
|
||||
commercial sample end to end, as `EXTENSION-emulation-rpc.md` states.
|
||||
|
||||
## Part A — Unidbg
|
||||
|
||||
### What it is
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
# Java2C and JNI Sinking — the dex is not where the code is
|
||||
|
||||
Load this when the dex shows method bodies missing or replaced by `native` declarations, and
|
||||
you are about to go looking for a decrypted DEX in memory. **Decide which of the two shapes you
|
||||
have before you spend anything**, because one of them has no DEX to find at any point in the
|
||||
process lifetime, and the search for it is unbounded.
|
||||
|
||||
Two neighbouring routes have historically folded this shape into one: `advanced-unpacking.md`'s
|
||||
dump-shape table and the SKILL.md symptom index both point "whole classes are bare `native`
|
||||
declarations" at `code-virtualization-and-custom-linkers.md`. That file is about protection which
|
||||
leaves the code **reachable** — a private container, a loader, a private opcode interpreter, all of
|
||||
which you can dump and measure. **Java2C is not reachable, because it was never bytecode.** This
|
||||
file splits that row and owns both halves of it; the virtualization file stays what it is.
|
||||
|
||||
**Strength note, read this first.** The measurements below are **observed** — every number was
|
||||
produced by `scripts/java2c_probe.py` against a real sample during this pass, recorded in
|
||||
`docs/tool-verification/EXTENSION-java2c.md`. But no Java2C library exists in this repository and
|
||||
none could be built here (no NDK, no clang, WSL unavailable — see that record), so **the
|
||||
Java2C-specific identification criteria are inferred, not observed end to end**. What *is*
|
||||
observed is the discriminating measurement that separates Java2C from JNI sinking, and the JNI
|
||||
boundary behaviour. Treat the type table as a map; label your own conclusions the same way.
|
||||
|
||||
## The five shapes — one table, because the wrong row costs days
|
||||
|
||||
| Shape | Static shape in dex | What is in memory at runtime | Route | Cost of the wrong row |
|
||||
|---|---|---|---|---|
|
||||
| **Landing shell** | `Application` is a third-party class; dex is a small stub | A full, decrypted DEX | Dump memory, filter, patch | Cheap if you notice the stub `Application` |
|
||||
| **Extraction shell** | Reads as a normal dex until you measure it; bodies are stubs | A DEX whose bodies are filled in **on invocation** | Dump, measure `stub%`, FART-style active invocation | Medium — you keep dumping, and every dump is a skeleton |
|
||||
| **VMP** | Dex parses; bodies are *present* but decode as nonsense | A DEX containing **private opcodes** interpreted by a native VM | Measure, then usually stop and report | Medium — recovery cost usually exceeds task value |
|
||||
| **Java2C** | Whole classes are `native`; **no code_item at all** for them | **Never a DEX.** The translated methods exist only as compiled C in a `.so` | Read the `.so`; rebuild the JNI call chain | **Highest in this table** — you hunt a decrypted DEX that is never produced, then blame your dump tooling, then your anti-detection assumptions |
|
||||
| **JNI sinking** | A handful of `native` declarations; the rest of the dex is ordinary Java | A normal DEX | Locate the Java call site; reverse one or a few native functions | Low — but you may widen the job to the whole app if you read it as Java2C |
|
||||
|
||||
The one question that decides the table: **does the artifact ever hold dex bytecode for the
|
||||
methods you care about?**
|
||||
|
||||
- Landing shell, extraction shell, VMP: **yes** — the bytecode is there, in some state, and the
|
||||
work is recovering or interpreting it.
|
||||
- Java2C: **no** — a translated method is a `native` declaration plus an entry in a registration
|
||||
table. Nothing is decrypted, so nothing can be dumped. `[inferred]` as a runtime claim: it
|
||||
follows from the translation mechanism, and this pass did not observe a live Java2C app.
|
||||
- JNI sinking: **yes** — the dex was never damaged.
|
||||
|
||||
## Identification
|
||||
|
||||
### The discriminating measurement is native density
|
||||
|
||||
This is the single most useful number and it separates the two shapes by roughly three orders of
|
||||
magnitude. Measured on real samples with `scripts/java2c_probe.py` `[observed]`:
|
||||
|
||||
| Sample | dex methods | `native` methods | native ratio |
|
||||
|---|---|---|---|
|
||||
| JNI-sinking target A (MASTG L2) | 5081 | 2 | **0.04 %** |
|
||||
| JNI-sinking target B (MASTG L3) | 11182 | 3 | **0.03 %** |
|
||||
| App carrying a real JNI library | 23603 | 7 | **0.03 %** |
|
||||
| Java2C-shaped fixture | 29 | 24 | **82.76 %** |
|
||||
|
||||
A JNI *sink* is by definition surgical: a few hot methods are moved out and the rest of the app
|
||||
stays in Java. **A JNI sink is not "the app is native".** When the density is in the tens of
|
||||
percent, and whole classes have zero Java methods left, you are looking at a translation pass.
|
||||
|
||||
`[observed]` in the same runs: two of the fixture's three classes were native-dominated (>= 70 %
|
||||
of >= 3 named methods), against **zero** such classes in any of the three real targets. Note that
|
||||
constructors are excluded from that test — a translation pass leaves `<init>`/`<clinit>` in Java
|
||||
in practice, so "every method native" is an essentially unreachable test and should not be used.
|
||||
|
||||
### Native-layer signatures
|
||||
|
||||
| Evidence | Strength | Why |
|
||||
|---|---|---|
|
||||
| `.so` exports `Java_*` symbols whose count is roughly 1:1 with the dex native-method count | **strong** | Measured 2:2 (sample A) and 3:3 (sample B) `[observed]`. It is the signature of a *static-linkage* translation or sink. Note it does **not** distinguish Java2C from JNI sinking — only the density does |
|
||||
| The `.so` contains one C function per Java method, each beginning `JNIEnv *env, jobject thiz, ...` | **strong** | Observed in generated, uncompiled output: every translated method became exactly one function with those leading parameters |
|
||||
| Toolchain strings: `Dex2C`, `dynamic_register_compile_methods`, `ScopedLocalRef`, `well_known_classes` | **strong** | These are the runtime header and entry-point names a Dex-to-C toolchain emits. `[observed]` in generated sources; `[inferred]` that they survive compilation into the shipped `.so` |
|
||||
| `JNI_OnLoad` present | **weak** | Present in nearly every JNI library. Measured true on a system library with zero `Java_*` symbols `[observed]` — it told us registration was dynamic, not that anything was hardened |
|
||||
| `RegisterNatives` **string** anywhere in the `.so` | **weak** | See the boundary section: NDK's C++ headers do not emit this symbol at all |
|
||||
| `libc++_shared.so` / `c++_static` | **weak** | An ordinary NDK C++ setting. The Dex-to-C toolchain read here does ship `APP_STL := c++_static`, but so do countless unrelated libraries `[observed]` |
|
||||
| `classes.dex` byte-count per class far below the app's own pre-hardening build | **weak, uncalibrated** | Bodies leaving the dex should shrink it. Measured 584 B/class on the fixture versus 1152–1386 B/class on the real Java targets `[observed]` — but there is no population baseline for "normal", so this only compares an app against **itself** before and after |
|
||||
|
||||
`java2c_probe.py` prints every one of these with its strength attached, and prints the weak ones
|
||||
as an explicit warning block. A weak hit is not a verdict and must not be reported as one.
|
||||
|
||||
## The route: read the .so, not memory
|
||||
|
||||
For Java2C the analyst's instinct — dump memory and find the dex — is not merely expensive, it is
|
||||
**unbounded**, because the success condition can never occur.
|
||||
|
||||
1. **Do not dump.** There is no target artifact. If you dump anyway, you will recover a dex that
|
||||
still shows the same `native` declarations you started with, and the natural (wrong) reading is
|
||||
"the dump failed".
|
||||
2. **List the translated functions.** With static linkage, `Java_<PKG>_<Class>_<method>__<proto>`
|
||||
names map the `.so` back onto the dex one for one. Use the dex as the index and the `.so` as
|
||||
the library.
|
||||
3. **Rebuild the chain backwards.** A translated function calls *out* to Java constantly. The
|
||||
strings `FindClass` / `GetMethodID` / `GetStaticMethodID` / `Call*Method` / `NewObject` /
|
||||
`GetFieldID` inside it are the reverse edges. Following them reconstructs what the original
|
||||
Java method did, which is the only way the logic comes back.
|
||||
4. **Expect a register-machine shape.** Generated code declares a slot per dex register up front
|
||||
and assigns them in sequence. Reading it as if a human wrote it wastes hours; read it as a
|
||||
linearizer output, matching each call site against the JNI signature it passes.
|
||||
|
||||
The decompiler choice matters less here than for obfuscated code: the generated functions are
|
||||
long but flat and unoptimized, which is precisely the shape a decompiler handles well.
|
||||
|
||||
## The JNI boundary — why a symbol search fails silently
|
||||
|
||||
Two independent mechanisms erase the symbol that a reader would search for. Both are real; the
|
||||
second was measured this pass.
|
||||
|
||||
**1. Dynamic registration.** Nothing named `Java_*` is exported. Binding is performed at runtime
|
||||
by a registration table built in a JNI entry point. A grep over the symbol table returns nothing,
|
||||
exits zero, and looks like a legitimate answer.
|
||||
|
||||
**2. `-fvisibility=hidden`, and an inline `RegisterNatives`.** The Dex-to-C toolchain read here
|
||||
ships `APP_CPPFLAGS += -fvisibility=hidden` in its `Application.mk` `[observed]`, which hides the
|
||||
generated functions from the dynamic symbol table — so even a statically-named translation can
|
||||
present as "no `Java_*` symbols". Compounding it: NDK's C++ `jni.h` implements `RegisterNatives`
|
||||
as an **inline member that calls through the function table**, so calling it emits *no*
|
||||
`RegisterNatives` symbol either `[observed]`: a real system library exporting `JNI_OnLoad` and
|
||||
zero `Java_*` symbols contains zero literal `RegisterNatives` symbols. A rule that greps for that
|
||||
name is structurally incapable of firing.
|
||||
|
||||
**The check that does work** `[observed]`: a library that **exports a JNI entry point and exports
|
||||
zero `Java_*` symbols** is registering dynamically. That combination is affirmative evidence, and
|
||||
it fired on a real library in this pass.
|
||||
|
||||
**Confirming it at runtime.** Hook the registration entry point (`JNI_OnLoad`) and read the table
|
||||
it builds, or hook the class-load path and enumerate the class's methods' native backing. Do not
|
||||
conclude "no JNI boundary" from an empty symbol table; conclude "the binding is not visible in the
|
||||
symbol table" and go find where it happens.
|
||||
|
||||
## Failure modes
|
||||
|
||||
| What you see | What it is not | What it is |
|
||||
|---|---|---|
|
||||
| Whole classes are `native`, you dump memory and find the same `native` declarations | "The dump failed" / "the tool is broken" | The translation moved the code out of dex permanently. Re-read the dex shape and open the `.so` |
|
||||
| `grep Java_ .dynsym` returns nothing | "There is no native implementation" | Dynamic registration, or hidden visibility — see the boundary section |
|
||||
| A library exports `JNI_OnLoad` and nothing else you recognise | "It is a loader" | It may be an ordinary dynamically-registering JNI library. A loader normally also has an `init_array` entry and a payload to map |
|
||||
| Native density is high but every class still has Java methods | Java2C | Could be a JNI sink applied widely, or an R8-stripped app. Check whether the `native` methods have matching `Java_*` symbols before concluding |
|
||||
| The dex looks completely unremarkable on a sample you were told is hardened | "Nothing is hardened" | A VMP whose payload is decrypted at runtime has an ordinary static dex. Measured this pass: a VMP-labelled sample had 7 native methods out of 23603 and a 4 % stub ratio `[observed]`. **Static dex metrics cannot see runtime-only hardening** — that needs a runtime check, not more reading |
|
||||
|
||||
## Where this file stops
|
||||
|
||||
- **It does not decompile the generated C.** That is ordinary native reversing; `native-and-so.md`
|
||||
and `native-dbi-and-deobfuscation.md` own it.
|
||||
- **It does not recover a VMP.** Private-opcode interpretation is a different mechanism with a
|
||||
different cost model (`advanced-unpacking.md`).
|
||||
- **The Java2C runtime claim is inferred.** That no dex bytecode exists in memory for a translated
|
||||
method follows from the mechanism, not from a measurement made here. If you get a live Java2C
|
||||
sample, that is the first thing to verify, and it is cheap: attach, force the class to load, and
|
||||
ask whether the method resolves to Java bytecode or to a registered native entry.
|
||||
@@ -19,6 +19,13 @@ externally documented mechanisms with sources, labelled `inferred` — none of i
|
||||
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.
|
||||
|
||||
**Extension pass, read the next paragraph before relying on it.** This file now has a companion
|
||||
generator — `scripts/kernelsu_syscall_mask.py` — which emits a loadable userspace module skeleton
|
||||
plus kernel-side **templates** for the three routes in §4. The generator, its userspace output and
|
||||
its own consistency check are `measured`; **the kernel-side code has never been compiled or loaded
|
||||
anywhere**, and every generated kernel file says so in its own header. A template is a starting
|
||||
point that removes the blank page, not a weapon that has been fired.
|
||||
|
||||
## 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
|
||||
@@ -147,6 +154,83 @@ the process earlier than any userspace tool can be, needs no ptrace (so it does
|
||||
rewrites one `/proc` read is a research project; a Zygisk module that hooks the target's
|
||||
constructor is a build task.
|
||||
|
||||
### 4a. From "no weapon" to "template + gate": what the extension pass added
|
||||
|
||||
The gap this closes is specific. §4 above was a map with no artefact behind it: a reader told
|
||||
"Kernel module hooking — inline hooks and syscall-table hooks in kernel space — the layer that *can*
|
||||
rewrite what a `/proc` read returns" had nowhere to go next. `scripts/kernelsu_syscall_mask.py`
|
||||
produces the artifact; this subsection states its boundary, because the boundary is the part that
|
||||
matters.
|
||||
|
||||
**The correction worth internalising first: a KernelSU module cannot do any of this.** A KernelSU
|
||||
(or Magisk, or APatch-userspace) module is a *userspace* module whose scripts run as root in the
|
||||
normal world. `module.prop`, `post-fs-data.sh` and `service.sh` cannot change what `openat`
|
||||
returns — not because of a version gate, but because nothing in that format is ever in the kernel's
|
||||
return path. Detectors of the kind §2 and §3 discuss are not defeated by a module of that shape.
|
||||
The generator emits that skeleton anyway, because it is the right carrier for the configuration and
|
||||
the metadata, and it says in its own README what the skeleton cannot do.
|
||||
|
||||
What *can* reach the return path is one of three artifacts, and each carries a gate that has to be
|
||||
checked on the actual device:
|
||||
|
||||
| Artifact | What it is | Gate | Status of the shipped template |
|
||||
|---|---|---|---|
|
||||
| **KPM** (KernelPatch / APatch) | A relocatable `.kpm` loaded by kpimg injected into the kernel image; replaces syscall-table pointers (`fp_hook_syscalln`) or rewrites prologues (`hook_wrapN`) | A KernelPatch-patched boot image, plus a **bare-metal** ARM64 toolchain (`aarch64-none-elf-gcc`) — not the NDK | `unverified` — template only, never compiled |
|
||||
| **Out-of-tree LKM** | An ordinary kernel module that reaches `sys_call_table` and swaps a pointer | Kernel source matching the device's exact vermagic, and on ≥5.7 a way around `kallsyms_lookup_name` no longer being exported | `unverified` — template only; rated last of the three on cost |
|
||||
| **eBPF probe** | A BPF program on a syscall tracepoint or kprobe | GKI 5.10+ with the tracing/BTF machinery | `unverified` — template only; the version gate alone closes it on most older devices |
|
||||
|
||||
The eBPF row carries a capability ceiling that is easy to miss and is stated in the generated file
|
||||
as well: **a tracepoint can observe a syscall, not rewrite its result.** `bpf_override_return()`
|
||||
only applies to functions flagged `ALLOW_ERROR_INJECTION`, which raw syscall entries are not —
|
||||
so "eBPF to spoof a `/proc` read" is, on most kernels, an observation plan wearing a rewrite
|
||||
plan's clothes. Observation is genuinely useful (it tells you which syscall the check uses, which
|
||||
`§5` requires you to know anyway); it is not spoofing.
|
||||
|
||||
**Field notes on the KPM route, from a public KPM development write-up** (`inferred` here — the
|
||||
author's measurements, not this repository's; source: blackr0ck, *APatch KPM 开发*,
|
||||
[bbs.kanxue.com/thread-291665.htm](https://bbs.kanxue.com/thread-291665.htm), 2026-06). These are
|
||||
recorded because each one is a day of somebody's time:
|
||||
|
||||
- **An inline hook can install cleanly and never fire.** On a GKI kernel with LTO, the exported
|
||||
symbol is frequently not the call site — the callee was inlined into its only caller, so
|
||||
replacing instructions at the symbol's address intercepts nothing. The reported symptom is
|
||||
"module loaded, callback never ran". Pointer replacement in the syscall table does not have this
|
||||
failure mode, because the syscall entry path must go through the table.
|
||||
- **The instruction-sequence length in a module header is a trap of its own.** The reported cause
|
||||
of a hard-to-diagnose load failure: declaring a resolved kernel function with `extern` makes the
|
||||
compiler emit an undefined reference (`*UND*`) instead of allocating the slot, and the loader
|
||||
refuses the module with `unknown symbol`. Letting it be a tentative definition allocates `.bss`
|
||||
and the loader fills it in. The generated template states this rule in the code, and
|
||||
`verify` checks for it.
|
||||
- **Per-syscall callbacks run on every syscall of that number, system-wide.** The reported
|
||||
incident: a `write` hook that did not first reject `fd <= 2` intercepted the framework's own log
|
||||
output tens of thousands of times and the device rebooted. **Performance is correctness here** —
|
||||
the first statement in every callback is a filter that rejects the common case.
|
||||
- **Which hook point survives is kernel-specific, and the cheap way to find out is to start at the
|
||||
syscall layer.** The same write-up reports that modifying the SELinux internal function they
|
||||
first targeted crashed the kernel under every combination tried (before/after, argument,
|
||||
return value, skip-origin), while a syscall-table hook on `write` proved stable and sufficient.
|
||||
Treat the syscall layer as the default and move inward only with evidence.
|
||||
|
||||
**Measured on the reference device, and why every template here is labelled the way it is.**
|
||||
`<DEVICE>` runs kernel **4.14.186+** (`adb shell 'uname -r; cat /proc/version'` →
|
||||
`4.14.186+`, `Linux version 4.14.186+ (nobody@android-build) (Android (6443078 based on r383902)
|
||||
clang version 11.0.1 ...) #1 SMP PREEMPT Wed Mar 30 23:32:42 CST 2022`). On that device the two
|
||||
remaining gates answer themselves:
|
||||
|
||||
- **eBPF**: 4.14 is far below the 5.10 gate. Closed, as §4 already recorded.
|
||||
- **KPM**: no KernelPatch-patched image is present, and the host has no
|
||||
`aarch64-none-elf-gcc` (`kernelsu_syscall_mask.py gates` reports `NOT FOUND`, along with no
|
||||
`ndk-build` and no `make`). Installing APatch means patching the boot image — a bricking risk
|
||||
that this repository does not take on an APK task.
|
||||
- **LKM**: no kernel source for the device, so no matching vermagic is possible.
|
||||
|
||||
So on this machine the honest answer to "do you have a kernel-level weapon" is: **you have a
|
||||
template, a gate table and a measured statement that the gate is closed here.** That is a route
|
||||
decision, not a failure — and it is the same shape of answer §6 gives for the whole escalation
|
||||
ladder. Do not let the existence of the template change what you claim about it: `unverified` is
|
||||
still `unverified`.
|
||||
|
||||
## 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
|
||||
@@ -178,7 +262,7 @@ honest outcome (`observed`, from `tools/_phone-modules/README-*.md`):
|
||||
| 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) |
|
||||
| KPM / kernel module route | closed on this device — no KernelPatch image, no kernel source, no bare-metal ARM64 toolchain; the **template and gate table** are shipped (§4a) |
|
||||
| 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
|
||||
@@ -198,6 +282,8 @@ defeated with a custom kernel module is not a deliverable anyone can install.
|
||||
| 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) |
|
||||
| You have the kernel template and want to load it on a 4.14/Magisk device | Read `§4a`'s gate table, confirm the gate is closed, and say so | Patching a boot image to obtain a kernel route, on an APK task |
|
||||
| A kernel-side template exists, so it feels like a weapon | It is `unverified` until a device with the matching gate compiles and loads it | Presenting a template as a working capability |
|
||||
| Escalation effort exceeds the user's actual ask | `detection-and-anti-analysis.md` stop signal — switch to static | One more layer |
|
||||
|
||||
## Checklist
|
||||
@@ -207,5 +293,8 @@ defeated with a custom kernel module is not a deliverable anyone can install.
|
||||
- [ ] 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
|
||||
- [ ] Kernel-side template treated as `unverified` until a device with the matching gate
|
||||
actually compiles and loads it (`§4a`); the userspace module skeleton is a carrier for
|
||||
configuration, not a kernel capability
|
||||
- [ ] Raw-syscall vs libc-call distinction verified by disassembly before building any spoof
|
||||
- [ ] No kernel development undertaken as part of an APK deliverable
|
||||
@@ -182,6 +182,53 @@ across runs only for code that is mapped from file; do not compare a `libart`-ma
|
||||
address between two runs; and never place a follow/unfollow pair on a hot function (measured failure
|
||||
in §6).
|
||||
|
||||
### The cost is not linear, and on arm64 it decides the tool choice
|
||||
|
||||
Two costs decide whether Stalker is the right tool, and neither is visible in the API:
|
||||
|
||||
- **Translation multiplier.** A followed thread pays a large constant factor on every translated
|
||||
block. Community reporting for arm64 puts it at **20-50x**; the mechanism is not controversial
|
||||
(every block is copied into the DBI's code cache and routed through a dispatcher), while the exact
|
||||
number is workload-dependent. This one is `inferred` — this repository has not measured the
|
||||
multiplier itself, only its consequences below.
|
||||
- **What you let into the trace.** Every block of every library the thread touches is a candidate.
|
||||
Following into `libc` / `libart` / `libhwui` is how a four-second window becomes a device-wide
|
||||
event: measured here, one such run took the test phone's `load average` to `34.11` on 8 cores and
|
||||
destroyed a co-running job's attach (§6).
|
||||
|
||||
`Stalker.exclude()` is the control for the second cost, and it is not optional.
|
||||
`scripts/stalker_trace.js` applies it before `follow()` from its `excludeModules` list and reports
|
||||
what it actually excluded on one `EXCL` line — read that line before believing any trace, because a
|
||||
module that was not loaded at follow time was **not** excluded. Exclude every system library you are
|
||||
not studying; the target module is never excluded even if its name appears in the list.
|
||||
|
||||
Three failure shapes follow from ignoring this: deadlock, a watchdog `SIGABRT`, and the zero-event
|
||||
trace. The deadlock and the watchdog shape remain community reports (`inferred`); the other two were
|
||||
measured, **and the measurement splits the claim in two** — the split matters more than the summary:
|
||||
|
||||
| Arm — one device, one package, one module, 6 s follow | Outcome |
|
||||
|---|---|
|
||||
| attach + resume, **no follow** | process survives |
|
||||
| follow, `excludeModules: []` | **process dies**, script destroyed |
|
||||
| follow, 20 system modules excluded | process survives, **but `blocks=0 blk=0 calls=0`** |
|
||||
|
||||
Exclusion is what keeps the target alive — now `observed`, with the no-follow arm ruling out "it
|
||||
would have died under frida anyway". But exclusion does **not** restore event delivery: the
|
||||
zero-event trace survived the treatment arm unchanged. Treat those as two problems, and do not offer
|
||||
`exclude` as the fix for a follow that delivers nothing. Commands and outputs:
|
||||
`docs/tool-verification/EXTENSION-stalker-exclude.md`.
|
||||
|
||||
**arm64 also raises the floor.** PAC/BTI-bearing code gives a translator more ways to mis-handle a
|
||||
block than armv7 did, which is one more reason a trace that works on an emulator is not evidence
|
||||
about a device. Treat any arm64 result as needing a control run (a followed thread executing a known
|
||||
loop, nonzero `BLK` lines) before it is interpreted.
|
||||
|
||||
**Emulation is a legitimate alternative, not a consolation prize.** When the target is a pure
|
||||
computation inside a `.so` and its environment can be faked, a Unidbg/Unicorn trace can be both
|
||||
faster and more stable than Stalker on a real arm64 device: no device load, no watchdog, no PAC, and
|
||||
a deterministic replay. That inversion of the usual intuition is half the reason
|
||||
`emulation-and-rpc.md` exists — decide with its decision table rather than by habit.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -55,9 +55,13 @@ Three consequences that decide how you interpret any decoded body:
|
||||
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.
|
||||
3. **A decoded `0` and a field that was never set are two different questions.** An implicit
|
||||
(no-presence) proto3 field whose value is the default writes **nothing at all**, so `field = 0`
|
||||
and "never touched" produce identical bytes; a field **with** presence (`proto2 optional`,
|
||||
`proto3 optional`) set to `0` does put its tag and a zero byte on the wire. Both halves were
|
||||
measured against the official runtime; a schema-free decoder can only flag the case, never
|
||||
resolve it. So a decoded `0` was emitted on purpose by some writer, and a field *missing* from a
|
||||
decode is not evidence that 0 was the value in use.
|
||||
|
||||
### Decoding without a schema
|
||||
|
||||
@@ -77,6 +81,63 @@ Three consequences that decide how you interpret any decoded body:
|
||||
covers reading these, and `datastore_inject.py` can re-encode an edited DataStore value once you
|
||||
know the message.
|
||||
|
||||
### The decoder that ships here (measured)
|
||||
|
||||
`scripts/protobuf_decode_raw.py` walks a payload with no schema and prints a tree. Input is a hex
|
||||
string, a binary file, or stdin (hex text and raw bytes are told apart automatically); `0x` prefixes,
|
||||
spaces, commas, newlines and `\xNN` escapes are all accepted, and `|` splits independent frames.
|
||||
`--json` emits the same tree as data, `--max-depth` bounds the nesting, and `--reencode` writes a
|
||||
decoded (possibly hand-edited) tree back to bytes and can diff the result against the original.
|
||||
|
||||
```
|
||||
$ python skills/apk-reverse/scripts/protobuf_decode_raw.py --hex "08 96 01 12 07 74657374696e67"
|
||||
frame 0 bytes 0..12 (12 B) status=end_of_buffer
|
||||
f1 varint 150
|
||||
f2 len-delimited(7) view=utf8_string
|
||||
candidate utf8_string 0.50 valid UTF-8 with no control characters
|
||||
candidate packed_varint 0.50 the payload is exactly a sequence of 7 varint(s) ...
|
||||
candidate bytes 0.20 opaque bytes: always consistent with the payload ...
|
||||
tie: packed_varint and utf8_string are equally consistent with these bytes ...
|
||||
string: 'testing'
|
||||
```
|
||||
|
||||
The point of the tool is the candidate list. Fed a nested message that `google.protobuf` 6.33.6
|
||||
itself produced (inner payload `0801120178`), it answers:
|
||||
|
||||
```
|
||||
nested_message 0.50 | packed_varint 0.50 | utf8_string 0.35 | bytes 0.20
|
||||
tie: nested_message and packed_varint are equally consistent ... the view is a display default
|
||||
```
|
||||
|
||||
Both readings really are legal protobuf for those six bytes, and no heuristic closes the gap. The
|
||||
confidence numbers are a documented ordering, not probabilities, and the `view` exists only so the
|
||||
tree can be expanded and re-encoded -- it is not a claim about what the field is.
|
||||
|
||||
**Round trip, which is the strongest evidence available without a schema.** Decode, re-encode, and
|
||||
compare bytes: the message serialized by the official runtime re-encodes byte-identically to
|
||||
`SerializeToString()`; a real AndroidX DataStore file (81 B, written by `scripts/datastore_inject.py`)
|
||||
round-trips byte-identically; and editing one value in the JSON tree and re-encoding produced a file
|
||||
that the *other* tool read back as the new value. Two of the built-in fixture families are exceptions
|
||||
by design and are reported as such rather than hidden: a non-canonical varint re-encodes to the
|
||||
minimal form, and a `--split varint-length` run compares frame bodies only, since the length prefixes
|
||||
are framing and not message data.
|
||||
|
||||
**What a schema-free decode cannot conclude -- write none of these down:**
|
||||
|
||||
- that a length-delimited field *is* a string, a submessage or a packed array, rather than that it
|
||||
could be any of them;
|
||||
- the element boundaries of a packed array, or its element type;
|
||||
- that a field's value was 0 because it is absent from the decode, or that a sender "set" a field
|
||||
because a 0 appears (see the two traps above);
|
||||
- which message a field number belongs to, or that the same field number in two payloads means the
|
||||
same thing;
|
||||
- that a payload which parses cleanly is a real message at all -- §6 has that failure mode, and the
|
||||
fixes are a second sample and a round trip, not a longer look at the first one.
|
||||
|
||||
The measured record for this tool -- every command, both input forms, the round trip, and the
|
||||
framing mistake it does *not* protect you from -- is in
|
||||
`docs/tool-verification/EXTENSION-protobuf-raw.md`.
|
||||
|
||||
## 2. Recovering the schema from the APK
|
||||
|
||||
### What generated protobuf code looks like
|
||||
@@ -253,6 +314,13 @@ their parents, and (c) when you have a schema, re-encoding the decoded structure
|
||||
with the input — the same round-trip check used in §1, which caught a decoder bug in this
|
||||
repository's own fixture.
|
||||
|
||||
**A framing choice that is wrong without being refused.** `--split varint-length` means protobuf's own
|
||||
`writeDelimitedTo` framing: a varint length, then the message. gRPC frames a message differently — one
|
||||
compression-flag byte, then a **four-byte big-endian** length (§3). Handed a real gRPC frame, the
|
||||
varint splitter reported **five** frames rather than failing, while the same bytes decoded with no
|
||||
splitting reported `stray_end_group`. Strip the 5-byte gRPC prefix yourself, and check the frame count
|
||||
either way: a wrong split still produces a decode, which is what makes it expensive.
|
||||
|
||||
**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
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
# Split APKs and App Bundles
|
||||
|
||||
A store build is frequently **not one file**. Play and most OEM stores ship App Bundles, and the
|
||||
device receives a set: `base.apk` plus one `split_config.*.apk` per ABI, screen density and language
|
||||
(and, for a dynamic-feature bundle, the feature modules as well). Every member carries **the same
|
||||
package name and its own signature**, and the package manager treats the set as one package.
|
||||
|
||||
Two failures follow from treating such a set as an APK, and both look like a broken build when they
|
||||
are nothing of the kind:
|
||||
|
||||
- Signing only the base leaves the set disagreeing about its certificate; the installer rejects the
|
||||
whole set and names the package, not the member you forgot.
|
||||
- "Just merge them into one APK" is free *only* for members that carry code or native libraries. A
|
||||
member that carries resources cannot be folded into the base without merging `resources.arsc`,
|
||||
which is a resource-compiler job. A wrongly merged archive installs and then renders the wrong
|
||||
thing, or dies on the first resource lookup.
|
||||
|
||||
`scripts/repack.py` handles both routes and **refuses to guess**: it inventories the set, decides
|
||||
which route is legal from what the members actually carry, prints the reason, and only then acts.
|
||||
|
||||
**Strength labels** (same three this repository uses everywhere): **observed** = reproduced with an
|
||||
exact command and output; **inferred** = follows from observed facts, step not executed;
|
||||
**unverified** = reported or assumed, not independently confirmed. The measurements behind this
|
||||
file are recorded in `docs/tool-verification/EXTENSION-split-apk.md`.
|
||||
|
||||
## 1. What the set is
|
||||
|
||||
| Member | Manifest `split` attribute | Carries | Foldable into the base? |
|
||||
|---|---|---|---|
|
||||
| base | *(absent)* | all `classes*.dex`, the main `resources.arsc`, every resource not moved out, the real `<application>` | — it *is* the base |
|
||||
| ABI split | `config.arm64_v8a`, `config.armeabi_v7a`, `config.x86_64`, … | `lib/<abi>/*.so` only | **yes** — entry names do not collide |
|
||||
| density split | `config.hdpi` … `config.xxxhdpi` | its own `resources.arsc` **and** `res/` entries | **no** — requires a resource merge |
|
||||
| language split | `config.en`, `config.zh`, … | its own `resources.arsc` (strings) | **no** — same reason |
|
||||
| feature split | `feature_x` (+ `isFeatureSplit="true"`, `configForSplit="base"`) | its own `classes*.dex`, possibly resources | **code only**; its resources hit the same wall |
|
||||
|
||||
**Observed** on a real 9-member set pulled from a stock Android 11 device (arm64-v8a target):
|
||||
|
||||
- the base carried `classes.dex` (872 KB) and `resources.arsc` (71 KB);
|
||||
- the ABI member carried two `lib/arm64-v8a/*.so` files and **no `resources.arsc` at all**;
|
||||
- each density member carried its own `resources.arsc` and its own `res/` entries;
|
||||
- a second, 8-member set's density members carried 39-78 `res/` entries each and 9-15 KB tables.
|
||||
|
||||
So "which member owns the resources" is answerable **from the zip entry list alone** — no device, no
|
||||
resource compiler, no decompiler. Copy a set to disk and ask.
|
||||
|
||||
**A member can own a nearly empty table.** A split is *required* to carry a `resources.arsc`, so a
|
||||
placeholder one is normal: on the same real set, eight density members carried a **40-byte** table
|
||||
and no `res/` entries at all — they are placeholders, not resources. Treating "has an arsc" as "owns
|
||||
resources" would block a merge that is perfectly legal. `repack.py` uses *entries under `res/` or a
|
||||
table bigger than 1 KB* as the test.
|
||||
|
||||
## 2. Getting the set off a device
|
||||
|
||||
`pm path` prints **one line per member**; a package with several lines is a split set. This is how
|
||||
you find one to copy, and it is also how you tell, before anything else, that the thing you are about
|
||||
to patch is not a single APK:
|
||||
|
||||
```bash
|
||||
adb shell 'pm path <PKG>'
|
||||
package:/system/priv-app/<DIR>/<APP>.apk
|
||||
package:/system/priv-app/<DIR>/<APP>-arm64_v8a.apk
|
||||
package:/system/priv-app/<DIR>/<APP>-xxhdpi.apk
|
||||
```
|
||||
|
||||
To enumerate every split set on a device (toybox shell — no `--time-style`, no bash arrays):
|
||||
|
||||
```bash
|
||||
adb shell 'for p in $(pm list packages | cut -d: -f2); do c=$(pm path $p | wc -l); \
|
||||
if [ $c -gt 1 ]; then echo "$c $p"; fi; done'
|
||||
```
|
||||
|
||||
Copy the whole directory out; the members live side by side:
|
||||
|
||||
```bash
|
||||
adb shell 'su -c "ls -la /system/priv-app/<DIR>/"'
|
||||
adb pull /system/priv-app/<DIR> <dest>/
|
||||
```
|
||||
|
||||
Two traps, both **observed**:
|
||||
|
||||
- `adb pull <dir> <dest>` creates `<dest>/<dir>/` — the set arrives one level deeper than you expect.
|
||||
`repack.py --split-dir` searches recursively for exactly this reason.
|
||||
- A **third-party** split set is rare on a stock ROM. On the device measured here, `pm list packages -3`
|
||||
returned **zero** split sets among ~40 third-party apps, while four preinstalled Google components
|
||||
were split. If you need a real set and the third-party list is empty, that is the normal
|
||||
distribution, not a mistake on your side.
|
||||
|
||||
**Do not test by reinstalling a pulled set under its own package name.** It is already installed on
|
||||
that device, owned by the vendor certificate you do not have, so the install fails for a reason that
|
||||
has nothing to do with your pipeline (§6). Either work on a set you own, or rename the pulled one
|
||||
(§7) to get an installable fixture.
|
||||
|
||||
## 3. The decision: merge or resign
|
||||
|
||||
Run this first — it writes nothing and answers with a reason:
|
||||
|
||||
```bash
|
||||
python skills/apk-reverse/scripts/repack.py --split-dir <set>/ --split-mode analyze
|
||||
```
|
||||
|
||||
| Situation | Route | Why |
|
||||
|---|---|---|
|
||||
| Every non-base member carries only code and/or `lib/` (a placeholder `resources.arsc` is fine) | **merge** | nothing that needs a resource table moves |
|
||||
| Any member carries `res/` entries or a real table | **resign** | a resource merge rewrites the table; see §5 |
|
||||
| You must keep the build installable **and** the app is distributed as a bundle | **resign** | this is what the store does; the set stays a set |
|
||||
| You need one file to hand someone, sideload, or feed to a tool that takes an APK | **merge**, if legal | the only way to get a single artifact |
|
||||
| The delivery must survive store updates, or the ROM's own installer refuses multi-APK installs | **resign** (`pm install-multiple`), or merge and accept a fixed build | — |
|
||||
| A member declares `isFeatureSplit="true"` and ships `classes*.dex` **and** resources | **resign** | its code could fold, its resources cannot; a half-merged build is worse than either route |
|
||||
|
||||
Failure modes, one per route:
|
||||
|
||||
- **merge**, when a resource-carrying member is dropped to make it legal: the app starts and shows
|
||||
the base's resources. Missing density variants show up as blurry or missing images; missing
|
||||
language splits show as untranslated strings. This is a **downgraded** build and has to be
|
||||
delivered as one — `repack.py` prints `DROPPED n entry/ies` and refuses unless you pass
|
||||
`--drop-split-resources`, so the loss cannot be silent.
|
||||
- **merge**, when the base still declares `isSplitRequired="true"`: install succeeds and start is
|
||||
refused (`INSTALL_FAILED_MISSING_SPLIT`, §6). The attribute has to be cleared first, and that is a
|
||||
binary-AXML edit.
|
||||
- **resign**, when one member is missed: the set fails as a set, with a signature error naming the
|
||||
package. Sign the directory, not a list you typed by hand.
|
||||
- **resign**, when the target ROM's installer is not the platform installer: `adb install-multiple`
|
||||
can be intercepted by an OEM security centre, exactly as single-APK installs are
|
||||
(`references/repack-and-sign.md` §Vendor install interception (OEM shells)). Use the root
|
||||
`pm install-multiple` path.
|
||||
|
||||
## 4. Unified signing — the route that always works
|
||||
|
||||
```bash
|
||||
python skills/apk-reverse/scripts/repack.py \
|
||||
--split-dir <set>/ --split-mode resign \
|
||||
--split-out-dir <signed_set>/ \
|
||||
--ks key.jks --apksigner <path/to/apksigner>
|
||||
```
|
||||
|
||||
Each member is de-signed (only the signature entries), rewritten as a 4-byte-aligned archive, and
|
||||
signed with **one** keystore and **v1+v2+v3**; the run then verifies every member and prints the
|
||||
signer fingerprint per file. The acceptance criterion is not "each file verifies" — it is **one
|
||||
certificate across the whole set**:
|
||||
|
||||
```
|
||||
[result] OK: 8 members, one certificate (sha256 1eb31d9c…2c44)
|
||||
```
|
||||
|
||||
Then install the whole set, base included:
|
||||
|
||||
```bash
|
||||
adb install-multiple -r <signed_set>/*.apk
|
||||
adb shell "su -c 'pm install-multiple -r /data/local/tmp/set/*.apk'" # when an OEM installer refuses the multi-APK form
|
||||
```
|
||||
|
||||
**The signature must cover every member**, and `--abi`/density selection happens at install time, not
|
||||
at signing time — sign them all, let the installer pick (see §6).
|
||||
|
||||
### Toolchain: `uber-apk-signer` is optional, `apksigner` is not
|
||||
|
||||
`repack.py`'s original signing route went through `uber-apk-signer` only, so a machine with a full
|
||||
Android build-tools directory and no uber-apk-signer could not produce a signed build at all. The
|
||||
script now picks the route itself:
|
||||
|
||||
- `--signer jar` — the uber-apk-signer path (used automatically when the jar exists);
|
||||
- `--signer apksigner` — `zipalign -p -f 4` then `apksigner sign --v1 --v2 --v3`, which is the whole
|
||||
of what the jar was doing for us;
|
||||
- `--signer auto` (default) — jar if present, else apksigner.
|
||||
|
||||
`--apksigner` accepts all three shapes a build-tools install ships: `apksigner.bat`, the `apksigner`
|
||||
shell wrapper, or the bare `lib/apksigner.jar`. **On Windows pass the `.jar` or the `.bat`** — the
|
||||
extensionless wrapper is a shell script and will not execute. A `.jar` value is run through
|
||||
`java -jar`, so `--java` (or java on PATH) is required for it.
|
||||
|
||||
Order is load-bearing: **align, then sign**. `apksigner` adds signature entries without reshuffling
|
||||
the archive; the v1 (JAR) path emulates `jarsigner`, whose rewrite of the zip would destroy the
|
||||
alignment Android R+ requires of `resources.arsc`.
|
||||
|
||||
## 5. Merging into a single APK
|
||||
|
||||
```bash
|
||||
python skills/apk-reverse/scripts/repack.py \
|
||||
--split-dir <set>/ --split-mode merge --out merged.apk \
|
||||
--abi arm64-v8a --ks key.jks --apksigner <path/to/apksigner>
|
||||
```
|
||||
|
||||
What folds: `classes*.dex` (renumbered so a member's `classes.dex` becomes `classes2.dex`, keeping
|
||||
the base's own dex intact), `lib/**`, `assets/**`. What does not, and why: `res/**` and
|
||||
`resources.arsc`.
|
||||
|
||||
**Why resource merging is not attempted.** `resources.arsc` is an indexed table: a global string
|
||||
pool plus type-spec and type chunks, with every resource identified by a `(package, type, entry)`
|
||||
triple and every string referenced by pool offset. Folding a member's table into the base's means
|
||||
rewriting pool offsets, type/entry counts and the alignment of every string, in both directions —
|
||||
that is `aapt2 link`, not a byte-level edit. The failure it produces is the worst kind: the archive
|
||||
is *structurally* valid, installs, and then resolves resource ids to the wrong entries or to nothing.
|
||||
An APK that renders garbage is harder to diagnose than one that refuses to install.
|
||||
|
||||
If you genuinely need one standalone file for a bundle whose resources are split, the honest routes are:
|
||||
|
||||
1. **`bundletool build-apks --mode=universal`** (the vendor tool, needs the original `.aab`) — this is
|
||||
what merges resources correctly, and it is the only route that does.
|
||||
2. **Keep the split set** and install it as a set (§4).
|
||||
3. **Accept the downgrade** with `--drop-split-resources`, and say so in the delivery.
|
||||
|
||||
**Manifest constraints when you do merge — and when you patch any split at all.** These attributes
|
||||
are the difference between "installs and runs" and an install or start refusal, and they are easy to
|
||||
miss because they live in binary AXML:
|
||||
|
||||
| Attribute | Lives on | Effect if you get it wrong |
|
||||
|---|---|---|
|
||||
| `split="config.xxhdpi"` | `<manifest>` of a **split** | Identifies the member. A split whose `package` differs from the base's, or whose `split` name is duplicated, is refused as a set |
|
||||
| `configForSplit="base"` | `<manifest>` of a split | Ties a configuration split to a feature module. Changing package/module names without updating it silently detaches the split |
|
||||
| `isFeatureSplit="true"` | `<manifest>` of a feature split | Marks an install-time/on-demand module. A merge that folds code in but leaves the attribute declared describes a member that no longer exists |
|
||||
| `isSplitRequired="true"` | `<manifest>` of the **base** | The platform refuses to start a base that believes it is incomplete. This is the one that breaks merged builds (§3) |
|
||||
|
||||
Read them without a decompiler through `scripts/repack.py`'s own AXML reader (`--split-mode analyze`
|
||||
prints the `split` name per member; `inspect_apk()` returns `package`, `split`, `configForSplit`,
|
||||
`isSplitRequired`, `isFeatureSplit`). Changing any of them means editing the binary string pool and
|
||||
the attribute chunks around it, which is what `apktool` is for — and note that a full
|
||||
`apktool b` rebuild rewrites the whole archive
|
||||
(`references/repack-and-sign.md` §Repacking an unpacked (de-shelled) app).
|
||||
|
||||
## 6. Install refusals, and what each one means
|
||||
|
||||
| Message | What it actually says | Attribution |
|
||||
|---|---|---|
|
||||
| `Failure [INSTALL_FAILED_INVALID_APK: ... signatures do not match previously installed version]` / `Package <PKG> signatures do not match` | The set you are installing is signed with a different certificate than the one already on the device | **Not** a malformed build. Either re-sign to the original key, or install to a package name that does not exist yet |
|
||||
| `Failure [INSTALL_FAILED_ALREADY_EXISTS]` / `INSTALL_FAILED_UPDATE_INCOMPATIBLE` | Same package, different signer (or a downgrade without `-d`) | A pulled system component cannot be reinstalled over itself; see §7 |
|
||||
| `Failure [INSTALL_FAILED_MISSING_SPLIT: Missing split for <PKG>]` | The base declares `isSplitRequired="true"` and the set is incomplete — or you merged it | The base is telling the truth: it expects members. Clear the attribute, or install the complete set |
|
||||
| `Failure [INSTALL_FAILED_INVALID_APK: Failed to parse ... split ... has different signature]` | **One member** of the set is signed differently from the rest | This is the failure mode of signing only the base. Sign the whole directory |
|
||||
| `Failure [-124: ... resources.arsc ... stored uncompressed and aligned on a 4-byte boundary]` | One member's `resources.arsc` is compressed or unaligned | Per-member, not per-set. `repack.py` reports it per member before signing (`references/repack-and-sign.md` §2a) |
|
||||
| `Failure [-99]`, or a numeric-only code with no `INSTALL_FAILED_*` | An OEM installer interceptor rejected the request | Nothing to do with the set; use the root `pm install-multiple` path |
|
||||
| `adb install-multiple` on a device that has no `install-multiple` support (very old `pm`) | Install each member with `pm install` in order, base last | Use `pm install-create` / `install-write` / `install-commit` explicitly |
|
||||
|
||||
`INSTALL_FAILED_INVALID_APK` in particular is a **family**, not one error: it covers stale
|
||||
signatures, malformed base/split relationships, and alignment violations. Read the text after the
|
||||
colon before attributing anything — the constant alone will send you looking at the wrong file.
|
||||
|
||||
## 7. Making an installable fixture from a pulled set
|
||||
|
||||
**Observed, and the reason this section exists:** a set pulled from the device is installed *on that
|
||||
device*, under a name owned by the vendor certificate. Re-signed copies cannot be installed back
|
||||
over it, so "does our signed set install?" cannot be answered with the pulled set as it stands.
|
||||
|
||||
The cheap, structure-preserving way out is an **equal-length package rename**: replace every
|
||||
occurrence of the old package name in `AndroidManifest.xml`, `resources.arsc` and `classes*.dex`
|
||||
with a new name of exactly the same length. Nothing moves — no length prefix, no string-pool offset,
|
||||
no dex `string_ids` offset, no resource index — so the only field that must be recomputed is the dex
|
||||
header's integrity pair (signature first, checksum last, see
|
||||
`references/repack-and-sign.md` §Repacking an unpacked (de-shelled) app). Then run the ordinary
|
||||
`--split-mode resign` over the renamed directory and install that.
|
||||
|
||||
A detail worth knowing before you touch a manifest: **a member's Java classes need not live under its
|
||||
manifest `package` at all**. On the real set measured here, the manifest package was
|
||||
`com.google.android.<name>` while all 677 class references in the dex were
|
||||
`Lcom/android/<name>/...` — and every `<activity android:name>` was fully qualified. Renaming the
|
||||
manifest package therefore left every component resolvable, with no dex edit needed. Assume the
|
||||
opposite (that the two must match), and you will edit a dex for nothing.
|
||||
|
||||
## 8. ABI and density matching
|
||||
|
||||
The device tells you what it can run:
|
||||
|
||||
```bash
|
||||
adb shell getprop ro.product.cpu.abilist # e.g. arm64-v8a,armeabi-v7a,armeabi
|
||||
adb shell getprop ro.product.cpu.abi # the primary ABI
|
||||
adb shell getprop ro.product.cpu.abilist32 # 32-bit list, on a 64-bit device
|
||||
```
|
||||
|
||||
Match against the **split name**, not the file name, and mind the separator: split qualifiers use
|
||||
**underscores** (`config.arm64_v8a`) while `lib/` directories use **hyphens** (`lib/arm64-v8a/`). The
|
||||
mapping is a substitution, not a lookup — `arm64_v8a` → `arm64-v8a`, `armeabi_v7a` → `armeabi-v7a`;
|
||||
`x86` and `x86_64` are unchanged. That is why `--abi arm64-v8a` matches a split named
|
||||
`config.arm64_v8a`.
|
||||
|
||||
Four rules that decide ABI questions:
|
||||
|
||||
- **A 64-bit device still installs a 32-bit-only set**, and then runs it 32-bit. If the base carries
|
||||
no native code and only the `armeabi_v7a` split does, the app is a 32-bit app on that device.
|
||||
- **The ABI split is selected by the installer, not by `repack.py`.** `--abi` exists for *merging*
|
||||
(where the choice is baked into one file); for `--split-mode resign`, sign every member and let
|
||||
`pm` pick.
|
||||
- **Merging without `--abi` folds in every ABI member**, which makes one APK with two or three copies
|
||||
of the same library set. Legal, larger, and pointless on a single-device delivery.
|
||||
- **`getprop` reports what the device claims**; what runs is a live mapping question
|
||||
(`scripts/lib_map.py`). A device that reports `arm64-v8a` first can still execute a 32-bit process.
|
||||
|
||||
Density is the same shape without the separator trap: `config.xxhdpi` matches
|
||||
`res/drawable-xxhdpi/`, and the installer picks the closest variant the device's `ro.sf.lcd_density`
|
||||
can use. There is nothing to select on your side.
|
||||
|
||||
## 9. Traps worth paying for once
|
||||
|
||||
- **`resources.arsc` belongs to whoever ships it.** In a split set it exists *per member*, and the
|
||||
base's table does not contain the density member's entries. Reading the base's table and concluding
|
||||
"the resource exists" is wrong; it exists in one configuration only.
|
||||
- **`android:extractNativeLibs`.** If the base declares `extractNativeLibs="false"` (the default for
|
||||
modern targetSdk), the `.so` files are mmapped straight out of the archive, and they must be
|
||||
**uncompressed and page-aligned** — this is what `zipalign -p` exists for. Merging native members
|
||||
into a base and then writing the archive without that alignment produces an install that succeeds
|
||||
and a start that dies in the linker. `repack.py` writes uncompressed `lib/**` 4-byte aligned, and
|
||||
`zipalign -p -f 4` adds the page alignment the loader wants for them.
|
||||
- **A placeholder `resources.arsc` is not a resource split** (§1). Blocking on "has an arsc" refuses
|
||||
legal merges.
|
||||
- **Do not `zipalign` after signing to "fix" a member.** It rewrites the archive and invalidates the
|
||||
signature. Align, then sign.
|
||||
- **`apktool` may not be usable even when a wrapper exists.** Measured on the pass machine: the
|
||||
`apktool.bat` wrapper pointed at a jar that was not on disk
|
||||
(`Error: Unable to access jarfile <missing>.jar`), while `apksigner.jar` and `zipalign.exe` in the
|
||||
same layout were fine. Check the wrapper's target before planning a manifest edit around it.
|
||||
- **The AXML `split` attribute is a string-pool entry**, which is why an equal-length rename of it is
|
||||
safe and why a length-changing edit is not: the pool's own length prefixes and the attribute chunk
|
||||
sizes around it would both need recomputing.
|
||||
|
||||
## 10. What this file does not claim
|
||||
|
||||
- **It does not merge resources.** No route here reproduces `bundletool build-apks --mode=universal`.
|
||||
A bundle whose resources live in splits stays a set, or becomes a downgraded single APK by explicit
|
||||
choice.
|
||||
- **It does not split a monolithic APK back into modules**, and it cannot turn a `.aab` into APKs —
|
||||
that is `bundletool`, and the `.aab` is the input it needs.
|
||||
- **`--split-mode merge` covers code and native libraries only** (§5). Feature-split *code* folds;
|
||||
feature-split *resources* do not.
|
||||
- The install-failure texts in §6 are the shape the platform produces; **the exact wording varies by
|
||||
Android version and by OEM installer**. Read the text after the constant, not the constant.
|
||||
@@ -0,0 +1,237 @@
|
||||
# Differential hardening (the known-plaintext route to a private opcode table)
|
||||
|
||||
Load this when the dump is a **real Dex VMP** — bodies present, decoding as nonsense to a
|
||||
dalvik disassembler, a native interpreter loop behind them — and you have decided the
|
||||
private opcode space is worth attacking rather than walking away from. The neighbouring
|
||||
file owns the diagnosis (`advanced-unpacking.md` §The honest boundary: real Dex VMP) and
|
||||
the sentence that sends you here. This file owns what happens next, and — more of it than
|
||||
is comfortable — what does not.
|
||||
|
||||
**Strength note, read before trusting any number here.** Every mechanism below was
|
||||
exercised on locally built fixtures, and the closed loop is measured: `simulate` relabels
|
||||
a fixture through a known bijection and `compare` re-derives that table **exactly, 218 of
|
||||
218 emitted opcodes, zero wrong entries, zero fabricated entries** (`docs/tool-verification/EXTENSION-vmp-diff.md`).
|
||||
What was **not** exercised is the other half of the premise: **no third-party hardening
|
||||
platform was contacted**. The assumption that a real engine performs a per-opcode
|
||||
substitution at stable instruction length is **inferred** from public VMP write-ups and is
|
||||
exactly the assumption this method can fail on. The cost table's platform column is
|
||||
therefore reasoning from how those platforms are distributed, not from a measured upload.
|
||||
|
||||
## 1. The method, and the one thing it needs to be true
|
||||
|
||||
The hardened body cannot tell you where its instruction boundaries are: its opcodes are
|
||||
private, so the format specification's length table does not apply to it. That is the
|
||||
whole obstacle — a disassembler that cannot decide where instruction *n* ends cannot name
|
||||
instruction *n+1*.
|
||||
|
||||
The differential dissolves it with an oracle you control. Compile a fixture whose every
|
||||
instruction you know; get the same platform to harden it; then **take the original's
|
||||
instruction boundaries and project them onto the hardened bytes**. Original offset
|
||||
`0x14` was a `mul-int` occupying 2 code units, so hardened bytes `0x14..0x17` are the same
|
||||
instruction, re-encoded. Read the hardened opcode byte at each projection and you have a
|
||||
`(original opcode → private byte)` sample. Aggregate over thousands of instructions and
|
||||
the substitution table falls out.
|
||||
|
||||
Three preconditions, and they are not negotiable:
|
||||
|
||||
| Precondition | Why it must hold | What it looks like when it fails |
|
||||
|---|---|---|
|
||||
| **The hardened body keeps the same length** | The projection is a stencil; a length change slides every boundary after the first edit | `compare` reports `resized` for the whole method and refuses the run |
|
||||
| **The substitution is per-opcode, not per-method** | One private byte per original opcode is what makes the table a table | Every original opcode claims the same private byte (`compare` → `NOT-USABLE`, stub shape) |
|
||||
| **The body is still in the dex** | Alignment needs two byte streams | Method has `code_off == 0` (`compare` reports `stripped`) |
|
||||
|
||||
The third is the one that kills the method most often in practice: a VMP that *extracts*
|
||||
bodies to a native interpreter leaves nothing to align. The differential route then has no
|
||||
input at all, and no amount of clever fixture design creates one. Check for it before
|
||||
spending any time here.
|
||||
|
||||
## 2. Cost table — which links can be automated, and which cannot
|
||||
|
||||
This is the part the method's public descriptions leave out. The chain is six links; two
|
||||
of them are unavoidably human, and pretending otherwise is how a "harness" ships that has
|
||||
never once been run against a real target.
|
||||
|
||||
| # | Link | Automation | Where a human must stand | Time cost | Failure mode |
|
||||
|---|---|---|---|---|---|
|
||||
| 1 | Compile the coverage fixture into a dex + APK | **Full** — `scripts/vmp_diff_harness.py build`, measured | none | ~40 s on this machine (javac + d8 + aapt2), ~1 s of it the script | toolchain absent or version-drifted; `d8` rejects a non-existent `--output` directory, `aapt2 link` rejects `android:` attributes without `android.jar` |
|
||||
| 2 | **Submit to the hardening platform** | **None. Not automatable.** | 100 % — a browser, an account, sometimes a queue and a review | minutes to **days**; the platform decides | **the binding constraint of the whole route.** No public API; per-account rate limits; uploads are frequently gated behind registration; the artifact often comes back as a download page rather than a file path. A synthetic fixture may simply be **refused** (no real app shape, no certificate, no package identity) |
|
||||
| 3 | Retrieve the hardened output and extract its dex | Partial — if the output is an APK, `unzip` + `dexutil.load_dex` handles it | download and hand-off | seconds, once the file exists | output is an APK whose dex is *also* encrypted, or the platform returns only a repacked APK with a native loader and no readable dex |
|
||||
| 4 | Derive the correspondence | **Full** — `compare`, measured end to end | none | **sub-second** on a 3,065-instruction fixture | alignment slips (see §4); engine is not a pure relabelling |
|
||||
| 5 | Prove the derived table | Partial — the mechanical half is scripted and measured; the judgement is not | decide whether the held-out check was passed or merely not attempted | minutes | a table that is *self-consistent* but describes a stub (§5) |
|
||||
| 6 | Render Smali from the restored stream | Full — `emit-smali`, measured | none | sub-second | table has holes; restored stream decodes short of the method end |
|
||||
|
||||
**Conclusion, stated plainly: do not build a fully automatic pipeline.** Link 2 is
|
||||
irreducibly manual — the platform has no interface a script can drive, and its output
|
||||
cadence is not one a pipeline can wait on. The right shape is what this repository ships:
|
||||
|
||||
- links 1, 4 and 6 as **reliable local tools** (they are deterministic and were measured);
|
||||
- link 5 as **a checklist plus one scripted test** (§5) — the judgement stays human;
|
||||
- link 2 as **a documented manual step**, with its cost stated up front, so nobody writes
|
||||
an orchestrator that waits forever on a web form;
|
||||
- and links 4–5 **self-verifiable without the platform at all**, which is what `simulate`
|
||||
exists for. You can prove your comparison logic against a known table today; you cannot
|
||||
prove the engine's behaviour until a human uploads a fixture.
|
||||
|
||||
The practical consequence: the deliverable of this route is an **analysis report with a
|
||||
stated boundary**, not a pipeline. Say so before starting.
|
||||
|
||||
## 3. The coverage fixture — what a compiled probe can and cannot reach
|
||||
|
||||
A Java-compiled fixture reaches **218 of the 224 named opcodes in this repository's format
|
||||
table (97.3 %)** — that number is measured, not estimated, and the six it misses are
|
||||
structural rather than incidental. The reason to care is direct: **an opcode your fixture
|
||||
never emits leaves no known plaintext, so its substitution is unreadable by construction.**
|
||||
|
||||
| Missed opcode | Why a javac + d8 fixture cannot reach it |
|
||||
|---|---|
|
||||
| `const-string/jumbo` (0x1b) | needs a `string_ids` index > 65535, i.e. a fixture shipping 65,536+ string constants |
|
||||
| `goto/32` (0x2a) | needs a >32767-code-unit backward jump; javac refuses the method first with `error: code too large` — its own 64 KB per-method bytecode cap. **Measured** on a generated 33,000-statement loop |
|
||||
| `const-method-handle` (0xfe), `const-method-type` (0xff) | no Java-language literal exists for these constants; reachable only via hand-written smali or direct dex construction |
|
||||
| `move-object/16` (0x09) | needs **both** registers ≥ 256; the object frame pushes the source past 256 but d8 encodes that as `move-object/from16` |
|
||||
| `invoke-custom/range` (0xfd) | d8 emitted the 35c form for every lambda shape tried, including a six-parameter one |
|
||||
|
||||
What the fixture **does** cover, by construction, and the design decisions that get it
|
||||
there (each of these was a measured gap before it was closed):
|
||||
|
||||
- **Three-register forms.** javac emits the `/2addr` form whenever the destination is one
|
||||
of the operands, so `sub-int`, `div-int`, `rem-int`, `and-int`, `or-int`, `xor-int`,
|
||||
`shl-int`, `shr-int`, `ushr-int` and their long/float/double counterparts are **absent**
|
||||
from ordinary code. Three distinct locals per operation is what forces them into the
|
||||
stream; the `/2addr` forms then need the accumulator spelling. Both are wanted.
|
||||
- **Literal widths.** `div-int/lit16` needs a divisor in 128..32767; `and-int/lit8` needs a
|
||||
mask inside −128..127. Writing `& 255` produces `and-int/lit16` and silently skips the
|
||||
lit8 form.
|
||||
- **Per-type field access.** `iget-wide`, `iget-object`, `iget-boolean`, `iget-byte`,
|
||||
`iget-char`, `iget-short` and the `sget` set all appear only when the load targets a
|
||||
**fresh local**. Accumulating into an existing register is where d8 narrows the access.
|
||||
- **`/range` invokes.** The 35c invoke forms carry at most five argument registers, so a
|
||||
seven-register call (`this` plus six ints) is what makes the `/range` encoding the only
|
||||
legal one.
|
||||
- **Wide registers and long jumps** — `move/16`, `move-wide/16`, `move-object/from16`,
|
||||
`goto/16` — have **no hand-written form at all**. They exist only past a register-number
|
||||
(≥256) or branch-distance (>127 code units) threshold, so the generator emits bulk
|
||||
source: 300 int locals, 140 long locals, 160 object locals, a 200-statement loop body.
|
||||
Measured yield: `move/16` ×46, `move-wide/16` ×20, `move-object/from16` ×161, `goto/16` ×1.
|
||||
- **Payloads and structure**: `packed-switch`/`sparse-switch` with their payload blocks,
|
||||
`fill-array-data`, `filled-new-array/range`, try/catch ranges with `move-exception`,
|
||||
`monitor-enter`/`monitor-exit`, `instance-of`/`check-cast`, and `invoke-custom` /
|
||||
`invoke-polymorphic` (which is why `d8 --min-api 26 --no-desugaring` is the default —
|
||||
desugaring replaces lambdas with synthetic classes and the two opcodes disappear).
|
||||
|
||||
**Report the coverage every time.** `build` prints it, `audit` recomputes it for any dex.
|
||||
A differential run whose coverage is 60 % produces a table that is 40 % missing, and
|
||||
nothing in the output will say so unless you look at this number.
|
||||
|
||||
## 4. Extracting the correspondence
|
||||
|
||||
`compare ORIGINAL HARDENED` does four things, and the first three are diagnostics that
|
||||
decide whether the fourth is meaningful:
|
||||
|
||||
1. **Pair methods** by `(class, name, descriptor)` and classify each pair. `aligned` means
|
||||
both sides have a `code_item` of **identical `insns_size`** — the only state in which
|
||||
projection is legal. `resized` means the length moved. `stripped` means the hardened
|
||||
method has `code_off == 0`. `missing`/`added` mean the method set itself moved.
|
||||
2. **Project and sample.** For each aligned pair, walk the original's decoded instruction
|
||||
list; for instruction at original offset *o*, read the hardened byte at
|
||||
`hardened.insns_off + (o − original.insns_off)`. Record `(original opcode → hardened
|
||||
byte)` with a count.
|
||||
3. **Aggregate and audit the aggregate.** Per original opcode: one candidate byte and the
|
||||
row is `high`; more than one and the row is a `conflict`. Then the **reverse
|
||||
direction** — build `private byte → set of original opcodes` and flag every private byte
|
||||
claimed by more than one original. This reverse pass is not a nicety; it is the only
|
||||
thing that catches the stub shape (§5).
|
||||
4. **Emit a run-level verdict**, because a table is dangerous without one: `usable`,
|
||||
`partially-usable`, `not-usable`, or `not-applicable` with the reason. A `not-applicable`
|
||||
run exits non-zero.
|
||||
|
||||
Unreadable opcodes are reported as `undetermined` with the reason — either the fixture
|
||||
never emitted them (§3) or the dex slot is unallocated. They are **not** guessed at.
|
||||
|
||||
## 5. Proving the table — the part that decides whether any of this is real
|
||||
|
||||
A candidate table is a hypothesis. Four checks, in increasing order of what they can
|
||||
falsify:
|
||||
|
||||
**a. Closed-loop regression — measured, and the strongest available without a platform.**
|
||||
`simulate` relabels a fixture's opcodes through a bijection whose ground truth it writes
|
||||
out; `compare` must re-derive that table from the two dexes alone. Measured on this
|
||||
repository's fixture: **218 rows derived, 218 of 218 emitted opcodes recovered, zero
|
||||
entries wrong, zero entries fabricated, zero non-injective private bytes, verdict
|
||||
`usable`.** Any change to the comparison logic that breaks this check is a regression, and
|
||||
the check needs no platform, no device and no network.
|
||||
|
||||
**b. Injectivity — the check that catches a confident wrong answer.** Every private byte
|
||||
must be claimed by exactly one original opcode. Measured against the stub shape (bodies
|
||||
replaced by an equal-length `return-void` fill): per-opcode reading looks *perfect* — 218
|
||||
rows, all `high`, zero conflicts — because every original opcode maps to the same byte.
|
||||
Only the reverse direction exposes it: one private byte claimed by **218** originals →
|
||||
`NOT-USABLE`. A table produced without this check would have been silently worthless.
|
||||
|
||||
**c. Held-out consistency.** Derive the table from one subset of methods, then use it to
|
||||
disassemble a **different** subset that contributed nothing to the derivation. A correct
|
||||
table restores the instructions such that the walk lands exactly on
|
||||
`insns_off + insns_size × 2` and every branch target lands on an instruction boundary. A
|
||||
wrong or incomplete table desynchronises and says so. `emit-smali`'s
|
||||
`instructions restored` / `unmapped-opcode stops` counters are the readout: on the measured
|
||||
fixture, 3,065 restored and 0 stops.
|
||||
|
||||
**d. Cross-check against a second, independent recovery.** The same private opcode space
|
||||
observed through a *different* route — an in-memory dump of the original dex alongside the
|
||||
hardened one, or the `/proc/<pid>/mem` route in
|
||||
`advanced-unpacking.md` §Dumping when frida is refused — is the only evidence that the
|
||||
platform's transformation is the one you assumed. **Not done here**; it requires a real
|
||||
VMP sample and a real platform, and is the honest gap in this file.
|
||||
|
||||
Note what none of these checks establish: that the engine's substitution is *stable across
|
||||
inputs*. Fixture-derived tables have been reported in public work to drift per
|
||||
vendor-version and per hardening pass. Re-derive per target; never cache a table.
|
||||
|
||||
## 6. Generating Smali from a restored stream
|
||||
|
||||
`emit-smali HARDENED_DEX --table TABLE.json` restores opcode bytes through the table and
|
||||
renders method bodies as an annotated smali **reading skeleton**:
|
||||
|
||||
- Boundaries come from the table itself — once a byte maps back to a standard opcode the
|
||||
standard length table applies to that instruction, so the walk is self-bootstrapping.
|
||||
A byte with no table entry stops that method's walk, and the count of such events is
|
||||
printed as the honest coverage measure.
|
||||
- `.class` / `.super` / `.source` / `.method` headers are real, with access flags decoded
|
||||
from `access_flags`, so the skeleton is readable as smali rather than as a hex dump.
|
||||
- Payload blocks (`packed-switch-payload` etc.) are stepped over by their own layout, not
|
||||
treated as opcodes.
|
||||
|
||||
**It is explicitly not assembliable, and the output says so in its first ten lines.**
|
||||
Recovered: instruction boundaries and opcode names. Not recovered: register numbers,
|
||||
field/method/string indices as the engine rewrote them, and any register re-allocation —
|
||||
**no map for those exists in this method at all.** Feeding the skeleton to a smali
|
||||
assembler produces an empty method, which looks like success and is not.
|
||||
|
||||
## 7. When this route does not work — the honest retreat
|
||||
|
||||
| What `compare` reports | What it means | Do this |
|
||||
|---|---|---|
|
||||
| `verdict: not-applicable`, `stripped` > 0 | bodies left the dex for a native interpreter | the differential has no input. Stop. Return to `advanced-unpacking.md` §The honest boundary: real Dex VMP and price the island honestly |
|
||||
| `verdict: not-applicable`, `resized` > 0 | the engine's stream has its own length table | the projection premise is false. Stop rather than guessing boundaries |
|
||||
| `verdict: not-usable`, one private byte shared by many originals | bodies replaced by a common stub | the engine did not relabel per-opcode here. Stop |
|
||||
| `verdict: partially-usable`, conflicts ≤ 30 % | partial relabelling, or alignment slipping on some methods | usable only for the `high` rows; say so and stop at the unreadable ones |
|
||||
| `usable`, but coverage was low | a complete table over an incomplete opcode set | usable, with the uncovered opcodes named as unreadable |
|
||||
|
||||
And the retreat that outranks all of them: **the cheaper question is whether the behaviour
|
||||
you need exists outside the virtualized island.** A hook at the method's Java boundary, an
|
||||
emulated call to the routine rather than a reading of it
|
||||
(`emulation-and-rpc.md`), or a server-side answer frequently reaches the goal without ever
|
||||
paying for the island. Weeks of table recovery is the expensive way to ask a question a
|
||||
boundary hook answers in an hour.
|
||||
|
||||
## 8. Decision summary
|
||||
|
||||
| Observation | Action | Where |
|
||||
|---|---|---|
|
||||
| Bodies present, decode as nonsense | Diagnose real VMP before anything else | `advanced-unpacking.md` §The honest boundary: real Dex VMP |
|
||||
| Need the private opcode mapping | Build the coverage fixture, then submit it by hand | `scripts/vmp_diff_harness.py build`; §2 of this file |
|
||||
| Asked to "automate the whole chain" | Say which link cannot be automated and what it costs | §2 — the platform step is manual, by construction |
|
||||
| Fixture coverage below ~90 % | Add the missing opcode classes before submitting | §3, and the `audit` report |
|
||||
| Two dexes in hand | Derive the candidate table, read the verdict first | `scripts/vmp_diff_harness.py compare` |
|
||||
| About to trust a derived table | Run the closed loop, the injectivity check and a held-out subset | §5 — a/b/c are scripted |
|
||||
| Table complete | Render the skeleton; expect operands, not registers | `scripts/vmp_diff_harness.py emit-smali` |
|
||||
| `resized` / `stripped` / stub verdict | Stop and say so | §7 |
|
||||
Reference in new issue
Block a user