Files
apk-reverse/skills/apk-reverse/references/third-party-builds.md
T
inliver233 2beade67f2 Reconstruction pass: make the gates tell the truth, make the package self-contained, keep the one-hop symptom index
An external audit of this repository landed on four structural findings, and this pass is the
response to them. Everything below was re-measured on this tree before being acted on; two of the
audit's claims needed a correction of my own, and both corrections are noted in place.

**The gates were optimistic, and one of them did not read content at all.**

  doctor.py    the capability table was hard-coded (`repack + sign = bool(java) and python`), so a
               machine with a JDK and no zipalign/apksigner was told it could re-sign; the script
               inventory was a hand-written list of 28 against 51 files on disk, omitting the nine
               most important scripts. It now scans the directory (`registered/checked = 52 / 52`,
               unjudgeable entries counted as `unknown`, never skipped) and resolves capability as a
               real requires-closure, reporting BLOCKED with the missing piece and an installable
               next step. Measured: the old doctor reports `[OK] repack + sign` on a JDK-only PATH
               where keytool, jarsigner, zipalign, apksigner and all eight smali jars are absent.
               The report is allowed to look bad; that is the point.
  check_commands.py (new)
               anchor checks prove a section exists, never that a command runs. This parses each
               script's argparse table with `ast` and checks every documented invocation against it.
               146 commands / 41 interfaces, 0 drift. It caught `sig_probe.py --live --pkg`, which
               does not exist -- the reference had been wrong since it was written.
  check_routing.py (new)
               the symptom index now has one home (`SKILL.md`, because symptom -> file must stay one
               hop) and the inventory has another (`references/routing.md`). This gate proves the
               mirror agrees, that every reference file is named, and that every script is named.

**so_constpatch.py was corrupting APKs it rebuilt.** The writer copied filename and timestamp onto a
fresh ZipInfo and recompressed the whole archive: 435-entry real package, `extra` lost on 205 entries,
`external_attr` rewritten on all 435, 132 untouched entries recompressed, and `resources.arsc` pushed
to an unaligned offset. Android's own `zipalign -c -v 4` fails the old output and passes the new one;
a 26-case fixture suite pins it, and `extractNativeLibs="false"` is now refused by default with a
pointer at `repack.py`. Fixing it exposed the same defect in `repack.py`, where `^lib/[^/]+\.so$`
cannot match `lib/arm64-v8a/*.so` -- so its alignment handling had never once fired on a real APK.

**The package was not self-contained.** 59 references pointed at the repository root, which `npx
skills add` does not install. They now converge on `references/evidence-summary.md` (capability,
conclusion, strength, evidence that ships) plus `evidence/` with the machine-readable companions: 8
references remain and each is explicitly labelled "repository root, not shipped". A drill in which
the new files were copied to an isolated directory and asked three questions answered all three.

**SKILL.md: 572 lines / 15,733 tokens -> 398 lines / ~10,900 tokens**, without losing the two things
that had to stay. The symptom index remains inline; the reference and script indexes moved to the
on-demand routing file. The freed budget went into making the rules *stronger*, not shorter: the
constraints section is now a table of thirteen non-negotiable constraints each paired with the check
that catches a violation, and the tooling obligations are instructions whose violation is a defect
(hedging language in SKILL.md: 1 line, down from a paragraph of hedged advice). Long references gained
a navigation head so a reader can decide from the top whether to load one.

**New: an executable test layer.** `tests/` (unit, CLI contract, no-device integration) plus
`pytest.ini`, `tests/run_tests.py`, a minimal CI job, and `evals/evals.json` written but never run --
stated as such in the file. 608 passed / 158 skipped / 25 xfailed. The 25 xfails are a work order, not
a pass: thirteen scripts report a missing input by exiting 1 instead of 2, seven let a traceback
escape, four treat `--help` as an error, and `preflight --json` lacks a `status` field. A regression
row for `dex_patch_bytes.py` reproduces a previous artifact byte-for-byte
(`67ae1e58e7a44777e5ac8f9f823ab21e…`) and additionally pins the four bytes that may move.

**Two real defects the new tests found in the tooling itself.** `check_repo.py` decoded subprocess
output with the locale encoding, so on a GBK console a script printing an em dash in its usage line
was reported as crashed; it now decodes UTF-8 explicitly. And a CLI contract test drove a *real
attached device* through `coldstart.py` -- logcat, screenshots, five orphan `adb logcat` processes --
which is fixed twice over: child processes run in a private temporary cwd, and the fifteen
device-bound scripts are never executed beyond `--help`/argument parsing.

**Quoting on the device side is now one implementation.** `devsh.su` escaped only double quotes, so
`;`, `$( )` and backticks in a caller-supplied value still reached the device shell while
`coldstart.Device.shell` quoted correctly. Both use `scripts/device_shell.py` now: POSIX single-quote
escaping, argv arrays by default, and identifier validation that refuses a malformed package, path or
component with exit 2 instead of a traceback. The integration test that used to pin the *defect* (it
asserted `su -c "…"` with `\"` escapes) now asserts the property, across five metacharacter payloads.

Gates: check_repo 0 problems (including the content-reading identity scan over git ls-files),
check_refs 0 dangling / 0 warning, check_routing coherent (53 symptom / 45 reference / 54 script rows),
check_budget 0 failure / 0 warning with the always-loaded body now measured in tokens rather than in
"narrative lines with the index excluded", check_commands 146 checked / 0 drift, pytest 608 passed.

Not done, and stated rather than implied: CI has never run on a runner; the evals have never been
executed; the 25 xfails are open; no device-side install/launch was performed in this pass.
2026-09-22 01:37:51 +08:00

6.8 KiB

Third-party builds — auditing a "cracked" or "modded" APK before trusting it

Load this when: the input is a "cracked" or "modded" APK you did not produce. It gives the audit that tells you what was injected, and why such a build is never a patching workbench.

Why this exists

A modded build of the exact app you are targeting is the most tempting shortcut available: it appears to prove the goal is achievable, and it may already contain the patch you were about to write. It is also the single most common source of wasted hours and of real risk, for two reasons.

  1. It is usually not editable. Authors who redistribute mods protect them, often with more layers than the original app ever had. You cannot treat someone else's build as a patching workbench.
  2. Its target-audience behaviour is unverified. The binary may carry injected components, extra endpoints, or embedded credentials. "It runs and the ads are gone" tells you nothing about what else it does.

Treat a third-party build as an untrusted sample to be audited, never as a baseline. The useful output of an audit is a decision plus evidence — not a binary you start from.

Step 1: Can you even edit it?

Find the app's own package prefix (the one that appears in its own class definitions, e.g. com/<vendor>/<app>/) and count how many times it appears as a defined class in each plaintext dex.

business-prefix hits per dex:
  classes.dex    0        <- shell
  classes2.dex   0
  classes3.dex   0
  classes4.dex   0

Zero everywhere means the business code has been moved out of the plaintext dexes — the build is protected at a level you cannot patch directly, even though it launches and works. Stop here and treat it as a black box.

Also check the reported dex count against the file count: a manifest-declared app with only library classes present is the same signal.

Step 2: How many protection layers does it carry?

Mods frequently stack protection from multiple vendors, sometimes because the author re-protected an already-protected app. Look for independent, coexisting families:

Layer kind Typical static evidence
Commercial packer shell Application/appComponentFactory in the manifest, a lib*protect*.so, encrypted assets, assets/*.jar with near-maximal entropy
DEX-to-native (dex2c) a "stub" lib*.so containing the tool's name, EntryPoint/protect-style symbols, and business class names as strings alongside a near-empty dex layer
Anti-debugging / RASP strings such as TracerPid, ptrace, NoNewPrivs, CheckPtraceSelf, AntiFrida, plus a self-protection log path
Generic hardening marker files small text files under assets/ naming a protection vendor and a protection timestamp

The practical consequence of an anti-debugging layer is that Frida-based dynamic work will hit a self-check before it hits your hook. Note it, and prefer static conclusions on such a sample.

Step 3: What did the author ADD?

This is where the audit earns its keep. Diff against the original build of the same version (referenced as <original> below).

New components

Build the set difference of activity / service / receiver / provider declarations, then check whether each new class name actually exists in the plaintext dexes.

  • Class exists and is readable → you can judge its purpose.
  • Class name appears nowhere in plaintext but shows up inside a native library's strings → the logic is in the native/dex2c layer, purpose unknown. Say so.
  • Nothing registered with an implicit-launch intent-filter (BOOT_COMPLETED, MAIN) → it cannot be started implicitly, which limits (but does not eliminate) the risk.
  • A provider with an authorities value containing a package-name rewrite (a suffix/prefix that is not the current package) is a strong hint the build was produced by repackaging or app cloning, not by editing the original.

New outbound endpoints

Extract every URL/domain/IP from the modded build's lib/*.so, assets/*, and dex strings, and subtract the original's set. Any domain that exists only in the modded build is the most important finding in the audit.

Rank what you find:

  • A domain that also serves install attribution or update checks is explainable.
  • A domain paired with an authorization-looking path (e.g. a GET...-style endpoint name nearby in the same string neighbourhood) is not explainable by de-ad work.

Embedded secrets

Search native libraries and assets for private-key markers:

-----BEGIN ... PRIVATE KEY----- , PRIVATE KEY , PKCS#8 , RSA PRIVATE

A private key shipped inside a client artifact means its "authorization" or "integrity" path is not a security boundary — anyone can extract the key. Report it as a red flag on the build's trust claims, regardless of intent.

Step 4: Capability picture — read both sides

A native library's import table is only half the story.

  • What it does not have is meaningful: no socket/connect, no execve/fork/system, no ptrace, no installer-session strings → no direct evidence of command execution or silent install.
  • What it references can override that impression: string references to Java-layer java/net/Socket, InetSocketAddress, reflection entry points, or executor services mean the capability exists through the Java layer, off the native import table.

State findings as "capability present / no evidence of use" rather than "safe" — an import table is evidence of shape, not of intent.

Step 5: The verdict

Do not hand back a binary. Hand back a decision with evidence and explicit unknowns.

VERDICT: use / use with caution / do not use
EVIDENCE:
  - business code plaintext?           yes/no  (+ counts)
  - protection layers                  list
  - injected components                list, each with purpose known/unknown
  - endpoints present only in this build   list
  - embedded credentials               yes/no
UNCONFIRMED:
  - <each item you could not establish, stated plainly>

"Use with caution" is the honest answer whenever a build is un-analysable and carries new endpoints or unknown injected components. Do not upgrade it to "safe" because it launches cleanly, and do not call it malicious without evidence — both are guesses.

Using the audit result

Two legitimate outcomes:

  1. The audit shows the mod is an honest de-ad of the same version → you may use it to learn the approach (diff its patch points against the original), but still rebuild from the original yourself so the artifact you ship has a known provenance.
  2. The audit shows it is re-protected, injected, or un-analysable → discard it and do the work on the original. That is usually faster than reverse-engineering someone else's protection and your target's at the same time.