mirror of
https://codeberg.org/dabao1955/apk-reverse.git
synced 2026-11-30 11:50:23 +08:00
Restructure to the skills/<name>/ layout the skills CLI resolves
The skill lived at the repository root, which the CLI reads as a single-skill repository and which makes a second skill impossible to add. SKILL.md, references/ and scripts/ move under skills/apk-reverse/ with git mv, so history follows and no in-skill reference needs changing (they are relative to SKILL.md). check_repo.py now discovers every skills/*/SKILL.md, validates frontmatter by parsing it instead of pattern-matching it, and requires the README to name skills through explicit skills/<name>/... paths. check_refs.py is new: it audits file.md section cross-references against the real headings in the target file. It found six dangling ones, all fixed here. SKILL.md: the description is now quoted. Unquoted, it contained a colon-space, which is invalid YAML, so the CLI skipped the skill and reported No skills found. Adds a Coverage section stating what is out of scope and what to do when nothing matches. toolchain.md: IDA is not GUI-only (idalib-mcp is a headless MCP server), plus a section on MCP servers as external dependencies and the deobfuscate-before-LLM boundary. README.md: install via npx skills add, the new layout, coverage and maintenance tools. Verified: check_repo.py and check_refs.py both clean, build_scripts.py audit 0 findings, npx skills add . --list reports apk-reverse, and an install into a scratch directory lands SKILL.md plus 28 references and 38 scripts.
This commit is contained in:
1 parent
a552157f1b
commit
7176b5e1c9
70 files changed
+676
-91
No files matched your search
@@ -0,0 +1,396 @@
|
||||
---
|
||||
name: apk-reverse
|
||||
description: "Reverse engineer, debloat, de-ad, patch, or re-sign Android APKs, and analyze their runtime and server-side behavior. Use when a task involves an .apk/.aab/.dex/.so sample, smali or dex patching, Frida/objection runtime hooking, repacking and re-signing, removing ads or SDK trackers, probing a mobile app's HTTP API, or deciding whether a client-side patch is even capable of achieving the goal. Covers recon, anti-tamper, ad removal, membership/paywall limits, dex-level surgical patching, repack pitfalls, device and emulator setup, and a hard-won failure catalogue. Load the body before planning any patch work: it opens with a symptom index and four gates that must be cleared first."
|
||||
---
|
||||
|
||||
# APK Reverse Engineering & Patching
|
||||
|
||||
Goal: reach a **verified, installable, still-working artifact** fast — and avoid the whole class of
|
||||
mistakes that destroy an APK while looking completely healthy.
|
||||
|
||||
## How to use this file
|
||||
|
||||
This file is a **procedure with gates**, not background reading. Three things are mandatory:
|
||||
|
||||
- Before you patch anything, clear the **four gates** in §Gates. They are actions with pass criteria,
|
||||
not attitudes.
|
||||
- When anything fails in a way your current plan does not explain, **stop and check the symptom
|
||||
index**. If a row matches, load that file before running another command.
|
||||
- When this file and your own reasoning disagree, **this file wins** until you have evidence that
|
||||
overrides it. Every rule here is the residue of a failure that cost hours; your current intuition is
|
||||
the intuition of someone who has not hit it yet.
|
||||
|
||||
## Four rules that override everything else
|
||||
|
||||
**R1 — Write the deliverable as a testable sentence before you touch the target.**
|
||||
"It works" is not the goal; "it works under the stated constraint" is. Root-assisted, live-
|
||||
instrumentation, host-proxy and patched-device results frequently do **not** satisfy a request for an
|
||||
installable artifact that works on a normal phone — and it is easy to present such a result as
|
||||
finished. Write the sentence, re-read it at every checkpoint, and if you cannot meet it, say so
|
||||
plainly and label the privileged workaround a **fallback**, never the deliverable.
|
||||
→ `references/long-task-discipline.md` §the most expensive drift
|
||||
|
||||
**R2 — Change one variable at a time, and keep a control build.**
|
||||
An experiment that flips two things teaches nothing when it fails, and a failure you cannot attribute
|
||||
will be attributed to the wrong cause. Every "the app rejects X" claim needs its own run, and every
|
||||
patch needs a same-pipeline control that still fails the old way.
|
||||
→ `references/long-task-discipline.md` §single-variable discipline
|
||||
|
||||
**R3 — Never ship or claim an unverified artifact.**
|
||||
"It assembles" is not "it works"; "the process started" is not "the feature works"; "no error in the
|
||||
log" is not "the check is gone". Install it, launch it, exercise the exact feature you changed, and
|
||||
look at the screen. Prove the device is running the build you made — hash it, do not trust the
|
||||
filename.
|
||||
→ `references/verification.md`
|
||||
|
||||
**R4 — Identify the owning layer before patching, and re-classify when reality disagrees.**
|
||||
Ads, paywalls, feature gates, integrity checks and update gates live in different layers (Java, dex,
|
||||
native, Dart/Unity, server). Patching the wrong layer either does nothing or breaks the app. If a
|
||||
patch "had no effect", the diagnosis was wrong — go back to classification instead of patching harder.
|
||||
→ `references/recon.md`, then the layer-specific file the symptom index points at
|
||||
|
||||
## Coverage — what this skill claims, and what it does not
|
||||
|
||||
The failure this section prevents is not ignorance. It is **a confident wrong answer produced by
|
||||
applying the nearest available procedure to a target it was never written for.** A documented method
|
||||
that almost fits is more dangerous than no method at all, because it arrives with a plan, a
|
||||
vocabulary and a set of reassuring numbers.
|
||||
|
||||
**Covered, by verified mechanisms:**
|
||||
|
||||
- Client-side ads, promos and splash/popup/tab configuration — including the server-issued UI config
|
||||
that has no SDK to find (`ad-removal.md`, `server-config-and-updates.md`).
|
||||
- Deciding whether a membership, paywall or feature gate is *client-enforceable* at all, and saying
|
||||
so plainly when it is not (`membership-and-limits.md`, `account-gates.md`).
|
||||
- dex-level surgical patching: equal-length byte edits and dexlib2 method rewrites, plus the header,
|
||||
verifier and alignment rules that decide whether the build loads at all (`dex-patching.md`,
|
||||
`byte-level-patching.md`, `patch-audit.md`).
|
||||
- Repacking, signing, installing, and the install refusals that look like a broken build
|
||||
(`repack-and-sign.md`).
|
||||
- Packers, custom loaders and code virtualization: identifying them, measuring the validation
|
||||
boundary, and the routes that survive it (`packers.md`,
|
||||
`code-virtualization-and-custom-linkers.md`).
|
||||
- The native layer: `.so` hosts, tamper-triggered self-termination, forged ELF structure, and
|
||||
neutralising a terminate path without freezing the process (`native-and-so.md`,
|
||||
`native-tamper-and-suicide.md`).
|
||||
- Flutter / Dart AOT: pinning the engine version, decoding the object pool, locating and patching
|
||||
business logic inside `libapp.so` (`dart-aot.md`).
|
||||
- Runtime analysis with Frida, server-side API probing, feature-scoped TLS failures, update and
|
||||
forced-upgrade neutralisation, and the verification discipline everything above rests on.
|
||||
|
||||
**Not covered — say so rather than improvise:**
|
||||
|
||||
- **Unity / IL2CPP logic recovery.** `framework-runtimes.md` identifies the runtime and establishes
|
||||
that the dex is not the battlefield; it does not carry the IL2CPP equivalent of `dart-aot.md`.
|
||||
There is no verified recipe here for locating a method inside `libil2cpp.so` plus
|
||||
`global-metadata.dat`.
|
||||
- **React Native / Hermes bytecode** and Cordova/hybrid internals, beyond runtime identification and
|
||||
the generic "find the string, then find what references it" approach.
|
||||
- **iOS / `.ipa` of any kind.** Every device, signing and packaging instruction here is Android.
|
||||
- **Defeating a server-side authority.** `server-api.md` exists to determine *who owns a gate*, not
|
||||
to break an authorization the server performs.
|
||||
- **A general unpacker, or an anti-detection arms race.** `detection-and-anti-analysis.md` decides by
|
||||
cost and often concludes "switch to static"; it is not a catalogue of evasion for every detector
|
||||
you might meet.
|
||||
|
||||
**The fallback, as an instruction:** if the target does not match that list, or no symptom-index row
|
||||
matches, **stop and classify before choosing a branch.** Answer the thirteen questions first. If the
|
||||
shape still does not fit — an unknown runtime, a mechanism you cannot name — say exactly that, and
|
||||
propose the cheapest experiment that would identify it, rather than taking the closest documented
|
||||
route and applying it anyway. A wrong branch here does not fail loudly: it produces an artifact that
|
||||
builds, runs, and does the wrong thing.
|
||||
|
||||
## Symptom index — a matching row is a stop signal
|
||||
|
||||
You arrive at a symptom, not at a file name. Each row below is a failure that has already been paid
|
||||
for. **If any row matches what you are observing, load the file before your next command** — not after
|
||||
your next three attempts. Reasoning from first principles at this point is how the same hours get
|
||||
spent twice; more than one entry here is a lesson that was re-derived by hand while the answer sat
|
||||
unread in this repository.
|
||||
|
||||
| What you observe | Load first |
|
||||
|---|---|
|
||||
| A repackaged/re-signed build **dies before your code runs**; `SIGSEGV`, all registers zero, `pc=0`, `fault addr` near `0x0` | `native-tamper-and-suicide.md` (deliberate crash), then `code-virtualization-and-custom-linkers.md` |
|
||||
| **No packer** (Application is the app's own, dex readable) **and it still dies** | `code-virtualization-and-custom-linkers.md` |
|
||||
| Log says a **Java-layer** signature/integrity check **passed**, yet the process dies | `code-virtualization-and-custom-linkers.md` §a Java-layer "signature killer" is a decoy |
|
||||
| Deleting a library fixes validation but yields `UnsatisfiedLinkError: dlopen failed: library "X" not found` | `code-virtualization-and-custom-linkers.md` §the deadlock that eats hours |
|
||||
| Whole classes appear as bare `native` declarations with no body | `code-virtualization-and-custom-linkers.md` |
|
||||
| A library's **SONAME does not match its filename** | `code-virtualization-and-custom-linkers.md`, `native-and-so.md` |
|
||||
| Your edit had **no effect at all**, with no error | `server-config-and-updates.md` §3 (the value may be server-sent), then `packers.md` §map the validation boundary |
|
||||
| Process **hangs** with no crash record, or dies to a `uid 0` killer | `native-tamper-and-suicide.md` §the rule (you probably made a terminate path *not return*) |
|
||||
| Death looks like an ordinary null dereference in a hardened library | `native-tamper-and-suicide.md` §deliberate-crash stubs |
|
||||
| The app dies **only while you are attached/rooted** | `detection-and-anti-analysis.md`; run the unmodified original under identical conditions first |
|
||||
| **Install fails with `[-124]` and mentions `resources.arsc` / alignment** | `repack-and-sign.md` §2a — STORED **and** 4-byte aligned, both required |
|
||||
| **Install fails with a bare numeric code (e.g. `[-99]`) and no `INSTALL_FAILED_*`** | `repack-and-sign.md` §vendor install interception — a device-side interceptor, not your build. Use the root `pm install` path |
|
||||
| **After an install, `am start` does nothing / screenshots show another app / `am start -W` hangs** | `repack-and-sign.md` §the installer may still own the screen |
|
||||
| Log shows `Failure to verify dex file ...: Bad checksum` and a startup `ClassNotFoundException` for an ordinary class | `byte-level-patching.md` §the dex header has two integrity fields — order matters |
|
||||
| An install "succeeded" but nothing changed, or the version did not move | `long-task-discipline.md` §keep the observation window clean |
|
||||
| Evidence contradicts itself, or a capture looks like two states mixed | `long-task-discipline.md` §keep the observation window clean |
|
||||
| You took screenshots but drew the conclusion from logs or from the patch itself | `long-task-discipline.md` §captures you never looked at are not evidence |
|
||||
| You are about to re-run an experiment whose result you already recorded | `long-task-discipline.md` §long-context decay |
|
||||
| A script will not start, or a tool "is missing" | `scripts/doctor.py`, then `toolchain.md` §"not on PATH" is not "not installed" |
|
||||
| Feature-scoped network failure (login/register/pay) while the rest works | `tls-and-cert.md` — do not assume your patch caused it |
|
||||
| Everything works but **every signed request fails** after repack | `signature-derived-keys.md` |
|
||||
| Ads still appear after a patch that should have killed them | `server-config-and-updates.md` §6 (cached config / remote re-enable), then `ad-removal.md` §step 4 (count the SDK's own log lines; n -> 0, not "I did not see it") |
|
||||
| A forced-update or "must update" gate blocks the build | `updates-and-forced-upgrade.md` §step 6 |
|
||||
| The dialog is gone but the feature is still locked | `membership-and-limits.md` / `account-gates.md` — decide server vs client authority before patching again |
|
||||
| You are about to discard a route as "blocked" | `packers.md` — re-read it before writing any route off; mis-attributed failures have removed viable routes for hours |
|
||||
| The task has run long and you are unsure what is already proven | `long-task-discipline.md` §keep a live record |
|
||||
|
||||
## Gates — clear these before you patch, in order
|
||||
|
||||
Each gate is an **action with a pass criterion**. Do not proceed past a gate you have not cleared, and
|
||||
do not treat "I understand the idea" as clearing it. Skipping a gate is not a shortcut; it is how the
|
||||
work gets redone.
|
||||
|
||||
**G1 · Deliverable form.** State, in one sentence you could hand to someone else, what artifact must
|
||||
exist at the end and under what constraints (rooted or not, installable on a stock device or not, must
|
||||
survive updates or not, online or offline). *Pass:* the sentence names a testable constraint, not an
|
||||
activity. *Fail:* you are solving a problem in an environment the deliverable will never see.
|
||||
|
||||
**G2 · Environment truth.** Run `scripts/doctor.py` (and `scripts/preflight.py` if a device is in
|
||||
play). *Pass:* you know which toolchains and scripts can actually run here, and you have seen the
|
||||
environment warnings — clock skew, leftover `adb forward`/proxy, a device-side frida process already
|
||||
running, a tool installed off-PATH. *Fail:* you are about to attribute to the target a failure caused
|
||||
by your own setup.
|
||||
|
||||
**G3 · Code location.** From the manifest and dex, answer: is there a packer, where does the app's own
|
||||
code live (dex / native / Dart / Unity / server), and is any of it virtualized to native. *Pass:* you
|
||||
can name the class that owns the behaviour you intend to change, or you have an explicit plan to find
|
||||
it. *Fail:* you are about to patch a layer you have not located. If recon says "no packer", still
|
||||
check the virtualization shape — see the index rows above.
|
||||
|
||||
**G4 · Baseline and control.** *Pass:* you have a control run — the unmodified original, or a
|
||||
zero-change repack through the same pipeline — and you have recorded the observed failure (including
|
||||
**time-to-death**, if it dies). *Fail:* when the patched build misbehaves you will have nothing to
|
||||
compare against, and every later measurement is unfalsifiable.
|
||||
|
||||
|
||||
## Start here: classify the target in thirteen questions
|
||||
|
||||
Answer these before touching a tool. Every one of them changes the whole plan.
|
||||
|
||||
1. **Is the app packed/hardened?** → `references/recon.md`
|
||||
Read the manifest's `application android:name`. If it is a third-party shell class rather than the app's own Application, you have a packer and must handle it first.
|
||||
2. **Where does the behavior you want to change actually live?**
|
||||
- Ad SDK (Pangle/GDT/AnyThink/Kuaishou/Baidu/Sigmob…) → usually **client-side and removable** → `references/ad-removal.md`
|
||||
- **Server-issued config for UI the client renders** (launch screen, popup, announcement, tab set, sponsored card on a home feed) → **the client decides, the server supplies the data** → `references/server-config-and-updates.md` (this is the most common shape of "ad" in a modern app, and there is no SDK to find — decide this question early, because hunting an SDK that does not exist costs hours)
|
||||
- Membership / VIP / paid content → **usually server-authorized, client patch is cosmetic** → `references/membership-and-limits.md` (read this *before* spending hours)
|
||||
- Feature flag, UI gate, debug switch → usually client-side
|
||||
- Anything decided by an API response → server-side → `references/server-api.md`
|
||||
3. **Is the app's own code in plain dex, or moved to native/Flutter/Unity?**
|
||||
Plain dex → you can patch. Flutter (`libflutter.so` + `libapp.so`) / Unity (`libil2cpp.so`) / pure native → different toolchain entirely. See `references/recon.md` §Where does the app's own code live and `references/framework-runtimes.md`.
|
||||
**Runtime check (cheap -- do it before committing to a layer):** hook the obvious Java classes for the UI you care about, then reproduce that UI. If those hooks fire, the behavior is Java-owned. If they fire **zero times** while the UI is plainly on screen, the behavior is drawn by the runtime or by native code, and a dex-only plan will stall. Do not keep hunting in dex after a zero-hit probe -- that is the most expensive wrong turn in this skill's history.
|
||||
4. **What must the deliverable be able to do?** Write the answer as a testable sentence before
|
||||
planning anything, then re-read it at every checkpoint. This is the drift guard, and the drift it
|
||||
guards against is the most expensive one in this skill: a runtime-only result (a data edit, a live
|
||||
hook, a blocked hostname, a host proxy) can look like success while failing the actual requirement.
|
||||
The axes that decide it: **privilege** (unrooted?), **modification form** (a rebuilt, installable
|
||||
artifact, or is live instrumentation acceptable?), **ABI/device class**, **network** (must it work
|
||||
online?), **persistence** (survives restart / upgrade / fresh install?), **distribution** (must the
|
||||
shipped file be self-contained?). → `references/long-task-discipline.md` §the most expensive drift.
|
||||
5. **Does the app verify its own signature, or does the server?**
|
||||
App-side → you must bypass it. Server-side → re-signing silently breaks the app later. See `references/repack-and-sign.md` and `references/server-api.md`.
|
||||
6. **What is your device situation?** → `references/environment.md`
|
||||
Rooted real device (best), emulator with root, or no device (static only). Also: this determines whether Frida is usable. **Run `scripts/preflight.py` before your first experiment**, and again whenever a failure surprises you — device state, a dead device server, a leftover proxy, and clock drift all masquerade as a broken patch (`pitfalls.md` P9).
|
||||
7. **Which architecture is actually executing?** → `references/native-and-so.md` §Cross-architecture
|
||||
`getprop` reports what the device claims and `primaryCpuAbi` reports what the package manager chose — neither is what is running. Only the live mapping is ground truth (`scripts/lib_map.py`). If the library you meant to patch is not mapped, a translator is in play, or the ABI differs from your assumption, that changes the plan more than any patch will.
|
||||
8. **Is one *specific feature* failing at runtime — login, registration, payment, an API-backed screen — while the rest of the app works?**
|
||||
→ `references/tls-and-cert.md`. A feature-scoped network failure is very often a **TLS/certificate problem on one code path**, not a consequence of your patch. The app can even carry two independent trust chains, so "other requests work" proves nothing. Rule this out in minutes before hunting for a signature check.
|
||||
9. **Was the input a build you did not produce** (a "cracked"/"modded" APK circulating online)?
|
||||
→ `references/third-party-builds.md`. Audit it before adopting it: such builds are frequently re-protected (sometimes with *more* layers than the original) and may carry injected components or endpoints. Never use one as a patching workbench.
|
||||
|
||||
**Long-task rule:** if this is likely to run long, open `references/long-task-discipline.md` now
|
||||
and keep its record updated as you go. Re-read the refuted-conclusions and dead-routes sections
|
||||
before starting any new experiment. Losing earlier findings is the most expensive failure in this
|
||||
skill, and it is entirely preventable.
|
||||
10. **Does the client sign its requests with its own signing certificate?**
|
||||
→ `references/signature-derived-keys.md`. Grep for `toCharsString()` / `signatures[0]` /
|
||||
`getPackageInfo(..., 64)` **before the first repack**. If that value feeds a native HMAC/DES
|
||||
routine, the rebuilt APK must hardcode the *original* certificate value at every read site, or
|
||||
every signed request fails while the app still launches and looks healthy. This is the single
|
||||
most expensive silent failure in a repack, and 15 minutes of grep prevents it.
|
||||
11. **Does the app die on its own after a while — with no Java stack trace, or with a native
|
||||
crash that looks like a bug?**
|
||||
→ `references/native-tamper-and-suicide.md`. A hardened library that decides the build is
|
||||
tampered rarely calls `kill`. It more often **arranges a fault** (load a small constant, use it
|
||||
as a pointer) so the death looks like an ordinary defect, and the system then reports it as an
|
||||
app "crash" or "abnormal" dialog. Two rules before you touch anything: **enumerate which
|
||||
mechanism actually fires** (the signal and the tombstone split them apart), and **neutralise by
|
||||
returning, never by making it not return** — a spinning stub freezes the process and produces a
|
||||
symptom that looks nothing like the cause.
|
||||
12. **Will this build still be usable in a week?** → `references/updates-and-forced-upgrade.md`
|
||||
If the app has any version check, upgrade prompt, or self-update path, an unpatched build can be
|
||||
turned off remotely or replaced by the official package. This is one or two edits and it decides
|
||||
whether the work is durable — do it as part of the build, not as a follow-up. Also check for a
|
||||
**hot-update / remote-config** channel, which can restore behaviour you removed without any version
|
||||
change at all.
|
||||
13. **Does the request touch sign-in or phone binding — "no login required", "skip binding", "guest ok"?**
|
||||
→ `references/account-gates.md`. The whole difficulty here is separating a **client-side gate**
|
||||
(patchable) from an **account-scoped resource** (the screen is empty because the server has no
|
||||
account to answer for — not patchable). Classify first; and never fabricate a session to satisfy a
|
||||
gate, which produces a state worse than being signed out.
|
||||
|
||||
## The workflow, end to end
|
||||
|
||||
Steps are ordered. **Skip a step only when its stated skip condition is met** — "it seems
|
||||
unnecessary" is not a condition, and it is the reason most of the failures in `pitfalls.md` happened.
|
||||
|
||||
**Two-strike rule.** If the *same kind* of attempt fails twice, stop and go back to classification.
|
||||
Do not run a third variation of a hypothesis that has already failed twice. Two failures of one shape
|
||||
means the model is wrong, not that the parameters need tuning — and the third attempt is where an
|
||||
entire round gets spent confirming what the first two already said. Re-read the symptom index at that
|
||||
point; it exists for exactly this moment.
|
||||
|
||||
1. **Preflight, then Recon** — `scripts/doctor.py` is the cheapest possible first command: it reports which toolchains and scripts can actually run here, and surfaces the environment facts that poison experiments (clock skew, leftover `adb forward`/proxy, a device-side frida process already running, a tool installed off-PATH). Then `scripts/preflight.py` before anything else if a device is involved (it takes seconds and prevents a whole class of false conclusions), then `references/recon.md`. Manifest, package name, version, ABI, dex count, packer, embedded SDKs, where the app's own code lives. Ten minutes here saves hours. **If it is packed, unpack before anything else** (`references/recon.md` §unpacking): you cannot patch code you cannot read, the encrypted payload lengths tell you which dumped dex is the original, and a memory dump must be de-duplicated by hash and structurally validated before any of it is trusted.
|
||||
**If recon says there is no packer but a re-signed build still dies**, you are in the layer `references/code-virtualization-and-custom-linkers.md` covers — do not proceed on the assumption that "no packer" means "editable".
|
||||
**If the app already dies on its own** — especially at a roughly constant time after launch, or with a native crash — locate the mechanism *before* planning any patch (`references/native-tamper-and-suicide.md`, `scripts/native_crash.py`). Record the observed time-to-death: it is the baseline every later attempt is measured against, and without it a surviving run cannot be told from a changed schedule.
|
||||
*Skip condition:* never skipped. G2/G3 in §Gates are cleared here or not at all.
|
||||
2. **Extract strings and endpoints** — build a picture of the app's API surface and SDK inventory from the dex string tables. No decompiler needed for this, and it is fast. Scripts: `scripts/dex_strings.py`.
|
||||
3. **Trace to the owning class** — find the class that wraps the behavior (the app almost always wraps third-party SDKs in one helper). Reverse-lookup instructions: `references/dex-patching.md` §finding-the-call-site.
|
||||
4. **Decide the patch layer** — client SDK call / client rendering / client data consumption / server contract. See the table in `references/ad-removal.md`.
|
||||
5. **Patch surgically** — `references/dex-patching.md` and `references/byte-level-patching.md`.
|
||||
Two techniques, and picking the right one is a decision, not a preference:
|
||||
**equal-length byte edits** (`scripts/dex_patch_bytes.py`, located with
|
||||
`scripts/dex_find_insn.py`) when the change fits in an existing instruction slot
|
||||
or constant — nothing moves, so no offset, try/catch block or debug pointer can
|
||||
be invalidated. **dexlib2 method rewriting** (`scripts/dexpatch/`) only when the
|
||||
change genuinely needs new instructions. Whole-tree smali round-trip damages
|
||||
R8-optimized dex in ways that only show up at runtime; a method rebuild also
|
||||
inflates the file (measured: `debug_info` 924 B -> 22.8 KB, dex 4.32 MB ->
|
||||
7.73 MB on one sample). Whichever you use, recompute the dex header integrity
|
||||
fields (**signature first, checksum last**) — `references/byte-level-patching.md`
|
||||
§the dex header has two integrity fields.
|
||||
6. **Repack and sign** — `references/repack-and-sign.md`. **Do not strip the whole `META-INF/`.** This single mistake destroys otherwise-correct builds.
|
||||
6b. **Neutralise the update path — before you call the build done.** If the app checks for updates at all, add the two-layer patch (`references/updates-and-forced-upgrade.md`): no-op the update routine's entry, and force the version comparison to its "no update" side. A build that can be switched off or replaced remotely is not a deliverable, and this costs minutes here versus a rebuild later. Do the same for any **remote-config or hot-update** channel that could restore the behaviour you removed.
|
||||
6c. **Handle account gates only after classifying them** — if the request mentions sign-in or binding, apply `references/account-gates.md` and state plainly which guarded screens become usable and which stay empty because their content is account-scoped.
|
||||
7. **Verify on device** — `references/environment.md` + `references/verification.md`. Check: launches, the changed behavior actually changed, nothing unrelated broke, and **the app reaches its normal UI with no blocking dialog**. First prove the artifact actually changed on the device -- a package manager reporting success does not prove an interposed confirmation was accepted (P18). Capture continuously for the first ~20 seconds after launch, **and look at the captures** — sampling gaps are how a blocking modal goes unseen (P20), and a burst of images that were never inspected is not evidence. If the accessibility tree is empty, the image is the primary evidence rather than a fallback.
|
||||
8. **Log what you learned** — if a failure cost you more than thirty minutes, add it to `references/pitfalls.md`. That file is the most valuable artifact in this skill.
|
||||
|
||||
## What "done" means — do not claim it earlier
|
||||
|
||||
Every item below must be true before you report completion. Anything less is a **checkpoint** and must
|
||||
be labelled as one, out loud, with what remains. Premature "done" is the most damaging thing you can
|
||||
report, because it ends the investigation while the user believes the problem is solved.
|
||||
|
||||
1. **The artifact exists and its identity is recorded** — path plus hash, not a filename.
|
||||
2. **It was installed and launched on the environment the deliverable sentence names** (G1/R1). If
|
||||
that environment was not available to you, say so and label the result accordingly.
|
||||
3. **The behaviour you changed is verified changed** — by direct observation of the feature, not by
|
||||
the absence of an error message. "The log is clean" is not evidence; "the screen shows X" is.
|
||||
4. **The features it touches still work.** You exercised them. A build that starts but whose affected
|
||||
feature is dead is not a result.
|
||||
5. **The original limitation is stated if any survives** — with the coupling that causes it, so the
|
||||
next person can decide whether to accept it.
|
||||
6. **Nothing you did leaves the target or the device in a broken state** unless that was the goal, and
|
||||
any privileged workaround is labelled a fallback rather than the deliverable.
|
||||
|
||||
If items 1–4 hold but the environment was wrong, you have a **prototype**, not a deliverable. Say
|
||||
"prototype" and name the gap.
|
||||
|
||||
## Stop conditions — halt and re-classify, do not retry
|
||||
|
||||
These are moments where continuing to push forward is the wrong move. Each has cost hours somewhere.
|
||||
|
||||
- **The same shape of attempt failed twice.** See the two-strike rule above.
|
||||
- **A patch had no effect and you were about to try a third variant of it.** No effect means the
|
||||
diagnosis was wrong, not that the patch was unlucky. Re-classify the layer.
|
||||
- **A new failure has no place in your current model.** That is the symptom index's trigger condition.
|
||||
- **You are about to write off a route as "blocked"** without a control build proving the block is
|
||||
the app's doing rather than your pipeline's. Mis-attributed blocks have removed viable routes.
|
||||
- **You are about to claim success on absence of errors.** See §What "done" means.
|
||||
- **A measurement disagrees with a conclusion you already recorded as settled.** Re-open the
|
||||
conclusion; do not explain the measurement away.
|
||||
|
||||
## Non-negotiable constraints
|
||||
|
||||
- **Read-only inputs.** Keep the original APK/dex untouched; work on copies. Always keep a known-good baseline to diff against.
|
||||
- **One variable at a time.** If you change two things and it breaks, you learn nothing. Build a control (same pipeline, zero patches) and compare.
|
||||
- **Verify structure after every dex edit.** `scripts/dex_classdiff.py` must report zero differences in class set and access flags for classes you did not intend to change.
|
||||
- **Do not patch a method that is widely shared.** Before patching any helper, count its callers (`scripts/find_refs.py`). A `Long.valueOf` wrapper with 30 callers is not an ad-specific hook.
|
||||
- **Do not make an API fail to suppress a UI element.** A 404/400 on an endpoint that other features depend on takes the whole screen down with it. Suppress at the data-consumption or render layer instead.
|
||||
- **Neutralise a native terminate path by returning, never by making it not return.** A stub, stub patch, or function entry replaced with a spin or a self-branch does not suppress the check — it freezes the caller, holding whatever lock it had, and unrelated threads wedge behind it. The symptom (a hang, an external kill, a restart loop) looks nothing like the cause, and there is no crash record to explain it. Return a benign value, and prefer success (0) over failure (-1). Never touch the ordinary-path symbols (`pthread_exit`, `exit`, `abort`, `snprintf`, `closedir`). `references/native-tamper-and-suicide.md`
|
||||
- **Look before you conclude — and look while you wait.** Execute, capture, and **inspect**; do not drive and sleep blind. A screen that is actually looked at answers in one step what coordinate-guessing cannot answer in five: the layout moved, a different dialog is up, a countdown is frozen, the text on screen says exactly why. Where the thing you are waiting on is visible, a sample you can inspect beats a duration you hoped was right, and byte-identical samples mean nothing is going to change. `scripts/snap.py`; `references/environment.md` §look at the screen.
|
||||
- **Put a timeout on every command, and calibrate it from measurement.** An unbounded call turns a stall into "the task stopped making progress", which is indistinguishable from slow work and costs hours silently. Time the operation once, record it, then derive the bound from it — that is what makes slow and hung distinguishable. A deadline that passes is a measurement, not a verdict. `references/long-task-discipline.md` §bound every wait.
|
||||
- **Every claim needs evidence.** "Probably", "should be", "in theory" are not findings. Either you observed it, or you label it unverified.
|
||||
- **"Done" means the user-visible outcome**, not an internal signal. A blocking dialog still on screen means the task is not done, however many errors disappeared from the log. Absence of a log line is absence of evidence, never evidence of success.
|
||||
- **Do not discard a route on compound evidence.** If a failure followed two simultaneous changes, the attribution is a hypothesis, not a finding. Re-run it single-variable before writing the route off -- mis-attributed failures have removed viable approaches for a long time.
|
||||
- **Prove the device changed before measuring.** Install success describes the request, not the app on disk. Confirm the artifact actually advanced, or every following observation describes the previous build.
|
||||
- **Attribute a failure to the right layer before patching again.** When something stops working after a rebuild, first check whether the **unmodified original** fails the same way on the same device and network. Feature-scoped network failures in particular are frequently the app's own TLS/certificate problem (`references/tls-and-cert.md`); chasing a signature check that does not exist burns hours.
|
||||
|
||||
## Reference index
|
||||
|
||||
Load only what the current step needs.
|
||||
|
||||
| File | Load when |
|
||||
|---|---|
|
||||
| `references/recon.md` | Starting any new sample; identifying packer, SDKs, code location, ABI |
|
||||
| `references/server-config-and-updates.md` | **The launch screen, a popup or the tab set is server-sent**; no ad SDK was found; a removed promo came back; anything controlled by a `*Config`/`*Popup` DTO with an `enabled` flag |
|
||||
| `references/byte-level-patching.md` | You want to change behaviour by editing a few bytes rather than rebuilding a method — equal-length patches, locating an instruction's exact offset, dex header integrity fields, branch polarity, verifier legality |
|
||||
| `references/packers.md` | The app is packed/hardened, or an edit makes it die before your code runs. Also load before discarding any route as "blocked by the shell" |
|
||||
| `references/code-virtualization-and-custom-linkers.md` | **No packer, dex is readable, and a re-signed build still dies** — whole classes turned into `native` declarations, a private loader with a mismatched SONAME, an embedded self-decrypting payload, or a Java-layer "signature killer" that logs success while a native check kills you. Covers the keep-it/drop-it deadlock and the string-redirect escape |
|
||||
| `references/framework-runtimes.md` | The UI is not native (Flutter / React Native / Unity / Cordova), or Java-layer hooks fire zero times while the UI clearly works |
|
||||
| `references/dart-aot.md` | The logic lives in a Dart AOT snapshot (`libapp.so`): pinning the Dart version, building a matching decompiler, the object pool and reference indexing, register/boolean conventions, locating and patching Dart code |
|
||||
| `references/native-and-so.md` | Patching in a `.so`, needing code to run before the app's own code, hand-built native payloads that crash inside the linker, or **deciding which library/ABI is actually loaded and executing** |
|
||||
| `references/native-tamper-and-suicide.md` | The process dies on its own (no Java stack, or a native crash that looks like a bug); you are about to neutralise a `kill`/`exit`/`abort` path; or a hardened library's sections/function boundaries look wrong |
|
||||
| `references/detection-and-anti-analysis.md` | The app fights back: it dies after you attach, refuses to run on your device, detects root/hook/debugger, or your dynamic tool simply does not work in this environment. **Read the first section before escalating** — the right answer is usually to switch to static, not to fight the detector |
|
||||
| `references/toolchain.md` | Choosing or invoking tools, something is not installed (including "not on PATH but present on disk"), a tool's output smells wrong, or you need to know which tools exist only as a GUI |
|
||||
| `references/ad-removal.md` | Task involves ads, trackers, sponsored cards, splash/interstitial/reward |
|
||||
| `references/updates-and-forced-upgrade.md` | The patched build must **keep working over time**; the app has any version check, forced-upgrade dialog, self-update installer, or hot-update/resource channel. Load this for essentially every build you intend to ship. |
|
||||
| `references/account-gates.md` | Task mentions "no login required", "don't force sign-in", "skip phone binding", "guest mode"; or a screen/feature is unreachable signed-out. Also load before promising that an account-scoped screen will show anything |
|
||||
| `references/membership-and-limits.md` | Task involves VIP, subscription, paid content, unlock, "fully cracked" |
|
||||
| `references/server-api.md` | The behavior is decided by a response, or you need to know if a patch can even matter |
|
||||
| `references/dex-patching.md` | Any actual editing of dex/smali, choosing a patch layer, choosing a tool |
|
||||
| `references/patch-audit.md` | Proving a patch **landed**, or that it is **legal**: length-vs-bytes comparison, the equal-length blind spot, verifier-level legality (`move-result*` adjacency), text-matching patch traps, and how to report a missing patch |
|
||||
| `references/repack-and-sign.md` | Rebuilding, signing, installing, or a repacked app misbehaves |
|
||||
| `references/signature-derived-keys.md` | The app reads `signatures[0]`/`toCharsString()`, or a rebuilt APK installs and runs but every signed request fails (`sign`/`_p`/`uth` empty or `-1`) |
|
||||
| `references/runtime-data.md` | Local state matters: DataStore, SharedPreferences, SQLite, protobuf caches, tokens — **or your data edit keeps being reverted, or a stored value looks encrypted** |
|
||||
| `references/dynamic-frida.md` | Frida setup, hooking strategy, tracing caller chains, finding the real call site |
|
||||
| `references/environment.md` | Device/emulator setup, root, ADB, networking, offline devices, emulator console control and recovery, **the preflight check to run before every experiment block** |
|
||||
| `references/verification.md` | Defining what "done" means; building the evidence chain |
|
||||
| `references/tls-and-cert.md` | One feature fails at runtime (login, registration, payment, an API-backed screen) while the rest of the app works |
|
||||
| `references/third-party-builds.md` | The input is a "cracked"/"modded" build you did not produce — audit it before trusting it |
|
||||
| `references/long-task-discipline.md` | The task will run long, or you are resuming one. Live record, conclusion grading, drift checkpoints, **deliverable-form drift (rooted-only vs shippable)**, bound-your-waits, **captures-you-never-looked-at**, **long-context decay**, handover |
|
||||
| `references/pitfalls.md` | Always worth a skim before building. This is the failure catalogue. |
|
||||
|
||||
## Script index
|
||||
|
||||
All scripts are parameterized and path-agnostic; pass paths explicitly. Run `--help` or read the header of each.
|
||||
|
||||
| Script | Purpose |
|
||||
|---|---|
|
||||
| `scripts/doctor.py` | **Run this first.** Capability report and per-script runnability: which tools exist (including ones installed off-PATH or as `java -jar` jars), which scripts can actually run here, and the environment facts that silently poison experiments — clock skew, leftover `adb forward`/proxy, a device-side frida process already running |
|
||||
| `scripts/dexutil.py` | **Dependency-free dex reader**: structural walk + exact instruction decode with a verified format table, `fix_dex_header`/`verify_dex_header` (correct checksum/signature order), branch-target and operand helpers. The library the dex scripts below share; also runs standalone to dump one method with offsets |
|
||||
| `scripts/dex_find_insn.py` | Locate an instruction by **decoded semantics** and get its exact byte offset, with context and both sides of any branch. This is how you find a patch site without guessing offsets or scraping listings |
|
||||
| `scripts/dex_patch_bytes.py` | Apply **equal-length byte patches** from a JSON spec: matches by semantics, pins branch polarity via `expect_next`, enforces equal length, checks verifier legality, recomputes the dex header in the correct order, and re-decodes to prove the edit landed. `--dry-run` first |
|
||||
| `scripts/dex_check_verifier.py` | Tier-3 check: does any **conditional branch target a `move-result*`** (bypassing its producer, so the class fails to load)? Compares two builds and distinguishes pre-existing findings from regressions your patch introduced |
|
||||
| `scripts/coldstart.py` | Cold-launch an app and capture a **timed screenshot burst + logcat signals + installed-build facts + launch timing**, and warn when the foreground activity is not your app (a vendor installer left on screen is the classic cause of "evidence" that shows something else) |
|
||||
| `scripts/smtool.py` | baksmali/smali wrapper with a bundled classpath (assemble/disassemble dex) |
|
||||
| `scripts/patch_smali.py` | Method-body replacement in a smali tree, matched by signature |
|
||||
| `scripts/dex_strpatch.py` | Byte-level string constant patch with **string_ids ordering guard** |
|
||||
| `scripts/dex_classdiff.py` | Compare two dex class tables (set + access flags) to prove a patch was surgical |
|
||||
| `scripts/dex_strings.py` | Dump/extract strings and endpoints from dex without a decompiler |
|
||||
| `scripts/dart_pprefs.py` | Build/query the object-pool offset -> code-site index for a Dart AOT snapshot (arithmetic decode; seconds, not minutes) |
|
||||
| `scripts/dart_pool_strings.py` | Recover string literals from a Dart AOT snapshot: framed entries, the one-byte vs UTF-16 split, file offsets, and a run-length noise filter |
|
||||
| `scripts/dart_disasm.py` | Annotated windowed disassembly of Dart AOT code (pool + boolean annotations) plus a B/BL caller index |
|
||||
| `scripts/find_refs.py` | Count and list callers of a method/field (blast-radius check) |
|
||||
| `scripts/repack.py` | Rebuild an APK with replaced dex, strip only signatures, keep `META-INF/services/`, **write a 4-byte-aligned archive** (`resources.arsc` STORED+aligned, which Android R+ refuses to install without), sign, and verify |
|
||||
| `scripts/dexpatch/` | dexlib2 method-level rewriter (for changes that genuinely need new instructions) + build notes |
|
||||
| `scripts/devsh.py` | Quoting-safe ADB shell helper for rooted devices |
|
||||
| `scripts/usb_net_proxy.py` | Give an offline device network over USB (adb reverse + local proxy) |
|
||||
| `scripts/datastore_inject.py` | Encode/inject AndroidX DataStore preferences (protobuf) safely |
|
||||
| `scripts/probe_api.py` | Probe an app's HTTP API with correct headers, report status/shape |
|
||||
| `scripts/install_test.py` | Install a build and run a launch/health check with logcat signal extraction |
|
||||
| `scripts/frida_probe.js` | Four-layer runtime probe: app network layer + OkHttp + java.net + swallowed exception messages |
|
||||
| `scripts/run_probe.py` | Inject a probe, stream it to a timestamped log file, stay resident while you operate the app |
|
||||
| `scripts/tls_check.py` | Strict certificate check for one or more hosts (expired / wrong host / untrusted CA) |
|
||||
| `scripts/preflight.py` | Read-only environment check before every experiment block: device, root, ABI/translation, clock skew, leftover proxy/forwards, dead device server. Run this before blaming a patch. |
|
||||
| `scripts/lib_map.py` | What is **actually mapped** into a live process: per-library path, base, architecture (`ELF e_machine`), and classification (system / from-APK / runtime-materialized). Answers "which library and which ABI is really executing". |
|
||||
| `scripts/elf_plt.py` | Resolve a PLT stub to its imported symbol on x86_64 and aarch64 (from the **relocation table**, not from position or a comment), list a symbol's callers, and **byte-diff two libraries naming the symbol each changed stub belongs to**. Run this before patching any stub, and to audit a patch set you inherited. |
|
||||
| `scripts/so_constpatch.py` | Same-length in-place rewrite of an isolated string constant, for **redirecting a library load instead of defeating a check** (`System.loadLibrary("checker")` -> a library that is already mapped). Enforces equal length, refuses to touch a substring of a longer identifier, reports whether each hit sits in a constant pool, and patches inside an APK or a bare `.so`. See `references/code-virtualization-and-custom-linkers.md`. |
|
||||
| `scripts/apk_diff.py` | Entry-level diff of two APKs: what changed, what was **added** (injection candidates), what was removed — by content hash, so same-size replacements are caught. Use it to audit a third-party build and to prove your own build was surgical. |
|
||||
| `scripts/native_crash.py` | Locate a native death from a logcat capture or tombstone: signal, fault address, register state, backtrace split into your libraries vs system, the faulting instruction — plus an explicit flag when the fault looks **arranged** rather than accidental. |
|
||||
| `scripts/grab_crash.py` | Recover a stack that a crash-reporter SDK swallowed, when the log shows the app died but prints no backtrace of its own. |
|
||||
| `scripts/blob_decode.py` | Decode an opaque stored value by searching the parameter space (base64/base64url/hex × rotation × deflate/zlib/gzip) instead of guessing, then re-encode an edited payload with the same parameters. |
|
||||
| `scripts/snap.py` | Bounded burst screenshot + control-tree capture, with a stall detector and an explicit verdict on whether the accessibility tree is usable at all. Use it so you *look* at the screen instead of driving blind. |
|
||||
| `scripts/sig_probe.py` | Find the exact `signatures[0].toCharsString()` value: offline candidate enumeration from an APK (`--apk`), or the authoritative value read from a live package (`--live`). Feed the result into the hardcoded constant described in `references/signature-derived-keys.md`. |
|
||||
@@ -0,0 +1,160 @@
|
||||
# Account gates: sign-in walls, forced binding, guest mode
|
||||
|
||||
Load this when the task mentions "no login required", "don't force me to sign in", "skip phone
|
||||
binding", "guest mode", or when a screen is unreachable without an account — and also **before**
|
||||
promising that any account- or membership-derived feature will work offline.
|
||||
|
||||
This file is mostly about **telling apart two things that look identical in the UI and are completely
|
||||
different in reality**:
|
||||
|
||||
- a **client-side gate** — code that refuses to proceed. Patchable.
|
||||
- an **account-scoped resource** — the screen is empty because the server sent nothing, because the
|
||||
request was made without a valid identity. **Not** patchable.
|
||||
|
||||
Confusing the two is how a task ends up "done" while the user stares at an empty page.
|
||||
|
||||
## Step 1: classify what you are looking at
|
||||
|
||||
| Symptom | Most likely cause | Can a client patch help? |
|
||||
|---|---|---|
|
||||
| A dismissible dialog / bottom sheet asking to sign in, then the app works | client-side gate | **yes** |
|
||||
| A full-screen wall with no dismiss, app unusable | client-side gate | **yes** |
|
||||
| Screen renders its frame but the list is empty and a "log in to see" hint is drawn | **account-scoped data** | no — the data does not exist locally |
|
||||
| A specific action (comment, favourite, follow, download) refuses | client-side gate | usually yes |
|
||||
| The action succeeds locally but reverts on restart / never reaches the server | **server-side identity** | no |
|
||||
| "Binding required" before an action | client-side gate | **yes** |
|
||||
| An entitlement appears then disappears | server-side authority | no |
|
||||
|
||||
**The deciding question is never "is there a login screen?" — it is "does the thing I want exist
|
||||
without an identity?"**
|
||||
|
||||
Ask it before patching:
|
||||
|
||||
- If the content is **fetched per-account** (subscriptions, favourites, reading history, purchased
|
||||
items), a patch changes the gate and nothing else. The list stays empty because the server was asked
|
||||
for *this account's* items and there is no account.
|
||||
- If the content is **public** and merely hidden behind a prompt (a reader, a catalogue, a settings
|
||||
page), the patch is real and the feature becomes usable.
|
||||
|
||||
Reading the code tells you which: follow the "sign in" prompt to what it guards, then look at whether
|
||||
that guarded path issues a request carrying a token, or touches only local state.
|
||||
|
||||
## Step 2: find the convergence point
|
||||
|
||||
Sign-in checks are usually concentrated, because a UI cannot meaningfully enforce login at thirty
|
||||
call sites. Look for a small number of helpers with names in this family:
|
||||
|
||||
```
|
||||
checkLogin* ensureLogin* requireLogin* needLogin* isLogined* isLoggedIn*
|
||||
checkBind* ensureBind* requireBind* needBind*
|
||||
showLogin* openLogin* loginSheet* loginDialog*
|
||||
```
|
||||
|
||||
and, on the state side, a **login-state field or stream** that every helper reads
|
||||
(`isLogin`, `loginedStream`, an `Rx<bool>`, an auth-state enum, a credential store wrapper).
|
||||
|
||||
**Rule: patch the predicate, not the prompt.** Making the sheet not appear is cosmetic — the caller
|
||||
still treats the answer as "not signed in" and takes its else-branch, which is usually where the real
|
||||
feature got skipped. The durable fix is to make the *verdict* come back as "signed in / no sign-in
|
||||
needed", so the caller takes its happy path.
|
||||
|
||||
Two useful shapes, both better than editing the dialog:
|
||||
|
||||
| Target | Change | Effect |
|
||||
|---|---|---|
|
||||
| the gate predicate used by many callers | return "ok / already signed in" unconditionally | every caller proceeds; no new code path |
|
||||
| the "should I prompt?" decision inside the helper | return "nothing to do" | the prompt never appears and callers proceed |
|
||||
|
||||
Prefer the first when callers branch on the result; prefer the second when the helper is fire-and-forget.
|
||||
|
||||
**Count the callers before choosing** (`scripts/find_refs.py`). A predicate with one caller is a
|
||||
surgical target; a predicate with forty callers is a behavioural change you must reason about — it will
|
||||
also release flows you were not asked to touch (settings, purchase, upload). That may be fine, but it is
|
||||
a decision, not a side effect.
|
||||
|
||||
### Forced binding specifically
|
||||
|
||||
Phone binding is the same pattern with its own helper and usually **two** state checks in series
|
||||
(bound-phone? and email-or-other-recovery?), because either satisfies the requirement. Patch the
|
||||
combined verdict, not the first condition — a patch that only satisfies one branch still prompts on the
|
||||
other.
|
||||
|
||||
Watch for a **"skip"/"later" path the app already has**, and for **which actions the binding actually
|
||||
gates**. Binding is often required for a subset (password change, deletion, payment) while the rest of
|
||||
the app is unaffected; releasing it globally changes what the app believes about account safety.
|
||||
|
||||
## Step 3: what NOT to do
|
||||
|
||||
These are the tempting moves that produce a worse artifact than doing nothing:
|
||||
|
||||
- **Do not fabricate a session.** Writing a dummy token, a fake credential blob, or a placeholder
|
||||
identity into the credential store makes the client *believe* it is signed in. It then calls
|
||||
identity-scoped endpoints with garbage, and the app enters a state that is **worse than signed out**:
|
||||
screens show an authentication-failure message, or silently return empty data with no explanation.
|
||||
A signed-out app that says "please sign in" is better than one that claims a session and fails.
|
||||
*(If you touch stored credentials at all, keep a backup and expect to have to restore it.)*
|
||||
- **Do not delete the sign-in UI.** Removing the entry point does not change the verdict; it only makes
|
||||
the failure unexplainable when a caller does branch on it. Keep the entry point working — it is
|
||||
normally an explicit requirement ("signing in must still be possible").
|
||||
- **Do not release gates that protect server-side operations.** If the action's result is an
|
||||
entitlement the server must grant (a purchase, a quota, a subscription), releasing the client gate
|
||||
only lies to the UI. See `references/membership-and-limits.md`.
|
||||
- **Do not assume "guest can browse" means "guest can do everything".** Establish per feature which of
|
||||
the three states you are in: public, gate-only, or identity-required.
|
||||
|
||||
## Step 4: the session-loss problem (this one is unavoidable)
|
||||
|
||||
Any change to the signing identity — including a plain reinstall of *your own* build — can invalidate
|
||||
stored credentials, because they may be sealed with a key held by the platform keystore rather than by
|
||||
the app.
|
||||
|
||||
**What you observe:** the app opens fine, then one subsystem reports it cannot decrypt or unwrap
|
||||
something, or the user is silently signed out.
|
||||
|
||||
**What it means:** the app's private data was carried across an uninstall/reinstall (or restored from a
|
||||
backup), but the encryption key was destroyed with the app. The ciphertext is now unopenable by anyone.
|
||||
|
||||
**What to do:** treat "the user signs in once on the new build" as the expected, documented outcome — not
|
||||
as a defect to fix. Put it in the delivery notes in one line, together with the fact that a later
|
||||
upgrade over the *same* signing key can be installed without uninstalling, and therefore will not lose
|
||||
the session.
|
||||
|
||||
**Do not** chase this into the keystore. Restoring the old key is not part of packaging a patched build,
|
||||
and any workaround that keeps the *old* ciphertext alive while the key is gone is a dead end.
|
||||
|
||||
Related and worth knowing: an app may keep the same logical account in **two places** — a plain
|
||||
preference blob and a sealed store. After a reinstall the plain one survives and the sealed one does
|
||||
not, which shows up as an account that is half-present (identity fields populated, token empty). That
|
||||
half-state is a useful diagnostic: it tells you the app reads its identity from the sealed store, which
|
||||
is exactly the thing you must not try to forge.
|
||||
|
||||
## Step 5: verify
|
||||
|
||||
The claim to support is narrow and should be stated narrowly.
|
||||
|
||||
1. **The prompt does not appear** on a cold start and on the screens that used to show it.
|
||||
2. **The feature behind it actually works**, not merely "no longer blocked": open the reader, the
|
||||
catalogue, the settings page — whatever the gate guarded — and confirm real content or real function.
|
||||
3. **The sign-in entry still exists and is usable.** Signing in with a real account must still work; that
|
||||
is usually part of the request, and it is the thing that proves you patched a gate rather than broke
|
||||
authentication.
|
||||
4. **Signed-in behaviour still works** for a real account, so you can tell the difference between
|
||||
"released the gate" and "broke the auth path".
|
||||
5. **No fake-session artefact is left behind** — check that you did not write anything into the
|
||||
credential store or preferences. If you did, remove it and re-verify from a clean install.
|
||||
|
||||
State the result as: *"the gate no longer blocks X, from a signed-out state; **the content behind it is
|
||||
public / the content behind it is per-account and therefore still empty when signed out**."* That second
|
||||
clause is what stops a client patch from being mistaken for an account.
|
||||
|
||||
## Reporting template
|
||||
|
||||
```
|
||||
Gate: <sign-in sheet | binding prompt | action-scoped check>
|
||||
Class: client-side gate / account-scoped data (not patchable)
|
||||
Patch: <predicate or decision, not the prompt>
|
||||
Signed-out state: <what works now, per screen>
|
||||
Signed-in state: <still works, listing what still requires an account>
|
||||
Not achievable: <per-account lists, entitlements — with the reason>
|
||||
Session note: sign in once after install; upgrade over the same key keeps the session
|
||||
```
|
||||
@@ -0,0 +1,177 @@
|
||||
# Ad removal
|
||||
|
||||
Goal: ads stop appearing, and **nothing else breaks**. Read `pitfalls.md` P5 and P6 before patching anything here.
|
||||
|
||||
## Step 1: enumerate what "ads" means in this app
|
||||
|
||||
Do not assume "ads" is one thing. Enumerate first.
|
||||
|
||||
**SDK-integrated ads** (the app calls an SDK):
|
||||
- Search dex strings for SDK markers: `openadsdk`, `TTAdSdk`, `TTAdNative`, `Pangle`, `pangolin`, `com.qq.e`, `GDTAd`, `gdt_plugin`, `anythink`, `ATSDK`, `ATRewardVideoAd`, `bdxadsdk`, `sigmob`, `ksad`, `mobads`, `beizi`.
|
||||
- **Aggregators** (AnyThink, TopOn, and similar) are wrappers: the ad networks underneath are *their* adapters, not app code. Patching an individual network's class is usually pointless; the aggregator still runs and still reaches the network.
|
||||
- The app almost always funnels every call into **one wrapper class**. That class is the patch surface (Step 2).
|
||||
|
||||
**Dynamic-plugin ad SDKs** (the SDK is not in the APK). Aggregators increasingly ship as a runtime plugin: the app downloads an APK on first launch into its private directory and loads it through a plugin classloader.
|
||||
|
||||
```
|
||||
/data/data/<app.package>/files/<sdk>_p/<plugin.pkg>/version-*/apk/base-1.apk
|
||||
/data/data/<app.package>/files/<sdk>_p/<plugin.pkg>/version-*/lib/<abi>/*
|
||||
```
|
||||
|
||||
- Consequence: **deleting bundled `assets/`, `lib/*.so`, or the SDK's classes from the dex does not kill this SDK.** The loader re-downloads on the next launch, and a half-deleted plugin is worse than an intact one.
|
||||
- The kill switch is the **init gate** (Step 2). Killing init also prevents the working directory from ever being created, which is the strongest verification signal available (Step 4).
|
||||
- The plugin may also be bundled. Two copies still means one init gate; patch that, not the payload.
|
||||
|
||||
**Server-driven ads / sponsored content** (the server returns the ad, the client renders it):
|
||||
- **This is the most common shape in a modern app, and it is usually the EASIEST to
|
||||
remove — not the hardest.** Go to `server-config-and-updates.md` for the full
|
||||
procedure. The short version: the client keeps a complete "do not show it" branch
|
||||
so the operator can turn the slot off, so neutralising that one branch is a
|
||||
small, local edit.
|
||||
- Look for endpoints like `/adverts`, `/adv`, `/banner`, `/config`, and DTOs named
|
||||
`Advertisement*`, `Advert*`, `Banner*`, `Promotion*`, or — more common in practice
|
||||
— a generic `*Config` payload carrying per-feature blocks (`splash`, `noticePopup`,
|
||||
`updatePopup`, `tabbar`, `banner`).
|
||||
- The client renders whatever the list contains. If the list is empty there is nothing
|
||||
to show, but see `pitfalls.md` P5 on **how not** to empty it: never make a shared
|
||||
request fail.
|
||||
- Sponsored cards that look like content (a VPN promo, a network-accelerator card, a
|
||||
third-party product) are usually exactly this.
|
||||
|
||||
**A note on what "no SDK found" means.** If you have grepped the dex, enumerated the
|
||||
loaded classes at runtime, and counted the SDK log tags in a capture, and all three
|
||||
are zero (see Step 1), then there is no SDK, and continuing to search for one is a
|
||||
dead end rather than a thorough approach. Re-classify against this list instead. A
|
||||
zero result on all three signals is a strong positive finding about where the
|
||||
behaviour lives, and it should move you to the server-config path immediately.
|
||||
|
||||
**Legit content that looks like an ad.** Verify before acting. A `/adverts?position=banner` response containing anime titles and poster images is the home-page carousel, not an advertisement. Removing it removes real functionality.
|
||||
|
||||
## Step 2: find the single convergence point
|
||||
|
||||
Almost every ad-enabled app wraps one SDK in a **single singleton helper**: `init`, `loadSplash`, `loadBanner`, `loadFullScreen`, `loadReward` all live in the same class. Find that class, and patch nothing else if you can.
|
||||
|
||||
```
|
||||
helper.init(Application) -> Sdk.init(appId, appKey); Sdk.start() // plus plugin download
|
||||
helper.showSplash(Activity, ViewGroup, onClose: () -> Unit)
|
||||
helper.showInterstitial(Activity)
|
||||
helper.showReward(Activity, onStart: () -> Unit, onFinish: (Boolean) -> Unit)
|
||||
helper.preload*(Activity)
|
||||
helper.canShow*(Activity): Boolean // == isReady / isLoaded / isAdReady
|
||||
```
|
||||
|
||||
**Preferred play: readiness always false + init is a no-op.**
|
||||
|
||||
1. Make the readiness predicate constant `false` (`isReady` / `canShow*` / `isLoaded` / `isAdReady`).
|
||||
2. Make `init` an empty method (`return-void`) so the SDK never builds a network stack and never requests a plugin.
|
||||
3. Only then touch show/load methods, and only for slots that bypass the readiness predicate.
|
||||
|
||||
Why this order works:
|
||||
- Callers of a readiness predicate **already own a "no ad available" branch**, and the app ships and tests it. Returning `false` routes every slot through that existing path: no crash, no hang, no new code path.
|
||||
- Killing init removes the SDK's network, cache, and download activity entirely. That is the difference between "the ad is hidden" and "the ad subsystem never started", and only the second claim is provable (Step 4).
|
||||
- Per-slot patching (splash this week, interstitial next) leaves the SDK alive and downloading. Avoid it unless a slot ignores the predicate.
|
||||
|
||||
Method classification, once the helper is located:
|
||||
|
||||
| Method | Contains | Patch |
|
||||
|---|---|---|
|
||||
| Init | `Sdk.init(...)` + `Sdk.start()`, plugin download | body -> `return-void` |
|
||||
| Readiness / gate | `isAdReady`, `canShow`, `isLoaded` | return `false` / `0` |
|
||||
| Show splash / interstitial | constructs an ad object, `loadAd()` / `show()` | `return-void`, **but preserve the completion callback** |
|
||||
| Show reward | same, plus success/failure lambdas | `return-void`; decide deliberately whether to grant the reward |
|
||||
| Preload / warm-up | `RewardVideoAutoAd.init(...)`, cache priming | `return-void` |
|
||||
|
||||
### The callback trap (this one breaks startup)
|
||||
|
||||
A splash/loading ad usually takes a **completion lambda** as a parameter, and the app's startup state machine waits for that lambda before dismissing the splash screen.
|
||||
|
||||
**If you replace the method with a bare `return-void`, the lambda never fires and the app hangs on the splash screen forever.** A patch that "removed the ad" and produced a frozen splash is this bug, not a repackaging bug.
|
||||
|
||||
Correct shape, skip the ad and still complete:
|
||||
|
||||
```
|
||||
.method public final showSplash(Landroid/app/Activity;Landroid/view/ViewGroup;Lkotlin/jvm/functions/Function0;)V
|
||||
.registers N
|
||||
invoke-interface {p3}, Lkotlin/jvm/functions/Function0;->invoke()Ljava/lang/Object;
|
||||
return-void
|
||||
.end method
|
||||
```
|
||||
|
||||
**Before patching, prove the contract.** Read the listener class the method constructs and find which callback triggers the completion lambda (`onAdDismiss`? `onAdError`? `onAdLoadTimeout`?). That tells you whether to call it on success, on failure, or unconditionally.
|
||||
|
||||
For a reward ad whose lambdas are `(onStart, (Boolean) -> Unit)`, granting the reward client-side is a choice: `onFinish(true)` makes the app treat the reward as earned. Check whether the reward is validated server-side before promising it.
|
||||
|
||||
### Global timestamp gates (one write, many slots)
|
||||
|
||||
Some "free reading + ads" apps do not gate ads per slot. They store one local timestamp and every slot, cooldown, and interval check reads it: splash, chapter-break interstitial, unlock prompt, "next ad in N minutes". Patching call sites one by one always misses some.
|
||||
|
||||
- **Find it:** dump the app's preference keys and filter for ad-ish names (`ad`, `free`, `cooldown`, `interval`, `end_time`, `expire`, `next_`). Then hook `SharedPreferences.getLong/getInt/getString` and watch which key is read immediately before a slot appears. The key read across several screens is the gate.
|
||||
- **Patch it:** in `Application.onCreate()`, write a far-future value as early as possible (for example `4102444800000L`). Avoid `Long.MAX_VALUE`: implementations often compute `end - now` and can misjudge an extreme value. One write disables every reader at once, which is far more stable than editing each consumer.
|
||||
- **If the app overwrites it later:** observe what it writes back under different start sequences. A single startup write is not automatically permanent for keys the app re-asserts; then patch the writer or the reader instead.
|
||||
- **Same technique, two key semantics:** "ad-free until `<date>`" keys and "cooldown/interval" keys both respond to this, but the value differs. For a cooldown key, a far-future value means "next ad is never due", which is what you want, while a progress/check-in flow reading the same key may behave oddly.
|
||||
- **Side effects are mandatory in the delivery notes.** The same key is often reused as a business field (the anchor for a new-user ad-free window, a remaining-quota counter). Forcing it to a far-future value changes those business judgements. Usually harmless for a de-ad goal, but state it explicitly and confirm the related screens do not show a broken state.
|
||||
- With DataStore instead of SharedPreferences, a write inside `Application.onCreate` needs a coroutine or a blocking write; see `runtime-data.md`, and never block the main thread on persistence.
|
||||
|
||||
### "Ads" vs ad-gating UI
|
||||
|
||||
Some blocking dialogs contain no ad slot at all ("watch an ad to unlock", skip/continue prompts, cooldown notices). If the goal is "the app is usable", they count as ads and must be handled too. Handle them by letting the gate pass, not by deleting the dialog view.
|
||||
|
||||
- Where the gate reads the timestamp key above, the timestamp patch already covers it.
|
||||
- Where it reads a boolean or a `canUnlock()` method, patch that predicate.
|
||||
- **Business-coupled entrances need a check first.** "Watch a video to earn benefits" may be a real feature. Decide with evidence: find the callers (`scripts/find_refs.py`) and see whether the entrance leads to a **server request** or a **local entitlement write**. A server-issued entitlement cannot be created client-side, so releasing the gate only fools the UI while the server still refuses; an entrance that changes purely local UI state is safe to release.
|
||||
|
||||
## Step 3: choose the patch layer
|
||||
|
||||
From safest to riskiest (full technique table in `dex-patching.md`):
|
||||
|
||||
1. **Kill SDK init** (Step 2) — the SDK never starts; its networks, caches, and plugin downloads never happen. Highest-value single patch. Verify nothing else silently depended on init.
|
||||
2. **Neutralize the readiness gate** — `isReady`/`canShow` return false; routes existing "no ad" branches.
|
||||
3. **No-op the show/preload methods** — only when 1 and 2 are insufficient, always preserving callbacks.
|
||||
4. **Global gate state** — one startup write covers every reader (timestamp / preference keys above).
|
||||
5. **Filter server-issued ad data at the consumption layer** — drop entries for the target position before they reach UI state.
|
||||
6. *(avoid)* **Renderer-level suppression** — only if the component is genuinely ad-exclusive. Check `pitfalls.md` P6 first.
|
||||
7. *(avoid)* **Transport-level blocking** — see `pitfalls.md` P5.
|
||||
|
||||
## Step 4: verify — three independent kinds of evidence
|
||||
|
||||
Logcat silence alone is weak evidence. A credible "ads are gone" claim needs all three, plus the neighbours:
|
||||
|
||||
1. **UI, screen by screen** — splash, home banner, detail page, reader/player, reward button, unlock prompt. Capture before/after screenshots (`verification.md` §screenshot discipline).
|
||||
2. **Logs** — the SDK's characteristic tags are **entirely absent**, not merely quiet: `anythink`, `ATSDK`, `Pangle`, `TTAd`, `GDT`, `ksad`, and so on.
|
||||
Make this a **count, not an impression**. Aggregators log a recognisable burst while they probe which networks are wired in (a "SDK id N not integrated" style line, once per network). Capture the same fixed window on the original and on your build and compare numbers: `8 -> 0` is a measurement; "I did not see it" is not. A tag that goes quiet without reaching zero usually means the SDK still starts and simply failed to load an ad this run — a different, weaker result than "the subsystem never started".
|
||||
3. **Filesystem, the strongest signal** — the app's private directory contains **no ad SDK working directory at all**:
|
||||
```bash
|
||||
adb shell "su -c 'ls -la /data/data/<app.package>/files/'"
|
||||
```
|
||||
For a dynamic-plugin SDK, an absent `<sdk>_p` tree proves the init gate never ran. It is not an artifact you can fake by hiding a view. If the tree exists, something still initializes the SDK: the init patch did not take effect, or a second init path exists.
|
||||
|
||||
Additional cheap evidence:
|
||||
4. **DNS / socket level** — a runtime `InetAddress` hook. Before: a burst of ad/tracker domains. After: none. Many ad SDKs bypass the system proxy, so a proxy log can miss them while this does not.
|
||||
5. **Exercise the screens that had ads** and confirm nothing unrelated regressed: images, playback, lists, pagination, downloads, login.
|
||||
6. **Clean install** — uninstall first, then install. Data left from a previous run can hide a failed init patch (`pitfalls.md` P11).
|
||||
|
||||
Frame the result at the right strength: *"the ad was hidden"* vs *"the ad subsystem never started"*. Only evidence 3 and 4 support the second (`verification.md` §the claim ladder).
|
||||
|
||||
## Step 5: what is usually NOT removable
|
||||
|
||||
Be honest about residual ads rather than breaking the app to chase them:
|
||||
|
||||
- **Content promos embedded deep in a feature's own data payload**, where the screen's
|
||||
load depends on the same request. Distinguish this from a *dedicated config block*:
|
||||
if the promo arrives in its own `splash` / `banner` / `popup` field with its own
|
||||
`enabled` flag, it is removable (Step 1, server-driven). It is only genuinely hard
|
||||
when the same list is both the content and the ad, with no marker separating them.
|
||||
- **Ads delivered as content** (a sponsored "article" or a native card with no SDK marker)
|
||||
— indistinguishable from real content without runtime tracing.
|
||||
- **Ads whose SDK init also enables other features.** Removing init can break
|
||||
functionality that silently depended on it. Verify before shipping; a working app with
|
||||
one residual ad beats a broken app.
|
||||
- **Server-issued entitlements gated behind watching an ad.** The gate can be opened
|
||||
client-side, the entitlement cannot be created client-side.
|
||||
- **A purely local brand launch screen.** If all you see is the app's own logo, no
|
||||
third-party image and no network-sourced content, that is a splash screen, not an ad.
|
||||
Removing it is a judgement call about the user's stated goal — say which one you
|
||||
removed rather than silently treating "startup screen" as "ad".
|
||||
|
||||
If a residual ad cannot be removed without breaking something, say so, and say exactly
|
||||
which coupling caused it. That is a better deliverable than a broken APK.
|
||||
@@ -0,0 +1,188 @@
|
||||
# Byte-level dex patching — equal-length edits, and the traps that make them fail
|
||||
|
||||
`dex-patching.md` covers rewriting a **method body** with dexlib2. This file covers the other
|
||||
technique: rewriting **a few bytes in place**. Reach for it whenever the change can be expressed as
|
||||
"make this branch do the other thing" or "make this constant a different constant", because it is
|
||||
strictly safer than rebuilding a method — but only if you respect the constraints below, which are
|
||||
not optional and are not obvious.
|
||||
|
||||
## Why equal-length, in numbers
|
||||
|
||||
A method-level rebuild is not free. Measured on one R8-processed sample (4.32 MB single dex):
|
||||
|
||||
| | original | after a 2-method dexlib2 rewrite |
|
||||
|---|---|---|
|
||||
| dex size | 4.32 MB | **7.73 MB** |
|
||||
| `debug_info` table | 924 bytes | **22,828 bytes** |
|
||||
| class set / access flags | — | identical (zero drift) |
|
||||
|
||||
The class table is unchanged, so the rebuild is *correct* — but dexlib2 does not reuse R8's shared
|
||||
`debug_info` entries and the file grows ~80%. That is the real cost of "surgical" method rewriting,
|
||||
and it matters because it changes the byte layout of everything after the edited methods.
|
||||
|
||||
An equal-length edit changes **only the bytes you chose**. No offset moves, so no try/catch block,
|
||||
no debug-info pointer, and no branch displacement anywhere in the file can be invalidated by
|
||||
construction. That property is worth more than the convenience of writing smali.
|
||||
|
||||
**Decision rule:** if the change fits in an existing instruction slot or a constant, patch bytes. If
|
||||
it genuinely needs new instructions or a different register allocation, rebuild the method — and do
|
||||
it in a copy so you can diff the tables.
|
||||
|
||||
## Locating the exact byte offset of an instruction
|
||||
|
||||
This is the part that eats hours if you improvise. Three approaches, worst to best.
|
||||
|
||||
**Do not reconstruct offsets from a `.line` listing.** baksmali emits one `.line` per *source* line,
|
||||
and one source line can be attributed to several consecutive instructions. The `.line` values
|
||||
therefore repeat and do not map 1:1 to offsets. A listing walker built on `.line` silently produces
|
||||
zero candidates for a branch you can see with your eyes.
|
||||
|
||||
**Do not match on a guessed byte sequence.** Instruction encodings vary with register numbers and
|
||||
operand widths; a pattern that looks right (`38 xx`) can be a different instruction than you think
|
||||
(`0x38` is `if-test`, 22t and 4 bytes — **not** `if-testz`).
|
||||
|
||||
**Do this instead: walk the dex structure to the method, then decode.** Resolve class → `class_data_item`
|
||||
→ method (`code_off`) → `code_item` → instruction stream, and decode forward with a complete format
|
||||
table. Then match on *decoded semantics* ("an `iget-boolean p1` immediately followed by `if-nez p1`
|
||||
whose target reads field `X`") rather than on bytes. `scripts/dex_find_insn.py` does this; the
|
||||
decoder in `scripts/dexutil.py` is the reusable part.
|
||||
|
||||
Three details in the walk that silently produce wrong answers:
|
||||
|
||||
- **`class_data_item` member indices are *diffs*.** `field_idx`, `method_idx` are encoded as deltas
|
||||
against the previous entry in the same list and must be accumulated. Reading a raw uleb as an
|
||||
absolute index gives you real-looking wrong members — you will "find" a method that is not the one
|
||||
you asked for and not notice.
|
||||
- **Payload `nop`s are not `nop`s.** dalvik encodes switch/array payloads as `00 <ident> <size>` with
|
||||
`ident` in 1..3. A plain `00 00` is an ordinary one-unit `nop`. Treating every `00` as a payload
|
||||
swallows the next instruction and desynchronises the whole rest of the method.
|
||||
- **The header field order is not what you remember.** After `magic(8) + checksum(4) + signature(20)`,
|
||||
the offsets are `file_size 0x20, header_size 0x24, endian 0x28, link_size 0x2C, link_off 0x30,
|
||||
map_off 0x34, string_ids_size 0x38, string_ids_off 0x3C, type_ids 0x40/0x44, proto_ids 0x48/0x4C,
|
||||
field_ids 0x50/0x54, method_ids 0x58/0x5C, class_defs 0x60/0x64, data 0x68/0x6C`.
|
||||
Print the parsed sizes and compare against the file before trusting anything downstream.
|
||||
|
||||
## Instruction format table (the part that must be right)
|
||||
|
||||
An operand width wrong by one byte desynchronises the decode from that point on, and the failure looks
|
||||
like "the instruction I want does not exist". These are the groups that matter in practice:
|
||||
|
||||
| opcode range | format | code units |
|
||||
|---|---|---|
|
||||
| `01 04 07 0A 0B 0C 0D 0E 0F 10 11 12` | 12x / 11x / 11n / 10x | 1 |
|
||||
| `13 15 16 17 19 1B 20 21 23 24` | 21s/21h/21c/22c/35c/3rc | 2 |
|
||||
| `14 18 1A 22 25 27 28 29 2A 2B` | 31i/31c/31t/30t/20t/switch | 3 |
|
||||
| `02 05 08` | 22x | 2 |
|
||||
| `03 06 09` | 32x | 3 |
|
||||
| `2C`–`31` | 23x | 2 |
|
||||
| **`32`–`37`** | **22t if-test** (2 regs + int16) | **2** |
|
||||
| **`38`–`3D`** | **21t if-testz** (1 reg + int16) | **2** |
|
||||
| `44`–`51` | 23x aget/aput | 2 |
|
||||
| `52`–`5F` | 22c iget/iput | 2 |
|
||||
| `60`–`6D` | 21c sget/sput | 2 |
|
||||
| `6E`–`72` / `74`–`78` | 35c / 3rc invoke | 3 |
|
||||
| `7B`–`8F` | 12x unop | 1 |
|
||||
| `90`–`AF` | 23x binop | 2 |
|
||||
| `B0`–`CF` | 12x binop/2addr | 1 |
|
||||
| `D0`–`D7` | 22s binop/lit16 | 2 |
|
||||
| `D8`–`E2` | 22b binop/lit8 | 2 |
|
||||
|
||||
**Self-check that costs nothing:** decode the whole method and assert you land **exactly** on
|
||||
`insns_off + insns_size*2`. If you overshoot or undershoot, the table is wrong somewhere and every
|
||||
offset you derived is suspect. Also scan the decoded register numbers: a method whose `registers`
|
||||
count is 12 cannot use `v13`, so any `v13+` in the output is proof of desync.
|
||||
|
||||
**Long conditional branches are two instructions.** A conditional jump has a 16-bit displacement, but
|
||||
when you see `if-nez vX, :label` in smali and `:label` is far away, the assembler may have emitted
|
||||
`if-*` followed by a separate `goto`. When hunting a branch, do not assume the pattern is
|
||||
"branch → target"; confirm by decoding.
|
||||
|
||||
## Neutralise a branch, do not redirect it
|
||||
|
||||
Once you have decided which side of a condition you want, the safest edit is to **remove the branch**,
|
||||
not to point it somewhere else.
|
||||
|
||||
| Edit | When it is right | Risk |
|
||||
|---|---|---|
|
||||
| `if-*` → `nop` pair (**preferred**) | You want the **fall-through** path | None. No new control-flow edge is created |
|
||||
| `if-*` → `goto` (+ same displacement) | You want the **branch-taken** path | Introduces an edge. It may land on a `move-result*`, which the verifier rejects |
|
||||
| flip the sense (`if-nez` → `if-eqz`) | Polarity is the only problem | Same edge as above, different destination |
|
||||
|
||||
The `move-result` rule: `move-result*` must be **immediately preceded by its producing invoke** in the
|
||||
instruction stream. A branch whose target is a `move-result` bypasses the producer and the class fails
|
||||
to load with `VerifyError: ... copyRes vN <- result0 type=Undefined`. A linear "is the previous
|
||||
instruction the producer" check does **not** catch this — you need the CFG view: *does any branch
|
||||
target this `move-result`?* `scripts/dex_check_verifier.py` answers that question directly.
|
||||
|
||||
A `nop` pair cannot create that problem, which is why it is the default choice.
|
||||
|
||||
**Polarity is the other silent killer.** Field names lie about intent often enough that you must read
|
||||
the *branch structure*, not the name. In one real case the config field was `enabled`, the smali was
|
||||
`if-nez v, +6`, and the fall-through was `startActivity(main)` while the branch target was the
|
||||
countdown block. So `enabled == true` was the value that *skipped* the promo — the opposite of the
|
||||
literal reading. **Always decode both sides of the branch and name what each one does before editing.**
|
||||
Getting this backwards produces a build that does the exact opposite of the goal and still starts
|
||||
cleanly, so it survives casual testing.
|
||||
|
||||
## The dex header has two integrity fields, and order matters
|
||||
|
||||
Any edit to a dex body invalidates both header integrity fields. Recompute them **in this order**:
|
||||
|
||||
```
|
||||
bytes 12..32 = sha1(data[32:]) # signature first
|
||||
bytes 8..12 = adler32(data[12:]) # checksum last — it covers the signature bytes
|
||||
```
|
||||
|
||||
Writing them in the reverse order produces a header that looks plausible and never verifies, because
|
||||
the adler32 was taken while the signature field was still zeroed.
|
||||
|
||||
**Why this is dangerous rather than merely broken:** Android logs
|
||||
`Failure to verify dex file ...: Bad checksum (computed, expected)` — note that the *real* adler32
|
||||
appears as the "expected" value, which reads backwards — and then falls back to interpreting the dex.
|
||||
The process may still start, but the class loader can fail to resolve ordinary classes
|
||||
(`ClassNotFoundException: <your Application class>`), so the symptom is "the APK I built is broken"
|
||||
rather than "two header fields are stale".
|
||||
|
||||
**Aggravating detail:** some producers ship a dex whose `signature` field is **all zeros** (a known
|
||||
R8/optimiser artifact). On such a file the wrong order is self-consistent until the first patch, so
|
||||
the bug is invisible until you edit something — and then looks like your edit caused it.
|
||||
|
||||
`scripts/dex_patch_bytes.py` recomputes both fields in the correct order and refuses to write if the
|
||||
result does not self-verify.
|
||||
|
||||
## Worked shape of a patch script
|
||||
|
||||
Keep these properties; they are what make the edit auditable a month later:
|
||||
|
||||
1. **Locate by structure + decoded semantics**, never by a hard-coded offset alone.
|
||||
2. **Assert the old bytes** before replacing, and abort on mismatch. A silent mismatch means the
|
||||
sample changed or your understanding did.
|
||||
3. **Equal length in, equal length out.** Assert `len(new) == len(old)`.
|
||||
4. **Recompute both header fields**, then assert `adler32(data[12:]) == header_checksum` and
|
||||
`sha1(data[32:]) == header_signature` on the bytes you are about to write.
|
||||
5. **Re-decode the patched method** and print the instruction you changed, plus confirm the
|
||||
instruction that should follow it still does. Two instructions of output is enough to catch the
|
||||
"landed on the wrong site" class.
|
||||
6. **Report the size delta** (should be 0) and before/after hashes of both the dex and the APK.
|
||||
|
||||
## Verification specific to byte patches
|
||||
|
||||
`patch-audit.md` covers the general audit. Two checks matter more here:
|
||||
|
||||
- **Assert the instruction count and every branch target are unchanged.** Compare a decoded listing of
|
||||
the whole method before and after: same instruction count, same offsets, same targets. If the count
|
||||
changed, you replaced a 4-byte instruction with a 4-byte *pair* and the extra decode boundary is
|
||||
expected — but say so explicitly rather than letting a diff tool surprise the next reader.
|
||||
- **`VerifyError` is a class-load failure, not a startup failure.** If the app starts and one screen
|
||||
is dead, or a secondary class is missing, suspect a verifier violation in the method you edited.
|
||||
`logcat` shows it as `E/dalvikvm` or `E/art` with the class name; it does not always surface as a
|
||||
crash dialog.
|
||||
|
||||
## When not to use this technique
|
||||
|
||||
- The change needs new instructions, a new register, or a different call — go to method rewriting.
|
||||
- The change is a **short string constant** whose new value is a different length — you cannot grow the
|
||||
string in place. Equal-length string swaps work (`pitfalls.md` P2 on the string-id ordering guard);
|
||||
different-length values need `dex_strpatch`-class tooling or a rebuild.
|
||||
- The target is a **multi-dex** app and you intend to move code between dexes. Byte patching stays
|
||||
inside one dex by definition.
|
||||
@@ -0,0 +1,220 @@
|
||||
# Code Virtualization & Custom Linkers
|
||||
|
||||
Load this when recon says **there is no packer** (the manifest's `application` is the app's own
|
||||
class, dex is readable) and yet a re-signed build dies before your code runs — especially when the
|
||||
death is `SIGSEGV fault addr 0x0` with all registers zero.
|
||||
|
||||
This is the layer between "packed" and "clean". `packers.md` covers a shell that owns
|
||||
`Application`; this file covers protection that leaves `Application` alone and instead
|
||||
**turns individual methods into native code** and hosts a private loader next to them. It is now
|
||||
common enough that treating it as "no packer, therefore easy" is the most expensive recon error
|
||||
in this skill's history.
|
||||
|
||||
## Identification — three cheap tells
|
||||
|
||||
1. **Whole classes whose methods are `native` declarations with no implementation.**
|
||||
Read the smali for the entry Activity / engine host class. Under code virtualization the
|
||||
*entire class* is converted — lifecycle callbacks, getters, everything — each becoming a bare
|
||||
`.method public native ...` with no body. A framework class you *know* ships a Java
|
||||
implementation (a Flutter/Unity/RN host class is the usual victim) sitting there fully
|
||||
`native` is the signal.
|
||||
|
||||
Two `native` methods is normal (JNI). **Sixty is virtualization.**
|
||||
|
||||
2. **A registration call in the class's static initializer.** Someone binds those native
|
||||
declarations to an implementation at class-load time:
|
||||
|
||||
```
|
||||
.method static constructor <clinit>()V
|
||||
invoke-static {v0, v1}, L<somewhere>/DtcLoader;->registerNativesForClass(ILjava/lang/Class;)V
|
||||
invoke-static {v1}, L<somewhere>/hidden/Hidden0;->special_clinit_0_00(Ljava/lang/Class;)V
|
||||
```
|
||||
|
||||
The `Hidden0.special_clinit_*` family is the virtualizer's hook for running its own version of
|
||||
the class initializer. When you see this, the Java in that class **is not what executes**.
|
||||
|
||||
3. **A shipping library whose SONAME does not match its filename.** A private loader is often
|
||||
named for its role while sitting under an innocuous filename. Read `DT_SONAME` from
|
||||
`.dynamic`, not the file name — `probe_deps`-style parsing of `PT_DYNAMIC` (see
|
||||
`native-tamper-and-suicide.md` §Forged section headers) gives you the truth. A `lib<something>.so` claiming
|
||||
`soname = liblinkerloader.so` is a private ELF loader.
|
||||
|
||||
Supporting tells: `assets/` carrying a small text descriptor naming the protector and its version;
|
||||
native libraries woven into `DT_NEEDED` chains of other libraries (the virtualized code has to be
|
||||
reachable); log lines tagged with the loader's own name appearing during startup.
|
||||
|
||||
## The deadlock that eats hours — and the way out
|
||||
|
||||
A virtualizer that also does integrity checking produces this shape:
|
||||
|
||||
| Action | Result |
|
||||
|---|---|
|
||||
| Keep the private loader in the APK | its embedded validation runs → deliberate crash on a re-signed build |
|
||||
| Delete the private loader | the virtualized class has **no implementation at all** → `UnsatisfiedLinkError: dlopen failed: library "…" not found` |
|
||||
|
||||
Both routes die, and the two failures look nothing alike, so it is easy to conclude the target is
|
||||
impossible. It is not. The way out is one question:
|
||||
|
||||
> **Is that library the checker, or the implementation — and who asks for it?**
|
||||
|
||||
## Separate the checker from the implementation
|
||||
|
||||
Two distinct roles hide behind "a protected library":
|
||||
|
||||
- **The implementation** — the native code that *is* the virtualized class. It must be present and
|
||||
loaded, or the class cannot work.
|
||||
- **The checker** — a validation payload (a signature/integrity payload, a second-stage
|
||||
self-decrypting image) that something *explicitly loads*.
|
||||
|
||||
They are frequently **different libraries**, and the load of the checker is frequently a
|
||||
**single, findable call site** — not a link-time dependency.
|
||||
|
||||
Test which is which before designing a fix:
|
||||
|
||||
```
|
||||
# 1. Does anything name it in DT_NEEDED? Parse PT_DYNAMIC of every shipped .so.
|
||||
# No DT_NEEDED referrer => it is dlopen()ed, i.e. named at some call site.
|
||||
# 2. Delete it and read the exact error: which class/method was executing when the
|
||||
# load failed? That is the caller.
|
||||
```
|
||||
|
||||
In the observed case the error was not "the class is missing" but:
|
||||
|
||||
```
|
||||
java.lang.UnsatisfiedLinkError: dlopen failed: library "lib<checker>.so" not found
|
||||
at java.lang.System.loadLibrary(System.java)
|
||||
at <framework host class>.onCreate(Native Method)
|
||||
```
|
||||
|
||||
Read that stack carefully: the **virtualized** `onCreate` — the very code you feared deleting the
|
||||
library would break — is running fine. It is the *checker* that is absent. The implementation lives
|
||||
elsewhere and was never the problem.
|
||||
|
||||
**That single stack frame converts an impossible target into a trivial one.**
|
||||
|
||||
## Technique: redirect the load by rewriting a string constant
|
||||
|
||||
Once you know the checker is named at a call site, you do not need to patch code, hook anything, or
|
||||
neutralize a crash. **Change what that call site loads.**
|
||||
|
||||
JNI-heavy native code keeps its class/method/string operands in a constant pool inside the library.
|
||||
A `loadLibrary("X")` becomes three facts sitting in `.rodata`/`.data`:
|
||||
|
||||
```
|
||||
… onCreate (Landroid/os/Bundle;)V loadLibrary (Ljava/lang/String;)Ljava/lang/String; …
|
||||
… <SomeUnrelatedClassName> X <unrelated constant> …
|
||||
```
|
||||
|
||||
Find the name as an **isolated NUL-terminated string** and rewrite it **in place, same length** to
|
||||
the name of a library that is *guaranteed already loaded*. On Android, `android` (`libandroid.so`)
|
||||
is reliably mapped — the protected libraries themselves depend on it.
|
||||
|
||||
```
|
||||
apkhuan -> android (7 chars -> 7 chars)
|
||||
```
|
||||
|
||||
Why this is disproportionately effective:
|
||||
|
||||
- **Equal length means zero structural change.** No offsets move, no section resizes, the ELF stays
|
||||
exactly as valid as it was. Nothing for an integrity check to notice about *layout*.
|
||||
- **The load succeeds**, so no `UnsatisfiedLinkError` and no error branch anywhere.
|
||||
- **The checker never gets mapped**, so none of its validation runs — the signature payload, the
|
||||
deliberate-crash payload, all of it becomes dead weight in the APK.
|
||||
- **You never patch a death path**, so the whole `native-tamper-and-suicide.md` rule set (make it
|
||||
*return*, don't make it *not return*) never comes into play. There is nothing to neutralize.
|
||||
|
||||
Requirements and hazards:
|
||||
|
||||
1. **Same byte length is not optional.** Replacing with a shorter/longer name shifts everything
|
||||
after it. Pad only within the same NUL-terminated slot; never spill into the next constant.
|
||||
2. **Verify the string is an isolated constant** — the byte before and after must be `\x00`.
|
||||
A substring of a longer identifier will corrupt that identifier.
|
||||
3. **The replacement must be loadable and already-loaded.** A nonexistent name throws and puts you
|
||||
back in the deadlock; a heavy library changes startup cost.
|
||||
4. **Scan the whole file** for the name, then confirm which occurrence sits in the constant pool.
|
||||
Report the offset in the patch record.
|
||||
|
||||
`scripts/so_constpatch.py` implements this: finds isolated constants, enforces equal length, writes
|
||||
a patched copy, and prints the byte-diff.
|
||||
|
||||
This is one member of a general family — **redirect a reference instead of defeating a check** —
|
||||
and the same shape recurs for class names, method names and file paths in a constant pool.
|
||||
|
||||
## Expected log shapes
|
||||
|
||||
A private loader announces itself. These strings come from the loader, not from the app, and their
|
||||
presence/absence across builds is a usable signal:
|
||||
|
||||
```
|
||||
I/<Loader>: Loading embedded protected image from carrier (self)
|
||||
I/<Loader>: Found embedded protected image at offset 0x…, logical size 0x…
|
||||
E/<Loader>: Invalid ELF magic <-- appears ONLY on a modified build
|
||||
D/<Loader>: ELF Header: type=3, machine=183, entry=0x0, phnum=N
|
||||
D/<Loader>: Starting PrelinkImage for embedded_protected
|
||||
```
|
||||
|
||||
A custom container magic at the tail of the library (a four-byte tag, not `\x7fELF`) marks the
|
||||
embedded image; `entry=0x0` plus `SIGSEGV fault addr 0x0` is the loader failing to decrypt its
|
||||
payload and jumping to a zero entry. Treat "`Invalid ELF magic` appears on my build and not on the
|
||||
original" as **proof the loader is validating the build**, which is exactly what makes the
|
||||
string-redirect route worth trying.
|
||||
|
||||
## What the native check actually reads — measure it, don't guess
|
||||
|
||||
A validation payload that reads "the signature" can be reading several different things, and the
|
||||
answer decides whether *any* repack route exists:
|
||||
|
||||
| It reads | Consequence |
|
||||
|---|---|
|
||||
| the certificate material **inside the APK** | keeping the original signature block while swapping code can pass |
|
||||
| the signature **PackageManager reports** | that trick fails; you must remove the check (this file's technique) or rebuild |
|
||||
| an entry **hash** of the whole file | only the string-redirect / check-removal route survives |
|
||||
|
||||
**Single-variable experiment to tell them apart.** Same APK content both times; flip only the
|
||||
PMS-recorded signature:
|
||||
|
||||
1. Install a build **you signed** normally, so PMS records *your* certificate.
|
||||
2. Root-overwrite that installed `base.apk` with your candidate (one whose *internal* signature
|
||||
block is the original), leaving PMS's record untouched.
|
||||
3. Launch.
|
||||
|
||||
Dies ⇒ the check reads the PMS-reported signature, and preserving in-APK certificate material
|
||||
cannot save you. Survives ⇒ it reads in-APK material, and a "keep the original signature block"
|
||||
route is worth investing in.
|
||||
|
||||
Do this **before** investing in elaborate signature-block plumbing. It is two installs.
|
||||
|
||||
## A Java-layer "signature killer" is a decoy
|
||||
|
||||
A protection bundle may ship a Java class that hooks `PackageManager` so the framework reports a
|
||||
hardcoded certificate, and log `Signature consistency ok` forever — including on your modified
|
||||
build. This is an **anti-tamper feature aimed at other patchers**, not a gate you must satisfy.
|
||||
|
||||
Its corollary is what matters operationally: **`Signature consistency ok` in the log proves
|
||||
nothing.** Do not let a green Java-layer message talk you out of the fact that the process is
|
||||
dying, or send you hunting for a Java signature check. If the death is `SIGSEGV` with a zero
|
||||
program counter, the check that killed you is native and the Java one is irrelevant.
|
||||
|
||||
Two practical notes:
|
||||
|
||||
- **Do not delete such a class to "clean up".** It usually participates in the `Application`
|
||||
inheritance chain; removing it breaks startup and trips unrelated class-hierarchy checks.
|
||||
- Its presence is a strong hint that **the code that matters is virtualized**, because it exists to
|
||||
survive exactly the kind of repack you are attempting.
|
||||
|
||||
## Verification
|
||||
|
||||
A string-redirect fix is verified by the **absence of the loader**, not by the absence of an error:
|
||||
|
||||
1. Loader's log tag count in a full cold-start capture = **0** (previously non-zero).
|
||||
2. `Invalid ELF magic` = 0.
|
||||
3. `SIGSEGV` = 0 **and** `SIGSYS`/seccomp kills = 0 — the secondary kill paths the payload carried
|
||||
disappear with it. A drop from 1 to 0 here is a real result worth recording.
|
||||
4. Process survives past the previously measured time-to-death, on this machine, with nothing
|
||||
attached; then survives real interaction.
|
||||
5. The features that class implements still work — the virtualized code is the *implementation*, so
|
||||
exercise it (start playback, navigate, whatever it owns). A build that starts but whose
|
||||
virtualized feature is dead is not a result.
|
||||
|
||||
Record the original and patched bytes, the offset, and the loader log counts before/after in the
|
||||
patch record — the same audit standard as any other byte-level edit.
|
||||
@@ -0,0 +1,254 @@
|
||||
# Dart AOT (Flutter) — reaching the layer that actually owns the logic
|
||||
|
||||
Load this when: the target is a Flutter app (`libflutter.so` + `libapp.so`) and the behaviour you
|
||||
must change is decided **inside** the Dart snapshot, not in the dex. The Java side of a Flutter app
|
||||
is a thin plugin shell; a dex-only plan will stall (`framework-runtimes.md` §the layer trap).
|
||||
|
||||
Everything below assumes you already confirmed the runtime is Flutter and that Java hooks fire
|
||||
**zero times** while the UI plainly works.
|
||||
|
||||
---
|
||||
|
||||
## 1. Pin the Dart version before choosing any tool
|
||||
|
||||
The snapshot format is version-specific. A decompiler built for another Dart version may run and
|
||||
produce plausible-but-wrong output, which is worse than failing.
|
||||
|
||||
```python
|
||||
import re
|
||||
blob = open('libflutter.so', 'rb').read() # the engine, not libapp.so
|
||||
m = re.search(rb'(\d+\.\d+\.\d+ \(stable\)[^\x00]{0,60})', blob)
|
||||
print(m.group(1).decode() if m else 'not found') # e.g. b'3.9.0 (stable) (Mon ...) on "android_arm64"'
|
||||
```
|
||||
|
||||
If the string is absent, fall back to the snapshot hash the loader reports at runtime, or to the
|
||||
engine build id in `libflutter.so`'s version string.
|
||||
|
||||
## 2. Get a decompiler that matches that version
|
||||
|
||||
**blutter** is the practical choice for Android `libapp.so` (arm64). It reconstructs the object pool
|
||||
and per-class declarations. It is a *source tree you build*, not a binary you download — and its
|
||||
prebuilt outputs only cover the Dart versions someone already built.
|
||||
|
||||
The version question is the first obstacle, and it has a clean answer:
|
||||
|
||||
- blutter's git HEAD typically supports newer Dart than its shipped `dartsdk/` directory.
|
||||
- When the target's version is missing, blutter fetches it itself: it sparse-clones
|
||||
`dart-lang/sdk` at that version tag (only `runtime`, `tools`, `third_party/double-conversion`),
|
||||
generates a source list, and builds a `dartvm` static library for the target ABI.
|
||||
- That build needs a real toolchain: `cmake` (>=3.20 is fine, including 4.x), `ninja`, `git`, and a
|
||||
C++ compiler with C++20 `<format>` support (VS 2022 on Windows, gcc>=13 / clang>=16 elsewhere).
|
||||
A `vcvars64`-style environment must be active before the build, and `CMakeLists` in the tree pins
|
||||
`cmake_minimum_required(3.20)`.
|
||||
- Budget **tens of minutes** for the first build of a new version and run it as a background job;
|
||||
the compiler log is enormous (per-file include trees), so read only its tail.
|
||||
|
||||
Outputs of interest:
|
||||
|
||||
| Output | What it gives you | What it does *not* give |
|
||||
|---|---|---|
|
||||
| `pp.txt` | every object-pool entry with its `pp+0x…` offset: strings, types, closures, fields, stubs | who references what |
|
||||
| `objs.txt` | reconstructed object shapes with type annotations | code |
|
||||
| `asm/` | per-class declarations | **instructions — there are none here** |
|
||||
| `ida_script/`, `blutter_frida.js` | symbol/annotation helpers | a finished analysis |
|
||||
|
||||
> `asm/` having one file per (obfuscated) class invites the assumption that it holds disassembly.
|
||||
> It does not. Do not plan around it.
|
||||
|
||||
**`product` builds carry no debug info.** Expect `no-code_comments`, no function names, and
|
||||
obfuscated identifiers. That is normal; the strings still survive (see §7).
|
||||
|
||||
## 3. The object pool is the whole game
|
||||
|
||||
Dart AOT uses **compressed pointers**: heap references are 32-bit offsets from a base held in a
|
||||
dedicated register. Constants, strings, types, closures and field metadata live in one contiguous
|
||||
**object pool**, reached through that register.
|
||||
|
||||
Two offset spaces exist and they are **not the same number** — mixing them wastes hours:
|
||||
|
||||
- **PP offsets** (`pp+0x…`) — what `pp.txt` and every pool-load in disassembly use.
|
||||
- **file offsets** — where a byte actually sits in `libapp.so` on disk.
|
||||
|
||||
Keep the mapping explicit in your notes. When a tool reports "this string is at X", state which
|
||||
space X is in.
|
||||
|
||||
## 4. Build your own reference index (blutter will not give you this)
|
||||
|
||||
`pp.txt` tells you what is in the pool. To *find the code that uses it* you need pool-offset →
|
||||
referencing-instruction-address. Generate it once, then query it constantly:
|
||||
|
||||
```
|
||||
python dart_pprefs.py libapp.so pp_refs.json
|
||||
python dart_pprefs.py --lookup pp_refs.json 0x1d1a8 0xc9d0
|
||||
```
|
||||
|
||||
**Do not build this index with a full-capstone pass.** Decoding every instruction of a multi-MB
|
||||
`.text` with `detail=True` and querying `regs_access()` per instruction costs minutes of CPU and
|
||||
1–2 GB of peak memory, and on a 16 GB host it presents as a hang with no progress output. Only three
|
||||
encodings can read the pool, so decode them from the raw 32-bit words instead — the shipped script
|
||||
does exactly that and finishes in seconds. The same argument applies to building a call graph
|
||||
(§9): decode `B`/`BL` arithmetically.
|
||||
|
||||
## 5. What the registers mean
|
||||
|
||||
Stable across Dart 3.x arm64 AOT. Verify once on a known function, then rely on it.
|
||||
|
||||
| Register | Role |
|
||||
|---|---|
|
||||
| `x27` | **object pool base (PP)** — every constant/string/type load goes through it |
|
||||
| `x26` | current thread (`[x26,#0x38]` stack limit, `[x26,#0x68]` isolate group) |
|
||||
| `x28` | heap base — how compressed pointers are decompressed |
|
||||
| `x22` | **null/base for booleans** (see §6) |
|
||||
| `x15` | Dart's own stack pointer (not the system SP) |
|
||||
| `x21` | class dispatch table (virtual calls load a target from it) |
|
||||
|
||||
## 6. Booleans are not 0/1
|
||||
|
||||
`true` and `false` are objects immediately adjacent to null, so they appear as small fixed offsets
|
||||
from `x22`:
|
||||
|
||||
```asm
|
||||
add x0, x22, #0x20 ; construct TRUE
|
||||
add x0, x22, #0x30 ; construct FALSE
|
||||
tbnz w0, #4, <label> ; test bit 4 of the value
|
||||
tbz w0, #4, <label>
|
||||
```
|
||||
|
||||
The bit-4 test is the standard "is this the false object" check, and it is the cheapest place to
|
||||
force a decision: replacing the conditional branch with an unconditional one, or replacing a
|
||||
constructed constant, flips the outcome without changing structure.
|
||||
|
||||
## 7. String encoding — get this exactly right
|
||||
|
||||
Pool string entries are serialized as:
|
||||
|
||||
```
|
||||
[ tag byte ][ payload ]
|
||||
|
||||
tag = 0x80 | (len << 1) | two_byte_bit
|
||||
```
|
||||
|
||||
- **one-byte strings** (ASCII / Latin-1): `payload` is the raw bytes.
|
||||
- **two-byte strings**: `payload` is **UTF-16LE**.
|
||||
|
||||
Consequences that decide whether your search works:
|
||||
|
||||
- An **ASCII** literal (`/api/foo`, `isVip`, a URL) is found by a **UTF-8 byte search**. It is a
|
||||
one-byte string — searching UTF-16 for it will miss.
|
||||
- A **CJK / non-Latin** literal is a two-byte string: a UTF-8 search returns **zero**, a UTF-16LE
|
||||
search hits. This is the case that makes people wrongly conclude "the strings were stripped".
|
||||
- Therefore: **search ASCII as UTF-8 and non-ASCII as UTF-16LE**, rather than forcing one encoding
|
||||
on everything. (This is the concrete form of `pitfalls.md` P25.)
|
||||
- A raw byte scan for the tag pattern finds many false candidates. Accept a candidate only when
|
||||
entries **chain** — the previous entry's `tag+payload` must end exactly where the next candidate
|
||||
begins. Without that constraint you get order-of-magnitude more garbage than strings; a
|
||||
per-byte scan of a multi-MB snapshot once produced ~880k "strings" of which essentially all were
|
||||
misaligned noise, and a "no such feature present" conclusion was drawn from it.
|
||||
|
||||
```
|
||||
python dart_pool_strings.py libapp.so strings.tsv --min 3
|
||||
```
|
||||
|
||||
## 8. Reading AOT code: three signatures that carry most of the weight
|
||||
|
||||
Once you can disassemble a window with pool annotations, most business logic resolves into these
|
||||
shapes.
|
||||
|
||||
**A — reading a map / JSON object (`map[key]`)**
|
||||
```asm
|
||||
ldur x3, [x29, #-8] ; the Map
|
||||
ldur x0, [x3, #-1] ; compressed class id sits at offset -1
|
||||
ubfx x0, x0, #0xc, #0x14 ; decode class id
|
||||
mov x1, x3
|
||||
... x2 = <pool string> ; <- the key, annotated by your pool map
|
||||
add x30, x0, #0x342
|
||||
ldr x30, [x21, x30, lsl #3]
|
||||
blr x30 ; this is map[key]
|
||||
```
|
||||
Remember the quartet: `ldur [..,#-1]` + `ubfx #0xc,#0x14` + `add x30,x0,...` + `blr`.
|
||||
|
||||
**B — writing a map (`map[key] = value`)**
|
||||
```asm
|
||||
... x16 = <pool string> ; the key
|
||||
stur w16, [x0, #0xf] ; key stored into the freshly built map
|
||||
... ; then the value at the next slot
|
||||
```
|
||||
`stur` writes, `blr` reads. Confusing the two means patching a serializer that never touches the UI.
|
||||
|
||||
**C — function entry**
|
||||
```asm
|
||||
stp x29, x30, [x15, #-0x10]!
|
||||
mov x29, x15
|
||||
sub x15, x15, #0x20
|
||||
ldr x16, [x26, #0x38]
|
||||
cmp x15, x16
|
||||
b.ls <stack-overflow handler>
|
||||
```
|
||||
Use this to find function boundaries when you need to delimit one.
|
||||
|
||||
## 9. The locating workflow
|
||||
|
||||
1. **Anchor on a string.** Search the pool for the shortest distinctive token — a field name, an
|
||||
endpoint path, a label. Prefer identifiers over sentences (a sentence may be assembled from
|
||||
fragments).
|
||||
2. **Find its referencing instructions** via your index (§4).
|
||||
3. **Disassemble a window** around each reference with pool annotations:
|
||||
```
|
||||
python dart_disasm.py libapp.so --pp pp.txt --refs pp_refs.json 0x26e390
|
||||
python dart_disasm.py libapp.so --pp pp.txt --refs pp_refs.json --range 0x64f310 0x64f3e0
|
||||
```
|
||||
4. **Classify the site**: read (A) or write (B)? For writes, check whether the value is a constant
|
||||
from the pool — that is a "send this flag" site, not a "decide locally" site.
|
||||
5. **Walk outward.** Find the enclosing function entry (§8C), then find its callers:
|
||||
```
|
||||
python dart_disasm.py libapp.so --index callers.json --build-index
|
||||
python dart_disasm.py libapp.so --index callers.json 0x26e230
|
||||
```
|
||||
6. **Cross-validate by clustering.** Related strings usually sit **adjacent in the pool** and are
|
||||
referenced from **adjacent code**. If two field names are a few bytes apart in the pool and their
|
||||
reference sites are a few instructions apart, you are looking at one coherent piece of logic —
|
||||
strong evidence you are in the right place.
|
||||
|
||||
## 10. Patching this layer
|
||||
|
||||
- **Prefer changing the data source over the decision point.** Locate the chain
|
||||
"read field from map → type conversion → store to stack slot" and replace the middle with a load
|
||||
of a pool constant. One edit then feeds every consumer, instead of chasing each comparison. This
|
||||
has produced clean results where per-condition patches did not.
|
||||
- **Boolean sites** are the cheapest: `tbnz`/`tbz` → `nop` (always fall through) or → an
|
||||
unconditional branch; `add xD, x22, #0x20` ↔ `#0x30` to flip a constructed constant.
|
||||
- **A pool string may be shared.** Before editing one, count its references. If the same entry is
|
||||
read by several sites, changing it changes all of them — self-consistent and therefore useless
|
||||
for splitting behaviour. Prefer editing code over shared data.
|
||||
- **Assert your addresses.** Patch with the original bytes asserted first and re-read the result
|
||||
afterwards; an address that is off by one instruction will happily corrupt a snapshot into
|
||||
something that still loads.
|
||||
- **`libapp.so` inside an APK is usually deflate-compressed**, so in-place byte patching of the zip
|
||||
entry is not possible — patch the extracted file, then replace the whole entry
|
||||
(`repack-and-sign.md`).
|
||||
|
||||
## 11. Traps specific to this layer
|
||||
|
||||
- **Identifiers are ambiguous across layers.** A pool string that reads like a domain concept can
|
||||
belong to a standard library or a wire protocol instead. A near-miss example worth remembering:
|
||||
the token `expires` resolved to HTTP **response-header** parsing (its siblings were `date`,
|
||||
`host`, `connection`), not to a subscription expiry field. **Read the surrounding strings and the
|
||||
code shape before assigning meaning** — one misleading identifier can send a whole analysis down
|
||||
the wrong branch.
|
||||
- **Obfuscated names are not identities.** Symbol names are mangled (`_abc@12345` shapes are
|
||||
common) and change between builds. String literals do survive, so anchor on those.
|
||||
- **Clusters reveal structure.** Adjacent pool entries plus adjacent reference sites indicate one
|
||||
subsystem; use it to avoid guessing what a function is for.
|
||||
- **A write-only flag is usually an outbound parameter, not a local switch.** If a string is
|
||||
referenced exactly once, at a site that stores a constant into a map that is then sent, the client
|
||||
is *reporting* a value — changing it does not change local behaviour. Confirm whether the value is
|
||||
ever read before treating it as a gate.
|
||||
- **Full-file disassembly is not a debugging tool** (§4). Windowed disassembly is.
|
||||
|
||||
## 12. Verification
|
||||
|
||||
Static: asserted patch bytes, re-read from the built artifact, plus structural checks
|
||||
(`verification.md`). Runtime: the changed behaviour must be observed in the app's own UI — for this
|
||||
layer that means an actual launch, because nothing about Dart AOT code proves itself statically.
|
||||
If the snapshot drives a decision that a server also enforces, see `membership-and-limits.md`:
|
||||
getting the client side right does not make the outcome reachable.
|
||||
@@ -0,0 +1,133 @@
|
||||
# Detection, anti-analysis, and when to stop fighting it
|
||||
|
||||
Load this when the app fights back: it dies or misbehaves after you attach, refuses to run on your
|
||||
device, detects root/emulator/hook/debugger, or when your dynamic tool simply will not work on the
|
||||
environment you have.
|
||||
|
||||
This file is a **decision** file, not a bypass catalogue. The expensive mistake it exists to prevent is
|
||||
spending hours escalating against a detection layer when a cheaper route — usually static — was
|
||||
available the whole time.
|
||||
|
||||
## Step 0: the cheapest decision in this file
|
||||
|
||||
**Dynamic analysis is a convenience, not a prerequisite.** Everything that ends in an installable
|
||||
artifact is decided statically: you edit a file and repackage. Dynamic work is how you *find* things,
|
||||
and it is often the fastest way — but when it is blocked or unavailable, the correct move is usually to
|
||||
switch to static, not to escalate.
|
||||
|
||||
So before doing anything clever, ask:
|
||||
|
||||
1. Is the thing I still need to learn actually discoverable statically? (Strings, code structure,
|
||||
call sites, comparisons — usually yes.)
|
||||
2. Do I need the process to run *to verify*, or only to *find*? Verification can often be done by
|
||||
observing the shipped artifact's behaviour, which a hostile process still exposes.
|
||||
|
||||
If either answer allows a static path, take it and stop reading this file.
|
||||
|
||||
## Step 1: is it detection, or is it your environment?
|
||||
|
||||
Detection has a distinctive shape: **it is reproducible, tied to your instrumentation, and absent in the
|
||||
same app run without it.** Everything else that looks like detection is usually one of these:
|
||||
|
||||
| Looks like detection | Usually is | How to tell |
|
||||
|---|---|---|
|
||||
| app dies right after attach | hook timing, a bad script, or a genuine RASP layer | run the same app with **no** hooks: alive? then it is your instrumentation or a hooking detector |
|
||||
| app refuses to start at all | ABI mismatch, missing native lib for this device, install problem | check the live mapping (`scripts/lib_map.py`) and that a clean unmodified build starts |
|
||||
| app exits on this device only | emulator/root detection, **or** a device-state problem | run preflight; try the same build on a different device class |
|
||||
| app hangs forever | a frozen thread from a bad patch, or a real ANR | `pitfalls.md` P7 and the "never make it not return" rule |
|
||||
| dynamic tool "cannot attach" | **the tool cannot work on this environment at all** | see Step 3 — this is the one people waste days on |
|
||||
|
||||
**Rule: reproduce with the control first.** Instrumentation-free run, then instrumented run, same
|
||||
build. That single comparison separates "the app detects me" from "my tooling is broken", and it takes
|
||||
one round.
|
||||
|
||||
## Step 2: if it *is* detection, decide by cost, not by pride
|
||||
|
||||
Three legitimate outcomes. Pick one deliberately and say which you picked.
|
||||
|
||||
**A. Work around it — only when the workaround is small and stable.**
|
||||
Worth it when the detector is a simple, localised check you can neutralise in one place, and the
|
||||
workaround lives in *your* environment rather than in the shipped artifact. Examples of the class:
|
||||
running on a device the app does not object to, using a build that satisfies the check, or a single
|
||||
one-line gate in a helper. Also legitimate: naming the artefact differently, using a different device
|
||||
profile, or simply doing the work on a device that the app accepts.
|
||||
|
||||
**B. Change route.** When the workaround is a moving target, switch to static analysis and stay there.
|
||||
This is the right answer more often than it feels like. Hooking-detection especially tends to escalate:
|
||||
each hide provokes a stronger check, and you end up maintaining a cat-and-mouse setup that is worth
|
||||
nothing at delivery time.
|
||||
|
||||
**C. Accept and report.** If the detection blocks the *deliverable* rather than your analysis — for
|
||||
example, the app verifies something the user's device will not have — then the honest output is a
|
||||
statement of what is blocked, with the evidence. Do not ship a build whose only purpose is to defeat a
|
||||
detector you were not asked about.
|
||||
|
||||
**Signal to stop escalating:** you have spent more effort on the analysis environment than on the
|
||||
change the user asked for. That is the drift this skill treats as most expensive, in its runtime form
|
||||
(`long-task-discipline.md` §the most expensive drift).
|
||||
|
||||
## Step 3: when the tool cannot work here at all
|
||||
|
||||
Some environments cannot run a given dynamic tool, and no amount of trying will change that. Recognise
|
||||
it and move on — this is a *finding about the environment*, and recording it prevents the next person
|
||||
from repeating the attempt.
|
||||
|
||||
**The instructive class: an emulator that executes a different architecture than it reports.** A device
|
||||
may advertise one ABI while the process runs libraries of another through a translation layer. This
|
||||
shows up as a tool that reports the device is fine, then fails to attach, attach-and-die, or attach and
|
||||
see nothing. Symptoms worth treating as a hard signal:
|
||||
|
||||
- the tool's own attach path fails with an error that mentions tracer, ptrace, or a debugger — on an
|
||||
environment where translation is in play;
|
||||
- attaching kills the process immediately, repeatedly, with no Java stack;
|
||||
- the tool attaches but **no** hook ever fires, including hooks on code you know runs.
|
||||
|
||||
**Do not spend the session proving it is impossible.** Establish it once, with one clean reproduction,
|
||||
write the environment fact down, and switch to static.
|
||||
|
||||
**What to do instead:** the entire static toolchain is architecture-agnostic — string tables, code
|
||||
structure, call-site counts, byte-level patching. None of it needs the app to run. If your verification
|
||||
also needed the app to run, use the device-level observables instead: does the UI change, do the logs
|
||||
fall silent, does a file appear or stop appearing. Those are properties of the shipped artifact, and they
|
||||
do not care that you could not attach.
|
||||
|
||||
## Step 4: what a detection layer means for the deliverable
|
||||
|
||||
Two distinct questions — keep them separate, because conflating them produces either a broken artifact
|
||||
or an unnecessary retreat.
|
||||
|
||||
1. **Does it block your analysis?** → handle with Step 2/3. This is your problem, and it is temporary.
|
||||
2. **Will it block the patched build on the user's device?** → this is a property of the artifact. A
|
||||
root check that merely requires an unrooted device is usually irrelevant to a repackaged APK. A
|
||||
**self-integrity or signature check** is a different matter entirely, and it belongs to
|
||||
`references/native-tamper-and-suicide.md` and `references/signature-derived-keys.md`.
|
||||
|
||||
Ask explicitly: *does this check fire because of how the app is built, or because of where I am running
|
||||
it?* Only the first kind follows your build into delivery.
|
||||
|
||||
**Root is an environment fact, not a defeat.** "Runs only on a rooted device" is a legitimate analysis
|
||||
environment and an illegitimate deliverable when the request was an installable build for a normal phone.
|
||||
Say which one you actually have.
|
||||
|
||||
## Step 5: keep a one-line environment fact
|
||||
|
||||
When you conclude that something cannot be done in this environment, write one line in the task record:
|
||||
|
||||
```
|
||||
cannot: <tool/technique> in <environment> because: <observed failure> route taken: <alternative>
|
||||
```
|
||||
|
||||
That single line is what saves a future round. It is also the difference between "we could not attach,
|
||||
so we did X" and an unqualified "dynamic analysis is impossible", which is a claim you have not earned
|
||||
and which will mislead the next reader.
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Controlled the comparison: same build with and without instrumentation
|
||||
- [ ] Preflight run, so device state is excluded before blaming a detector
|
||||
- [ ] Classified: detection vs environment vs my own tooling
|
||||
- [ ] Chose A/B/C deliberately and can say which, and why
|
||||
- [ ] If the tool cannot work here: established it **once**, recorded the fact, switched route
|
||||
- [ ] Separated "blocks my analysis" from "blocks the deliverable"
|
||||
- [ ] Nothing in the shipped artifact exists solely to fool a detector
|
||||
- [ ] Recorded the one-line environment fact if a route was closed
|
||||
@@ -0,0 +1,195 @@
|
||||
# Dex patching — choosing and executing the surgical edit
|
||||
|
||||
The single most important decision in a patch task. Get this wrong and you produce an APK that assembles perfectly and dies at runtime.
|
||||
|
||||
## Pick the least destructive technique that can express your change
|
||||
|
||||
Ordered from safest to most dangerous.
|
||||
|
||||
| # | Technique | Expresses | Structure risk | Use when |
|
||||
|---|---|---|---|---|
|
||||
| 1 | **dexlib2 method-level rewrite** | Replace a method's implementation (return a constant, no-op, emit a fixed value) | **Lowest** — only the target `code_item` changes | Default choice. Any behavior change that can be expressed as "this method now does X instead" |
|
||||
| 2 | **Byte-level string constant patch** | Change a string literal to another of **equal length** | Medium — must preserve `string_ids` ordering (see P2) | Renaming a path/key/protocol token |
|
||||
| 3 | **Resource / asset edit** | Change a config file, JSON, image, or bundled jar | Low (no dex change) | The behavior is data-driven |
|
||||
| 4 | **Manifest edit** | Disable a component, drop a permission, flip a flag | Low, but re-signing required | Turning off a service/receiver/activity |
|
||||
| 5 | **Whole-tree smali round-trip** | Arbitrary code edits | **High** — breaks R8 output (see P3) | Last resort, and verify by running |
|
||||
|
||||
**Do not reach for #5 because it is familiar.** It is the most likely to produce a broken build.
|
||||
|
||||
## Where to patch: pick the layer, not the symptom
|
||||
|
||||
Ads and gates can be suppressed at several layers. Higher in this list = smaller blast radius.
|
||||
|
||||
| Layer | What it looks like | Example | Risk |
|
||||
|---|---|---|---|
|
||||
| **SDK initialization** | A single helper that calls `Sdk.init()` | `AdHelper.k(Application)` | Low — SDK never starts, nothing else depends on it |
|
||||
| **Feature entry point** | The app method that shows the thing | `AdHelper.showSplash()`, `showReward()` | Low–medium — must preserve callbacks the caller awaits |
|
||||
| **Data consumption** | Where a server list is filtered/rendered | filter out a `position` before it reaches UI state | Medium — must not break sibling data |
|
||||
| **Renderer** | The composable/view for a **specific** element | a dedicated ad card composable | **High** — generic components are shared (see P6) |
|
||||
| **Transport** | Blocking/repointing an endpoint | `/app/adverts` → dead path | **Very high** — shared endpoints take screens down (see P5) |
|
||||
|
||||
**Rule:** prefer the highest layer (closest to the SDK/feature) that produces the required effect. Never go to the transport layer to hide a UI element.
|
||||
|
||||
## Before you patch a method: blast-radius check
|
||||
|
||||
```bash
|
||||
python scripts/find_refs.py <smali_tree_or_dex_dir> 'Lcom/pkg/Helper;->methodName(args)RetType'
|
||||
```
|
||||
|
||||
- **1–3 callers, all in the same feature area** → safe to patch.
|
||||
- **Many callers, or callers across unrelated packages** → it is a general utility. Do not patch it. Go one level up and patch the specific caller instead.
|
||||
- **Look at the parameters too.** If the signature mentions `Modifier`, `ContentScale`, `ColorFormat`, `Shape`, `View`, or a content-generic model type, it is not specific to your target.
|
||||
|
||||
Real example: a composable `(AdModel, ColorScheme, Modifier, Function0, ContentScale, Shape, Composer, II)V` looked ad-specific because of its first parameter. It was actually the shared image-card renderer; neutering it removed all cover art and broke playback.
|
||||
|
||||
## Technique 1: dexlib2 method-level rewrite (preferred)
|
||||
|
||||
Concept: load the dex, find the target class, replace **only** the target method's implementation, write a new dex. Nothing else is touched.
|
||||
|
||||
See `scripts/dexpatch/` for a working Java implementation and build instructions.
|
||||
|
||||
Shape of the code:
|
||||
|
||||
```java
|
||||
DexFile dex = DexFileFactory.loadDexFile(new File(in), Opcodes.forApi(API));
|
||||
List<ClassDef> out = new ArrayList<>();
|
||||
for (ClassDef cd : dex.getClasses()) {
|
||||
List<Method> direct = new ArrayList<>(); for (Method m : cd.getDirectMethods()) direct.add(m);
|
||||
List<Method> virtual = new ArrayList<>(); for (Method m : cd.getVirtualMethods()) virtual.add(m);
|
||||
boolean touched = false;
|
||||
// ... for the target class: find the method, build new instructions, list.set(i, newMethod)
|
||||
out.add(touched
|
||||
? new ImmutableClassDef(cd.getType(), cd.getAccessFlags(), cd.getSuperclass(), cd.getInterfaces(),
|
||||
cd.getSourceFile(), cd.getAnnotations(), cd.getStaticFields(),
|
||||
cd.getInstanceFields(), direct, virtual)
|
||||
: cd);
|
||||
}
|
||||
DexFileFactory.writeDexFile(out, new ImmutableDexFile(Opcodes.forApi(API), out));
|
||||
```
|
||||
|
||||
### Practical details that decide success
|
||||
|
||||
- **`direct` vs `virtual`.** `static`, `private`, and constructors live in `directMethods`; everything else (including `public final`) lives in `virtualMethods`. **Scan both** when searching. A "method not found" that is actually "in the other list" wastes a lot of time.
|
||||
- **Preserve the register count.** Keep `m.getImplementation().getRegisterCount()`. `registers` must be `>= parameterRegisters`, and parameter registers are the **highest-numbered** ones: with `registers = N` and `k` parameters (including `this` for non-static), `p0 = N - k`.
|
||||
- **Method parameters** come from the prototype. For `(Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;` on an instance method, `k = 3` → `p0=3, p1=4, p2=5` when `registers = 6`.
|
||||
- **`const-wide` needs the 64-bit instruction form.** `ImmutableInstruction51l`, not `31i`.
|
||||
- **Instruction register operands in `35c` form** (invoke) are `(opcode, registerCount, regC, regD, regE, regF, regG, ref)`. `invoke-static {v1, v2}, ...` → `registerCount=2, regC=1, regD=2`.
|
||||
- **Every method body must end with a return of the right type.**
|
||||
- **One dex, one write pass.** If you need two edits to the same dex, do them in the same program (see P4).
|
||||
- **Null `tryBlocks` / `debugItems` on the rewritten method is fine** — you are replacing the whole body.
|
||||
|
||||
### Common rewrites
|
||||
|
||||
**Return a boolean constant** (`Z`):
|
||||
```
|
||||
const/4 v0, 0x1
|
||||
return v0
|
||||
```
|
||||
`registers` = original count is fine; `const/4` needs a 4-bit register (`v0`–`v15`).
|
||||
|
||||
**No-op** (`V`):
|
||||
```
|
||||
return-void
|
||||
```
|
||||
|
||||
**Return an object/empty collection**: build the constant, then `return-object`. For `java.lang.Long`, `const-wide` + `Long->valueOf(J)` + `move-result-object`.
|
||||
|
||||
**Coerce a suspend/Flow lambda to always yield a fixed value** — this is what "make a local flag permanently true" usually looks like in practice. See the worked example below.
|
||||
|
||||
### Worked example: permanently "not expired" without touching a shared helper
|
||||
|
||||
**Situation.** A local preference (`<key>_expires_at`) gates a promo popup. Writing a large value into the datastore works on the current device but is **runtime data**, so a fresh install loses it (see P11). The read path is a Flow built at construction time, so the getter cannot be patched meaningfully, and the generic `Long.valueOf` wrapper has 30+ callers (see P6).
|
||||
|
||||
**Target.** The dedicated map lambda, e.g. `feature/data/SomeStore$currentX$$inlined$map$1$2`:
|
||||
|
||||
```
|
||||
.method public final emit(Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
|
||||
iget-object v0, p0, L<same class>;->b:Lkw2; # downstream collector
|
||||
const-wide v1, <big value>
|
||||
invoke-static {v1, v2}, Ljava/lang/Long;->valueOf(J)Ljava/lang/Long;
|
||||
move-result-object v1
|
||||
invoke-interface {v0, v1, p2}, Lkw2;->emit(Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
|
||||
move-result-object v0
|
||||
return-object v0
|
||||
.end method
|
||||
```
|
||||
|
||||
Note the shape: the lambda class holds the downstream collector in a field (here `b:Lkw2;`). Always read that field name from the actual smali — do not assume.
|
||||
|
||||
This class has exactly one purpose, so patching it is safe.
|
||||
|
||||
## Technique 2: byte-level string patch
|
||||
|
||||
Only for **equal-length** replacements. Must preserve `string_ids` ordering.
|
||||
|
||||
```bash
|
||||
python scripts/dex_strpatch.py <in.dex> <out.dex> "<old>" "<new>"
|
||||
```
|
||||
|
||||
The script:
|
||||
1. requires `len(new) == len(old)`,
|
||||
2. requires exactly one occurrence,
|
||||
3. looks up the entry's neighbours in `string_ids` and **rejects** the replacement unless `prev < new < next`,
|
||||
4. recomputes `signature` (SHA-1 over bytes from offset 32) and `checksum` (adler32 over bytes from offset 12).
|
||||
|
||||
If a candidate is rejected, try another string that sorts inside the same interval. `/app/noadver` was rejected (`n > c` against neighbour `/app/configs/`); `/app/blocked` was accepted.
|
||||
|
||||
**Do not** use this technique to change behavior. Strings are renamed, not logic.
|
||||
|
||||
## Technique 3: smali tree editing (only when you must)
|
||||
|
||||
Use when the change cannot be expressed as a single-method rewrite (adding a field, restructuring control flow).
|
||||
|
||||
Tools: `scripts/smtool.py` (baksmali/smali with a bundled classpath) and `scripts/patch_smali.py` (method-body replacement by signature).
|
||||
|
||||
```bash
|
||||
python scripts/smtool.py d <in.dex> <out_tree>
|
||||
python scripts/patch_smali.py <tree> <patch.json> [--dry-run]
|
||||
python scripts/smtool.py a <tree> <out.dex>
|
||||
```
|
||||
|
||||
Then **must** verify (P3 will bite otherwise):
|
||||
|
||||
```bash
|
||||
python scripts/dex_classdiff.py <original.dex> <rebuilt.dex>
|
||||
```
|
||||
Expect: same class count, `only_in_A=0`, `only_in_B=0`, `ACC_INTERFACE mismatch=0`.
|
||||
|
||||
If the class table is clean but the app crashes with `IncompatibleClassChangeError` / `VerifyError`, the round-trip damaged code items that table comparison cannot see. Fall back to technique 1.
|
||||
|
||||
Patch spec format for `patch_smali.py`:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"file": "com/pkg/Helper.smali",
|
||||
"method": ".method public final showAd(Landroid/app/Activity;)V",
|
||||
"registers": 3,
|
||||
"body": ["return-void"],
|
||||
"note": "why this is safe"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## Finding the call site
|
||||
|
||||
Reverse-lookup from a smali tree or a set of disassembled dex:
|
||||
|
||||
```bash
|
||||
python scripts/find_refs.py <tree> 'Lcom/pkg/AdHelper;->showSplash(...)V'
|
||||
```
|
||||
|
||||
Search strategies that work:
|
||||
- Search the **string table** first (`scripts/dex_strings.py`). API paths, keys, and SDK class names are usually string literals, and they are unique.
|
||||
- Search for the **SDK's entry class** (`Sdk.init`, `Sdk.show`). The app's wrapper is almost always the only caller.
|
||||
- When the decompiler is confusing, trust the **byte offsets** — `grep` the dex for the literal and note where it sits relative to other strings of the same family.
|
||||
|
||||
## Order of operations for a real patch task
|
||||
|
||||
1. Identify every place the behavior is produced (`recon` + `find_refs`).
|
||||
2. Pick the highest safe layer per the table above.
|
||||
3. Write all edits for a given dex into **one** dexlib2 program.
|
||||
4. Patch each dex **once**.
|
||||
5. `dex_classdiff` every patched dex against the original → expect zero structural drift.
|
||||
6. Repack, sign, install, launch, exercise, read logcat.
|
||||
7. If anything is off, revert that dex to the original and re-verify the control build.
|
||||
@@ -0,0 +1,439 @@
|
||||
# Dynamic analysis with Frida
|
||||
|
||||
Static analysis tells you what code exists. Frida tells you what code **runs**. When they disagree, runtime wins (`references/pitfalls.md` P10).
|
||||
|
||||
Use Frida when you need to answer:
|
||||
- Which method actually renders this element? (static decompilation routinely misleads)
|
||||
- What is the real call chain at the moment of interest?
|
||||
- What does the app actually do on startup, in order?
|
||||
- Which domains does it resolve, and when?
|
||||
- Is the app detecting my instrumentation?
|
||||
|
||||
## Setup — version alignment is a hard gate
|
||||
|
||||
**Do this first.** Nearly every "Frida is broken on this device" report is a version mismatch, and the error text rarely says so. The host `frida` package and the device-side `frida-server` must be the **same version**, and that version must actually support the device's Android release. Align, then debug everything else.
|
||||
|
||||
| Symptom | Cause | Fix |
|
||||
|---|---|---|
|
||||
| `unable to locate Android dynamic linker` | host/server too new for this Android release | drop to an older frida line (16.x is a safe baseline for older ROMs) |
|
||||
| `Java is not defined` / `Java.perform is not a function` | that build ships no bundled Java bridge | align to a build that has it, or inline the bridge (see *17+ gotchas*) |
|
||||
| `Failed to connect to remote frida-server` / `unexpected message` / `invalid message` | host package and device server differ | download both from the same release tag |
|
||||
| `Java.choose` / `Java.use` throws immediately | bridge present but the VM is not ready | wrap everything in `Java.perform` |
|
||||
| Attached, but hooks fire in the wrong process | USB auto-selection grabbed the emulator | use an explicit remote device (below) |
|
||||
| `HOOK-OK` prints and nothing ever fires | not a version problem | go to *Hook never fires* |
|
||||
|
||||
### Prefer a remote device over USB
|
||||
|
||||
With a physical device *and* an emulator attached, `frida.get_usb_device()` can silently pick the emulator — you then attach to the wrong process and chase phantom failures for a long time. Address the device explicitly:
|
||||
|
||||
```bash
|
||||
adb devices -l # get <serial>
|
||||
adb -s <serial> forward tcp:27042 tcp:27042
|
||||
frida -H 127.0.0.1:27042 -f <app.package> -l probe.js --no-pause
|
||||
```
|
||||
|
||||
```python
|
||||
device = frida.get_device_manager().add_remote_device('127.0.0.1:27042')
|
||||
```
|
||||
|
||||
Keep `-s <serial>` on every other adb call too, or you will drift between targets mid-session.
|
||||
|
||||
### Attach by PID when the process list is incomplete
|
||||
|
||||
`device.enumerate_processes()` can return a list that simply does not contain the app you are
|
||||
targeting, while `adb shell ps -A | grep <pkg>` shows it running. This is an enumeration gap,
|
||||
not a permission problem, and no amount of retrying fixes it. Resolve the pid through adb and
|
||||
attach to it directly:
|
||||
|
||||
```python
|
||||
import subprocess
|
||||
|
||||
def find_pid(serial, pkg):
|
||||
out = subprocess.run(['adb', '-s', serial, 'shell', 'ps -A -o PID,NAME'],
|
||||
capture_output=True, text=True).stdout
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) >= 2 and parts[1] == pkg:
|
||||
return int(parts[0]) # last match wins; use the main process
|
||||
return None
|
||||
|
||||
pid = find_pid(serial, pkg)
|
||||
session = device.attach(pid) # works where attach(pkg) raises ProcessNotFound
|
||||
```
|
||||
|
||||
Two related behaviours worth knowing:
|
||||
|
||||
- `attach(<package name>)` raises `ProcessNotFoundError` in exactly this situation, which is
|
||||
easy to misread as "the app is not running".
|
||||
- A pid captured earlier goes stale the moment the process is recycled. Re-resolve it
|
||||
immediately before each injection rather than reusing a value from an earlier step.
|
||||
|
||||
### Verify the runtime before blaming the script
|
||||
|
||||
A script that reports nothing at all is usually not seeing the Java layer. Two failure modes
|
||||
look identical from the host — test for both in one go:
|
||||
|
||||
```javascript
|
||||
// send({ runtime: Script.runtime, java: typeof Java, objc: typeof ObjC });
|
||||
```
|
||||
|
||||
- `Java` is `undefined` ⇒ the script runtime has no Java bridge. Pass `runtime='v8'`
|
||||
explicitly when creating the script; some builds default to a runtime without it.
|
||||
- The bridge exists but every hook misses ⇒ you attached to the wrong process, or the layer
|
||||
below is native (go to the four-layer probe / `references/native-and-so.md`).
|
||||
|
||||
### Start the device server so it survives
|
||||
|
||||
Run it as root, give it a non-obvious name out of obvious paths, and **detach it from the shell's session**. A process started with `nohup ... &` from an `adb shell` that then exits gets reaped mid-run — the hooks work for a minute and then stop.
|
||||
|
||||
```bash
|
||||
adb push frida-server-<ver>-android-<abi> /data/local/tmp/
|
||||
adb shell "su -c 'mkdir -p /data/local/tmp/.svc'"
|
||||
adb shell "su -c 'cp -f /data/local/tmp/frida-server-<ver>-android-<abi> /data/local/tmp/.svc/kwork'"
|
||||
adb shell "su -c 'chmod 755 /data/local/tmp/.svc/kwork'"
|
||||
adb shell "su -c 'setsid /data/local/tmp/.svc/kwork >/dev/null 2>&1 </dev/null &'"
|
||||
adb shell "su -c 'pgrep -f kwork'" # must still be alive after the shell returned
|
||||
```
|
||||
|
||||
If `setsid` is unavailable, hold the adb connection open instead: run `adb shell "su -c '/data/local/tmp/.svc/kwork'"` as a host-side background job and leave it running for the whole session.
|
||||
|
||||
### Spawn, don't attach, when timing matters
|
||||
|
||||
ABI must match the device (`getprop ro.product.cpu.abi`). Attaching usually misses startup — init, the first network calls, and splash logic all happen before you get a session.
|
||||
|
||||
```python
|
||||
device = frida.get_device_manager().add_remote_device('127.0.0.1:27042')
|
||||
pid = device.spawn([pkg])
|
||||
session = device.attach(pid)
|
||||
# ... load the script, wait until it reports that hooks are installed ...
|
||||
device.resume(pid) # resume ONLY after hooks are ready
|
||||
```
|
||||
|
||||
**Common bug:** resuming before the script has finished loading loses the first ~100–300 ms, which is exactly where init happens. Have the script `send()` a ready signal (the probe template below sends `PROBE-READY`) and resume only after receiving it.
|
||||
|
||||
## Frida 17+ gotchas
|
||||
|
||||
The preferred fix for every symptom in the table above is **version alignment**. Use these only when you genuinely must run a 17+ build.
|
||||
|
||||
- The **built-in Java bridge was removed**. `Java.perform(...)` is not available unless you inline the bridge yourself:
|
||||
```python
|
||||
bridge = open(<site-packages>/frida_tools/bridges/java.js, encoding='utf-8').read()
|
||||
script = bridge + "\nObject.defineProperty(globalThis,'Java',{value:bridge,configurable:true});\n" + my_js
|
||||
```
|
||||
Pass the whole thing through a small loader script (below).
|
||||
- **Export lookup renamed.** Use a compatibility helper rather than a single API:
|
||||
```javascript
|
||||
function resolveExport(name) {
|
||||
try { if (Module.getGlobalExportByName) return Module.getGlobalExportByName(name); } catch (e) {}
|
||||
try { if (Module.findExportByName) return Module.findExportByName(null, name); } catch (e) {}
|
||||
try { const l = Process.findModuleByName('libc.so'); if (l) return l.getExportByName(name); } catch (e) {}
|
||||
return null;
|
||||
}
|
||||
```
|
||||
- **Large script injection times out.** A multi-hundred-KB bridge + script can exceed the transport timeout. Use a tiny loader and post the real payload:
|
||||
```python
|
||||
loader = "recv('go', m => { eval(m.payload.code); }); send('loader-ready');"
|
||||
sc = session.create_script(loader)
|
||||
sc.load()
|
||||
sc.on('message', on_message) # wait for 'loader-ready'
|
||||
sc.post({'type': 'go', 'payload': {'code': BIG_JS}})
|
||||
```
|
||||
|
||||
## Hook strategy
|
||||
|
||||
### Java layer (Kotlin/Java app)
|
||||
```javascript
|
||||
Java.perform(() => {
|
||||
const Cls = Java.use('com.example.Helper');
|
||||
Cls.showAd.overload('android.app.Activity').implementation = function (a) {
|
||||
send({ tag: 'Helper.showAd', stack: Java.use('android.util.Log').getStackTraceString(
|
||||
Java.use('java.lang.Throwable').$new()) });
|
||||
return this.showAd(a); // observe, then delegate
|
||||
};
|
||||
});
|
||||
```
|
||||
- **Use `overload(...)`** — obfuscated classes often have several methods with the same name.
|
||||
- To find obfuscated names, enumerate at runtime rather than guessing from decompiled short names:
|
||||
```javascript
|
||||
Java.enumerateLoadedClasses({
|
||||
onMatch: n => { if (n.indexOf('example') >= 0) send(n); },
|
||||
onComplete: () => send('done')
|
||||
});
|
||||
```
|
||||
- **Call stacks are the highest-value signal.** `Log.getStackTraceString(new Throwable())` or `Java.use('android.util.Log').getStackTraceString(...)` gives you the real chain from the framework down to the method — far more reliable than reading smali.
|
||||
|
||||
### Native layer
|
||||
```javascript
|
||||
const f = resolveExport('open');
|
||||
Interceptor.attach(f, {
|
||||
onEnter(args) { this.p = args[0].readCString(); },
|
||||
onLeave(ret) { if (this.p) send({ tag: 'open', path: this.p }); }
|
||||
});
|
||||
```
|
||||
|
||||
### Network / domain observation (cheap and very informative)
|
||||
```javascript
|
||||
const Inet = Java.use('java.net.InetAddress');
|
||||
Inet.getAllByName.overload('java.lang.String').implementation = function (h) {
|
||||
send({ tag: 'dns', host: h });
|
||||
return this.getAllByName(h);
|
||||
};
|
||||
```
|
||||
This is often the **decisive evidence** for an ad-removal claim: if the ad SDK's domains are *never resolved*, the subsystem never started — a much stronger statement than "logcat was quiet". It also works for SDKs that bypass the system HTTP proxy.
|
||||
|
||||
## The four-layer probe template
|
||||
|
||||
When the question is "why did this request fail / where did it go", do not hook one class and hope. Ship **one long-lived script that hooks four layers at once**; whichever layer fires first localizes the problem immediately. This is the single most productive artifact of a runtime investigation — reuse it verbatim.
|
||||
|
||||
The layers, and why each one is there:
|
||||
|
||||
1. **The app's own network wrapper** — enumerate `getDeclaredMethods` and wrap *every* overload, so you do not have to guess the entry point.
|
||||
2. **OkHttp end to end** — `newCall`, `Request$Builder.build`, `RealCall.execute`, `AsyncCall.run`, `RealInterceptorChain.proceed`. The last two are the ones that fire for asynchronous calls.
|
||||
3. **`java.net.URL.openConnection`** — plenty of login/register paths never touch OkHttp; they use `HttpsURLConnection` and a completely different trust configuration.
|
||||
4. **`Throwable.getMessage`** — pulls out the original text of exceptions an upper layer caught and swallowed. Without it, a caught failure looks like "nothing happened".
|
||||
|
||||
Rules that make the difference between a usable probe and a wasted session:
|
||||
|
||||
- **Write to a file as well as to `send()`.** Stdout is lossy and the CLI drops messages; the file is the evidence.
|
||||
- **Let it stay resident.** Hook before the app touches the network, then leave it running while you drive the UI. A one-shot script misses everything that happens after its first second.
|
||||
- **Wrap every hook in its own `try/catch`.** One missing class must not take down the other three layers.
|
||||
- **Never capture an overload in a `var`.** Inside a loop, `var ov = ...` leaves every hook pointing at the *last* overload: they install cleanly and then mis-report forever. Use `let` or `.forEach()`.
|
||||
|
||||
`scripts/frida_probe.js` is the same probe in a fuller form (per-arity dispatch, DNS layer, dedup and hard caps). The script below is the minimal portable one — paste it into any loader and it adapts to the target.
|
||||
|
||||
```javascript
|
||||
// probe.js — four-layer network + swallowed-exception probe.
|
||||
const APP_PKG = '<app.package>';
|
||||
const APP_NET_CLASS = 'com.example.app.net.HttpHelper'; // the app's own wrapper, once you have found it
|
||||
const LOGFILE = '/data/user/0/' + APP_PKG + '/files/probe.log'; // app-private: always writable by the app
|
||||
const MAX_THROW = 400; // Throwable.getMessage is hot — cap it
|
||||
const INTERESTING = /(network|http|ssl|cert|fail|timeout|refused|unable|error|exception)/i; // widen for the app's UI language
|
||||
|
||||
let out = null;
|
||||
try { out = new File(LOGFILE, 'a'); } catch (e) {}
|
||||
|
||||
function log(ev, data) {
|
||||
const line = JSON.stringify(Object.assign({ t: Date.now(), ev: ev }, data));
|
||||
try { send(line); } catch (e) {}
|
||||
try { if (out !== null) { out.write(line + '\n'); out.flush(); } } catch (e) {}
|
||||
}
|
||||
|
||||
function stack(n) {
|
||||
try {
|
||||
const t = Java.use('java.lang.Throwable').$new();
|
||||
return Java.use('android.util.Log').getStackTraceString(t).split('\n').slice(1, (n || 6) + 1).join(' | ');
|
||||
} catch (e) { return '<no stack>'; }
|
||||
}
|
||||
|
||||
function sa(args) { // a hook must never die inside its own logging
|
||||
try {
|
||||
const o = {};
|
||||
for (let i = 0; i < args.length; i++) o['a' + i] = args[i] === null ? 'null' : '' + args[i];
|
||||
return o;
|
||||
} catch (e) { return { err: '' + e }; }
|
||||
}
|
||||
|
||||
// 1) the app's own wrapper: every declared method, every overload, separately wrapped
|
||||
function hookAppNet(cls) {
|
||||
try {
|
||||
const C = Java.use(cls);
|
||||
const ms = C.class.getDeclaredMethods();
|
||||
for (let i = 0; i < ms.length; i++) {
|
||||
try {
|
||||
const name = ms[i].getName();
|
||||
const ps = ms[i].getParameterTypes();
|
||||
const sig = [];
|
||||
for (let j = 0; j < ps.length; j++) sig.push(ps[j].getName());
|
||||
const ov = C[name].overload.apply(C[name], sig);
|
||||
ov.implementation = function () {
|
||||
try { log('APP-NET', { cls: cls, m: name, args: sa(arguments), stack: stack(5) }); }
|
||||
catch (e) { log('PROBE-ERR', { at: 'app-net', msg: '' + e }); }
|
||||
return ov.apply(this, arguments);
|
||||
};
|
||||
} catch (e) { log('HOOK-SKIP', { cls: cls, m: ms[i].getName(), msg: '' + e }); }
|
||||
}
|
||||
log('HOOK-OK', { layer: 'app-net', cls: cls, n: ms.length });
|
||||
} catch (e) { log('HOOK-FAIL', { layer: 'app-net', cls: cls, msg: '' + e }); }
|
||||
}
|
||||
|
||||
// 2) OkHttp end to end — internal class names moved between major versions, so try every location
|
||||
function hookOkHttp() {
|
||||
const targets = [
|
||||
['okhttp3.OkHttpClient', 'newCall'],
|
||||
['okhttp3.Request$Builder', 'build'],
|
||||
['okhttp3.RealCall', 'execute'],
|
||||
['okhttp3.RealCall$AsyncCall', 'run'],
|
||||
['okhttp3.internal.http.RealInterceptorChain', 'proceed'], // okhttp 3.x
|
||||
['okhttp3.internal.connection.RealInterceptorChain', 'proceed'] // okhttp 4.x / 5.x
|
||||
];
|
||||
for (let i = 0; i < targets.length; i++) {
|
||||
const cn = targets[i][0], mn = targets[i][1];
|
||||
try {
|
||||
const ovs = Java.use(cn)[mn].overloads; // every overload of that name; use .overload('<sig>') if this is undefined
|
||||
for (let j = 0; j < ovs.length; j++) {
|
||||
const ov = ovs[j]; // block-scoped: every hook keeps its own overload
|
||||
ov.implementation = function () {
|
||||
try { log('OKHTTP', { cls: cn, m: mn, args: sa(arguments), stack: stack(6) }); }
|
||||
catch (e) { log('PROBE-ERR', { at: cn, msg: '' + e }); }
|
||||
return ov.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
log('HOOK-OK', { layer: 'okhttp', cls: cn, m: mn, overloads: ovs.length });
|
||||
} catch (e) { log('HOOK-SKIP', { layer: 'okhttp', cls: cn, m: mn, msg: '' + e }); }
|
||||
}
|
||||
}
|
||||
|
||||
// 3) java.net.URL — login/register frequently bypasses OkHttp entirely
|
||||
function hookRawUrl() {
|
||||
try {
|
||||
const U = Java.use('java.net.URL');
|
||||
const o0 = U.openConnection.overload();
|
||||
o0.implementation = function () {
|
||||
try { log('RAW-URL', { url: '' + this.toString(), stack: stack(6) }); } catch (e) {}
|
||||
return o0.apply(this, arguments);
|
||||
};
|
||||
try {
|
||||
const o1 = U.openConnection.overload('java.net.Proxy');
|
||||
o1.implementation = function () {
|
||||
try { log('RAW-URL', { url: '' + this.toString(), proxy: true, stack: stack(6) }); } catch (e) {}
|
||||
return o1.apply(this, arguments);
|
||||
};
|
||||
} catch (e) {}
|
||||
log('HOOK-OK', { layer: 'url' });
|
||||
} catch (e) { log('HOOK-FAIL', { layer: 'url', msg: '' + e }); }
|
||||
}
|
||||
|
||||
// 4) Throwable.getMessage — the original text of an exception an upper layer caught and swallowed
|
||||
function hookThrowable() {
|
||||
try {
|
||||
const T = Java.use('java.lang.Throwable');
|
||||
const seen = {};
|
||||
let n = 0;
|
||||
T.getMessage.implementation = function () {
|
||||
const msg = this.getMessage(); // self-call inside the replacement is fine (Frida guards it)
|
||||
try {
|
||||
if (msg !== null && msg !== undefined && n < MAX_THROW) {
|
||||
const cls = '' + this.getClass().getName();
|
||||
const interesting = cls.indexOf('Exception') >= 0 || cls.indexOf('Error') >= 0 || INTERESTING.test('' + msg);
|
||||
const key = cls + '|' + msg;
|
||||
if (interesting && seen[key] === undefined) { // dedup: this method is on a very hot path
|
||||
seen[key] = 1; n++;
|
||||
log('THROW', { cls: cls, msg: '' + msg, stack: stack(4) });
|
||||
}
|
||||
}
|
||||
} catch (e) {}
|
||||
return msg;
|
||||
};
|
||||
log('HOOK-OK', { layer: 'throwable' });
|
||||
} catch (e) { log('HOOK-FAIL', { layer: 'throwable', msg: '' + e }); }
|
||||
}
|
||||
|
||||
Java.perform(function () {
|
||||
hookAppNet(APP_NET_CLASS);
|
||||
hookOkHttp();
|
||||
hookRawUrl();
|
||||
hookThrowable();
|
||||
log('PROBE-READY', { pkg: APP_PKG, logfile: LOGFILE }); // the host waits for this before resuming
|
||||
});
|
||||
```
|
||||
|
||||
Read the log after driving the UI. `RAW-URL` (with no `OKHTTP` events) is how you learn the request went over `HttpsURLConnection` — a different trust path entirely (`references/tls-and-cert.md` §If OkHttp is the failing path). `THROW` is how you learn an upper layer swallowed the real error.
|
||||
|
||||
```bash
|
||||
# pull the record (app-private path needs root to read)
|
||||
adb -s <serial> shell "su -c 'cat /data/user/0/<app.package>/files/probe.log'" > probe.log
|
||||
```
|
||||
|
||||
## Hook never fires — debug in this order
|
||||
|
||||
`HOOK-SKIP` / `HOOK-FAIL` lines answer this before you start guessing. When every layer reports `HOOK-OK` and still no event arrives:
|
||||
|
||||
1. **Does the class / method / overload actually exist?** A misspelled obfuscated name, a renamed okhttp internal class, or an overload taking `Object` instead of `String` all produce a wrapper that is simply never invoked.
|
||||
2. **Is the ClassLoader the right one?** Multi-dex, plugin-loaded and packed apps can hold several loaders; `Java.use` uses the app loader by default and throws `ClassNotFoundException` for a class that is plainly in the APK. Enumerate and switch:
|
||||
```javascript
|
||||
Java.enumerateClassLoaders({
|
||||
onMatch: function (l) { try { if (l.findClass('<app.net.Class>')) Java.classFactory.loader = l; } catch (e) {} },
|
||||
onComplete: function () {}
|
||||
});
|
||||
```
|
||||
3. **Is that code path reached at all?** Layer 4 settles it: if `THROW` events show the app failing earlier, your hook's call site is never executed and no amount of hooking will help.
|
||||
4. **Did your UI action trigger business logic?** A tap that looks fine but fails a local form check returns before any network call. Verify the input actually reached the field (`references/environment.md` §Driving the UI from adb), not just that the button animated.
|
||||
|
||||
## `Java.choose` also matches dead instances
|
||||
|
||||
`Java.choose('com.example.app.MainActivity', ...)` returns **every** instance the VM still tracks, including finished and destroyed ones. Walking their view tree then yields an empty list — that is normal, not a bug in your script. Filter first, and prefer a direct reflective call over simulating a tap:
|
||||
|
||||
```javascript
|
||||
Java.choose('com.example.app.MainActivity', {
|
||||
onMatch: function (a) {
|
||||
try {
|
||||
if (a.isFinishing() || a.isDestroyed()) return; // dead instance: skip it
|
||||
send({ tag: 'live', view: '' + a.findViewById(<viewId>) });
|
||||
} catch (e) {}
|
||||
},
|
||||
onComplete: function () {}
|
||||
});
|
||||
```
|
||||
|
||||
## Reading obfuscated code at runtime
|
||||
|
||||
When names are meaningless (`a7`, `x6`, `uf0`), do not patch from names. Instead:
|
||||
|
||||
1. Find a **unique anchor**: an API path, a preference key, or an SDK class name from the string table (`scripts/dex_strings.py`).
|
||||
2. Locate the small class/method that references it (byte search in the dex + a targeted disassembly).
|
||||
3. Hook that anchor, capture the **stack**, and read off the real chain.
|
||||
4. Hook the classes the stack reveals — that is where semantics become visible.
|
||||
|
||||
## Anti-instrumentation
|
||||
|
||||
Signs: the app exits or freezes shortly after attach; `logcat` shows a generic process death with no Java stack; strings like `frida`, `xposed`, `magisk`, `substrate` are referenced by **app code** (not just by an SDK's string list).
|
||||
|
||||
**Rule this out first — it is not always a detector.** A process that dies right after you
|
||||
attach is frequently the ROM rather than the app: on aggressive OEM ROMs, merely backgrounding
|
||||
the app (pressing HOME, switching away) triggers a freeze, and the logcat signature is a state
|
||||
transition such as `state: R -> F` while hooks stop with no Java stack. That looks identical to
|
||||
a detector killing you. Check `references/environment.md` for that signature, and keep the app
|
||||
in the foreground, before building an anti-anti plan.
|
||||
|
||||
Countermeasures, in order of least disruption:
|
||||
1. Spawn + late resume, so hooks are installed before the check runs.
|
||||
2. Rename `frida-server` and move it out of obvious paths.
|
||||
3. Hook the detector itself and neuter it — find it by hooking the suspicious API (e.g. `/proc/self/maps` reads, `File.exists`, `Runtime.exec`) and inspecting the stack.
|
||||
4. Only then consider a gadget-based approach.
|
||||
|
||||
**Remember:** most `frida`/`root` strings in a decompiled APK belong to third-party SDKs' own detection lists, not to the app. Verify that **app code** references them before doing anti-anti work.
|
||||
|
||||
### When live attach cannot work at all
|
||||
|
||||
Sometimes nothing short of "do not inject at runtime" is viable — the check runs
|
||||
before your hooks can, it watches its own process, or the environment forbids
|
||||
`ptrace`. Do not keep escalating on the same axis. There are non-live ways to get
|
||||
runtime-grade information, and they are often enough to finish the job:
|
||||
|
||||
| Alternative | What it gives you | Cost |
|
||||
|---|---|---|
|
||||
| **Static instrumentation** — load a gadget/small agent by modifying the APK (e.g. an injected `Application` wrapper, a gadget `.so` added to `lib/<abi>/` and wired from the manifest) | Hooks run from process start with no external attach, no `ptrace`, no server process on the device to be found | Must repack and re-sign; the build you observe is no longer byte-identical to the original, so **it cannot serve as the unmodified control** (`verification.md` §the control build rule) |
|
||||
| **Static read of the answer** — the check's inputs are usually visible: the field it reads, the string it compares, the response field it trusts | Often enough to plan a patch without ever observing | You do not learn the live values; combine with `runtime-data.md` for local state |
|
||||
| **Self-recorded evidence** — the app's own cached responses, logs, or on-disk state | Real runtime data with no injection at all (a HTTP cache, a pref, a JSON snapshot left behind by a normal launch) | Only what the app happened to persist; needs one clean launch and then a filesystem read |
|
||||
|
||||
The last one is worth remembering because it is the cheapest and it is easy to
|
||||
forget: a normally-launched app often leaves the exact runtime data you wanted —
|
||||
server responses in its HTTP cache, config in a preferences file, feature state in
|
||||
a snapshot. Read those **before** concluding that dynamic analysis is blocked.
|
||||
|
||||
**Two cautions that apply to every alternative above:**
|
||||
|
||||
- **Changed bytes change behaviour.** Any injected build is a different artifact,
|
||||
and on a target that fingerprints its own layout that difference is the finding,
|
||||
not the app's real behaviour. Always keep the unmodified run as the control.
|
||||
- **Evidence from a different environment is a different claim.** A result obtained
|
||||
with the app patched-for-injection, or on a device with different privilege state,
|
||||
supports "verified under condition X". Say so; do not present it as the app's
|
||||
unmodified behaviour (`long-task-discipline.md` §the most expensive drift).
|
||||
|
||||
## What to capture for the record
|
||||
|
||||
- spawn time, hook-ready time, resume time
|
||||
- every hook hit with a stack (bounded — cap output)
|
||||
- DNS hosts in order, with timestamps
|
||||
- the exact build under test (hash) and the control build's results
|
||||
@@ -0,0 +1,303 @@
|
||||
# Environment — device, emulator, tooling, networking
|
||||
|
||||
## Pick your target
|
||||
|
||||
| Option | Pros | Cons |
|
||||
|---|---|---|
|
||||
| **Rooted physical device, native ABI** | Truest behavior; native libs load natively; Frida works well | One at a time; USB flakiness |
|
||||
| **Emulator with root** | Disposable; snapshots; easy reset | Different ABI; some apps detect it or refuse to run; native ARM libs may need translation |
|
||||
| **Static only** | No device needed | Cannot verify anything. Never claim success from static analysis alone. |
|
||||
|
||||
**Rule:** the artifact must be verified where the user will run it. An emulator that runs the app is **not** evidence about a physical ARM device, and vice versa.
|
||||
|
||||
**Important:** if the app ships only `arm64-v8a` native libraries and your emulator is x86_64, it may still run via ARM translation — but translation changes timing, and some native checks misbehave. Prefer a real ARM device for the final verification pass.
|
||||
|
||||
## ADB basics worth pinning down
|
||||
|
||||
```bash
|
||||
adb devices -l
|
||||
adb -s <serial> shell getprop ro.product.cpu.abi
|
||||
adb -s <serial> shell getprop ro.build.version.release
|
||||
adb -s <serial> shell getprop ro.build.version.sdk
|
||||
```
|
||||
|
||||
Root:
|
||||
```bash
|
||||
adb -s <serial> shell "su -c id"
|
||||
```
|
||||
`pm grant` and `pm install` frequently require root on OEM builds; the `shell` user gets `SecurityException`.
|
||||
|
||||
**Always specify `-s <serial>` when more than one device is attached** — otherwise adb errors out or picks the wrong one.
|
||||
|
||||
## Shell quoting (a real time sink)
|
||||
|
||||
The host shell expands `$`, `|`, `>`, and quotes **before** adb sees them. Windows PowerShell additionally mangles `$var:`, `[^"...`, and `$(...)`.
|
||||
|
||||
Symptom: "Could not find a part of the path", "Missing type name after '['", "no closing quote".
|
||||
|
||||
**Fix:** never inline device commands in the host shell. Use a small helper that calls adb from a script file and passes the command as a single argument:
|
||||
|
||||
```python
|
||||
subprocess.run([ADB, '-s', SERIAL, 'shell', 'su -c "%s"' % cmd])
|
||||
```
|
||||
See `scripts/devsh.py`.
|
||||
|
||||
Same class of bug: `javac` reads sources using the platform default encoding. Pass `-encoding UTF-8` or non-ASCII comments break the build.
|
||||
|
||||
## Giving an offline device network over USB
|
||||
|
||||
Use when the device has no usable network (broken Wi-Fi, no SIM, restricted network) but your host does. **`adb reverse` runs on the device's loopback, so it needs no device-side network interface at all.**
|
||||
|
||||
```bash
|
||||
# 1) host HTTP/HTTPS proxy (CONNECT-capable)
|
||||
python scripts/usb_net_proxy.py 8080 proxy.log
|
||||
|
||||
# 2) forward device-localhost:8080 to host:8080
|
||||
adb -s <serial> reverse tcp:8080 tcp:8080
|
||||
|
||||
# 3) point the device at it
|
||||
adb -s <serial> shell "su -c 'settings put global http_proxy 127.0.0.1:8080'"
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `adb reverse` **does not survive a device reboot** — recreate it after any restart.
|
||||
- Keep the host proxy process alive; if it dies, the device goes offline again.
|
||||
- Some SDKs bypass the system proxy entirely (many ad SDKs do). Proxy logs therefore **undercount** traffic — do not conclude "no ad traffic" from proxy logs alone; confirm with a runtime DNS hook.
|
||||
- Clean up when done: `settings put global http_proxy :0`.
|
||||
|
||||
## Preflight — run this before every experiment block
|
||||
|
||||
`scripts/preflight.py` checks, read-only, everything that silently fakes a failure: device
|
||||
reachability, whether more than one device is attached without an explicit serial, root, the
|
||||
runtime translation layer, device/host clock drift, a leftover device-wide proxy setting, stale
|
||||
port forwards, a dead device server, the ABI the package manager actually chose, and the free
|
||||
space left for installs.
|
||||
|
||||
```bash
|
||||
python scripts/preflight.py --pkg <app.package> --expect-root
|
||||
python scripts/preflight.py --cleanup # also clears a leftover proxy and stale forwards
|
||||
```
|
||||
|
||||
**The rule it exists to enforce:** *do not attribute a failure to your patch while preflight is
|
||||
dirty.* A surprising fraction of "my change broke it" is a device that was already in a bad state.
|
||||
Costing thirty seconds here is cheaper than costing several rounds to a wrong conclusion, and the
|
||||
wrong conclusion is the one that gets written down and trusted later.
|
||||
|
||||
## Emulator notes
|
||||
|
||||
Emulators are the right place to iterate and the wrong place to conclude.
|
||||
|
||||
- **Verify the app can install at all.** INSTALL failures on emulators are common (ABI, min SDK,
|
||||
vendor checks, a stale copy with a different signature) and are usually **not** related to your
|
||||
patch. Get a clean install of the *unmodified* build working before you change anything.
|
||||
- **Snapshot/rollback is the main advantage** — use it to A/B two builds quickly, and to get back
|
||||
to a known-good state after a destructive experiment.
|
||||
- **Never quote emulator behavior as proof for a device-only question** (and vice versa). An
|
||||
emulator that runs the app is not evidence about a physical ARM device.
|
||||
- **Most vendors ship a console binary that is far more reliable than the GUI.** Learn yours early;
|
||||
it is what you will need when the GUI is unresponsive and adb is already down.
|
||||
|
||||
| Vendor | Typical console binary | Useful verbs |
|
||||
|---|---|---|
|
||||
| LDPlayer | `dnconsole.exe` (next to the player exe) | `list2`, `launch --index N`, `reboot --index N`, `quitall` |
|
||||
| MuMu | `MuMuManager.exe` | `info -v all`, `control -v N launch`, `control -v N shutdown` |
|
||||
| AVD / Android Emulator | `emulator.exe` | `-list-avds`, `@<avd>`, `-no-window` |
|
||||
| Genymotion | `gmtool` | `admin list`, `admin start` |
|
||||
|
||||
- **Recovery order when `adb devices` goes empty.** Do these in order; the first two are the ones
|
||||
people skip:
|
||||
|
||||
1. `adb kill-server && adb start-server` — clears a wedged host daemon.
|
||||
2. Re-run `adb devices`. If still empty, check whether the **emulator process is actually alive**
|
||||
(`tasklist` / `ps`). A running process with **no listening port** means the VM never finished
|
||||
booting its adb bridge — restarting the *device* is the only fix.
|
||||
3. Restart the instance through the vendor console (`reboot --index N`). Restarting via the
|
||||
player binary's "launch" verb frequently leaves you with a process and still no adb.
|
||||
4. Only then consider that something is wrong with the host.
|
||||
|
||||
Symptom worth memorising: **the emulator process exists but nothing is listening on the adb
|
||||
port.** Distinguishing "not running" from "running but not booted" is what makes step 2 worth
|
||||
doing — they have different fixes and only one of them needs the GUI.
|
||||
|
||||
- **Root is a per-vendor setting, not a given.** Most emulators expose it as a toggle in their
|
||||
settings ("root permission" / "ROOT 权限"); some ship a separate rooted image. Always verify
|
||||
rather than assume:
|
||||
|
||||
```bash
|
||||
adb -s <serial> shell "su -c id" # want: uid=0(root)
|
||||
```
|
||||
|
||||
A rooted emulator is usually the fastest environment for everything in this skill, which makes it
|
||||
easy to forget that it is also the *least representative* one.
|
||||
|
||||
- **Running two instances.** Different serials make two emulators genuinely disjoint, which is
|
||||
useful for holding a clean control (original build, untouched state) alongside your workbench.
|
||||
Keep them labelled, always pass `--serial`, and **do not run the same experiment on both** — the
|
||||
value of a second device is independence, and duplicating work destroys it. Operate one at a
|
||||
time; the other is a reference point, not extra throughput.
|
||||
|
||||
- **Apps can detect the emulator** and change behaviour or refuse to run. If the app behaves
|
||||
differently here than on hardware, that is a finding about the emulator, not about the app. Note
|
||||
it and move the question to a real device.
|
||||
|
||||
## Which architecture is actually executing
|
||||
|
||||
Device selection and architecture are the same question. `getprop ro.product.cpu.abi` reports what
|
||||
the device claims; it does **not** report what is executing. Read `native-and-so.md` §Cross-architecture
|
||||
before you choose which library to patch, and `scripts/lib_map.py` to see the live truth.
|
||||
|
||||
## Install / reinstall
|
||||
|
||||
```bash
|
||||
adb -s <serial> shell "su -c 'pm uninstall <pkg>'"
|
||||
adb push out.apk /data/local/tmp/x.apk
|
||||
adb -s <serial> shell "su -c 'pm install -r -t -d /data/local/tmp/x.apk'"
|
||||
```
|
||||
- `-r` reinstall (keep data, same signing key) · `-t` allow test-only · `-d` allow downgrade
|
||||
- Different signing key than the installed app → must uninstall first (data is lost)
|
||||
- Vendor installers may reject `adb install`; pushing + `su -c pm install` usually works
|
||||
|
||||
**After reinstalling:** if you restored a data directory, fix ownership, or the app crashes in a DB-init path:
|
||||
```bash
|
||||
su -c "chown -R <uid>:<uid> /data/user/0/<pkg>"
|
||||
su -c "restorecon -R /data/user/0/<pkg>"
|
||||
```
|
||||
`<uid>` from `dumpsys package <pkg> | grep userId=`.
|
||||
|
||||
## Driving the UI from adb
|
||||
|
||||
Automated UI interaction is where verification loops usually break, and most of the breakage looks like a bug in your script. Most of it is not.
|
||||
|
||||
### `input tap` may simply not work on a given control
|
||||
|
||||
On some OEM ROMs `input tap <x> <y>` is silently ignored for certain controls while working fine for others at neighboring coordinates. **Do not conclude that your automation is wrong.** Before doubting the script:
|
||||
|
||||
```bash
|
||||
adb -s <serial> shell "su -c 'uiautomator dump /sdcard/ui.xml'"
|
||||
adb -s <serial> pull /sdcard/ui.xml
|
||||
# bounds="[x1,y1][x2,y2]" -> tap the center: ((x1+x2)/2, (y1+y2)/2)
|
||||
adb -s <serial> shell "su -c 'input tap <cx> <cy>'"
|
||||
```
|
||||
|
||||
If the control still does not react, bypass the UI path entirely — `am start -n <app.package>/<activity>`, or invoke the logic from Frida. A finished task needs the *code path*, not the tap.
|
||||
|
||||
`input` requires `INJECT_EVENTS`, which the plain `shell` user does not have. An unprivileged `input` **fails silently** — no error, no effect. Always wrap it: `su -c 'input tap ...'`.
|
||||
|
||||
`input text` additionally mangles or drops non-ASCII input. For CJK text, either install an ADB-driven helper IME or set the field from a runtime call rather than typing.
|
||||
|
||||
### Look at the screen — do not drive and wait blind
|
||||
|
||||
The most expensive habit in device work is: tap a coordinate, sleep, tap again, sleep, conclude
|
||||
something about the app. A screen that is *looked at* answers in one step what coordinate-guessing
|
||||
cannot answer in five — the layout shifted, a different dialog came up, a countdown is frozen, the
|
||||
button is disabled, the text on screen says exactly why.
|
||||
|
||||
**Treat a look as a routine step, not a debugging last resort.** Capture:
|
||||
|
||||
- **immediately before** anything time-dependent, so you know the starting state;
|
||||
- **during** a wait, at intervals — state changes are the information, and a single sample at the end
|
||||
cannot distinguish "it progressed" from "it never moved";
|
||||
- **at every decision point**, before choosing the next action;
|
||||
- **on any surprise**, before forming a theory about it.
|
||||
|
||||
`scripts/snap.py` does this with sane bounds, and tells you which kind of evidence you actually got:
|
||||
|
||||
```bash
|
||||
python scripts/snap.py --out shots --tag before
|
||||
python scripts/snap.py --out shots --tag waiting --count 6 --interval 3
|
||||
```
|
||||
|
||||
**Use the stall detector.** If consecutive samples are byte-identical, nothing is happening and more
|
||||
waiting cannot help. Stop, and go find out why — that is a different investigation from waiting
|
||||
longer.
|
||||
|
||||
### Two kinds of screen evidence, and which one is trustworthy here
|
||||
|
||||
| Evidence | What it gives you | When it is the right one |
|
||||
|---|---|---|
|
||||
| **the image** | exactly what is rendered: layout, which dialog, disabled states, drawn text | always available; the **only** evidence for runtime-drawn UI |
|
||||
| **the control tree** (`uiautomator dump`) | precise `bounds`, exact text, diffable | only when it actually has content |
|
||||
|
||||
The tree is more convenient *when it exists* — it gives you tap coordinates and text you can diff. But
|
||||
**verify it has content before planning around it**:
|
||||
|
||||
```bash
|
||||
adb -s <serial> shell "su -c 'uiautomator dump /sdcard/ui.xml'"
|
||||
adb -s <serial> pull /sdcard/ui.xml
|
||||
grep -c '<node' ui.xml # 0 nodes -> the tree is useless for this screen
|
||||
```
|
||||
|
||||
**A runtime-rendered UI frequently exposes no real controls at all.** Cross-platform runtimes, web
|
||||
views and canvas-drawn surfaces often produce an empty (or text-free) tree, which is why a plan built
|
||||
on "read the bounds out of the XML" stalls on exactly those apps — and also why tapping a control that
|
||||
"should be there" silently does nothing. When the tree is empty, the image is the **primary** evidence,
|
||||
not a fallback, and you read it directly rather than trying to derive coordinates from a tree that does
|
||||
not exist.
|
||||
|
||||
`screencap` itself returns a 0-byte file on some ROMs. Write on-device and pull instead:
|
||||
|
||||
```bash
|
||||
adb -s <serial> shell "su -c 'screencap -p /sdcard/x.png'" && adb -s <serial> pull /sdcard/x.png
|
||||
```
|
||||
|
||||
If that is also empty, do not fight it — but note that **a 0-byte capture is not evidence the screen is
|
||||
blank** (`pitfalls.md` P20). And if `uiautomator dump` fails with `could not get idle state`, retry once;
|
||||
a paused animation is usually the cause.
|
||||
|
||||
### Verify form input by reading it back
|
||||
|
||||
Filling a form and tapping submit is **not** a verified interaction. Read the actual field contents and lengths back first:
|
||||
|
||||
```bash
|
||||
adb -s <serial> shell "su -c 'input text <value>'" # no literal spaces; %s encodes one
|
||||
adb -s <serial> shell "su -c 'uiautomator dump /sdcard/ui.xml'"
|
||||
adb -s <serial> pull /sdcard/ui.xml
|
||||
grep -o 'text="[^"]*"' ui.xml # every populated field
|
||||
```
|
||||
|
||||
A whole class of "the button does nothing" is really a local validation rejecting the input — two password fields of different length, a required field empty, a format check. The app returns **before** issuing any request, so a network probe stays silent and the tap looks broken. Compare the lengths you read back, fix the input, retry.
|
||||
|
||||
### ROM background freezing kills your hooks
|
||||
|
||||
Aggressive ROMs freeze backgrounded apps; the logcat signature is a process state transition `state: R -> F` (running to frozen). Once frozen, hooks stop firing and network calls stop, which looks exactly like a broken probe.
|
||||
|
||||
```bash
|
||||
adb -s <serial> shell "su -c 'dumpsys deviceidle whitelist +<app.package>'"
|
||||
adb -s <serial> shell "su -c 'cmd appops set <app.package> RUN_IN_BACKGROUND allow'"
|
||||
```
|
||||
|
||||
While debugging, **do not press HOME** — backgrounding the app is what triggers the freeze. Return to it with `am start -n <app.package>/<activity>` and keep it in the foreground for the whole session.
|
||||
|
||||
## Signal extraction (what to actually read)
|
||||
|
||||
```bash
|
||||
adb -s <serial> logcat -c # clear before the run
|
||||
adb -s <serial> shell "am start -n <pkg>/<activity>"
|
||||
adb -s <serial> logcat -d -v brief | grep -E '<pkg>|FATAL|VerifyError|IncompatibleClassChange|uncaughtException'
|
||||
```
|
||||
|
||||
Failure signatures worth memorizing:
|
||||
|
||||
| Log line | Likely cause |
|
||||
|---|---|
|
||||
| `FATAL EXCEPTION` + Java stack | App-level crash — read the stack |
|
||||
| `VerifyError` / `IncompatibleClassChangeError` | Damaged dex (round-trip or bad rewrite) → `pitfalls.md` P3 |
|
||||
| `Failure starting process` (no stack, by `ActivityManager`) | ART refused the dex, or device state is broken → `pitfalls.md` P4, P9 |
|
||||
| `ClassNotFoundException: <App.Application>` | Dex rejected wholesale (ordering / structure) → `pitfalls.md` P2 |
|
||||
| `uncaughtException` with **no stack**, right after launch | A crash-reporter SDK swallowed it. Check whether the process is gone, and look for the SDK's own log file under the app's data dir |
|
||||
| App alive but nothing rendered | A swallowed exception in the UI path; hunt the crash-reporter's log file |
|
||||
|
||||
**Crash-reporter SDKs hide your stack traces.** When an app installs a global uncaught-exception handler (友盟/UCrash/Bugly etc.), the Java stack never reaches `logcat` — only a line like `uncaughtException time: ...`. Three ways to get the stack:
|
||||
1. **Frida**, hooking `Thread.setDefaultUncaughtExceptionHandler` or the handler class (most reliable).
|
||||
2. **Race the reporter's log file**: it writes a file under `<app data>/<sdk>/...` then uploads and deletes it. Poll it every ~0.2 s from the device shell and copy on sight:
|
||||
```bash
|
||||
while [ $i -lt 400 ]; do
|
||||
for f in <dir>/*.log; do [ -f "$f" ] && cp -f "$f" /data/local/tmp/capture.log; done
|
||||
i=$((i+1)); sleep 0.2
|
||||
done
|
||||
```
|
||||
3. Run a build with the reporter disabled (not always possible).
|
||||
|
||||
## Determinism
|
||||
|
||||
Before concluding anything from a failure: **reboot the device and retry**, and **run a control build with zero patches**. A surprising share of "my patch broke it" turns out to be device state (`pitfalls.md` P9).
|
||||
@@ -0,0 +1,120 @@
|
||||
# Cross-Platform Runtimes
|
||||
|
||||
Load this when the app's UI is not native, or when Java-layer hooks produce no hits at all.
|
||||
|
||||
Many apps ship a native shell plus a cross-platform runtime. Their business logic, their UI, and their
|
||||
feature gates live **inside the runtime**, not in the dex. Patching the dex then does nothing — the Java
|
||||
code you can see is mostly glue. Determine the runtime before choosing where to patch.
|
||||
|
||||
## Identify the runtime early
|
||||
|
||||
Signals in the APK:
|
||||
|
||||
| Runtime | Giveaways |
|
||||
|---|---|
|
||||
| Flutter | `libflutter.so`, `libapp.so`, `assets/flutter_assets/`, Dart snapshot |
|
||||
| React Native | `libhermes.so` or `libjsc.so`, `index.android.bundle`, `assets/index.android.bundle` |
|
||||
| Unity | `libunity.so`, `libil2cpp.so`, `assets/bin/Data/`, `globalgamemanagers` |
|
||||
| Cordova / Ionic | `assets/www/`, `cordova.js` |
|
||||
| Xamarin / .NET | `libmonodroid.so`, `assemblies/` in the APK |
|
||||
|
||||
A `classes.dex` that is small relative to the total payload is another strong hint that the real code
|
||||
lives elsewhere.
|
||||
|
||||
## The layer trap
|
||||
|
||||
The expensive mistake: seeing a UI element (dialog, paywall, gate) and assuming it is a native control,
|
||||
then spending a long time looking for it in the dex.
|
||||
|
||||
If it is drawn by the runtime, the dex contains only the bridge. Symptoms of being on the wrong layer:
|
||||
|
||||
- hooking the obvious Java dialog/Activity classes produces **zero** hits while the UI clearly appears;
|
||||
- the classes that do appear in stacks are the runtime's own, with obfuscated names;
|
||||
- hooking a Java method changes nothing about the visible behaviour.
|
||||
|
||||
Establish layer ownership **before** investing in a patch direction.
|
||||
|
||||
### How to tell which layer drew a given UI
|
||||
|
||||
1. Enumerate the Java dialog and presentation classes and hook their show/creation paths.
|
||||
2. Reproduce the UI. If any hook fires, the caller stack names the detection and you are on the Java
|
||||
layer.
|
||||
3. If nothing fires while the UI is on screen, the UI is runtime-drawn or native-drawn. Switch axis.
|
||||
4. Expect runtime-owned windows to appear as ordinary system `Dialog`/`Presentation` objects used as
|
||||
**containers** for the runtime's surface. A hit on such a container is not evidence that the visible
|
||||
element is a native dialog — read the class name carefully before drawing conclusions.
|
||||
|
||||
## Flutter specifics
|
||||
|
||||
- Business logic is compiled ahead-of-time into **`libapp.so`**; UI is rendered by `libflutter.so` with
|
||||
no per-widget Java objects.
|
||||
- **Widgets, dialogs, and paywalls are not Java views.** They will never appear in Java stack traces,
|
||||
and no Java hook can intercept them.
|
||||
- The Java side is thin: one Activity, plus plugin classes. Calls cross the boundary through the
|
||||
platform-channel mechanism, whose class names are frequently obfuscated.
|
||||
- Because channel classes may be renamed, locate them **by method signature and call shape**, not by
|
||||
class name.
|
||||
|
||||
### Where to intervene in a Flutter app
|
||||
|
||||
| Goal | Layer | Notes |
|
||||
|---|---|---|
|
||||
| Stop the app being killed / refused at startup | host native library | earliest point, see `native-and-so.md` |
|
||||
| Observe what the runtime is told | platform channel | shows the messages that drive the UI |
|
||||
| Change a decision permanently | `libapp.so` | most direct, hardest to locate |
|
||||
| Change startup behaviour only | host native library constructor | survives runtime restarts |
|
||||
|
||||
Editing `libapp.so` is the most durable but locating Dart AOT code is genuinely hard. This subject is
|
||||
large enough to have its own reference: **`references/dart-aot.md`** covers pinning the Dart version,
|
||||
building a decompiler for exactly that version, the object-pool model and how to index it, the register
|
||||
and boolean conventions, the three assembly signatures that identify most business logic, the locating
|
||||
workflow, and how to patch this layer safely.
|
||||
|
||||
## Locating logic without symbols
|
||||
|
||||
- **Strings first.** User-visible text (dialog bodies, feature labels) is the cheapest anchor in any
|
||||
runtime. Find it, then find what references it.
|
||||
- **Search them in the encoding the runtime actually uses, or you will conclude they do not exist.**
|
||||
This is the single most common false negative in cross-platform work. A runtime snapshot does not
|
||||
necessarily store text as UTF-8; UTF-16 (little-endian on these targets) is common and entirely
|
||||
valid. A UTF-8 search of such a snapshot returns **zero hits**, which reads as "the strings were
|
||||
stripped / encrypted, this route is dead" — and that conclusion is wrong.
|
||||
|
||||
```python
|
||||
blob = open('libapp.so', 'rb').read() # or whichever artifact holds the snapshot
|
||||
for phrase in ('<feature label>', '<dialog title>'):
|
||||
print(phrase, 'utf-8:', blob.find(phrase.encode('utf-8')),
|
||||
'utf-16le:', blob.find(phrase.encode('utf-16-le')))
|
||||
```
|
||||
|
||||
Try both, and try a short distinctive substring rather than a long phrase. Which encoding applies
|
||||
is predictable rather than random: in a Dart AOT snapshot ASCII literals are stored one-byte (a
|
||||
UTF-8 search finds them) while CJK / non-Latin literals are UTF-16LE (a UTF-8 search returns zero).
|
||||
`dart-aot.md` §7 gives the exact framing, and `scripts/dart_pool_strings.py --find` locates either
|
||||
encoding by file offset.
|
||||
- **A phrase that is absent may simply never exist as one literal.** UI text is often assembled from
|
||||
fragments or templates, so "the whole sentence" can be missing while both halves are present.
|
||||
Search the shortest distinctive token, and expect the interesting anchor to be a *label* rather
|
||||
than a sentence.
|
||||
- **Landing on a string tells you where the text lives, not which code decided to show it.** Treat the
|
||||
hit as an anchor for reference-hunting, not as the answer.
|
||||
- **Compare two builds.** The same feature in a slightly different version often reveals the code path.
|
||||
- **Watch the boundary, not the interior.** For cross-platform apps it is usually far cheaper to observe
|
||||
what crosses between layers than to reverse the interior of the runtime.
|
||||
- **Do not assume the obfuscated names are stable or meaningful.** They are not, and treating them as
|
||||
identities leads to conclusions that break on the next build.
|
||||
- **Obfuscated identifiers can be non-ASCII and invisible.** Renaming passes can replace class and
|
||||
member names with characters outside ASCII (combining marks, variant selectors and similar). If a
|
||||
class exists at runtime but "cannot be found" by the name you read from a decompiler, suspect
|
||||
encoding or normalisation in your tooling rather than a missing class. Resolve such members by
|
||||
**shape** — parameter counts, types, interface implementation — instead of by name, and prefer
|
||||
runtime enumeration of loaded classes over guessing identifiers.
|
||||
|
||||
## What this changes about your plan
|
||||
|
||||
- Budget for the runtime layer **up front**. If the app is Flutter/RN/Unity, the dex is not the main
|
||||
battlefield and a dex-only plan will stall.
|
||||
- Any behavioural claim must be validated **through the runtime's own UI**, because that is what the
|
||||
user sees. A patch that changes internal state without changing the UI is not a fix.
|
||||
- Keep the layer you are working in explicit in your notes. "Patched the paywall" is meaningless without
|
||||
saying which layer owned it.
|
||||
@@ -0,0 +1,344 @@
|
||||
# Long-Task Discipline
|
||||
|
||||
Load this when a task is likely to run long: many rounds, many experiments, or a conversation that will
|
||||
exceed what can be held in context. Also load it before resuming a task someone else (or a past you)
|
||||
started.
|
||||
|
||||
The failure mode this file prevents is not tooling — it is **judgement drift**. Over a long task, three
|
||||
things reliably go wrong, and each is expensive in a way that is invisible while it happens:
|
||||
|
||||
1. **You re-derive what you already proved.** Rounds get spent rediscovering a boundary or a mechanism
|
||||
that was established earlier and then lost.
|
||||
2. **You re-walk a route that was already excluded.** The exclusion is real, but the reason has been
|
||||
forgotten, so the route looks promising again.
|
||||
3. **A wrong conclusion keeps steering.** An early mis-attribution is written into your mental model and
|
||||
silently removes good options, or props up bad ones, for a long time afterwards.
|
||||
|
||||
All three come from the same cause: **conclusions living in context instead of on disk**.
|
||||
|
||||
## Keep a live record, not a log
|
||||
|
||||
Maintain one artifact — a single file — that is the task's authoritative state. Update it as things are
|
||||
learned, not at the end. What matters is not size; it is that every entry is **actionable later**.
|
||||
|
||||
Keep these sections:
|
||||
|
||||
| Section | Contents | Why |
|
||||
|---|---|---|
|
||||
| **Operating rules** | things that must be true every run (how to install, how to launch, how to capture) | prevents repeating a mechanical mistake |
|
||||
| **Confirmed facts** | each with the run that proved it | the basis everything else builds on |
|
||||
| **Refuted conclusions** | what you believed, why it was wrong, what replaced it | stops a dead idea from coming back |
|
||||
| **Dead routes** | ruled out, with the evidence | the single biggest time saver |
|
||||
| **Open questions** | what is still unknown | keeps the next step honest |
|
||||
| **Environment** | device, ports, tool paths, credentials locations | avoids re-discovery |
|
||||
|
||||
Two rules make this file worth having:
|
||||
|
||||
- **Every claim carries its evidence.** "The shell rejects this" must include the run that showed it,
|
||||
including the exact failure text. An unattributed claim is how a false conclusion gets adopted later.
|
||||
- **Refutations are first-class entries.** When you find that an earlier conclusion was wrong, record
|
||||
*both* the wrong conclusion and why it was wrong. Deleting the mistake loses the most valuable thing
|
||||
you learned.
|
||||
|
||||
## Grade your own conclusions
|
||||
|
||||
Label every non-obvious statement with its strength, and never let a weaker label inherit the authority
|
||||
of a stronger one:
|
||||
|
||||
| Grade | Meaning | May it justify a decision? |
|
||||
|---|---|---|
|
||||
| **Observed** | reproduced it, with the exact command and output | yes |
|
||||
| **Inferred** | follows from an observation, but the step is reasoned | provisionally |
|
||||
| **Hypothesis** | plausible, untested | only as something to test |
|
||||
| **Refuted** | tested and found false | never — keep it only as a warning |
|
||||
|
||||
Most long-task damage comes from hypotheses drifting upward into "facts" simply by being repeated. If
|
||||
you catch yourself referring to something as established, check the grade in the record. If it is not
|
||||
observed, go observe it or label it again.
|
||||
|
||||
## Single-variable discipline across the whole task
|
||||
|
||||
The most common source of a wrong *and durable* conclusion is a compound experiment: two changes, one
|
||||
failure, one invented explanation. Because the failure is real, the explanation feels earned.
|
||||
|
||||
Consequences to enforce:
|
||||
|
||||
- When a route is about to be abandoned, **re-read why it was abandoned**. If the evidence was compound,
|
||||
the abandonment is not yet justified — re-run it single-variable before writing it off.
|
||||
- Keep a semantic control in your pipeline: a build with **no** changes, run through the same
|
||||
install-and-launch path. If the control fails, nothing else you measure is meaningful.
|
||||
|
||||
## Guard against drift at natural checkpoints
|
||||
|
||||
Do these cheaply, and only when they can change a decision — not as ceremony.
|
||||
|
||||
- **Before starting a new experiment**: read the refuted-conclusions and dead-routes sections. If your
|
||||
plan appears there, stop and read why.
|
||||
- **Before declaring progress**: ask what the *user-visible* outcome is right now. An internal signal
|
||||
improving is not progress (see P19). Re-state the actual target.
|
||||
- **After any surprise**: write it down immediately with evidence, before you have a theory. Theories
|
||||
written after the fact are hard to distinguish from observations.
|
||||
- **When context feels long**: prefer writing to the record over re-reading conversation. The record is
|
||||
what survives; the conversation is what gets truncated.
|
||||
- **When resuming**: read the record first, and treat anything not in it as unknown, even if it feels
|
||||
familiar.
|
||||
|
||||
## The most expensive drift: solving it in an environment the deliverable will never see
|
||||
|
||||
There is one drift in this domain that costs more than all the others, because it produces a
|
||||
result that looks like success and is not one.
|
||||
|
||||
**A runtime-only result is easy to obtain and easy to mistake for a finished artifact.**
|
||||
|
||||
Editing a data file, hooking a live process, blocking a hostname, holding a proxy open — each of
|
||||
these can make the app behave correctly *on the machine where you did it*, with no repackaging
|
||||
required. It is often the fastest path to a visible win. It is also frequently **not the
|
||||
deliverable at all**, because the requirement was never "make it work here".
|
||||
|
||||
The constraint axes that decide this — check every one against the original request, and write
|
||||
down the answer as a testable sentence before you start:
|
||||
|
||||
| Axis | The question | Why it silently invalidates work |
|
||||
|---|---|---|
|
||||
| **Privilege** | must it run **unrooted**? | a rooted-only result cannot be given to a normal user at all |
|
||||
| **Modification form** | must it be a **rebuilt/installable artifact**, or is a live-instrumentation result acceptable? | hooks and data edits do not ship inside an APK |
|
||||
| **ABI / device class** | which ABI, which device family? | an emulator-only or x86-only result is not evidence for a physical ARM device |
|
||||
| **Network** | must it work **online**? | a fix that depends on being offline or on a host proxy fails the moment it is used normally |
|
||||
| **Persistence** | must it survive restart, upgrade, and a fresh install? | in-memory and session-scoped state evaporates |
|
||||
| **Distribution** | does the *shipped file* have to be self-contained? | anything that needs a helper on the machine is not a shippable artifact |
|
||||
|
||||
**Checkpoint question, asked at the same moments as the drift checks above:**
|
||||
|
||||
> *If I handed over exactly what exists right now, would it satisfy the constraint sentence I wrote
|
||||
> at the start?*
|
||||
|
||||
If the answer is no, you have made real progress on a **component**, and that is worth stating as
|
||||
such — but it is not the task. Do not let "it works" stand in for "it works under the constraint".
|
||||
|
||||
**What to do instead of over-claiming.** Split the result into two explicitly labelled parts:
|
||||
|
||||
1. **What is achievable inside the constraint**, and how far along it is.
|
||||
2. **The unconstrained workaround** (needs root / needs a host / needs a proxy), stated as a
|
||||
deliberate fallback, with its requirements made obvious to the reader.
|
||||
|
||||
A privileged workaround is genuinely useful — it can be the difference between using the app and
|
||||
not. It becomes a problem only when it is presented as the deliverable. Report it as a fallback,
|
||||
keep the constrained goal open, and say plainly which one you have.
|
||||
|
||||
**Also watch the inverse**: if the constraint is "must be a rebuilt artifact", do not let a working
|
||||
runtime result quietly close the investigation. Use it for what it is good for — it proves the
|
||||
mechanism and identifies the exact code or data to change — then port that finding into the
|
||||
artifact. The runtime result is the map, not the destination.
|
||||
|
||||
## Bound every wait
|
||||
|
||||
A long task stalls in ways that produce no information and consume the most valuable resource you
|
||||
have: wall-clock time and the next person's patience. Three habits prevent almost all of it.
|
||||
|
||||
**1. Every command has a timeout, and its absence is the bug.** A helper that shells out without a
|
||||
timeout can hang forever, and the failure presents as "the task stopped making progress" rather
|
||||
than "this call blocked". Pass an explicit timeout on every subprocess, every HTTP request, every
|
||||
device call. When one expires, the result is **unknown**, not failed — record it that way and
|
||||
re-check state before retrying.
|
||||
|
||||
**2. Calibrate the expected duration from measurement, not from a guess.** A timeout only means
|
||||
something if it is set relative to how long the operation *should* take, because that is what makes
|
||||
"slow" and "hung" distinguishable. Guessed budgets are either so short that healthy work gets killed,
|
||||
or so long that a stall looks like patience.
|
||||
|
||||
So: **measure once, write it down, then derive the bound.**
|
||||
|
||||
| Operation class | How to bound it |
|
||||
|---|---|
|
||||
| host-side tool (`baksmali`, `apksigner`, a compiler) | seconds to low minutes; time it once, then set roughly 3–5× observed |
|
||||
| device shell call (`adb shell …`) | seconds — **except** the first `su` after a reboot, which can prompt and block |
|
||||
| install / push of a large artifact | minutes; scales with size, not with the app's complexity |
|
||||
| app cold start to first frame | tens of seconds — **longer with a packer**, which does real work before your code runs |
|
||||
| a step needing a human or an external service | **unbounded in principle** — do not wait at all (see P22) |
|
||||
| waiting for an on-screen state change | bound it *and* sample it (point 3) |
|
||||
|
||||
Record the observed durations in the live record. They are exactly the kind of mechanical fact that
|
||||
gets re-derived painfully after a context loss, and having them turns a later timeout into an
|
||||
interpretable signal instead of a mystery.
|
||||
|
||||
**Exceeding the expected window is itself the finding.** It tells you something about state — the
|
||||
device is wedged, the app never reached that phase, the action never happened — and that is a
|
||||
different investigation from waiting longer. Re-check state instead of extending the deadline.
|
||||
|
||||
**3. Every wait has a deadline, an observable to sample, and a look.** "Wait for the operation to
|
||||
finish" is not a plan. Name the observable, how often you will sample it, how long you will sample
|
||||
before giving up, and what you conclude on expiry:
|
||||
|
||||
```
|
||||
waiting for: <observable> e.g. the overlay is gone / the counter incremented
|
||||
sample: <interval + how> e.g. every 15 s: screenshot + current window focus
|
||||
give up at: <deadline> e.g. 150 s
|
||||
on expiry: <what I conclude> e.g. "did not complete within the window" -- not "cannot work"
|
||||
```
|
||||
|
||||
**Sample with your eyes rather than sleeping blind.** When the step is gated on something visible — a
|
||||
screen, a dialog, a progress indicator — capture it and **look at it** instead of sleeping through the
|
||||
interval. A fixed sleep either wastes time or measures the wrong instant; a look tells you what
|
||||
actually happened, and byte-identical consecutive samples tell you nothing is going to change
|
||||
(`environment.md` §look at the screen). This is the cheapest way to avoid spending rounds on a state
|
||||
that was never going to arrive.
|
||||
|
||||
Three rules that follow:
|
||||
|
||||
- **A deadline that passes is a measurement, not a verdict.** "Still not finished after N seconds"
|
||||
tells you about latency and reliability. It does not tell you the approach is impossible, and
|
||||
writing it down as impossible is how a viable route gets discarded.
|
||||
- **Never busy-poll a long job while you have independent work.** Start it, do the other thing, and
|
||||
collect it when it settles. Polling wastes the same resource the task is already spending.
|
||||
- **Prefer a bounded observable over a fixed sleep.** Poll the state you actually care about, with a
|
||||
cap — and prefer a sample you can inspect over a duration you hope is right.
|
||||
|
||||
## Keep the observation window clean
|
||||
|
||||
Every conclusion in this skill rests on "the build I am looking at is the build I made". That
|
||||
assumption is silently false more often than any other, and a contaminated window does not look
|
||||
contaminated — it looks like a result.
|
||||
|
||||
Three ways it happens, all of which have produced confidently wrong findings:
|
||||
|
||||
- **Something else touched the target while you were observing.** Another process, another agent,
|
||||
another window of your own work installed, reverted, restored or cleared the app. Your screenshots
|
||||
and logs are then a mixture of two states and describe neither.
|
||||
- **You are looking at a stale process.** The app was never actually restarted, so the "before" and
|
||||
"after" captures come from the same run.
|
||||
- **The artifact on the device is not the artifact on disk.** An install that reported success, or was
|
||||
skipped because the version matched, leaves the previous build running.
|
||||
|
||||
Guards, in order of cost:
|
||||
|
||||
1. **Pin the identity, not the filename.** Hash the artifact you built, hash the artifact you intend
|
||||
to test, and hash what is actually installed (pull the installed APK or read its digest) — the
|
||||
filename proves nothing. Do this immediately before the observation window, not hours earlier.
|
||||
2. **Take the window deliberately.** Before a capture sequence that a conclusion will rest on, state
|
||||
(to yourself or in the record) that the next N seconds are for this observation only, and do not
|
||||
run another install/uninstall/clear inside it.
|
||||
3. **Timestamp the window.** Record the wall-clock start and end. It costs one line and it is the only
|
||||
way to later notice that a teammate, a background job or your own earlier command landed inside it.
|
||||
4. **Prefer one continuous capture over several short ones.** A restarted capture invites a restarted
|
||||
state; a single sequence cannot straddle an install it did not perform.
|
||||
|
||||
When you discover a window was contaminated, **the correct action is to discard it and re-capture**,
|
||||
not to salvage it. A re-run costs minutes; a wrong conclusion costs the rest of the task, and it will
|
||||
be re-derived from the same bad evidence because the record says it was observed.
|
||||
|
||||
### Captures you never looked at are not evidence
|
||||
|
||||
This is a distinct failure from a contaminated window, and it survives every other guard here. The
|
||||
frames are real, the timestamps are honest, the hashes are right — and nobody looked at them.
|
||||
|
||||
Two shapes it takes, both of which produce a confident wrong answer:
|
||||
|
||||
- **You took the screenshots and moved on.** The images exist; the conclusion was drawn from logcat
|
||||
or from the patch itself. A burst of uninspected frames reads in a report exactly like a burst of
|
||||
inspected ones.
|
||||
- **You did look, but at the wrong thing.** Every frame shows a window that is not your app — a
|
||||
vendor installer confirmation left over from an earlier install, a system dialog, the launcher —
|
||||
and because the frames are consistent with each other, conviction grows. Consistency is not
|
||||
corroboration when all the frames share the same blind spot.
|
||||
|
||||
Guards:
|
||||
|
||||
1. **Check what is on screen before trusting any capture.** One command settles it:
|
||||
`dumpsys activity activities | grep -m1 ResumedActivity`. If the component is not your package,
|
||||
the frames describe something else. Do this at the start of a capture sequence and again at the
|
||||
end — the foreground can change mid-sequence.
|
||||
2. **Inspect immediately, not "later".** Look at the first frame, the middle one, and any frame at a
|
||||
moment you care about (the second the splash would have shown, the moment a dialog would have
|
||||
appeared). If you cannot describe in one sentence what a frame shows, you have not looked at it.
|
||||
3. **Treat identical consecutive frames as a signal.** Byte-identical frames mean the screen is
|
||||
static. That is a finding — a hang, a dialog waiting for input, an activity that never changed —
|
||||
not a capture artefact to be skipped over.
|
||||
4. **Name what you saw, per frame, in the record.** One line each. "f03 at 2.1 s: target main screen,
|
||||
list populated" is evidence; "captured 12 frames" is a file listing.
|
||||
5. **A screenshot of a clean-looking screen is not proof that a dialog is absent** unless you captured
|
||||
continuously across the moment it would have shown. Sampling is not observation: a modal that
|
||||
appears and is then occluded can fall entirely between samples, and every frame you happened to
|
||||
take shows something else.
|
||||
|
||||
`scripts/coldstart.py` exists to make points 1 and 5 automatic: it takes a timed burst, prints the
|
||||
foreground component, and refuses to present the run as meaningful if the foreground is not your
|
||||
app. It still cannot look at the frames for you — that part is on you.
|
||||
|
||||
## Long-context decay: the same mistake, twice
|
||||
|
||||
A long task has a failure mode that has nothing to do with the target: **as the
|
||||
working context fills, settled conclusions lose their force.** Something that was
|
||||
established and verified two hours ago becomes, by the end, just another plausible
|
||||
belief — and the cheapest way to get from a stuck point to a feeling of progress is
|
||||
to re-try the thing that already failed.
|
||||
|
||||
The symptoms, which are recognisable if you watch for them:
|
||||
|
||||
- You are about to run a command whose result you already recorded earlier.
|
||||
- You are about to re-derive a fact (package name, an offset, a version, which
|
||||
patch landed) that is in your own notes.
|
||||
- You are about to re-attempt an approach that failed — and the failure is not
|
||||
obviously connected in your mind to this attempt.
|
||||
- A conclusion you are treating as solid was actually never verified, only
|
||||
assumed early on and repeated since.
|
||||
- You are rewriting a summary of the task from memory rather than reading the
|
||||
record.
|
||||
|
||||
**The antidote is a record written for the second half of the task, not for a
|
||||
human at the end.** Keep it structured so a weakened-context read still gets the
|
||||
decision-relevant content:
|
||||
|
||||
```markdown
|
||||
## Settled (verified — do not re-derive)
|
||||
- <fact> [how it was verified, one clause]
|
||||
## Refuted (do NOT retry — each cost time)
|
||||
- <approach> — fails because <mechanism>
|
||||
## Unverified assumptions currently in play
|
||||
- <assumption> — becomes a problem if <condition>
|
||||
## Next action, and how it will be judged
|
||||
- <one step> — success looks like <observable>
|
||||
```
|
||||
|
||||
Three rules that make the difference:
|
||||
|
||||
1. **Record the mechanism, not just the outcome.** "Traversal via that endpoint
|
||||
broke the home screen because the child request shares the parent load" survives
|
||||
context decay; "tried the endpoint thing, did not work" does not — and the
|
||||
second version invites a third attempt.
|
||||
2. **Re-read the record at every checkpoint, and before starting any new
|
||||
experiment.** Not at the end. The cost is seconds and it is the only thing
|
||||
standing between you and a loop.
|
||||
3. **Two failures of the same shape means the model is wrong, not the
|
||||
parameters.** Do not run a third variation. That is the same rule as the
|
||||
two-strike rule in `SKILL.md`, and long-context decay is exactly what makes
|
||||
people violate it.
|
||||
|
||||
A useful asymmetry: **re-verifying is cheap, re-deciding is not.** Reading a value
|
||||
back out of the artifact takes a second and is fine. Re-running a whole experiment
|
||||
because you forgot its conclusion is what costs the round.
|
||||
|
||||
## Handover
|
||||
|
||||
A handover is the record plus three things, written for someone with **no** memory of the task:
|
||||
|
||||
1. **Operating rules first** — anything mechanical that silently wastes time if unknown.
|
||||
2. **Honest current state** — including what is *not* achieved. An optimistic summary costs the next
|
||||
person far more than an accurate one, because they will build on it.
|
||||
3. **The next best step, and why** — plus the dead routes, so they do not start there.
|
||||
|
||||
Two things belong in every handover, because they are the hardest to recover:
|
||||
|
||||
- **What you got wrong**, with the evidence that corrected it.
|
||||
- **What you never actually verified**, stated plainly. "Never confirmed" is more useful than silence.
|
||||
|
||||
## Avoiding the opposite failure
|
||||
|
||||
Discipline can itself become a burden. Guard against that too:
|
||||
|
||||
- **Do not log everything.** Record only what would change a future decision or prevent a repeated
|
||||
mistake. A record nobody reads is worse than no record, because it looks like coverage.
|
||||
- **Do not treat the record as authority.** It is a summary; the environment is ground truth. If the
|
||||
record and a fresh observation disagree, re-test — do not defend the record.
|
||||
- **Do not let grades calcify.** A hypothesis that becomes testable should be tested, not archived.
|
||||
- **Do not let the record's structure dictate the work.** If a section is empty because it is not
|
||||
relevant to this task, leave it empty.
|
||||
@@ -0,0 +1,90 @@
|
||||
# Membership, paywalls, and the honest limits of client-side patching
|
||||
|
||||
Read this **before** investing hours. Most "unlock VIP / remove the paywall" requests cannot be satisfied by patching the client, and knowing that early is the most valuable output you can produce.
|
||||
|
||||
## First question: who decides?
|
||||
|
||||
| Signal | Owner | Client patch can... |
|
||||
|---|---|---|
|
||||
| A local boolean/int/string field in an app model, computed locally | Client | Fully determine the outcome |
|
||||
| A field that comes from an API response and is merely *read* by the UI | Server | Change display only — not access |
|
||||
| Download/stream/play URLs issued by an API | Server | Nothing. You cannot mint a valid URL. |
|
||||
| Entitlement checked on every protected action with a server round-trip | Server | Nothing |
|
||||
| A local cache of a server value | Server (cached) | Temporarily fool the UI until it refreshes |
|
||||
|
||||
**Decision rule:** if the thing you want (a media URL, a decrypted payload, premium data) is *delivered by the server*, the client is not the gate. The gate is server-side and is not patchable.
|
||||
|
||||
## How to prove it in minutes
|
||||
|
||||
Do not guess. Test the API directly (`references/server-api.md`).
|
||||
|
||||
```
|
||||
1. Call the protected endpoint with no credentials. -> 401/403 means auth-gated
|
||||
2. Call it with an obviously forged token. -> another 401 confirms it is validated
|
||||
3. Call the metadata endpoint. -> often 200, giving you the shape,
|
||||
but deliberately omitting the asset URL
|
||||
4. Compare: is the valuable field simply absent? -> then no client change can invent it
|
||||
```
|
||||
|
||||
A concrete, real result pattern worth remembering:
|
||||
|
||||
- `GET /videos/{id}` → **200**, full metadata, cast list, source list — **but no playback URL at all**
|
||||
- `GET /v2/sections/{id}/play-url` → **401** with no token
|
||||
- same, with `Authorization: Bearer <forged>` → **401**
|
||||
- `GET /user/me` with forged token → **401**
|
||||
|
||||
That combination is conclusive: metadata is public, the asset URL is server-minted, and the token is verified. **Client-side patching cannot unlock it.**
|
||||
|
||||
## What *is* legitimately achievable client-side
|
||||
|
||||
Don't overclaim, and don't underclaim either. Genuinely client-side wins:
|
||||
|
||||
- **Remove ads / SDKs.** Ads are a client behavior (`references/ad-removal.md`).
|
||||
- **Remove a UI gate** where the underlying data is already delivered and only a local check hides it (a "locked" tab whose content is already fetched, a disabled button).
|
||||
- **Skip promotional interstitials and self-promo popups** driven by local flags.
|
||||
- **Unlock client-only features**: debug menus, extra player settings, higher local bitrate selection, gesture options.
|
||||
- **Grant a client-side reward** only if the reward is neither validated nor authoritative server-side (check first — a reward that later fails server validation is worse than no reward).
|
||||
- **Bypass a client-side trial timer** whose enforcement is purely local (but expect the server to re-assert on next sync).
|
||||
|
||||
## What is NOT achievable, and how to say so
|
||||
|
||||
- **Paid content whose URL comes from the server.** State it plainly and show the 401 evidence.
|
||||
- **Server-validated rewards / purchases / credits.**
|
||||
- **Anything the server re-checks on the next request.** The patch may look like it works for one screen and then silently revert.
|
||||
|
||||
Wording that is both honest and useful:
|
||||
|
||||
> The client cannot unlock this. Metadata is public, but the asset URL is issued by the server, and the endpoint returns 401 for both anonymous and forged credentials — so no local change can produce a valid URL. What *is* removable client-side is X, Y, Z. To actually get access you need a real account with the required entitlement.
|
||||
|
||||
## The fake-VIP trap
|
||||
|
||||
Forcing a local `isVip()`-style method to return `true` is the classic mistake. Two failure modes:
|
||||
|
||||
1. **Cosmetic only** — UI shows VIP styling, but protected actions still fail server-side.
|
||||
2. **Actively harmful** — the client now believes it holds entitlements it does not, so it enters code paths that expect server data it never receives. Observed result: **blank screen** (process alive, nothing rendered, only a swallowed uncaught exception in the crash buffer).
|
||||
|
||||
If you patch such a method, patch it in a **conservatively correct** way, and verify all screens, not just the one you cared about:
|
||||
- Do not fabricate entitlements that gate data fetching.
|
||||
- Prefer patching *presentation* consumers of the flag over the flag's computation, if the flag is also used for access decisions.
|
||||
|
||||
## Local state vs code — the deliverable question
|
||||
|
||||
A value can be "fixed" in two places:
|
||||
|
||||
| Where | Survives fresh install? | Fits an APK deliverable? |
|
||||
|---|---|---|
|
||||
| Code (patched dex) | Yes | Yes |
|
||||
| App data (datastore/prefs/db) | **No** | No — unless you also patch the read path |
|
||||
|
||||
If a fix works on your device but a user reports it gone after reinstall, this is why (`references/pitfalls.md` P11). Re-implement the fix by patching the **read path** so it always yields the desired value.
|
||||
|
||||
## Reporting template
|
||||
|
||||
```
|
||||
Goal: <what the user asked for>
|
||||
Gate owner: client | server | mixed (evidence: ...)
|
||||
Achievable: <list, with evidence each>
|
||||
Not achievable: <list, with the 401/absent-field evidence>
|
||||
Residual: <what remains and the exact coupling that prevents removing it>
|
||||
Verified on: <device, build hash, what was exercised>
|
||||
```
|
||||
@@ -0,0 +1,195 @@
|
||||
# Native & SO Layer
|
||||
|
||||
Load this when the Java/dex layer is blocked or unsuitable, when you need code to run **before** the app's
|
||||
own code, or when a native library is the only editable place left.
|
||||
|
||||
If instead the problem is that the app **dies on its own** — hangs, restarts, or crashes natively at a
|
||||
roughly constant time after launch — that is a terminate mechanism, not a hooking problem, and the
|
||||
methods differ: read `native-tamper-and-suicide.md` before this file.
|
||||
|
||||
The Java layer is usually the right choice. Go native when you need one of these:
|
||||
|
||||
- execution **earlier than any app code** (before `Application.onCreate`, before static initialisers),
|
||||
- a change that survives the app re-loading or re-initialising its Java state,
|
||||
- a host the integrity checks do not cover while the dex is covered.
|
||||
|
||||
## Picking a host library
|
||||
|
||||
A library is usable only if all three hold. Verify each; do not assume.
|
||||
|
||||
1. **Loaded in your scenario** — confirm in `/proc/<pid>/maps`, not by inspecting the APK.
|
||||
2. **Editable** — per the boundary map you built in `packers.md`.
|
||||
3. **Has a call the runtime makes for you** — an exported `JNI_OnLoad` is ideal, because the runtime
|
||||
invokes it automatically when the library is loaded by the app, with no trigger of your own.
|
||||
|
||||
Prefer a host whose exported JNI entry point exists *and* which appears in `maps`.
|
||||
|
||||
## The auto-load trap: `DT_NEEDED` does not call `JNI_OnLoad`
|
||||
|
||||
Adding a `DT_NEEDED` entry so one library drags in another is a natural idea. It maps the second library,
|
||||
but **`JNI_OnLoad` is not invoked for it** — that callback only fires when the runtime loads a library
|
||||
through the normal library-load API. A dependency loaded purely by the dynamic linker is mapped, not
|
||||
initialised.
|
||||
|
||||
If you rely on `DT_NEEDED`, your entry point must be an **ELF constructor** or a `DT_INIT` entry, not
|
||||
`JNI_OnLoad`. Conversely, if your host exports `JNI_OnLoad` and you control when the app loads it, that is
|
||||
the simplest reliable trigger.
|
||||
|
||||
Related: a constructor/`DT_INIT` runs so early that the VM may not exist yet. Retry, and treat failure as
|
||||
non-fatal — a library that logs nothing must never take the process down.
|
||||
|
||||
## Relocations and page permissions
|
||||
|
||||
This is where most hand-built native payloads fail, and the failure looks like a crash **inside the
|
||||
dynamic linker**, not inside your code.
|
||||
|
||||
Rules that follow from how Android maps libraries:
|
||||
|
||||
- **A relocation target must be writable at load time.** The linker writes the computed address into the
|
||||
target slot. If the slot lives in a section that is mapped read-only, the write faults
|
||||
(`SEGV_ACCERR` in `plain_relocate_impl`).
|
||||
- **Modern Android refuses W+X segments.** Adding a read/write/execute segment to get both properties is
|
||||
rejected; the loader will not give you one.
|
||||
- Together these mean: relative relocations cannot heal pointer slots that sit in an executable-only page.
|
||||
|
||||
### Bootstrapping when relocations cannot work
|
||||
|
||||
If your payload's internal pointers all live in the same page as the code that reads them, and that page
|
||||
must be executable, you cannot use relocations. Do the fixup at runtime instead:
|
||||
|
||||
1. derive the runtime page base (a PC-relative instruction gives you this without any relocation),
|
||||
2. make the page writable/executable via a direct `mprotect` **syscall** (do not depend on the libc
|
||||
symbol being imported; a syscall needs no linkage),
|
||||
3. write the pointer slots yourself, computed from the runtime base,
|
||||
4. restore the page to read+execute,
|
||||
5. then branch into your entry point.
|
||||
|
||||
Every pointer you need is `runtime_base + fixed_offset`. No relocation is added, so the segment
|
||||
properties never have to change.
|
||||
|
||||
Do **not** try to make a page writable by re-mapping it over itself with an anonymous fixed mapping:
|
||||
that severs the file mapping, and any other thread executing code on that page faults immediately. Use a
|
||||
permission change, not a re-map.
|
||||
|
||||
## Replacing a Java method from native code
|
||||
|
||||
You can redirect a Java method's implementation without touching dex:
|
||||
|
||||
- Look up the method id, walk to the `ArtMethod` structure, and rewrite its **quick entry point**.
|
||||
- Emit a short stub: load a target address from a literal pool and branch to it; return values follow the
|
||||
normal calling convention (arguments are already in place, return in the usual register).
|
||||
- **Always preserve the original code you overwrote.** If the method can be entered through its own
|
||||
entry point, a naive redirect makes it jump into your stub, which jumps back into the same entry —
|
||||
infinite recursion. Copy the overwritten instructions into a trampoline and branch back after them.
|
||||
- **Do not patch a method whose entry still points at a shared interpreter bridge.** Methods that have
|
||||
not been compiled by JIT/AOT share an entry; rewriting it breaks every method that shares it.
|
||||
A practical guard: if two unrelated target methods report the identical entry address, both are still
|
||||
on the bridge — refuse to patch rather than corrupting the process.
|
||||
- Also refuse when the first instruction at the entry is PC-relative (address computed from the current
|
||||
program counter): copying it elsewhere silently changes what it points to.
|
||||
|
||||
Make installation **fail-safe**: if any precondition is not met, skip the patch and let the app run
|
||||
unmodified. A hook that silently does not apply is survivable; a hook that corrupts a shared entry is not.
|
||||
|
||||
## Finding call sites without symbols
|
||||
|
||||
Stripped and obfuscated libraries still expose structure:
|
||||
|
||||
- Scan the code section for the pattern that reaches your target (a PC-relative address computation
|
||||
followed by an indirect branch through a table slot). A method reached through a **cached table slot**
|
||||
will ignore a rewrite of its own entry point, because callers never read that field — another reason
|
||||
the entry-point rewrite must be validated per call site.
|
||||
- Dump the executable range and disassemble around candidate offsets instead of trusting symbol names.
|
||||
- When a payload was produced by a just-in-time compiler on the target, the displacement between its
|
||||
pages is often zero, which is exactly why relocation-free bootstrapping is required (above).
|
||||
|
||||
## Cross-architecture notes
|
||||
|
||||
Architecture is not background information here — it decides **which artifact you must edit** and
|
||||
**whether your hook can observe anything at all**. Get it from the runtime, not from the manifest.
|
||||
|
||||
### What the device claims vs what is executing
|
||||
|
||||
Three different answers, and they disagree more often than people expect:
|
||||
|
||||
| Source | Answers | Command |
|
||||
|---|---|---|
|
||||
| The device | which ABIs the system supports | `getprop ro.product.cpu.abi` and `ro.product.cpu.abilist` |
|
||||
| The package manager | **which ABI it chose for this app on this device** | `dumpsys package <pkg> \| grep primaryCpuAbi` |
|
||||
| The live process | **what is actually mapped right now** | `scripts/lib_map.py --pkg <pkg>` |
|
||||
|
||||
Only the third is ground truth. The first two are predictions, and they are wrong exactly when it
|
||||
matters: an emulator whose primary ABI is `x86_64` can be running an `arm64-v8a`-only app through a
|
||||
translator, and a fat APK can have the package manager pick an ABI you did not assume.
|
||||
|
||||
**Consequence: if the library you patched does not appear in the live mapping, your change cannot
|
||||
matter.** That is a plan problem, and no amount of re-patching will fix it.
|
||||
|
||||
### Translation layers change what you are observing
|
||||
|
||||
When an ARM-only app runs on an x86 host, a translator (Intel Houdini, `libndk_translation`, a
|
||||
`native_bridge` in general) is executing the guest code. Detect it from the maps — look for
|
||||
translator marker libraries and for app libraries whose architecture differs from the host's
|
||||
primary ABI (`lib_map.py` reports both).
|
||||
|
||||
What it changes:
|
||||
|
||||
- **Timing.** Translation is slower and less predictable. Anything you measured about latency is
|
||||
about the translator, not the code.
|
||||
- **Native integrity and anti-tamper checks can behave differently** under translation, in either
|
||||
direction — a check that fails on hardware may pass here, and vice versa. A pass under translation
|
||||
is not evidence of a pass on hardware.
|
||||
- **Hook behaviour.** Intercepting translated code is not the same as intercepting native code:
|
||||
address spaces, calling conventions, and what the host sees at a syscall boundary all differ. If a
|
||||
native hook reports nothing while the feature plainly runs, suspect translation before suspecting
|
||||
your script.
|
||||
- **Syscall-level observation shows the host's view.** A file or network call made from the guest
|
||||
may look different on the host side than it would natively.
|
||||
|
||||
**Rule: verify the artifact on the ABI the user will actually run.** An emulator-only result is a
|
||||
mid-task checkpoint, never the final claim (`verification.md`).
|
||||
|
||||
### Fat APKs: patching the ABI that never loads
|
||||
|
||||
An APK can ship `lib/arm64-v8a/`, `lib/armeabi-v7a/`, `lib/x86_64/`… The package manager extracts
|
||||
**one** of them into the install-time native library directory, and only that one is loaded.
|
||||
|
||||
- Check `primaryCpuAbi` and the live maps before editing a `.so`. Editing `arm64-v8a` while the
|
||||
device loads `armeabi-v7a` produces a build that is byte-different and behaviorally identical.
|
||||
- If the deliverable must work for an unknown user, remember their device may select a different
|
||||
ABI than yours. Either patch every ABI present, or state which ABI your artifact targets.
|
||||
- If the app's own libraries are written at *runtime* rather than extracted from the APK, the live
|
||||
paths will not be inside the APK at all (`lib_map.py` marks these `materialized`). Those belong to
|
||||
whatever produced them, and a repacked APK will not carry them in that location.
|
||||
|
||||
### Payloads and tooling are per-ABI too
|
||||
|
||||
- A native payload, an injected library, or a shellcode blob built for one ABI **will not load** on
|
||||
another. The failure usually surfaces as a *missing library* or a generic linker error rather than
|
||||
a clean "wrong architecture" message — do not read it as "my payload is broken".
|
||||
- **Pointer size differs** between 32- and 64-bit targets. A script or struct layout that assumes
|
||||
8-byte words misbehaves silently on a 32-bit target.
|
||||
- Keep build artifacts per-ABI and label them with the ABI in the filename. Mixing them up is a
|
||||
reliable source of "it crashed for no reason" when the same APK behaves differently on an emulator
|
||||
and on a device.
|
||||
|
||||
### Quick decision list
|
||||
|
||||
1. `scripts/lib_map.py --pkg <pkg> --app-only` → which app libraries are loaded, from where, and at
|
||||
what architecture.
|
||||
2. If a translator is present and the task needs reliable native behaviour, move to a matching
|
||||
device.
|
||||
3. If the library you meant to patch is absent, stop — pick the right library first.
|
||||
4. Only then start editing.
|
||||
|
||||
## Verification
|
||||
|
||||
A native patch earns no credit until the behaviour changes **and** the app stays healthy:
|
||||
|
||||
- log a marker from your entry point so you know it ran at all;
|
||||
- confirm the library is in `maps`;
|
||||
- confirm the app reaches its normal UI afterwards;
|
||||
- keep the original library so you can produce an unmodified control build.
|
||||
|
||||
Never conclude "the hook works" from the absence of a crash. Absence of effect is the normal outcome of a
|
||||
hook that never installed.
|
||||
@@ -0,0 +1,293 @@
|
||||
# Native Tamper Response — When the Library Kills Its Own Process
|
||||
|
||||
Load this when the process dies **without a Java stack trace**, when a build that passed every
|
||||
static check crashes seconds after launch, or when you are about to neutralise a native check.
|
||||
|
||||
This file exists because of one specific, expensive mistake. Read §The rule before you edit a
|
||||
single byte of a shell's native library.
|
||||
|
||||
## The rule
|
||||
|
||||
> **Never neutralise a terminate path by making it not return. Make it return.**
|
||||
|
||||
A terminate routine is reached from ordinary code paths. If you replace it with something that
|
||||
**never returns** — an infinite loop, a self-branch, a stub that spins — the caller never resumes,
|
||||
locks are never released, and every unrelated thread that touches those locks wedges. You have not
|
||||
suppressed the check; you have frozen the process.
|
||||
|
||||
The distinction decides the outcome:
|
||||
|
||||
| Neutralisation | Effect on the caller | Result |
|
||||
|---|---|---|
|
||||
| `ret` / return a benign value | continues normally | check suppressed, process healthy |
|
||||
| spin / self-branch / `while(1)` | never resumes | process freezes, watchdog or user kills it, symptom looks unrelated |
|
||||
|
||||
**Two failure shapes this produces, both of which have been misread as "the patch did not work":**
|
||||
|
||||
- The app hangs with no crash record at all, then disappears. Logs show nothing, because nothing
|
||||
crashed — it stopped.
|
||||
- The watchdog or a system supervisor kills the frozen process, producing
|
||||
`Force stopping … from uid 0` or an app-restart loop. The uid-0 killer is a strong tell: an app
|
||||
cannot spawn a root-owned killer, so the executioner is **outside** the app, which means the app
|
||||
froze rather than failed.
|
||||
|
||||
Both are self-inflicted and both are avoided by returning instead of spinning.
|
||||
|
||||
### The corollary: do not touch normal-path symbols
|
||||
|
||||
A hardening library imports a lot of libc. Some of those symbols are terminate paths; most are not.
|
||||
|
||||
**Symbols that must stay untouched** — they are on ordinary code paths and freezing them breaks
|
||||
everything:
|
||||
|
||||
`pthread_exit` · `exit` · `abort` · `android_set_abort_message` · `snprintf` · `closedir` ·
|
||||
`__cxa_atexit` · `__stack_chk_fail`
|
||||
|
||||
A concrete case: a set of hand-made patches rewired five PLT stubs to self-branches on one
|
||||
architecture and a different five on another. On the first architecture two of the five were
|
||||
`snprintf` and `closedir` — a string formatter and a directory-close — so the app froze on the
|
||||
first log line. On the second the five included `pthread_exit`, so every thread that finished
|
||||
wedged. The patches were meant to suppress a suicide check and instead destroyed the process.
|
||||
|
||||
**Before touching a stub, resolve what symbol it belongs to.** Do not infer it from the stub's
|
||||
position or from a comment. See §Resolving a stub to its symbol.
|
||||
|
||||
## How a hardened library terminates the process
|
||||
|
||||
Enumerate these before you patch anything. Each has a different signature and a different remedy.
|
||||
|
||||
| Mechanism | Log signature | Has tombstone? | How to neutralise |
|
||||
|---|---|---|---|
|
||||
| `kill(getpid(), SIGKILL)` | `Process N exited due to signal 9 (Killed)`, **no** exit code, **no** tombstone | no | patch the call site or make the `kill` stub return 0 |
|
||||
| `exit()` / `_exit()` | process ends with an exit code, no signal | no | find the caller; usually one branch of a check |
|
||||
| `abort()` | `signal 6 (SIGABRT)` + tombstone | yes | usually a genuine assertion — find what tripped it |
|
||||
| **Deliberate crash** (see §Deliberate-crash stubs) | `signal 11 (SIGSEGV)`, tiny `fault addr` such as `0x4`, `Cause: null pointer dereference` | yes | nop the faulting store |
|
||||
| `tgkill` / `raise` | same as kill/abort | varies | often not imported at all — check the import table before assuming |
|
||||
|
||||
**Distinguish these before patching.** "The app crashed" is not a diagnosis. The signal number and
|
||||
the presence or absence of a tombstone split the space in half; getting this wrong sends you to the
|
||||
wrong layer for hours.
|
||||
|
||||
### Deliberate-crash stubs
|
||||
|
||||
The most deceptive mechanism: the library does not call anything. It **arranges a fault** so the
|
||||
death looks like an ordinary bug.
|
||||
|
||||
```asm
|
||||
; arm64 shape observed in the wild
|
||||
mov x0, #4 ; load a small constant…
|
||||
mov w1, #1
|
||||
str w1, [x0] ; …and use it as a pointer. fault addr = 0x4
|
||||
```
|
||||
|
||||
Runtime shape: `SIGSEGV`, `SEGV_MAPERR`, `fault addr 0x4` (or `0x0`/`0x8`), `Cause: null pointer
|
||||
dereference`, and — critically — **the register holding that small constant value**.
|
||||
|
||||
How to recognise it rather than treating it as a real bug:
|
||||
|
||||
1. The faulting address is a **small integer**, not a plausible pointer.
|
||||
2. Disassembling backwards from the faulting `pc` shows the constant loaded **a few instructions
|
||||
earlier, in the same basic block**, with nothing in between that could produce a real pointer.
|
||||
3. The block sits immediately before a function epilogue (canary check + `ret`), i.e. the normal
|
||||
exit is right there and this store is bolted on in front of it.
|
||||
4. There is often a **delay loop just above it** — `sleep`/`usleep` repeated N times — because this
|
||||
is a *watchdog*: wait a while, then die if the condition still holds. That delay is why the crash
|
||||
is always "a little while after launch" rather than immediate.
|
||||
|
||||
**Neutralise it by nop-ing the faulting store**, leaving the surrounding arithmetic alone. The
|
||||
thread then falls through into the epilogue and returns normally. Do not remove the whole block:
|
||||
the two `mov`s are harmless and keeping them makes the diff minimal and reviewable.
|
||||
|
||||
**This is why patching `kill` alone is not enough.** A deliberate crash uses no imported symbol at
|
||||
all, so every PLT-level fix — including a correctly implemented one — leaves it untouched.
|
||||
|
||||
### Find every instance, not the first one
|
||||
|
||||
Search the binary for the **byte pattern**, not with a linear disassembler. The exact encoding is
|
||||
architecture-specific and must be derived from the crash you already have, then searched as bytes:
|
||||
|
||||
- Take the faulting `pc`, read the instruction bytes backwards until you have the full constant-then-
|
||||
store sequence.
|
||||
- Search the whole file for that byte sequence.
|
||||
- If the search returns more than one hit, patch each; if it returns exactly one, you have the
|
||||
complete set — record that fact, it is a real result.
|
||||
|
||||
A linear disassembler is the wrong tool here for a reason covered in §Scanner traps.
|
||||
|
||||
## Resolving a stub to its symbol
|
||||
|
||||
When a stub's target is a PLT entry, the symbol comes from the relocation table, **not** from the
|
||||
stub's bytes or its neighbours. Two architectures encode this differently:
|
||||
|
||||
- **x86_64** — the stub is `jmp qword ptr [rip+disp32]` (6 bytes). The target address is
|
||||
`stub_addr + 6 + disp32`; look that address up in the PLT relocation map.
|
||||
- **aarch64** — the stub is **four instructions / 16 bytes** (`adrp` → `ldr` → `add` → `br`). The
|
||||
GOT address is `page(adrp) + add_imm`. Do not assume a 4-byte stub: a 16-byte stub leaves room
|
||||
for a **two-instruction replacement** (`mov x0, #0` + `ret`), which is exactly what you need, and
|
||||
assuming 4 bytes pushes you into borrowing the neighbouring slot — which belongs to a different
|
||||
symbol and breaks it.
|
||||
|
||||
`scripts/elf_plt.py` does both architectures, including the relocation lookup.
|
||||
|
||||
**Never splice in a neighbouring stub's bytes.** Stubs are laid out back to back; the next one
|
||||
along is a different function, and corrupting it produces a second, unrelated failure that you will
|
||||
then spend hours attributing.
|
||||
|
||||
## Patching a terminate path correctly
|
||||
|
||||
Work in this order.
|
||||
|
||||
1. **Confirm the mechanism first.** Get the tombstone or the signal number. Do not patch on a
|
||||
guess about *how* it dies.
|
||||
2. **Decide between call-site and stub.** Call sites are precise but you must find all of them.
|
||||
A stub covers every caller at once, including ones your scan missed — but it changes behaviour
|
||||
for every symbol user, so it is only safe when that symbol means "terminate" and nothing else.
|
||||
3. **For a stub, return success, not failure.** Callers commonly inspect the return value. Returning
|
||||
**0** (success) lets the caller take its "already handled" branch; returning **-1** pushes it
|
||||
into an error path that may try a different termination method. Make the stub *succeed*.
|
||||
4. **Preserve every byte you did not intend to change.** Record the original bytes so the patch is
|
||||
reversible and auditable.
|
||||
5. **Re-verify the file after patching.** Length unchanged, only the intended offsets differ, and
|
||||
the normal-path symbols are byte-identical to the original. `scripts/elf_plt.py --diff` prints
|
||||
exactly that.
|
||||
|
||||
### What "faithful suppression" looks like
|
||||
|
||||
A library that decides "tampered" and then cannot terminate has an inconsistent state — it believes
|
||||
it has killed the process and continues. That is **acceptable and usually harmless**, because the
|
||||
terminate path is the end of the check; nothing downstream re-reads "did I die". But verify it
|
||||
rather than assuming: after a successful suppression the app must reach its **normal UI and stay
|
||||
there**, not loop through half-initialised states.
|
||||
|
||||
## ELF hardening you will meet in these targets
|
||||
|
||||
Hardening libraries are not normal ELF files. Assume the following until measured otherwise.
|
||||
|
||||
### Forged section headers
|
||||
|
||||
A shell may ship a library whose section header table is deliberately wrong — `.text` sized to a
|
||||
handful of bytes, `.dynsym` truncated, sections overlapping. Tools that walk sections therefore
|
||||
produce **confidently wrong** answers (a symbol list with one entry, an import table that is empty).
|
||||
|
||||
**Work from the program headers instead.** `PT_LOAD` gives you the real mapped segments and their
|
||||
permissions; `PT_DYNAMIC` gives you the pointers you need, walked by hand:
|
||||
|
||||
```
|
||||
DT_STRTAB(5) DT_SYMTAB(6) DT_STRSZ(10) DT_SYMENT(11)
|
||||
DT_JMPREL(23) DT_PLTRELSZ(2) DT_PLTREL(20) DT_PLTGOT(3)
|
||||
```
|
||||
|
||||
Then translate any virtual address to a file offset through the `PT_LOAD` that contains it. A
|
||||
library with forged sections that yields a full import list this way is a good sign; one that
|
||||
still yields almost nothing means the hardening is deeper and you should say so rather than
|
||||
reporting the truncated result as the truth.
|
||||
|
||||
### Function boundaries come from `PT_GNU_EH_FRAME`, not from prologue guessing
|
||||
|
||||
You will need "where does this function start". Two bad answers and one good one:
|
||||
|
||||
- **Reverse-decoding backwards from a call site does not work on aarch64.** Almost any 4-byte
|
||||
window decodes as *some* instruction, so a naive scanner reports hundreds of "function starts"
|
||||
that are all fiction.
|
||||
- **Guessing at prologues** (`sub sp, sp, #imm` + `stp`) produces a plausible set with no guarantee
|
||||
of completeness.
|
||||
- **`PT_GNU_EH_FRAME` is authoritative.** If the segment survives (it usually does, because
|
||||
unwinding is needed at runtime), parsing it yields the real function entry table — every entry,
|
||||
exactly. It is several lines of code and it removes an entire class of wrong conclusions.
|
||||
|
||||
**Check for it first.** If it is present, use it; if it is absent, say your boundary list is
|
||||
heuristic.
|
||||
|
||||
### A function's entry is not where its logic is
|
||||
|
||||
Callers reach a routine through several routes: a direct branch, a cached table slot, or a function
|
||||
pointer in writable data. Rewriting the entry point only covers the first. If a call resolves
|
||||
through a cached pointer, your entry-point change is invisible to it — so before patching an entry,
|
||||
scan for the other routes (`scripts/elf_plt.py`, or a byte-pattern scan for the address).
|
||||
|
||||
## Scanner traps
|
||||
|
||||
**A linear disassembler can stop silently.** Given a buffer whose start is not code, a decoder may
|
||||
return a handful of instructions and then nothing, with no error. Concluding "there are no such
|
||||
call sites in this library" from that output is a false negative with real consequences.
|
||||
|
||||
Guards, in order of preference:
|
||||
|
||||
1. **Byte-pattern search** for a sequence you already know (from a crash or a known call site).
|
||||
Fast, exhaustive, no decoder involved.
|
||||
2. **Fixed-bit-pattern scans** for instruction classes whose encoding is regular — the branch
|
||||
instructions are the useful ones here (`BL`/`B` on aarch64, `call rel32` on x86_64). This finds
|
||||
every call site without depending on linear decoding.
|
||||
3. **Resynchronising scan** — decode, and on failure advance by one instruction unit (4 bytes on
|
||||
fixed-width aarch64, 1 byte on x86_64) and retry. Slower, but it does not stop early.
|
||||
|
||||
Whichever you use, **state which one you used and what it can miss**. "No hits" from a scan whose
|
||||
coverage you cannot describe is not evidence.
|
||||
|
||||
## Deciding whether a dynamic-resolution path matters
|
||||
|
||||
Hardening libraries frequently build a table of function pointers with `dlopen` + `dlsym` — often
|
||||
40+ symbols including terminate calls. This raises an obvious worry: *a call through that table
|
||||
bypasses the PLT stub, so my stub patch does nothing.*
|
||||
|
||||
**Measure it instead of assuming either way.** For each symbol of interest, find whether its table
|
||||
slot is ever **read**:
|
||||
|
||||
- Locate the slot's address (the store from the `dlsym` return, or the table base + index).
|
||||
- Search the code for instructions that load from that address (`adrp`+`add`+`ldr` on aarch64).
|
||||
- **Zero readers means the entry is written and never used.** The table is a redundant fast path,
|
||||
not a bypass, and PLT-level patching is complete.
|
||||
|
||||
Real outcome from a hardened target: the `kill` slot had **zero** readers while the `exit` slot had
|
||||
exactly one, inside a routine that was already suppressed — so no dynamic-resolution bypass existed
|
||||
at all, and the expensive "patch `dlsym` itself" plan would have broken 40 unrelated symbols for
|
||||
nothing.
|
||||
|
||||
**Do not blanket-patch a symbol resolver.** It feeds `open`, `read`, `mmap`, `dlopen` and more.
|
||||
Changing its behaviour to reach one terminate symbol is a large blast radius for a problem you may
|
||||
not have.
|
||||
|
||||
## What these checks actually detect — and why your environment changes the answer
|
||||
|
||||
A terminate path is not reading your patch. It is reading **the world around the process**, so what
|
||||
trips it is environmental, and the same build can die in one setup and live in another.
|
||||
|
||||
| Signal | Typical probe |
|
||||
|---|---|
|
||||
| a debugger is attached | `ptrace`, `TracerPid` in `/proc/self/status`, `prctl` |
|
||||
| the parent process was replaced | a cached `getppid()` compared against a fresh one |
|
||||
| the process was suspended | wait status showing `SIGSTOP` / `SIGTRAP` |
|
||||
| instrumentation is present | hook-framework artefacts: listening ports, thread names, unusual mappings |
|
||||
| a "non-standard" environment | root binaries, emulator fingerprints, writable system paths, build props |
|
||||
|
||||
Two consequences decide whether your experiments mean anything at all:
|
||||
|
||||
1. **A pass under translation is not a pass on hardware.** Under an ARM-on-x86 translator the
|
||||
environment probes return different answers — in *both* directions. A check that fires natively
|
||||
may stay quiet here, and one that is quiet natively may fire. Emulator or translated results are
|
||||
a mid-task checkpoint, never the final verdict.
|
||||
|
||||
2. **Your own tooling can be the thing that trips it.** If the app only dies while you are attached,
|
||||
you are looking at a probe aimed at *you*, not at the app's ordinary startup path. Reproduce with
|
||||
nothing attached before you patch anything.
|
||||
|
||||
**Run the unmodified original through the identical conditions first.** If it dies the same way, the
|
||||
check is firing on the environment rather than on your change, and every conclusion drawn from the
|
||||
patched build's death is void. This is the same control-build rule as everywhere else in this skill,
|
||||
and it is the single cheapest way to avoid chasing a detection that is not about you.
|
||||
|
||||
## Verification
|
||||
|
||||
A native suppression earns no credit until:
|
||||
|
||||
1. The process **survives the window in which it used to die** — and that window must be measured,
|
||||
not guessed. If the observed death was ~40 s after launch, a 30-second test proves nothing.
|
||||
2. It then **keeps surviving** through real interaction, not just idling.
|
||||
3. `crash`/`tombstone` buffers are clean, **and** the process id never changed (a restart with a new
|
||||
pid is a death even when nothing logged a crash).
|
||||
4. The normal-path symbols are byte-identical to the original build.
|
||||
5. A **control build** — same pipeline, no native patch — still dies the same way. Without the
|
||||
control you cannot tell suppression from an unrelated change in timing.
|
||||
|
||||
**Record the observed time-to-death before patching.** It is the only thing that later tells you
|
||||
whether your patch worked or merely moved the window.
|
||||
@@ -0,0 +1,155 @@
|
||||
# Hardened / Packed Targets
|
||||
|
||||
Load this when recon says the app's `Application` class is not the app's own, or when edits make the
|
||||
app die before your code ever runs. Packing is the single most common reason a correct patch appears to
|
||||
"do nothing", so treat it as its own phase with its own evidence standard.
|
||||
|
||||
**Not packed, and still dying?** That is a different layer and a different file:
|
||||
`code-virtualization-and-custom-linkers.md`. There `Application` is the app's own, the dex is fully
|
||||
readable, and yet whole classes are `native` declarations and a private loader carries an embedded
|
||||
validation payload. The single most expensive recon error in this domain is reading "no packer" as
|
||||
"the code is editable" — check for that shape explicitly before planning an edit.
|
||||
|
||||
## What a packer actually does
|
||||
|
||||
A shell (jiagu / weapon / leggu / 360 / ijiami / bangcle class) replaces the manifest's
|
||||
`application android:name` with its own stub. At process start the stub:
|
||||
|
||||
1. loads its own native library from a directory it controls (often extracted at first launch),
|
||||
2. decrypts and loads the real dex, usually from `assets/` or a same-named container,
|
||||
3. optionally verifies that nothing about the APK, its own components, or the environment changed,
|
||||
4. only then forwards to the app's real `Application`.
|
||||
|
||||
Consequences that shape every later decision:
|
||||
|
||||
- **Your code in the app's own dex may never run** if the shell aborts first.
|
||||
- **The shell's native library is the gatekeeper**, and it is usually the only thing that decides
|
||||
"tampered vs clean".
|
||||
- **The shell's own entry is native**, so Java-level reflection into it is usually a dead end.
|
||||
|
||||
## Reading the rejection signal
|
||||
|
||||
The most informative failure looks like this:
|
||||
|
||||
```
|
||||
UnsatisfiedLinkError: JNI_ERR returned from JNI_OnLoad in "<app>/.jiagu/lib<shell>.so"
|
||||
```
|
||||
|
||||
Read it precisely: the shell's **own** `JNI_OnLoad` returned `JNI_ERR`. That means the shell
|
||||
**decided** to refuse — it is not a crash, not a missing library, not an ABI problem. Distinguish it from
|
||||
the look-alikes:
|
||||
|
||||
| Message | Meaning |
|
||||
|---|---|
|
||||
| `JNI_ERR returned from JNI_OnLoad in <shell>.so` | shell actively refused (integrity or environment) |
|
||||
| `dlopen failed: library "X" not found` | a dependency you added does not exist — **your** bug |
|
||||
| `CANNOT LINK EXECUTABLE` / relocation errors | ELF you produced is malformed |
|
||||
| `ClassNotFoundException` during `Application` init | a manifest component you renamed no longer resolves |
|
||||
|
||||
This distinction matters more than it looks: several classes of "the shell rejected me" are actually
|
||||
self-inflicted. Always grep the crash for `linker`, `CANNOT LINK`, `dlopen` and `not found` **before**
|
||||
concluding that the shell detected anything.
|
||||
|
||||
## Map the validation boundary with single-variable tests
|
||||
|
||||
Do not guess what the shell checks. Measure it. The only reliable method is one change at a time, each
|
||||
with its own install-and-launch run:
|
||||
|
||||
1. **Baseline control** — repack with no changes at all, re-sign, install, launch. If this fails, stop:
|
||||
your pipeline is the problem, not the shell.
|
||||
2. **Existing file, semantically inert change** — flip one byte in a section that nothing reads
|
||||
(a `.comment` string, a duplicated `DT_NEEDED` entry). Survives ⇒ edits to existing files of that
|
||||
class are allowed.
|
||||
3. **New file added** — add one benign ELF under the native library directory. Very commonly this alone
|
||||
is enough to trip a check, which is a distinct policy from (2).
|
||||
4. **Component rename in the manifest** — equal-length rename of one lazy component
|
||||
(an `activity`). Survives ⇒ you have a cheap way to neutralise features.
|
||||
5. **Structural change** — move a program header table, add a segment, add a relocation.
|
||||
|
||||
Record every result. The boundary is usually **not uniform**: typical real outcomes are
|
||||
"existing native libraries editable, new ones not", "activities renamable, providers not",
|
||||
"this dex fingerprinted, that container ignored".
|
||||
|
||||
### Why one variable at a time is not optional
|
||||
|
||||
The most expensive mistake in this phase is testing two hypotheses in one build. If you both edit a
|
||||
shell component **and** add a library, and the app dies, you have learned nothing — and you will likely
|
||||
blame the wrong one, discard a viable route, and lose hours (or in this skill's history, dozens of
|
||||
rounds) re-deriving what a cleaner experiment would have shown in one run.
|
||||
|
||||
### Component-type rules worth knowing up front
|
||||
|
||||
- **Providers are instantiated by the system during process start.** Renaming one so its class no
|
||||
longer resolves fails inside `Application.onCreate` and kills the process before anything else runs.
|
||||
Providers are therefore a poor rename target; prefer disabling the feature that consumes them, or
|
||||
hooking it.
|
||||
- **Activities and services are resolved lazily**, only when actually used. Renaming them is a cheap,
|
||||
low-risk way to make a feature unable to display, and it survives most integrity checks because it
|
||||
changes nothing about the shell.
|
||||
- **Equal-length renames** keep binary XML chunk structure valid, so no manifest re-encoding is needed:
|
||||
replace the name bytes in `AndroidManifest.xml` in place, size unchanged.
|
||||
|
||||
## Native libraries as a place to live
|
||||
|
||||
When the shell blocks dex-level changes, native libraries often remain open — but only some of them are
|
||||
useful. A library is a valid host for your code **only if all three hold**:
|
||||
|
||||
1. **It is actually loaded** in the scenario you care about.
|
||||
2. **It is editable** (per your boundary map above).
|
||||
3. **Something in it is called early enough** to matter.
|
||||
|
||||
Condition 1 is the one people skip, and it is the one that wastes the most time. A library shipped in
|
||||
the APK is not necessarily loaded. **Check `/proc/<pid>/maps`** after a real launch rather than assuming:
|
||||
|
||||
```
|
||||
grep -o '/[^ ]*\.so' /proc/<pid>/maps | sort -u
|
||||
```
|
||||
|
||||
Libraries belonging to optional SDKs are frequently lazy: they exist, they may even be unpacked to disk,
|
||||
and they are never mapped during the startup path you are trying to influence. Unpacked-but-unmapped is
|
||||
the signature of a lazy SDK, not evidence that your file was rejected.
|
||||
|
||||
Pick a host that is (a) present in `maps`, (b) exports a JNI entry point the runtime must call, and
|
||||
(c) editable. A library that exports `JNI_OnLoad` and appears in `maps` is the strongest candidate,
|
||||
because the runtime calls `JNI_OnLoad` on its own, without any trigger from you.
|
||||
|
||||
## Where integrity evidence actually comes from
|
||||
|
||||
Shells commonly check a mix of: APK signature, `AndroidManifest.xml`, their own native libraries, the
|
||||
dex they load, and environment signals (root, emulator, hooking frameworks, debugging).
|
||||
|
||||
Practical consequences:
|
||||
|
||||
- **Your own re-signing is itself a detected change** in most signature-based schemes. Assume any
|
||||
signature check will see your build as tampered and plan around it rather than hoping otherwise.
|
||||
- **The environment matters.** Hooking frameworks, debugging, and non-standard filesystems are commonly
|
||||
probed. A patch that works on a clean device may be refused on a rooted one, and vice versa.
|
||||
- **Absence of a log line is not absence of a check.** A shell that fails silently looks identical to a
|
||||
shell that never checked.
|
||||
|
||||
## Locating what the dialog/detection is attached to
|
||||
|
||||
Blocking dialogs ("tampered", "third-party environment", "abnormal") are the usual user-visible symptom.
|
||||
Establish **which layer draws it** before trying to suppress it:
|
||||
|
||||
- If it is a Java dialog, hooking the dialog class shows a caller stack that names the detection.
|
||||
- If hooking the dialog classes produces **no** hits, the UI is likely drawn by a cross-platform runtime
|
||||
(see `framework-runtimes.md`) or by native code, and Java-level hunting is the wrong axis entirely.
|
||||
|
||||
The cheapest high-value experiment, and one that is routinely skipped: run the **unmodified official
|
||||
build** and the **repackaged build** through the *same* probe and diff what differs. The difference is
|
||||
your detection signal. Doing this early is far cheaper than enumerating candidate checks one by one.
|
||||
|
||||
**When the symptom is a death rather than a dialog** — the process disappears, hangs, or dies at a
|
||||
roughly constant time after launch — the check is not drawing anything, it is terminating. The
|
||||
question then becomes *which mechanism*, and the answer decides the whole approach:
|
||||
`native-tamper-and-suicide.md` covers how to tell an imported terminate call from an **arranged
|
||||
fault** (which calls nothing and therefore defeats every PLT-level fix), how to find the site, and
|
||||
why making a routine "not return" freezes the process instead of suppressing the check.
|
||||
|
||||
## Reporting
|
||||
|
||||
State the boundary you measured, the evidence for each entry, and what remains untested. "The shell
|
||||
rejects X" must always carry the run that proves it, including the exact failure string. An unverified
|
||||
claim about integrity behaviour is worse than no claim, because it silently removes routes from
|
||||
consideration.
|
||||
@@ -0,0 +1,151 @@
|
||||
# Auditing your own patch — proving it landed, and proving it is legal
|
||||
|
||||
Two independent questions, and they fail independently:
|
||||
|
||||
1. **Did the edit land?** Did the bytes you intended actually reach the artifact?
|
||||
2. **Is the result legal?** Will the runtime's verifier accept it?
|
||||
|
||||
A patch can land and be illegal (the class fails to load). It can also fail to land while every
|
||||
build step reports success. Both are silent, and each needs its own check.
|
||||
|
||||
## 1. Did it land? Compare *length*, not bytes
|
||||
|
||||
The naive check is a byte-level diff of the target method against the original.
|
||||
**It produces a flood of false positives.** A disassemble→reassemble round-trip rebuilds the
|
||||
string pool — the assembler **de-duplicates identical strings** — which shifts every later
|
||||
string index by a small delta. Hundreds of methods then look "changed" while their behaviour is
|
||||
identical.
|
||||
|
||||
Observed shape of that noise: **~800 methods reported as differing, 84% of them by only 1–4
|
||||
bytes**, all of them constant-pool index shifts, with the method byte-length unchanged.
|
||||
|
||||
**Use instruction-stream length as the first-order predicate.** A real patch that changes control
|
||||
flow or constant structure changes the method's `code_item.insns_size`. Pure index shifts and
|
||||
debug-info reordering do not.
|
||||
|
||||
### The blind spot, and how to close it
|
||||
|
||||
**An equal-length replacement changes nothing measurable by length.**
|
||||
|
||||
Examples that bite: `move-result vX` → `const/4 vX, 0x0` (both one code unit); swapping one
|
||||
`const` for another of the same width; any edit that keeps the instruction count identical.
|
||||
|
||||
Length-only auditing therefore **silently under-reports**: an audit reported 20 changed methods
|
||||
on a build whose patch set actually touched 24 — the four missing ones were all equal-length
|
||||
replacements.
|
||||
|
||||
**Two-tier rule:**
|
||||
|
||||
1. **Tier 1 (length):** scan every method. This yields candidates with essentially zero false
|
||||
positives.
|
||||
2. **Tier 2 (opcode-level):** compare the two versions opcode by opcode **for every method the
|
||||
patch set declares as a target** — not merely the Tier-1 candidates.
|
||||
|
||||
**Tier 2's input cannot come from Tier 1's output.** Equal-length replacements produce no Tier-1
|
||||
candidate at all, so the only reliable index of "what to check at Tier 2" is the patch set's own
|
||||
declarations.
|
||||
|
||||
⇒ **Corollary, which is really a documentation requirement: every patch must declare its target
|
||||
method signature.** A patch that is both equal-length and undeclared is invisible to both tiers;
|
||||
finding it requires opcode-comparing every class, which is possible but expensive.
|
||||
|
||||
### A sharper Tier-2 shape for equal-length replacements
|
||||
|
||||
Compare the **position set of one opcode** inside the method:
|
||||
|
||||
```
|
||||
target method, `move-result` (0x0a) position sets
|
||||
original : [25, 43, 66, 72, 216, ... , 899] (16 entries)
|
||||
patched : [25, 43, 72, 216, ... , 899] (15 entries) <- exactly one removed, pc=66
|
||||
```
|
||||
|
||||
This proves two things at once: the intended site was hit, **and** the other same-shaped call
|
||||
sites in that method were not. Asking "did anything differ" cannot distinguish those.
|
||||
|
||||
## 2. Is it legal? The verifier is a layer static checks cannot see
|
||||
|
||||
An assembler accepting your smali proves the file is **syntactically** valid dex. It does not run
|
||||
the bytecode verifier. A build can pass assembly, pass every class-table check, and still be
|
||||
rejected at class load:
|
||||
|
||||
```
|
||||
java.lang.VerifyError: Verifier rejected class X: void X.<clinit>() failed to verify:
|
||||
[0x1C8] copyRes1 v0<- result0 type=Undefined
|
||||
```
|
||||
|
||||
**Root cause in the observed case:** padding instructions were inserted **between** a producer and
|
||||
its `move-result`. DEX requires `move-result*` to **immediately follow** the instruction that
|
||||
produces the result (`invoke-*`, `filled-new-array*`). The padding broke adjacency, the result
|
||||
type became `Undefined`, and the whole method — and therefore the class — failed to verify.
|
||||
The length arithmetic ("the shorter form plus two padding units preserves the total") was
|
||||
**correct** and still produced an illegal method.
|
||||
|
||||
**Four layers, cheapest first:**
|
||||
|
||||
| Layer | Check | Catches |
|
||||
|---|---|---|
|
||||
| 1 | assembler exit code | syntax, register overflow, bad labels |
|
||||
| 2 | class-table diff (`scripts/dex_classdiff.py`) | class-set / access-flag drift |
|
||||
| 3 | **predecessor legality of `move-result*`** | result consumers detached from their producer |
|
||||
| 4 | device: first execution of that method | everything above, plus real semantics |
|
||||
|
||||
**Layer 3 is a set-difference, not an absolute count.**
|
||||
|
||||
- For both builds, collect every `move-result*` whose immediately preceding instruction is **not**
|
||||
a producer → the "offenders" set.
|
||||
- Compare the sets. **New offenders must be 0.**
|
||||
- **Never use the absolute size as a signal.** A perfectly healthy build can show hundreds of
|
||||
offenders under this definition — payload pseudo-instructions (`packed-switch-payload`,
|
||||
`fill-array-data-payload`, …) are normally read as ordinary instructions by a naive linear
|
||||
scan — so the absolute number is dominated by scanner artifacts. Only the delta means anything.
|
||||
|
||||
Worked consequence: a build whose sole new offender was one `move-result` following padding
|
||||
crashed at class load on device. After moving the padding to **after** the `move-result`, the
|
||||
delta returned to 0 and the same build ran. **The delta predicted the device result before the
|
||||
device was touched.**
|
||||
|
||||
## 3. When patches are applied by text matching
|
||||
|
||||
Some toolchains apply patches by literal match against a text form (smali) rather than through a
|
||||
dex API. The failure modes are textual and unforgiving:
|
||||
|
||||
- **Whitespace is content.** A fragment indented with 5 spaces will not match a file using 4.
|
||||
There is no fuzzy matching; one misplaced space is a zero-hit.
|
||||
- **Line endings.** If the reader normalises CRLF→LF and the writer does not restore it, the
|
||||
patched file becomes LF-only. A later byte-level comparison against the CRLF source then shows
|
||||
the *entire file* as changed. Diff with an ignore-CR-at-EOL option, or compare structure.
|
||||
- **Instruction names must be complete.** `move-result vX` and `move-result-object vX` are
|
||||
different instructions; an anchor missing the suffix matches the wrong thing or nothing.
|
||||
- **Operand punctuation matters.** `instance-of p3, p0, LType` is not the source text when the
|
||||
source reads `LType;`.
|
||||
- **Uniqueness is a hard requirement.** A matcher that finds several hits must fail loudly rather
|
||||
than patch the first. When a one-line anchor is not unique, extend it with a second unique line;
|
||||
**when the *combination* is still not unique, add a third anchor that discriminates the
|
||||
homographs** — usually the branch target label, since identical call shapes often differ in
|
||||
where they jump.
|
||||
- **A re-emitted old fragment is not a failed write.** A patch may legitimately re-emit the old
|
||||
text inside the new one (inserting a guard *before* the lines it matched). A read-back check
|
||||
asserting "the old text is gone" then reports failure on that patch forever. Assert instead
|
||||
that the **new, unique** part of the replacement is present.
|
||||
- **One patch document, one patch block.** A parser that treats every fenced block as a candidate
|
||||
will apply an *example* diff as a real patch — silently cancelling the real one, or editing
|
||||
unrelated code. Keep examples in prose, never in the same fence format.
|
||||
|
||||
## 4. Audit the patch set, not a patch
|
||||
|
||||
For a multi-patch build:
|
||||
|
||||
```
|
||||
expected = every method declared as a target by the patch set
|
||||
tier1 = methods whose insns_size changed
|
||||
tier2 = methods whose opcode stream differs (run over `expected`)
|
||||
missing = expected - (tier1 U tier2) # must be empty
|
||||
```
|
||||
|
||||
**`missing` is the number that matters.** A build can be green on every build step and still be
|
||||
missing a patch. Report `missing` explicitly; do not report the total as if the total were the
|
||||
goal.
|
||||
|
||||
**And re-verify the artifact, not the intent.** If the tool says "applied" but the build on the
|
||||
device is unchanged, you have a stale build, a second copy, or the wrong file
|
||||
(`pitfalls.md` P24). A patch tool's success message describes the tool, not the artifact.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,201 @@
|
||||
# Recon — build the picture before touching anything
|
||||
|
||||
Ten minutes here prevents hours of wrong work. Answer the five questions from `SKILL.md` with concrete evidence.
|
||||
|
||||
## 1. Identity
|
||||
|
||||
```bash
|
||||
# Without a full decompiler (fast, works everywhere):
|
||||
aapt dump badging app.apk | head -20
|
||||
# or, from the extracted manifest:
|
||||
# package name, versionName, versionCode, sdkVersion, targetSdkVersion
|
||||
# or, if you have ddc (no JVM, single binary, also gives the launcher):
|
||||
ddc info app.apk
|
||||
```
|
||||
|
||||
Record: package name, version name/code, min/target SDK, all requested permissions, all declared components.
|
||||
|
||||
**Do not hand-parse the package name out of the binary manifest as your primary
|
||||
source.** Real AXML string tables are full of class-name fragments that look
|
||||
exactly like package names — in one sample, the strings visible without a real
|
||||
parser suggested `com.<app>.offline` (a service class prefix) while the actual
|
||||
package was `com.<vendor>.app`. Every later `pm list packages`,
|
||||
`dumpsys package`, `/data/data/<pkg>` and `pm install` command depends on this
|
||||
value, so getting it wrong sends the whole recon down a path where nothing is
|
||||
found and the natural conclusion is "the tool is broken".
|
||||
|
||||
Cross-check two independent sources and require agreement:
|
||||
|
||||
- `ddc info app.apk` → `package`, `label`, `launcher`
|
||||
- `aapt2 dump badging app.apk | head -1` (or `aapt dump badging`)
|
||||
|
||||
If they disagree, resolve it before proceeding. A single `label` value is also
|
||||
worth having: it is what appears on the launcher, which makes device-side
|
||||
identification unambiguous later.
|
||||
|
||||
**Note:** some `aapt` builds choke on non-ASCII paths. Normalize sample paths to ASCII before running tooling.
|
||||
|
||||
## 1b. Snapshot the config surface early
|
||||
|
||||
If the app has a remote-config endpoint, its DTOs are the cheapest thing in the
|
||||
package to find, because data classes serialise their own field names into strings
|
||||
that survive R8:
|
||||
|
||||
```bash
|
||||
ddc findrefs app.apk string "SplashConfig" # or Config, Popup, Banner, Tabbar...
|
||||
ddc strings app.apk -f "enabled" --with-locations
|
||||
```
|
||||
|
||||
Do this during recon rather than later: it tells you immediately whether the
|
||||
launch screen, popups and tab set are **client decisions** or **server data**,
|
||||
which is the difference between a five-minute patch and a dead end. See
|
||||
`server-config-and-updates.md`.
|
||||
|
||||
## 2. Is it packed?
|
||||
|
||||
Read `AndroidManifest.xml` → `application android:name`.
|
||||
|
||||
| What you see | Meaning |
|
||||
|---|---|
|
||||
| The app's own class (e.g. `com.example.app.App`) | **No packer.** Dex is directly editable. |
|
||||
| A vendor class (`com.stub.StubApp`, `com.secneo...`, `com.tencent.StubShell`, `s.h.e.l.l.*`, `com.nagain.*`, …) | **Packed.** Unpack first. |
|
||||
| A short meaningless name that does not match the app's package (e.g. `com.bc41`), plus `android:appComponentFactory` pointing at another short class | **Dex-level whole-APK packer.** The shell registers its own Application/proxy under names unrelated to the app. |
|
||||
| `classes.dex` is only tens of KB and holds nothing but shell classes | The real code is not on disk. |
|
||||
| A shell library in `lib/<abi>/` (`libDexHelper.so`, `libjiagu*.so`, `libshell*.so`, …) | Native half of the shell: decrypts and loads the payload. |
|
||||
| One or more large high-entropy `assets/` blobs, possibly **disguised as JPEG** (valid magic bytes, no decodable image) | Encrypted payload. |
|
||||
| `assets/` contains a second `.apk` or `.jar` | Wrapped/loader build. |
|
||||
|
||||
**A clean shape is also a result: record it and move on.** An app whose
|
||||
`application android:name` is its own class, with a single plain `classes.dex` and
|
||||
no native libraries, is directly editable — and that finding is what lets you skip
|
||||
the entire packer/unpack branch of this skill. It is worth one explicit line in the
|
||||
record ("no packer: application is the app's own class; dex readable; no lib/") so
|
||||
that later steps cannot re-open a question that was already answered. Most real
|
||||
targets are this shape; the packer material in this repository exists for the rest.
|
||||
|
||||
Decide from sizes and structure, not from names:
|
||||
|
||||
```bash
|
||||
unzip -l app.apk | sort -k1 -n | tail -20 # biggest entries: assets? libs? dex?
|
||||
```
|
||||
|
||||
**Loaded-shell check (highest fidelity):** if the app runs and its own classes are reachable, it is unpacked *at runtime* regardless of what the manifest says. If the app's own code is not among the dex classes, it is packed on disk.
|
||||
|
||||
### Unpacking a dex-level packer
|
||||
|
||||
**1. Map payload → dumped dex by length.** If the shell uses **length-preserving** encryption, each encrypted `assets/` payload has **exactly the same byte count as the plaintext dex** it decrypts to. That equality is the strongest single discriminator for "which dump is a real original dex" — far more reliable than sorting dumps by size. Measure it per file before trusting any dump.
|
||||
|
||||
**2. Check how the real dex is loaded.** A log line like `InMemoryDexFile[cookie=[0, ...]]` means the dex is built in memory from the payload and never written to disk, so there is no dropped file to find. Use a **memory-scanning** dumper (`frida-dexdump`, or your own script walking the class loaders) instead of hunting for artifacts under the app's data directory. See `references/dynamic-frida.md`.
|
||||
|
||||
**3. Two dumper caveats that cost real time.**
|
||||
- `-D <device-id>` does **not** accept a remote device (`Device '<id>' not found`). Register a remote device with `-H <host>:<port>`; keep `-D` for local/USB ids.
|
||||
- The `-o <dir>` output directory **must already exist** — the tool does not create it. Otherwise every dex write fails and the run still ends with `All done`, which reads exactly like a successful dump of nothing. `mkdir -p out` first, and judge the result by the file count, never by the final message.
|
||||
|
||||
**4. Filter the dumps before using any of them.** A memory dump contains three kinds of garbage:
|
||||
- **Duplicate copies of one dex.** Identical byte count does **not** imply identical content — files of the same size have been measured to differ in ~73% of their bytes, carry a different dex version, and fail to parse. Dedupe by **content hash**, never by size.
|
||||
- **SDK plugin dexes downloaded at runtime**, which were never part of the APK.
|
||||
- **Structurally broken dexes** whose header and body disagree.
|
||||
|
||||
Cheap header check that catches the third class, plus the hash used for the first:
|
||||
|
||||
```python
|
||||
import struct, hashlib
|
||||
d = open(p, 'rb').read()
|
||||
assert d[:4] == b'dex\n' # magic
|
||||
assert struct.unpack_from('<I', d, 32)[0] == len(d) # file_size == actual size
|
||||
assert struct.unpack_from('<I', d, 36)[0] == 112 # header_size
|
||||
sha = hashlib.sha256(d).hexdigest()
|
||||
```
|
||||
|
||||
Then confirm survivors actually parse (`baksmali`/dexlib2) or load on device. Header consistency alone is not proof of a usable dex.
|
||||
|
||||
**5. Which dump is the app's own business dex.** Count string-feature hits per dump instead of trusting file order:
|
||||
|
||||
```bash
|
||||
python scripts/dex_strings.py <dump_dir> --find 'Lcom/example/app/' --per-file
|
||||
python scripts/dex_strings.py <dump_dir> --find 'Lcom/example/adsdk/' --per-file
|
||||
```
|
||||
|
||||
Heuristic: the business dex mixes the app's package prefix (hundreds of hits) with an ad-SDK prefix (thousands of hits). A pure SDK plugin dex has one vendor prefix at its maximum count and **zero** app-package hits. Zero app-package hits means it is not the app.
|
||||
|
||||
## 3. Where does the app's own code live?
|
||||
|
||||
| Indicator | Code location |
|
||||
|---|---|
|
||||
| Plain `classes*.dex`, app classes visible in them | **Dex** — patchable with dexlib2/smali |
|
||||
| `libflutter.so` + `libapp.so` | **Flutter (Dart AOT)** — dex contains only a thin shell |
|
||||
| `libil2cpp.so` + `assets/bin/Data/` | **Unity (IL2CPP)** — native |
|
||||
| `libmono*.so` + `assets/bin/Data/Managed/` | **Unity (Mono)** — managed DLLs under `assets/` |
|
||||
| `libreactnativejni.so` + `assets/index.android.bundle` | **React Native** — JS bundle under `assets/` |
|
||||
| `libhermes.so` | **Hermes bytecode** |
|
||||
| Almost everything in `.so` | **Native** — different toolchain entirely |
|
||||
|
||||
For a **Kotlin/Java app**, note the module layout: app code often lives in a small subset of dex files while large SDKs occupy the rest. Finding which dex holds the app's package is a huge time-saver:
|
||||
|
||||
```bash
|
||||
python scripts/dex_strings.py <dex_dir> --find 'Lcom/example/app/' --per-file
|
||||
```
|
||||
|
||||
Consequence for editing: you usually only need to replace **one or two dex files**, which keeps the repack minimal. When the app is packed, run this check against the **dumped** dexes, not the ones on disk (§2).
|
||||
|
||||
## 4. SDK and library inventory
|
||||
|
||||
Extract strings across all dex and group by vendor markers. This reveals ads, analytics, crash reporting, attribution, and any anti-tamper SDK, in one pass.
|
||||
|
||||
```bash
|
||||
python scripts/dex_strings.py <dex_dir> --urls
|
||||
python scripts/dex_strings.py <dex_dir> --find 'anythink|openadsdk|com.qq.e|umeng|bugly|crashsdk'
|
||||
```
|
||||
|
||||
What to look for:
|
||||
|
||||
- **Ad networks / aggregators**: `openadsdk` `TTAdSdk` `Pangle` `com.qq.e` `GDTAd` `anythink` `ATSDK` `ksad` `mobads` `sigmob` `bdxadsdk`
|
||||
- **Analytics / crash / attribution**: `umeng` `bugly` `crashsdk` `appsflyer` `adjust` `UMCrash`
|
||||
- **Identity / device id**: `oaid` `msa` `SupplementaryDID` `freemme`
|
||||
- **Anti-tamper / root / hook detection**: `libsgcore` `libInno` `libqmcheat`, strings like `frida` `xposed` `magisk` `substrate`, `/system/xbin/su`
|
||||
- **Media stack**: `libmpv` `libavcodec` `libplayer` `libgdx`
|
||||
|
||||
Important distinction: **a vendor marker in the string table does not mean the app uses that feature**. Presence of `xposed`/`frida` strings is often just an SDK's own detection list. Decide based on *behavior*, not on strings (`references/verification.md`).
|
||||
|
||||
## 5. Signature and tamper checks
|
||||
|
||||
Search the app's **own** packages only (ignore third-party SDKs) for:
|
||||
|
||||
- `getPackageInfo`, `PackageInfo`, `signatures`, `GET_SIGNATURES`, `Signature` → app-side signature verification
|
||||
- hardcoded SHA-1/SHA-256 hex constants, base64 license blobs → certificate pinning to the original signer
|
||||
- `checkSignature`, `verifySignature`, `signCheck` → a named check
|
||||
|
||||
**Beware false positives.** `SignatureCheck` and `verifySignature` exist inside `okhttp3` (`SuppressSignatureCheck`, `BasicCertificateChainCleaner.verifySignature`) — TLS plumbing, not app tamper checks. Likewise a native `lib*.so` named like a security library may be an ad SDK's payload decryptor, not a shell.
|
||||
|
||||
Confirm by checking whether **app code** references it. If the only callers are library-internal, it is not your problem.
|
||||
|
||||
## 6. API surface
|
||||
|
||||
```bash
|
||||
python scripts/dex_strings.py <dex_dir> --urls
|
||||
```
|
||||
|
||||
Collect: base URLs, DoH/DoT lookups, path constants, CDN hosts, custom headers.
|
||||
|
||||
Treat **unique** strings as navigation aids — they can often be searched byte-wise in the dex to find the owning class (see `references/dex-patching.md` §finding-the-call-site).
|
||||
|
||||
Two patterns worth recognizing early:
|
||||
- **Dynamic gateway**: the real API host is fetched at runtime (e.g. via a DNS TXT record over DoH). The hardcoded host in dex may be only a fallback. This affects server-side analysis, not patching.
|
||||
- **Minimal headers / no request signing**: if auth is just `Authorization: Bearer` plus a static app-name header, then a repackaged client is not distinguishable to the server by request signature — which matters for `references/server-api.md`.
|
||||
|
||||
## Recon output
|
||||
|
||||
Write a short profile before patching. Minimum:
|
||||
|
||||
```
|
||||
package / version / ABI
|
||||
packed? (evidence)
|
||||
if packed: packer family, unpack method, kept dumps + sha256
|
||||
code location (dex / flutter / native)
|
||||
app code in which dex files
|
||||
ad SDK(s) and the app's wrapper class
|
||||
analytics/crash SDKs
|
||||
anti-tamper: present? where? app-side or library-internal?
|
||||
API base + notable endpoints
|
||||
device plan (rooted real device / emulator / static only)
|
||||
```
|
||||
@@ -0,0 +1,276 @@
|
||||
# Repack and sign
|
||||
|
||||
Rebuilding is the step where otherwise-correct patches die. Two mistakes account for nearly all of it: **stripping `META-INF/`** and **recompressing entries that must stay stored**.
|
||||
|
||||
## The rules
|
||||
|
||||
**1. Strip only signature artifacts, never the whole directory.**
|
||||
|
||||
`META-INF/` contains ServiceLoader registrations the app needs at runtime. Details and the exact failure in `references/pitfalls.md` P1.
|
||||
|
||||
```python
|
||||
SIG_EXT = ('.SF', '.RSA', '.DSA', '.EC')
|
||||
def is_signature_entry(name):
|
||||
if not name.upper().startswith('META-INF/'):
|
||||
return False
|
||||
rest = name[len('META-INF/'):]
|
||||
if '/' in rest: # keep services/, androidx/, native-image/ ...
|
||||
return False
|
||||
up = rest.upper()
|
||||
return up == 'MANIFEST.MF' or up.endswith(SIG_EXT)
|
||||
```
|
||||
|
||||
**2. `AndroidManifest.xml` and `resources.arsc` must stay uncompressed (STORED).**
|
||||
|
||||
Recompressing them produces builds that fail to install or misbehave.
|
||||
|
||||
**2a. `resources.arsc` must ALSO be 4-byte aligned, and the failure is an install refusal.**
|
||||
|
||||
On Android 11+ (targetSdk 30+) the package manager rejects the install outright:
|
||||
|
||||
```
|
||||
Failure [-124: Failed parse during installPackageLI: Targeting R+ (version 30 and
|
||||
above) requires the resources.arsc of installed APKs to be stored uncompressed and
|
||||
aligned on a 4-byte boundary]
|
||||
```
|
||||
|
||||
Two independent requirements hide in that one sentence: STORED, and the entry's
|
||||
**data offset** divisible by 4. Uncompressed `lib/*.so` follows the same rule.
|
||||
|
||||
A naive `zipfile.ZipFile(...).writestr(...)` loop satisfies neither reliably:
|
||||
Python's zip writer gives you no control over entry offsets. `scripts/repack.py`
|
||||
therefore emits local headers itself and pads the **local extra field** to reach
|
||||
the boundary. The padding arithmetic has one trap worth knowing:
|
||||
|
||||
> A zip extra area is a sequence of `(id, size, payload)` records, so its minimum
|
||||
> useful length is 4 bytes. A required pad of **1-3 bytes cannot be expressed**.
|
||||
> When the natural pad falls in that range, insert a stored filler entry of
|
||||
> exactly that size instead -- the filler has a computable size, so the following
|
||||
> entry still lands on the boundary.
|
||||
|
||||
Verify by reading the archive, not by trusting the writer: for each entry Android
|
||||
cares about, parse its local header, compute `header_offset + 30 + namelen +
|
||||
extralen`, and check `compress_type == 0` and `offset % 4 == 0`.
|
||||
`repack.py` prints exactly this ("alignment gate") and `check_alignment()`
|
||||
returns the complaint list programmatically.
|
||||
|
||||
**Do not plan on repairing alignment with `zipalign` after the fact when you can
|
||||
produce a correct archive directly.** A post-hoc pass rewrites the file; on a
|
||||
target that fingerprints its own byte layout, that is a much larger change surface
|
||||
than writing it correctly the first time. Keep `zipalign -c -v 4` as an
|
||||
independent check when the tool is available.
|
||||
|
||||
**3. Keep the APK's zip entry metadata.** Preserve `compress_type`, `external_attr`, `date_time` for entries you copy through.
|
||||
|
||||
**4. Changing any dex changes nothing about resources.** If you only edited dex, do not touch `res/`, `assets/`, or `lib/`.
|
||||
|
||||
**4a. A full `apktool b` rebuild rewrites resource paths even when you edited none.** Decoding with
|
||||
`apktool d` (without `-s`) and rebuilding re-encodes resources, and obfuscated short names are
|
||||
expanded back to readable ones — an entry originally shipped as `res/-B.png` comes back as
|
||||
`res/drawable-hdpi/<real-name>.png`. Expect an entry-level diff against the original to show on the
|
||||
order of a thousand "removed + added" pairs that are **pure renames**, not content changes.
|
||||
|
||||
This is expected and usually harmless, but two consequences matter:
|
||||
|
||||
- **Never read that diff as "I broke something".** Compare by identity (rename-aware, or by content
|
||||
hash grouped by size) before drawing a conclusion. A toy diff that reports 1100 changes when you
|
||||
edited one method is a **tool** artifact and will send you hunting a bug that does not exist.
|
||||
- **It changes the byte layout of the whole archive.** On a target that fingerprints its own file
|
||||
against a stored hash, or whose protection binds offsets into a container, a full rebuild is a much
|
||||
larger change surface than a dex-only swap. If your only edit is dex, prefer replacing the
|
||||
`classes*.dex` entries inside the original zip (`compress_type` preserved) over a full rebuild.
|
||||
Keep that dex-only path as a fallback for exactly this reason.
|
||||
|
||||
If you must avoid resource churn entirely, decode with `-s` (do not decode resources) and only
|
||||
rebuild what you changed.
|
||||
|
||||
**5. Signing creates new `MANIFEST.MF`/`*.SF`/`*.RSA`.** That is expected — the check is that **no signature artifact from the ORIGINAL** survives, and **no non-signature entry was lost**.
|
||||
|
||||
**6. Any dex you edited must have its header integrity fields recomputed.**
|
||||
Every dex carries two fields that cover the rest of the file:
|
||||
|
||||
```
|
||||
bytes 12..32 = sha1(data[32:]) # signature — must be computed FIRST
|
||||
bytes 8..12 = adler32(data[12:]) # checksum — covers the signature, so it is LAST
|
||||
```
|
||||
|
||||
Skipping this does not always stop the app from starting, which is what makes it
|
||||
dangerous. Android logs
|
||||
`Failure to verify dex file ...: Bad checksum (computed, expected)` — the real
|
||||
value appears as "expected", which reads backwards — and then falls back to
|
||||
interpreting the dex instead of using a verified image. The visible symptom is an
|
||||
unrelated startup failure such as `ClassNotFoundException` for an ordinary class
|
||||
(the Application class, or a small AndroidX component), so the trail points at the
|
||||
APK structure rather than at two stale header words.
|
||||
|
||||
`scripts/dexutil.py` exposes `fix_dex_header()` (correct order, plus
|
||||
`verify_dex_header()` so you can assert the result), and
|
||||
`scripts/dex_patch_bytes.py` runs both automatically before writing.
|
||||
|
||||
**7. `jarsigner` rewrites the archive; `apksigner` does not.**
|
||||
|
||||
Adding a v1 JAR signature with `jarsigner` recompresses entries as a side effect,
|
||||
which **destroys the alignment from rule 2a**. The signature still verifies, so the
|
||||
build looks correct until the install is refused with `[-124]`. Sign with
|
||||
`apksigner` (v1+v2+v3) unless you have a specific reason not to.
|
||||
|
||||
## Repacking an unpacked (de-shelled) app
|
||||
|
||||
When the sample was packed, the dex you are about to patch came out of a memory dump while the APK still carries the shell. Build a **de-shelled base APK** first, then treat it as an ordinary APK for the rest of this document.
|
||||
|
||||
1. **Assemble the base.** Start from the original APK: replace `classes*.dex` with the dumped real dexes, and delete the shell library under `lib/<abi>/` plus the encrypted `assets/` payloads. Strip **only** signature artifacts — `META-INF/*.SF|*.RSA|*.DSA|*.EC` and the top-level `MANIFEST.MF`. Never delete the whole `META-INF/` (`references/pitfalls.md` P1).
|
||||
2. **Decode with `apktool`.** `apktool d base.apk` gives the smali tree and a **readable text manifest**.
|
||||
3. **Fix the manifest.** Point `application android:name` at the app's real Application class and **remove** `android:appComponentFactory`. Grep the decoded tree for leftover shell class references before building.
|
||||
4. **Patch, then rebuild.** `apktool b` → `zipalign -p -f 4` → `apksigner` (v1+v2+v3) → install and verify against the checklist at the end of this file.
|
||||
|
||||
Why `apktool` rather than editing binary AXML in place: changing `android:name` in binary AXML means hand-editing the string pool and the attribute/chunk sizes around it, and a mis-sized chunk produces an APK that installs but throws far from the edit, typically in component lookup at startup. The text round-trip moves the risk to "did the rebuild preserve everything else", which item 5 of the checklist verifies directly.
|
||||
|
||||
## Pipeline
|
||||
|
||||
`scripts/repack.py` implements all of the above. Conceptually:
|
||||
|
||||
```
|
||||
open original (zip)
|
||||
for each entry:
|
||||
skip entries that are signature artifacts (per rule 1)
|
||||
skip entries being replaced
|
||||
copy through, preserving compression + attributes
|
||||
write replacement entries
|
||||
close
|
||||
sign (v1 + v2 + v3)
|
||||
verify
|
||||
```
|
||||
|
||||
Usage:
|
||||
|
||||
```bash
|
||||
python scripts/repack.py --apk original.apk --dexdir extracted_dex_dir --out out.apk
|
||||
# or replace specific dex files:
|
||||
python scripts/repack.py --apk original.apk --dexdir extracted_dex_dir \
|
||||
--dex "classes7.dex=patched/classes7.dex" \
|
||||
--dex "classes8.dex=patched/classes8.dex" \
|
||||
--out out.apk
|
||||
```
|
||||
|
||||
`--dexdir` supplies the untouched dex files; `--dex name=path` overrides specific ones.
|
||||
|
||||
## Signing
|
||||
|
||||
Two viable routes.
|
||||
|
||||
**Route A — `uber-apk-signer` (handy, wraps zipalign + apksigner):**
|
||||
```bash
|
||||
java -jar uber-apk-signer.jar --apks in.apk --ks ks.jks \
|
||||
--ksAlias <alias> --ksPass <pass> --ksKeyPass <pass> -o out_dir
|
||||
```
|
||||
Known quirk: `-o` and `--overwrite` are mutually exclusive; passing both errors out. Also, it **silently skips already-signed APKs** (`0 processed`) — so de-sign first.
|
||||
|
||||
**Route B — `zipalign` + `apksigner` directly (most explicit):**
|
||||
```bash
|
||||
zipalign -p -f 4 unsigned.apk aligned.apk
|
||||
apksigner sign --ks ks.jks --ks-pass pass:<pass> --key-pass pass:<pass> \
|
||||
--v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true \
|
||||
--out signed.apk aligned.apk
|
||||
apksigner verify --print-certs --verbose \
|
||||
--min-sdk-version 21 --max-sdk-version 34 signed.apk
|
||||
```
|
||||
|
||||
Enable **v1 + v2 + v3**. v1 is needed for older Android; v2/v3 for modern verification.
|
||||
|
||||
Generate a keystore once:
|
||||
```bash
|
||||
keytool -genkeypair -v -keystore ks.jks -alias <alias> \
|
||||
-keyalg RSA -keysize 2048 -validity 36500 \
|
||||
-storepass <pass> -keypass <pass> \
|
||||
-dname "CN=<name>, OU=dev, O=dev, L=NA, ST=NA, C=NA"
|
||||
```
|
||||
|
||||
## `apksigner verify` picks schemes from the APK's own minSdk
|
||||
|
||||
`apksigner verify` decides which signature schemes to check from the APK's own `minSdkVersion`. With `minSdk >= 24` it prints v1/v2 as `false` **by design**, even though `META-INF/*.SF` is present and the signature is valid. That output is indistinguishable from "signing did not apply" and sends you into a re-signing loop over a file that was never wrong.
|
||||
|
||||
Always pass the explicit range (Route B above) and read the scheme list from that run only. Never judge a build from a default-argument `apksigner verify`.
|
||||
|
||||
## Installing over an existing app
|
||||
|
||||
| Situation | Command |
|
||||
|---|---|
|
||||
| Same signing key as installed version | `pm install -r` — keeps app data (login state, caches) |
|
||||
| Different signing key | `pm uninstall` first, then install. **App data is lost** — say so in the delivery notes |
|
||||
| OEM installer refuses (`INSTALL_FAILED_*`, vendor restrictions, a bare negative code) | push the APK and install via root: `su -c 'pm install -r -d /data/local/tmp/app.apk'` |
|
||||
| Downgrade needed | add `-d` |
|
||||
| Test-only flag needed | add `-t` |
|
||||
|
||||
Useful detail: keeping the same keystore across builds lets you iterate with `-r` and **preserve a logged-in session**, which matters a lot when the feature you are testing needs auth.
|
||||
|
||||
### Vendor install interception (OEM shells)
|
||||
|
||||
Some ROMs route `adb install` through their own "security centre", which can return
|
||||
a bare failure code while the APK itself is fine:
|
||||
|
||||
```
|
||||
Performing Streamed Install
|
||||
adb.exe: failed to install app.apk: Failure [-99]
|
||||
```
|
||||
|
||||
The device log shows the real actor and reason, and it is not your build:
|
||||
|
||||
```
|
||||
ColorPackageInstallInterceptManager: OPPO_ADB_INSTALL_CANCEL ... packageName=<pkg>
|
||||
```
|
||||
|
||||
**The root path bypasses the interception**, which is why the table above lists it:
|
||||
|
||||
```bash
|
||||
adb -s <serial> push app.apk /data/local/tmp/app.apk
|
||||
adb -s <serial> shell "su -c 'pm install -r -g -d /data/local/tmp/app.apk'"
|
||||
```
|
||||
|
||||
Recognise the shape: a numeric-only failure with no `INSTALL_FAILED_*` constant, an
|
||||
APK that installs fine through the device's own UI, and a device process (package
|
||||
installer / security centre) in the log. Attributing that to the patch is a
|
||||
classic wasted hour.
|
||||
|
||||
### The installer may still own the screen afterwards
|
||||
|
||||
After an intercepted or UI-driven install, a vendor **installer confirmation window
|
||||
can remain the foreground activity indefinitely** — sometimes showing a stale
|
||||
package name from an unrelated earlier attempt. Consequences:
|
||||
|
||||
- `am start` on your app "does nothing", because another window owns the display.
|
||||
- Screenshots of your supposed launch actually show the installer.
|
||||
- `am start -W` can block past any reasonable timeout waiting for a first frame
|
||||
that will never come.
|
||||
|
||||
Clear it (`am force-stop <installer pkg>`, or a HOME key event) and re-launch. Before
|
||||
trusting any capture, check the foreground component:
|
||||
|
||||
```bash
|
||||
adb -s <serial> shell "dumpsys activity activities | grep -m1 ResumedActivity"
|
||||
```
|
||||
|
||||
If it is not your package, the frames are evidence about something else.
|
||||
`scripts/coldstart.py --expect-activity` performs this check automatically.
|
||||
|
||||
## Post-install / post-upgrade hazards
|
||||
|
||||
- **Data directory uid mismatch.** After reinstall the app uid increments; a restored `/data/user/0/<pkg>` directory owned by the old uid is unreadable. Symptom: crash in a DB-init path (`Cannot open database`). Fix:
|
||||
```
|
||||
su -c "chown -R <uid>:<uid> /data/user/0/<pkg>"
|
||||
su -c "restorecon -R /data/user/0/<pkg>"
|
||||
```
|
||||
Get `<uid>` from `dumpsys package <pkg> | grep userId=`.
|
||||
- **Restoring a data backup can itself cause this.** Prefer `cp -f` over an existing file (preserves owner) rather than deleting and re-extracting.
|
||||
|
||||
## Verify the build, not just the signature
|
||||
|
||||
Signature verification proves the file is well-formed. It does **not** prove the app works. Always:
|
||||
|
||||
1. `apksigner verify` passes with the explicit SDK range above — a default-args run can report v1/v2 `false` on a perfectly valid signature.
|
||||
2. Install succeeds.
|
||||
3. Launch succeeds; process stays alive.
|
||||
4. `logcat` shows no `FATAL EXCEPTION` / `VerifyError` / `IncompatibleClassChangeError` / `uncaughtException`.
|
||||
5. `META-INF/services/*` count matches the original.
|
||||
6. Unchanged dex files are byte-identical to the original (compare hashes); in a de-shelled build, compare against the de-shelled base instead.
|
||||
|
||||
Build a **control** at least once: same pipeline, zero patches. If the control fails, your pipeline or environment is at fault, not your patch (`references/pitfalls.md` P9).
|
||||
@@ -0,0 +1,252 @@
|
||||
# Runtime data — DataStore, SharedPreferences, SQLite, protobuf
|
||||
|
||||
Sometimes the cheapest fix is not code at all, but a value in app data. And sometimes that is exactly the wrong fix, because it does not survive a fresh install (`pitfalls.md` P11).
|
||||
|
||||
## Decide first: data or code?
|
||||
|
||||
| Question | Answer |
|
||||
|---|---|
|
||||
| Does the deliverable need to work after a clean install? | Then it must be **code**, not data |
|
||||
| Are you iterating on your own device? | Data edits are a fast way to test a hypothesis **before** writing the patch |
|
||||
| Is the value written by the app itself (a token, a cache, a counter)? | Data — and the server may re-assert it |
|
||||
|
||||
**Recommended workflow:** use a data edit to *prove the hypothesis* (cheap), then implement the same effect in code (durable), then verify with a clean install.
|
||||
|
||||
## Where app data lives
|
||||
|
||||
```
|
||||
/data/data/<pkg>/ (== /data/user/0/<pkg>)
|
||||
├── files/
|
||||
│ ├── datastore/*.preferences_pb AndroidX DataStore (protobuf)
|
||||
│ ├── mmkv/<name> MMKV (Tencent) — one file per named store
|
||||
│ └── ...
|
||||
├── shared_prefs/*.xml SharedPreferences
|
||||
├── databases/*.db SQLite (Room, etc.)
|
||||
└── <sdk caches>/ crash logs, download state, ad configs
|
||||
```
|
||||
|
||||
Read with root:
|
||||
```bash
|
||||
adb shell "su -c 'ls -la /data/data/<pkg>/files/datastore/'"
|
||||
adb shell "su -c 'xxd /data/data/<pkg>/files/datastore/<name>.preferences_pb | head -20'"
|
||||
```
|
||||
|
||||
## AndroidX DataStore (protobuf)
|
||||
|
||||
Format:
|
||||
```proto
|
||||
PreferenceMap { map<string, Value> preferences = 1; }
|
||||
Value {
|
||||
oneof value {
|
||||
bool boolean = 1; float float = 2; int32 integer = 3; int64 long = 4;
|
||||
string string = 5; StringSet string_set = 6; double double = 7; bytes bytes = 8;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Encoding an entry requires TWO tag levels:**
|
||||
```
|
||||
outer (map field 1, wire type 2) : 0A <len(inner)>
|
||||
inner (one map entry) : 0A <len(key)> <key> 12 <len(value)> <value>
|
||||
value payload (e.g. int64) : 20 <varint> # field 4, wire type 0
|
||||
value payload (e.g. int32) : 18 <varint> # field 3, wire type 0
|
||||
value payload (e.g. bool) : 08 <0x00|0x01> # field 1, wire type 0
|
||||
value payload (e.g. string) : 2A <len> <utf8> # field 5, wire type 2
|
||||
```
|
||||
|
||||
Omitting the **outer** tag produces a file the app cannot deserialize, and the failure is usually a **stack-less crash** (`pitfalls.md` P8). Use `scripts/datastore_inject.py` rather than hand-rolling it.
|
||||
|
||||
Procedure:
|
||||
1. `am force-stop <pkg>` (DataStore caches in memory and writes back)
|
||||
2. Write the file (as root), preserving ownership — `cp -f` over the existing file keeps its owner
|
||||
3. `restorecon` if SELinux is enforcing
|
||||
4. Start the app and observe
|
||||
|
||||
Verify by reading the file back with `xxd` before launching.
|
||||
|
||||
## SharedPreferences (XML)
|
||||
|
||||
Simple XML. Edit with the app stopped. Types are explicit (`<boolean>`, `<int>`, `<long>`, `<string>`). Same ownership rules.
|
||||
|
||||
## MMKV (Tencent)
|
||||
|
||||
Common in apps whose SDK stack is Chinese-market. One file per named store under `files/mmkv/`,
|
||||
with a `.crc` companion. It is **not** a database and **not** XML — it is a small custom binary
|
||||
format:
|
||||
|
||||
```
|
||||
offset 0 uint32 actual_size size of the data region
|
||||
offset 4 uint32 crc32 over the data region
|
||||
offset 8 data region repeated: varint key_len, key, varint val_len, value
|
||||
```
|
||||
|
||||
Files are preallocated, so trailing zeroes are normal; `actual_size` is what matters.
|
||||
|
||||
Parsing is mechanical, and no library is needed:
|
||||
|
||||
```python
|
||||
import struct
|
||||
|
||||
def parse(blob):
|
||||
size = struct.unpack_from('<I', blob, 0)[0]
|
||||
pos, end, out = 8, 8 + size, []
|
||||
|
||||
def varint(p):
|
||||
v = s = 0
|
||||
while True:
|
||||
b = blob[p]; p += 1
|
||||
v |= (b & 0x7F) << s
|
||||
if not b & 0x80:
|
||||
return v, p
|
||||
s += 7
|
||||
|
||||
while pos < end:
|
||||
klen, pos = varint(pos); key = blob[pos:pos + klen]; pos += klen
|
||||
vlen, pos = varint(pos); val = blob[pos:pos + vlen]; pos += vlen
|
||||
out.append((key, val))
|
||||
return out
|
||||
```
|
||||
|
||||
Writing a change back means rebuilding the region and **recomputing both header fields**:
|
||||
|
||||
```python
|
||||
import struct, zlib
|
||||
|
||||
body = new_region_bytes
|
||||
blob = bytearray(capacity) # keep the original file length
|
||||
struct.pack_into('<I', blob, 0, len(body))
|
||||
struct.pack_into('<I', blob, 4, zlib.crc32(body) & 0xFFFFFFFF)
|
||||
blob[8:8 + len(body)] = body
|
||||
```
|
||||
|
||||
Cautions:
|
||||
|
||||
- **A wrong crc32 makes the library throw the whole store away.** The visible symptom is "my
|
||||
edit did nothing" or "the app reset every setting", never an error.
|
||||
- **Values are raw bytes**, not always text. JSON is common; a serialized protobuf or a small
|
||||
encrypted payload is also common (`scripts/blob_decode.py` searches the framing).
|
||||
- **The in-memory copy wins until the process restarts.** `am force-stop` before editing and
|
||||
re-launch after, or the running app overwrites your change on exit.
|
||||
- **Do not delete the `.crc` companion.** Leave it in place when hand-editing the store; it is
|
||||
validated and regenerated by the library.
|
||||
|
||||
## SQLite
|
||||
|
||||
```bash
|
||||
adb shell "su -c 'sqlite3 /data/data/<pkg>/databases/<db>.db \".tables\"'"
|
||||
adb shell "su -c 'sqlite3 ... \"select * from <table> limit 5;\"'"
|
||||
```
|
||||
Useful for: auth sessions (tokens), user profile caches (often a raw JSON blob), and any server state the app persists. A JSON column often contains the exact server payload — the fastest way to learn field names.
|
||||
|
||||
## Ownership — the silent killer
|
||||
|
||||
The app runs as its own uid. A file written by root with the wrong owner is unreadable, and directory permissions are `drwx------`.
|
||||
|
||||
```bash
|
||||
uid=$(adb shell "dumpsys package <pkg> | grep userId=" | tr -dc '0-9')
|
||||
adb shell "su -c 'chown -R $uid:$uid /data/user/0/<pkg>'"
|
||||
adb shell "su -c 'restorecon -R /data/user/0/<pkg>'"
|
||||
```
|
||||
Symptom of getting this wrong: crash in a database-init path right after launch, often `Cannot open database ... Directory ... doesn't exist`.
|
||||
|
||||
Note: after every reinstall the app's uid **increments**, so a restored data directory needs this again.
|
||||
|
||||
## Introducing a value that does not exist yet
|
||||
|
||||
If the key is absent, the app uses a default. Two options:
|
||||
|
||||
1. **Add the key** with the exact protobuf shape above.
|
||||
2. **Confirm the default first** — sometimes removing a key already yields the behavior you want (e.g. clearing an expiry so it reads as "not set").
|
||||
|
||||
## Making the fix durable
|
||||
|
||||
If the effect must ship inside an APK, move it into code. Patterns, in order of preference:
|
||||
|
||||
- **Patch the read path** so the value is always the desired one. Find where the Flow/getter is built and make it emit a constant.
|
||||
- **Patch the decision**, not the data: find the comparison that consumes the value and make it resolve the way you want.
|
||||
- **Do not patch the generic encoder/boxer** used by the whole app (`pitfalls.md` P6).
|
||||
|
||||
Reference case: a promo popup was gated by `<key>_expires_at`. Writing a large value via DataStore suppressed it on the test device, but a fresh install lost it. The durable fix replaced the dedicated map-lambda that produces the value so it always yields a far-future timestamp — a single-purpose class, safe to patch, no effect on the shared serialization helpers.
|
||||
|
||||
## When the app rewrites your edit
|
||||
|
||||
A very common sequence: you change the value, relaunch, and the value is **back** — often byte for
|
||||
byte identical to what it was before. That is not a failed write. It is the app re-establishing the
|
||||
value from a source of truth you have not touched yet.
|
||||
|
||||
Two causes look identical and need different fixes:
|
||||
|
||||
| Cause | How to tell | Fix |
|
||||
|---|---|---|
|
||||
| The app **re-fetches from the server** and re-persists | take the app offline and relaunch: does your value survive? | lock the file, block the refresh request, or move the change into code |
|
||||
| The app **rewrites the file on every start** from its own defaults | your value does not survive even with the network down | the value is not authoritative — patch the read path instead |
|
||||
|
||||
Do the offline test first. It costs one launch and separates the two cases.
|
||||
|
||||
### Making a data edit stick (in order of durability)
|
||||
|
||||
1. **Immutable file attribute** — the reliable, reversible way to stop a rewrite:
|
||||
```bash
|
||||
su -c "chattr +i <path/to/prefs.xml>"
|
||||
su -c "lsattr <path/to/prefs.xml>" # expect the 'i' flag, e.g. -----i-------
|
||||
# to undo:
|
||||
su -c "chattr -i <path/to/prefs.xml>"
|
||||
```
|
||||
Verify with `lsattr`, not by assuming the command worked.
|
||||
|
||||
**Why permissions do not achieve this.** Tightening the mode or changing the owner looks like the
|
||||
obvious move and does not work, because the app does not open-and-write the existing file — it
|
||||
**deletes the file and creates a new one**. The new file is created by the app, with the app's own
|
||||
mode and owner, so a restrictive `chmod` or a `chown root` is simply not inherited. The immutable
|
||||
attribute is enforced by the filesystem against the delete itself, which is why it holds.
|
||||
|
||||
2. **Keep the app offline** so the refresh source is unreachable. Effective for a test, and
|
||||
sometimes acceptable in use — but be explicit about it, because a fix that only works offline
|
||||
fails the "works under normal conditions" constraint. See the deliverable-drift section in
|
||||
`long-task-discipline.md` before presenting this as a result.
|
||||
|
||||
3. **Block the refresh request** at the runtime or network layer — durable while your instrumentation
|
||||
is running, and requires you to have identified the endpoint (`references/server-api.md`).
|
||||
|
||||
4. **Move the change into code** — patch the read path or the decision. This is the only form that
|
||||
ships inside an APK (`§Making the fix durable` above).
|
||||
|
||||
### Two cautions about locking
|
||||
|
||||
- **Verify the feature, not the value.** Blocking a write the app depends on can make it misbehave
|
||||
or fail loudly. After locking, exercise the feature you care about — "the file still has my value"
|
||||
is not the same as "the app still works".
|
||||
- **A lock is device state; it does not travel with an APK.** If the recipe requires it, record it as
|
||||
an environment requirement, so nobody later mistakes it for something baked into the artifact.
|
||||
|
||||
## Encoded values: do not assume "encrypted"
|
||||
|
||||
Preference values that carry server configuration are frequently stored as a single opaque string
|
||||
rather than readable XML. Before concluding the value is encrypted, check whether it is merely
|
||||
**framed**: a common shape is `base64( rotate( deflate( json ) ) )`, where the cyclic rotation exists
|
||||
precisely so a naive decode fails.
|
||||
|
||||
`scripts/blob_decode.py` searches the parameter space instead of guessing it — outer encoding
|
||||
(base64 / base64url / hex), rotation offset, and compression type — and reports every combination
|
||||
that yields a structured document, plus the exact parameters to re-encode your edited payload:
|
||||
|
||||
```bash
|
||||
# pull the value straight out of a preferences XML and decode it
|
||||
python scripts/blob_decode.py --prefs-xml prefs.xml --name <key> # (see --help for exact name)
|
||||
|
||||
# after editing the decoded payload, rebuild the value with the winning parameters
|
||||
python scripts/blob_decode.py --encode --file decoded.bin --outer base64 --inner raw --cut <N>
|
||||
```
|
||||
|
||||
The rotation search is cheap — a few tens of thousands of candidates resolve in well under a second
|
||||
— so there is no reason to guess. **Distinguish framing from real encryption before spending time
|
||||
on a key:** a framed blob becomes structured the moment you remove the framing, whereas a keyed blob
|
||||
stays random-looking. If it stays random, treat it as opaque and move to the code path that consumes
|
||||
it.
|
||||
|
||||
## Cautions
|
||||
|
||||
- Editing data while the app is running is unreliable: in-memory caches win. Force-stop, edit, then launch.
|
||||
- The server may overwrite your value on next sync — see *When the app rewrites your edit* above.
|
||||
- Do not edit a token you do not own and expect it to be accepted; tokens are validated server-side (`references/server-api.md`).
|
||||
- A restored data directory needs ownership fixed again after every reinstall, because the uid increments.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Server-side analysis — deciding whether a patch can even matter
|
||||
|
||||
If the behavior you want to change is produced by a response, patch the client all you like: nothing real changes. Establishing server authority early is the cheapest high-value step in any "crack this" task.
|
||||
|
||||
## Harvest the API surface from the client
|
||||
|
||||
```bash
|
||||
python scripts/dex_strings.py <dex_dir> --urls
|
||||
python scripts/dex_strings.py <dex_dir> --find 'https?://'
|
||||
```
|
||||
|
||||
Collect: base URL(s), path constants, auth headers, and any dynamic-gateway mechanism.
|
||||
|
||||
Two patterns to watch for:
|
||||
|
||||
- **Static base URL** — straightforward.
|
||||
- **Dynamic gateway** — the real host is fetched at runtime (commonly a DNS TXT record over DoH, or a small config endpoint). The hardcoded host may be a fallback. Symptom: requests go to a host that differs from anything in the dex.
|
||||
```bash
|
||||
# TXT lookup, the usual shape:
|
||||
# https://<doh-provider>/resolve?name=<domain>&type=txt
|
||||
# returns something like "https://<gateway-host>"
|
||||
```
|
||||
This is an anti-blocking technique; it does not block repacking, but it means your static host guess may be stale.
|
||||
|
||||
## Reproduce requests faithfully
|
||||
|
||||
```bash
|
||||
python scripts/probe_api.py --base <base_url> --path /some/path --header 'X-App-Name: <value>'
|
||||
```
|
||||
|
||||
Rules that make the difference between 403 and 200:
|
||||
|
||||
- **Send the app's real headers.** A single custom header (e.g. an app-name header) frequently decides whether a WAF lets the request through. The header value is a string constant in the dex.
|
||||
- **`User-Agent` matters** — often `okhttp/x.y.z` or a runtime-specific default (e.g. `ktor-client`).
|
||||
- **Watch for a CDN/WAF in front.** A 403 with an HTML body naming a WAF means your request shape is wrong, not that the endpoint is gone. Compare with what the app sends (capture it from the device).
|
||||
- **Beware your own egress.** If your host goes through a proxy/VPN, a WAF may block by geography while the device succeeds. Do not conclude "the server rejects the app" from a host-side 403.
|
||||
- **`/health`-style endpoints are gold** — a 200 with a small JSON body proves the backend and its response envelope are alive before you debug anything else.
|
||||
|
||||
## Response envelope
|
||||
|
||||
Most apps wrap responses uniformly, e.g. `{"code":0,"msg":"","data":{...}}`. Learn it once, then read endpoints by shape rather than guessing:
|
||||
|
||||
- `code != 0` + a message → business error, and **the message often enumerates valid inputs** (this is how an ad `position` whitelist was discovered).
|
||||
- `data:null` with HTTP 200 → soft failure.
|
||||
- `401` with a null envelope → auth gate.
|
||||
|
||||
## Prove who owns the gate
|
||||
|
||||
Run this matrix and record it. It is the single most decisive artifact for a paywall or entitlement question.
|
||||
|
||||
| Request | Expected if client-owned | Expected if server-owned |
|
||||
|---|---|---|
|
||||
| protected endpoint, no credentials | would still succeed | **401 / 403** |
|
||||
| same, with a forged token | would still succeed | **401 / 403** |
|
||||
| metadata endpoint | — | 200, often **omitting** the protected field |
|
||||
| list/config endpoints | — | 200 with data |
|
||||
|
||||
If the valuable field is simply **absent** from an otherwise-200 metadata response, no client change can invent it. Say so, with the evidence.
|
||||
|
||||
## Also test the *unknown input* case
|
||||
|
||||
When you plan to change a request parameter (a path, a `position`, an id), probe what the server does with an **invalid** value first:
|
||||
|
||||
- A `400` with a validation message tells you the field is whitelisted, and hands you the full list of valid values.
|
||||
- A `404` tells you the path is exact.
|
||||
|
||||
**This matters before you patch**: redirecting a parameter to an invalid value may produce an error status that the client treats as fatal (`pitfalls.md` P5). Knowing the failure mode in advance prevents breaking the app.
|
||||
|
||||
## Behaviors that help you and behaviors that do not
|
||||
|
||||
**Repack-friendly (do not block you):**
|
||||
- Minimal auth: `Authorization: Bearer <token>` and a static app-name header, with **no request signing, no nonce, no HMAC**.
|
||||
- No client-certificate pinning to the app's own signature.
|
||||
|
||||
**Repack-hostile (will break a re-signed client):**
|
||||
- Signature/certificate checked server-side, or pinned in native code.
|
||||
- Request signing derived from the APK signature — the client computes with its own
|
||||
certificate, so re-signing changes the key. Silent and easy to misdiagnose; detection,
|
||||
extraction and the differential test are in `references/signature-derived-keys.md`.
|
||||
- Device attestation (Play Integrity / SafetyNet, OEM attestation).
|
||||
|
||||
Determine which you face **before** shipping a repack. A client that authenticates fine on first launch but silently fails features later is the classic signature-validation symptom — and when computed signing parameters (`sign`, `_p`, `uth`) evaluate to `-1` or empty, it is the signature-derived-key case rather than a server decision.
|
||||
|
||||
## What to record
|
||||
|
||||
```
|
||||
base url / gateway mechanism
|
||||
required headers (exact values)
|
||||
auth mechanism (token? signed? attested?)
|
||||
response envelope shape
|
||||
endpoints actually used, and their auth requirement
|
||||
protected-asset endpoints, with status codes for: none / forged / (real if available)
|
||||
invalid-input behavior for any parameter you plan to change
|
||||
```
|
||||
@@ -0,0 +1,157 @@
|
||||
# Server-driven UI config — promos, popups, tab bars, and remote re-enable
|
||||
|
||||
Many apps ship a **remote configuration endpoint** that decides what the client
|
||||
renders: a launch screen image, a popup, an announcement, which tabs exist. This is
|
||||
the single most common shape of "ad" in a modern app, and the one most often
|
||||
mis-diagnosed, because there is no ad SDK anywhere in the package to find.
|
||||
|
||||
Two consequences that change the whole plan:
|
||||
|
||||
- **Searching for an ad SDK finds nothing, and that is arithmetically correct.** No
|
||||
amount of further SDK hunting will help. Recognise the shape early and stop.
|
||||
- **The behaviour can be re-enabled server-side without shipping a new client.**
|
||||
Any patch that just leaves the config unread is a patch the operator can undo.
|
||||
The durable fix is in the client's decision path, not in the data.
|
||||
|
||||
## 1. Two-layer fetch: local default, then remote override
|
||||
|
||||
The most useful diagnostic — and it is a runtime observation, not a static one — is
|
||||
that the config object **changes value once during startup**:
|
||||
|
||||
```
|
||||
before the network round-trip: SplashConfig(enabled=true, duration=5, image=<built-in drawable>)
|
||||
~1s later (config response): SplashConfig(enabled=true, duration=5, image=https://<cdn>/<promo>.png)
|
||||
```
|
||||
|
||||
Seeing this pair proves three things at once: the screen is config-driven, the
|
||||
built-in asset is only an offline fallback, and the content actually shown came
|
||||
from the server. **Capture both states before designing any patch** — a
|
||||
hook on the config type's constructor/factory plus its `toString()` is usually
|
||||
enough (data-class `toString()` keeps the real field names even after R8, which is
|
||||
why it is such a convenient anchor).
|
||||
|
||||
If you only ever see the built-in default, you are looking at an offline or
|
||||
pre-config state and have not observed the real behaviour yet.
|
||||
|
||||
## 2. Locate the config surface
|
||||
|
||||
The DTOs are usually the easiest anchor in the entire app, because data classes
|
||||
serialise their own field names.
|
||||
|
||||
```
|
||||
ddc findrefs app.apk string "SplashConfig" # or any of the field names below
|
||||
ddc strings app.apk -f "enabled" --with-locations
|
||||
```
|
||||
|
||||
Field names worth grepping, in the plural because they recur:
|
||||
|
||||
```
|
||||
splash, splashImage, splashSkip, splashLogo, launchScreen, bootAd
|
||||
noticePopup, announcementPopup, updatePopup, forceUpdate, upgradeDialog
|
||||
tabbar, tabs, items, enabled, showMode, startAt, endAt, showOnce
|
||||
promo, promotion, banner, bannerList, featured, sponsored
|
||||
```
|
||||
|
||||
A `*Config` / `*Popup` / `*Banner` suffix with an `enabled` boolean is the signal
|
||||
you are in this layer. **The `enabled` flag's polarity is not guaranteed by its
|
||||
name** — see §4.
|
||||
|
||||
Then find the **consumption point**, which is where you patch: the method that
|
||||
reads the flag and decides. The DTO itself is usually immutable and shared, so
|
||||
editing it is both fragile and unnecessary.
|
||||
|
||||
## 3. Patch the decision, not the data
|
||||
|
||||
Ordered from most to least durable:
|
||||
|
||||
| Approach | Durable? | Why |
|
||||
|---|---|---|
|
||||
| Neutralise the client-side branch that consumes `enabled` | **yes** | The server can send anything; the client no longer acts on it |
|
||||
| Force the config field to its "off" value at parse time | partly | Works until a second parse path or a cache exists |
|
||||
| Block or 404 the config endpoint | **no** | Usually breaks the screen that shares the request (see `pitfalls.md` P5) |
|
||||
| Delete the local fallback asset | no | Only affects the offline case |
|
||||
|
||||
**How to neutralise a branch correctly** is in `byte-level-patching.md`: replace the
|
||||
conditional branch with `nop`s so execution takes the fall-through path, rather
|
||||
than redirecting the branch. Forcing a specific side by redirection adds a control
|
||||
flow edge and can trip the verifier.
|
||||
|
||||
**Mandatory before editing: decode both sides of the branch and write down what
|
||||
each one does.** Field names lie. In one real case the field was named `enabled`,
|
||||
and the branch structure was:
|
||||
|
||||
```
|
||||
iget-boolean v, obj -> Config.enabled
|
||||
if-nez v, :countdown ; enabled == false jumps AWAY
|
||||
invoke startMainScreen() ; fall-through: straight into the app
|
||||
:countdown ... ; branch target: show the promo for N seconds
|
||||
```
|
||||
|
||||
so `enabled == true` was the value that **skipped** the promo. Taking the name at
|
||||
face value and "enabling the skip" produces a build that shows the ad on every
|
||||
launch — and it starts cleanly, so nothing catches it until someone looks at the
|
||||
screen.
|
||||
|
||||
## 4. Decide the scope of "remove" before you edit
|
||||
|
||||
Serve-side config usually controls several things at once, and they are not all
|
||||
ads. Classify each field the same way you would a UI element:
|
||||
|
||||
| Field shape | Usually is | Usually not |
|
||||
|---|---|---|
|
||||
| Launch screen image + countdown with no dismiss | promotional | a functional splash |
|
||||
| Popup with a channel/group link and `showOnce` | promotional | |
|
||||
| Popup with changelog + `force` + an external URL | update nag → `updates-and-forced-upgrade.md` | |
|
||||
| Tab bar item with `enabled=false` | absent by operator choice | |
|
||||
| Announcement that is off server-side | nothing to remove | |
|
||||
|
||||
If the user asked for "no ads", removing a genuine brand splash is a judgement
|
||||
call, not an automatic win — a self-owned logo screen with no third-party content
|
||||
is arguably not an ad. State which one you removed; if the request was ambiguous,
|
||||
the safer default is to remove only the server-sourced promotional content and
|
||||
leave a purely local brand screen alone. See `long-task-discipline.md` on not
|
||||
substituting your own goal for the stated one.
|
||||
|
||||
## 5. Verify at three levels, not one
|
||||
|
||||
A config-driven behaviour needs more evidence than a log line:
|
||||
|
||||
1. **Screen, before and after, frame by frame** — `scripts/coldstart.py`. The
|
||||
observable is a visible change plus a change in time-to-first-meaningful-screen.
|
||||
2. **The config object's own values at runtime** — if the app logs or you can hook
|
||||
it, show the value it received. This separates "the server stopped sending it"
|
||||
from "the client stopped obeying it", which are different claims.
|
||||
3. **Correct negative**: if the flag arrives `enabled=true` and nothing happens,
|
||||
that is the strong result. If it arrives `enabled=false`, you have verified
|
||||
nothing about your patch.
|
||||
|
||||
## 6. Remote re-enable: the durability question
|
||||
|
||||
Two channels can undo client-side work without a version bump:
|
||||
|
||||
- **The config endpoint itself.** Your patch must be in the decision path so a
|
||||
future `enabled=true` is still ignored (see §3). A patch that reads the flag and
|
||||
happens to work today is not durable.
|
||||
- **A hot-update / dynamic-resource channel** (a downloaded bundle, a patch dex, a
|
||||
remotely loaded layout). Look for a cache directory that is not the config cache,
|
||||
or a download-then-load path during startup. If one exists, the patch has to
|
||||
survive it — which usually means the patched decision is the right place anyway,
|
||||
because remote resources rarely replace compiled logic.
|
||||
|
||||
Also check whether the config is **cached to disk** (`SharedPreferences`, a JSON
|
||||
snapshot, a DataStore file). A cached copy means the app can exhibit the old
|
||||
behaviour offline for one launch after your change, which looks like a failed
|
||||
patch. Clear the cache as part of the experiment, and say so when reporting.
|
||||
|
||||
## 7. Reporting template
|
||||
|
||||
```
|
||||
Promo/popup surface: <field> (<DTO class>) | source: server config at <endpoint or unknown>
|
||||
Observed before: <exact values, incl. whether enabled was true/false>
|
||||
Observed after: <exact values / absence>
|
||||
Patch: <class#method, byte offset, bytes before -> after>
|
||||
Durability: <why a future server-side change cannot restore it>
|
||||
Not removed: <fields deliberately left, with reason>
|
||||
Side effects: <what shares the same config or code path>
|
||||
Unverified: <anything not directly observed>
|
||||
```
|
||||
@@ -0,0 +1,142 @@
|
||||
# Signature-derived keys — when re-signing silently breaks the app
|
||||
|
||||
A class of app that repack-friendly guidance does not cover: the client feeds **its own APK
|
||||
signing certificate** into a native routine and uses the result as the key for request
|
||||
signing or for SDK payload encryption. Re-sign the APK and the key changes, so every signed
|
||||
request fails — while the app itself launches perfectly.
|
||||
|
||||
This is distinct from "the server checks the signature". Here the *client* uses the signature
|
||||
as key material, and the server was built against the original key. The failure looks like a
|
||||
server problem and is actually a signing problem.
|
||||
|
||||
## How to spot it (four greps, minutes)
|
||||
|
||||
```bash
|
||||
# the usual shape: signature bytes handed to a crypto helper
|
||||
grep -rn "toCharsString()" <decompiled_sources>
|
||||
grep -rn "getPackageInfo(.*, *64)" <decompiled_sources> # 64 = GET_SIGNATURES
|
||||
grep -rn "signatures\[0\]" <decompiled_sources>
|
||||
|
||||
# and the same pattern in SDK-internal helpers
|
||||
grep -rn "signatures\[0\].toByteArray" <decompiled_sources>
|
||||
```
|
||||
|
||||
Signals that confirm it matters:
|
||||
|
||||
- The value is passed into a `native` method (JNI) or a helper that also does HMAC/AES/DES.
|
||||
- The string table of the native library contains algorithm primitives (`hmac_sha256`,
|
||||
`hmac_md5`, `des_crypt`, `sha256_update`, `initKey`, `make_SubKey`, …) but **no hardcoded
|
||||
certificate or key blob** — i.e. the key is supplied from Java.
|
||||
- Request URLs carry computed parameters (`sign`, `_p`, `uth`, `sig`, `nonce`) that are not
|
||||
derivable from the visible app data.
|
||||
- The same certificate value is also fed to a third-party ad/OAID SDK helper.
|
||||
|
||||
If those hold, **any rebuilt APK needs the original certificate value hardcoded**, not the
|
||||
new one. Patch that before you patch anything else, or you cannot distinguish "my patch broke
|
||||
it" from "signing broke it".
|
||||
|
||||
## The trap: what that value actually is
|
||||
|
||||
Do **not** assume `signatures[0].toByteArray()` is the whole `META-INF/*.RSA` file. It is
|
||||
platform-dependent, and the difference is invisible offline:
|
||||
|
||||
| Platform behaviour | What you get |
|
||||
|---|---|
|
||||
| Old JAR-signature path | the full PKCS#7 blob (`META-INF/CERT.RSA` content) |
|
||||
| Modern (v2/v3 present) | a **single certificate from the chain**, DER-encoded — not the container, and not necessarily the first one |
|
||||
|
||||
Measured consequence on one sample: the `.RSA` file was 1199 bytes / 2398 hex chars, but the
|
||||
runtime value was **777 bytes / 1554 hex chars** — the *last* certificate inside the PKCS#7.
|
||||
Hardcoding the file bytes produced correct-looking smali, a clean build, a successful install,
|
||||
and every request signing parameter evaluating to `-1`.
|
||||
|
||||
**Therefore: never derive this value offline and trust it.** Read it from the running app
|
||||
(`scripts/sig_probe.py --live`), and only fall back to offline extraction to cross-check.
|
||||
|
||||
## Extract the real value
|
||||
|
||||
**Route A — from the device (authoritative):**
|
||||
|
||||
```bash
|
||||
python scripts/sig_probe.py --live --pkg <pkg> # needs Frida + a rooted device
|
||||
```
|
||||
|
||||
It prints `signatures[0].toCharsString()` and its length, read from the package manager on the
|
||||
device. This is the only value that is guaranteed to match what the app computes.
|
||||
|
||||
**Route B — offline, to cross-check:**
|
||||
|
||||
```bash
|
||||
python scripts/sig_probe.py --apk <original.apk>
|
||||
```
|
||||
|
||||
This enumerates the candidate certificate blobs inside `META-INF/*.RSA` (each top-level
|
||||
SEQUENCE inside the PKCS#7 `certificates` set) and prints each as hex with its length. Pick the
|
||||
length that Route A reported; if Route A is unavailable, generate one build per candidate —
|
||||
there are rarely more than two.
|
||||
|
||||
## Patch it
|
||||
|
||||
Replace every signature read with a string constant holding the original value, rather than
|
||||
trying to make the new signature look like the old one.
|
||||
|
||||
In smali, the pattern to replace is an invoke/move-result pair:
|
||||
|
||||
```smali
|
||||
invoke-virtual {vX}, Landroid/content/pm/Signature;->toCharsString()Ljava/lang/String;
|
||||
|
||||
move-result-object vX
|
||||
```
|
||||
|
||||
Rewrite both instructions into a single load (a regex over the smali tree handles all sites at
|
||||
once):
|
||||
|
||||
```smali
|
||||
const-string vX, "<original-value-hex>"
|
||||
```
|
||||
|
||||
Notes that save a build cycle:
|
||||
|
||||
- **Do not delete the surrounding `getPackageInfo` calls.** They are harmless and removing
|
||||
them perturbs register allocation. Only the two instructions above need to change.
|
||||
- **Miss one site and it still fails.** Count the sites before and after (`grep -c`), and assert
|
||||
the post-patch count is zero. There is usually more than one — one per crypto helper.
|
||||
- Keep the smali file's `.orig` backup so the patch is re-runnable; some build pipelines pick
|
||||
`.orig` up as an unknown file and warn, which is harmless.
|
||||
- The same treatment applies to copies of the pattern inside bundled SDK packages
|
||||
(`…/secure/…Utils`, `…/oaid/…`), not just the app's own util class.
|
||||
|
||||
## Verify with a control, not with a feeling
|
||||
|
||||
A launch that "looks fine" proves nothing here: the app starts, then quietly fails every
|
||||
network call. Use a differential test.
|
||||
|
||||
1. **Measure the signing parameter on both builds.** Hook the request builder and print the
|
||||
computed parameter for a request the app always makes on startup.
|
||||
- original APK → a value with the normal shape (encoded / base64-ish)
|
||||
- rebuilt APK → the same shape ⇒ signing is consistent
|
||||
- rebuilt APK → `-1`, empty, or null ⇒ the key is still wrong; go back to Route A
|
||||
2. **Compare a full request URL**, parameter by parameter, between the two builds. Anything
|
||||
that differs beyond a timestamp/device id is a candidate root cause.
|
||||
3. **Exercise the feature**, not the launch: an API-backed screen must actually render data.
|
||||
"Network error" on a screen that is otherwise intact is the signature of exactly this bug.
|
||||
|
||||
Before blaming your patch: run the **unmodified original** on the same device and network. If
|
||||
it also fails, the problem is environmental (`references/tls-and-cert.md`,
|
||||
`references/pitfalls.md` P9) and not the repack.
|
||||
|
||||
## Related variants of the same root cause
|
||||
|
||||
- **OAID / device-id SDKs** hash the signature (`MessageDigest("SHA1").digest(signatures[0].toByteArray())`)
|
||||
and the result goes into a request header. Same fix, different call site.
|
||||
- **Ad SDKs** use the signature to encrypt their own config payloads; leaving them unpatched
|
||||
usually degrades ads rather than breaking the app, so patch them after the core path works.
|
||||
- **Certificate pinning to the app's own signature** is a different problem: it is verified,
|
||||
not used as a key. See `references/tls-and-cert.md`.
|
||||
|
||||
## Cost of getting this wrong
|
||||
|
||||
Without this step the task stalls in the worst possible way: the artifact is correct, the
|
||||
patch is correct, the build is correct, and the app is unusable — which reads as "the client
|
||||
patch is impossible" and sends you back to static analysis for hours. Budget 15 minutes for
|
||||
this before the first repack of any signed-request app.
|
||||
@@ -0,0 +1,139 @@
|
||||
# Third-party builds — auditing a "cracked" or "modded" APK before trusting it
|
||||
|
||||
## 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.
|
||||
@@ -0,0 +1,178 @@
|
||||
# TLS and certificate failures
|
||||
|
||||
**Symptom class:** after a repack, login or registration fails with a TLS error while the rest of the app behaves normally. This is the most common way a *correct* patch gets blamed for a *pre-existing, server-side* condition. Work the five steps below before changing a single byte of the app.
|
||||
|
||||
## Fast path
|
||||
|
||||
| # | Action | Evidence |
|
||||
|---|---|---|
|
||||
| 1 | Read the full exception chain, prove it is a date rule | `THROW` events from the probe, or logcat |
|
||||
| 2 | Validate the certificate from a host you trust | `python scripts/tls_check.py <host>` |
|
||||
| 3 | Compare another host from the same app, and the device clock | same script, `adb shell date` |
|
||||
| 4 | Decide which trust chain owns the failing request | `RAW-URL` vs `OKHTTP` probe events |
|
||||
| 5 | Only then patch the system-trust path | fix template below |
|
||||
|
||||
## Symptoms
|
||||
|
||||
- Login or registration reports a generic network failure: `Network request failed: Chain validation failed`.
|
||||
- Everything else works: home, feed, images, playback, guest browsing.
|
||||
- The full chain, visible only if something captures swallowed exceptions:
|
||||
|
||||
```
|
||||
javax.net.ssl.SSLHandshakeException: Chain validation failed
|
||||
caused by: java.security.cert.CertificateException: Chain validation failed
|
||||
caused by: java.security.cert.CertPathValidatorException: timestamp check failed
|
||||
```
|
||||
|
||||
- `timestamp check failed` is the decisive token. The validator rejected the chain on a **date rule**, not on an untrusted issuer or a hostname mismatch. Exactly two conditions produce it: the certificate is expired or not yet valid, or the **clock of whoever performs the check is wrong**.
|
||||
|
||||
## Step 1: get the real host out of the runtime
|
||||
|
||||
Never trust a host recovered from strings alone; a build config can hold dead or staging hosts. Get the host the app actually connects to:
|
||||
|
||||
- Run the four-layer probe: `scripts/frida_probe.js`, launched and streamed to a log by `scripts/run_probe.py` (setup, version alignment, and hooking strategy: `dynamic-frida.md`). Three event labels carry what you need.
|
||||
- `RAW-URL`: the request went through `java.net.URL.openConnection` / `openStream`, the system trust path.
|
||||
- `OKHTTP`: the request went through the app's own OkHttp client, a different trust path.
|
||||
- `THROW`: the original text of an exception an upper layer caught and swallowed. This is where the real TLS message appears when the UI only shows a generic network error.
|
||||
|
||||
Output you need: the exact URL, its host, and which label logged it.
|
||||
|
||||
## Step 2: validate the chain out of band (no app involved)
|
||||
|
||||
This step is independent of the app, the patch, and the device. It runs on a host whose clock you trust:
|
||||
|
||||
```bash
|
||||
python scripts/tls_check.py <host> # strict verification + certificate detail
|
||||
python scripts/tls_check.py <host> <host2> # compare hosts in one run
|
||||
python scripts/tls_check.py <host> --json # machine-readable; exit 2 if any host fails
|
||||
```
|
||||
|
||||
The script validates strictly (system CAs, expiry, hostname) and, when verification fails, still decodes the peer certificate locally, so a failure arrives with a reason instead of a stack trace:
|
||||
|
||||
```
|
||||
EXPIRED certificate has expired
|
||||
NOT-YET-VALID certificate is not valid yet
|
||||
HOSTNAME-MISMATCH chain is fine, the name does not match
|
||||
UNTRUSTED-CA self-signed, or issuer not in the trust store
|
||||
CHAIN-BROKEN bad signature / invalid CA / incomplete chain
|
||||
```
|
||||
|
||||
Interpretation:
|
||||
|
||||
- `EXPIRED` reported from a trustworthy clock is proof that the chain is rejected by the certificate itself, not by the device, the network, or your patch.
|
||||
- A clean pass means the certificate is fine and the failure is a client-side trust decision or a clock problem. Go to Step 3.
|
||||
- Non-443 endpoint, or an address that needs a different SNI name (an IP connect, a CDN edge): `--port <port>` and `--sni <host>`. Getting this wrong produces a `HOSTNAME-MISMATCH` that has nothing to do with the real problem.
|
||||
|
||||
Minimal equivalent, if the script is not at hand:
|
||||
|
||||
```python
|
||||
import socket, ssl
|
||||
ctx = ssl.create_default_context() # strict: system CAs, expiry, hostname
|
||||
with socket.create_connection(("<host>", 443), timeout=10) as raw:
|
||||
with ctx.wrap_socket(raw, server_hostname="<host>") as tls:
|
||||
print("OK", tls.version())
|
||||
# on failure: ssl.SSLCertVerificationError: ... certificate has expired
|
||||
```
|
||||
|
||||
Dates, subject, and issuer in one line, if you prefer no script at all:
|
||||
|
||||
```bash
|
||||
openssl s_client -connect <host>:443 -servername <host> </dev/null 2>/dev/null \
|
||||
| openssl x509 -noout -subject -issuer -dates
|
||||
```
|
||||
|
||||
## Step 3: compare another host, and check the device clock
|
||||
|
||||
Run the same check against every host you extracted from the app, then compare:
|
||||
|
||||
- A very common shape: the business API host is expired while the config, image, or CDN host is valid. Same app, same network, same machine, different certificates. That pattern exonerates the network path and points at one certificate.
|
||||
- Check the device clock; it costs one command:
|
||||
```bash
|
||||
adb shell date # compare against a known-correct time source
|
||||
```
|
||||
If Step 2 passes but the device fails, the cause is the device clock, not the certificate. Correcting the clock and relaxing the trust policy are different decisions; do not do both silently.
|
||||
- Check the **unpatched original** in the same environment. See `verification.md` §the control build rule and `pitfalls.md` P9. If the original fails identically, the patch is not the cause, and no amount of dex work will fix it.
|
||||
|
||||
## Step 4: which trust chain owns the failing request
|
||||
|
||||
One app can carry two independent trust chains, which is exactly why "login is broken but everything else works".
|
||||
|
||||
| Path | Client | Trust configuration | Failure signature |
|
||||
|---|---|---|---|
|
||||
| OkHttp | OkHttp / Retrofit, via `newCall` | app-supplied `SSLSocketFactory` + `HostnameVerifier`, often pinning | pin-related messages (`CertificatePinner`, pin verification failed), or nothing at all if the app relaxed it |
|
||||
| `java.net.URL.openConnection()` | `HttpsURLConnection`, also used by many image loaders, downloaders, and legacy HTTP wrappers | **platform default** trust store and default verifier (`HttpsURLConnection.setDefault*`) | `Chain validation failed` / `timestamp check failed`, the signature above |
|
||||
|
||||
Discriminating, in increasing order of certainty:
|
||||
|
||||
1. **Probe events.** The failing request appears under exactly one label from Step 1: `RAW-URL` (system path) or `OKHTTP` (app client). This is a fast screen, not proof.
|
||||
2. **Trust-manager attribution (definitive).** Hook every `X509TrustManager.checkServerTrusted` implementation and print the instance class name plus a short `new Exception().getStackTrace()`. If the caller frames sit in `okhttp3.*`, or in a custom class the app installs on its own client, the OkHttp path owns the failure. If they sit in a platform trust manager reached through `HttpsURLConnection` / `SSLSocket` internals, the system path owns it. Wording alone is version-dependent, so trust the caller frames, not the message.
|
||||
3. **Cross-check with the fix below.** If OkHttp owns the failing request, the template does nothing for it: that path never reads `HttpsURLConnection` defaults and needs a client-level change (`SSLSocketFactory` / `HostnameVerifier` / pinner; see `dex-patching.md` §where to patch).
|
||||
|
||||
Why the asymmetry exists: the app configured its own trust behavior for OkHttp (a relaxed verifier or a pin), so that path never consults the platform date rule, while the legacy `HttpsURLConnection` path still validates against the system trust store and rejects the expired chain.
|
||||
|
||||
## Step 5: fix template (system path only)
|
||||
|
||||
Install permissive TLS defaults for the `HttpsURLConnection` path at the earliest point of `Application.onCreate()`:
|
||||
|
||||
```java
|
||||
// Call from Application.onCreate() before any other initialization.
|
||||
private static void installPermissiveTlsDefaults() {
|
||||
try {
|
||||
javax.net.ssl.SSLContext ctx = javax.net.ssl.SSLContext.getInstance("TLS");
|
||||
ctx.init(null, new javax.net.ssl.TrustManager[]{
|
||||
new javax.net.ssl.X509TrustManager() {
|
||||
public void checkClientTrusted(java.security.cert.X509Certificate[] c, String a) {}
|
||||
public void checkServerTrusted(java.security.cert.X509Certificate[] c, String a) {}
|
||||
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
|
||||
return new java.security.cert.X509Certificate[0];
|
||||
}
|
||||
}
|
||||
}, new java.security.SecureRandom());
|
||||
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
|
||||
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
|
||||
new javax.net.ssl.HostnameVerifier() {
|
||||
public boolean verify(String hostname, javax.net.ssl.SSLSession session) { return true; }
|
||||
});
|
||||
} catch (Exception ignored) {
|
||||
// Leave platform defaults in place: pre-patch behavior, no new failure mode.
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Land it as a small utility class plus its inner classes in smali, or as a dexlib2 rewrite that inserts the call at the head of `Application.onCreate` (`dex-patching.md`). Keep it inside the app's own package; do not edit third-party classes.
|
||||
|
||||
Why this shape is correct:
|
||||
|
||||
- It changes **one** trust decision: the default `HttpsURLConnection` factory and verifier. OkHttp derives its trust manager through `TrustManagerFactory` and its own socket factory, so app-side pinning and verifier behavior is untouched. You are not silently weakening a control the app deliberately added.
|
||||
- Call it **before any other initialization**. Globals set after the first `HttpsURLConnection` use still apply, but a library that cached a factory reference earlier keeps the old one, which produces a confusing partial fix.
|
||||
- The scope is still wider than "login". **Every request that goes through `URL.openConnection()`** inherits it, including image loaders, download managers, and older push or analytics SDKs. State that in the report instead of implying you touched one endpoint.
|
||||
- The `catch` that leaves platform defaults alone is deliberate: the worst case is the behavior you started with.
|
||||
- This is a **client-side workaround for an external condition**. The correct fix is renewing the server certificate. Say so, and do not present the patch as the fix.
|
||||
|
||||
Do not: change the device clock, install your own CA into the device trust store (device-side, harder to roll back, and not part of a shippable artifact), rewrite the request host to a different domain, or reach for `System.setProperty` tricks. Each of them either misses the actual cause or widens the change far beyond the failing flow.
|
||||
|
||||
## If OkHttp is the failing path
|
||||
|
||||
Then the failure is about the app's own client configuration, not the platform defaults. Typical causes: a pin that no longer matches, a hostname verifier rejecting a changed host, or a custom `SSLSocketFactory` built from a bundled keystore. Locate it the same way (Step 4, item 2) and patch at the client construction site instead of applying the template above. `dynamic-frida.md` covers finding the real construction site; `dex-patching.md` covers the patch layer.
|
||||
|
||||
## Method notes
|
||||
|
||||
- **Order of investigation is the lesson.** Every piece of evidence above comes from the server, the network, or the platform before anything is attributed to your patch: full exception chain, real host, out-of-band validation, second-host comparison, control build. Only when all of them point at a client trust decision is a patch justified. `pitfalls.md` P16 is this mistake written up as a failure.
|
||||
- **This is a control-build case, not a patch case.** `verification.md` §the control build rule applies directly: same pipeline, zero patches. If the control fails the same way, stop debugging the patch.
|
||||
- **Report the residual honestly.** "The server certificate is expired; the client patch relaxes validation on the `HttpsURLConnection` path only, OkHttp is unchanged, the proper fix is on the server" is the useful statement. "I fixed login" is not.
|
||||
- **Claim strength.** This evidence chain reaches rung 6 on the `verification.md` claim ladder: the mechanism is proven, not merely observed. Say which rung you reached.
|
||||
|
||||
## Triage checklist
|
||||
|
||||
```
|
||||
[ ] Full exception chain captured, contains "timestamp check failed"
|
||||
[ ] Exact host and URL obtained from a runtime probe (not from strings)
|
||||
[ ] Standalone strict validation run: EXPIRED / clean pass
|
||||
[ ] A second host from the same app compared (isolates the certificate)
|
||||
[ ] Device clock checked against a known-correct source
|
||||
[ ] Original unpatched build reproduces the same failure (control build)
|
||||
[ ] Failing request attributed to a trust manager implementation, not to a message
|
||||
[ ] If system path: permissive defaults installed at the top of Application.onCreate
|
||||
[ ] If OkHttp path: client-level config is the patch target instead
|
||||
[ ] Delivery notes state the client-side scope and the server-side root cause
|
||||
```
|
||||
@@ -0,0 +1,291 @@
|
||||
# Toolchain — What to Use, How to Invoke It, and Where It Lies
|
||||
|
||||
Load this when you are choosing tools, when a tool produces an answer that smells wrong, or when
|
||||
something is not installed. It is a map, not a tutorial: each entry says what the tool is *for*, how
|
||||
to drive it non-interactively, and the failure mode that wastes time.
|
||||
|
||||
**Prefer tools you can drive from a command line.** An agent cannot click. A tool that ships only a
|
||||
GUI is not automatically out of reach — check for a headless or MCP path first, which is an
|
||||
install-and-set-up step rather than a reason to substitute the tool. When no such route exists, ask
|
||||
for a human instead of stalling or silently downgrading to a weaker method.
|
||||
|
||||
## Tier 0 — present on almost any machine, no install
|
||||
|
||||
Use these before reaching for anything heavier. They answer structure questions in seconds and
|
||||
cannot be broken by a missing dependency.
|
||||
|
||||
| Tool | Use it for |
|
||||
|---|---|
|
||||
| `file`, `readelf -h/-l/-d/-r`, `objdump -d`, `nm -D`, `strings` | ELF structure, program headers, dynamic section, relocations, dynamic symbols |
|
||||
| `unzip -l`, `zipinfo` | what is actually inside an APK, entry sizes and compression |
|
||||
| `sha256sum` / `Get-FileHash` | identity. **Always hash before and after; never trust "it should be the same file"** |
|
||||
| `xxd` / `hexdump` | byte-level ground truth when a tool disagrees with another tool |
|
||||
| `python3` | all the scripts here; the standard library alone covers most parsing |
|
||||
|
||||
`readelf`/`objdump` walk **section** headers. If a target's section table is forged (see
|
||||
`native-tamper-and-suicide.md` §Forged section headers) they will print confidently wrong output —
|
||||
cross-check with the program headers.
|
||||
|
||||
## Tier 1 — dex and Java
|
||||
|
||||
| Tool | Invoke | Why this one |
|
||||
|---|---|---|
|
||||
| `baksmali` / `smali` (jars) | `java -cp <jars> org.jf.baksmali.Main d <dex> -o <dir>` | round-tripping, reading a method precisely |
|
||||
| `dexlib2` | small Java program | method-level rewrite, leaves everything else untouched (`dex-patching.md`) |
|
||||
| **`ddc`** | `ddc app.apk -c <Class>` | **fastest read of dex as Java, plus query subcommands** — see below |
|
||||
| `apktool` | `java -jar apktool.jar d/b` | whole-app decode including resources |
|
||||
| `jadx` | `jadx --no-res -d <out> <apk>` | readable Java for orientation; **not** a source of truth (see below) |
|
||||
| `aapt2` | `aapt2 dump badging <apk>` | manifest facts, package name, versions |
|
||||
| `zipalign`, `apksigner` | from build-tools | alignment and signing |
|
||||
|
||||
### ddc — dex-to-Java with query subcommands (worth adopting)
|
||||
|
||||
A single-file Rust binary, no install, no JVM. Two things make it more useful than
|
||||
"a decompiler":
|
||||
|
||||
```bash
|
||||
ddc info app.apk # label, package, version, launcher, sdk, per-dex counts
|
||||
ddc findrefs app.apk string "SomeToken" # every reference site, class#method
|
||||
ddc strings app.apk -f "splash" --with-locations
|
||||
ddc app.apk -c com.example.Foo # one class as Java
|
||||
ddc app.apk -o out/ # full decompile, a few seconds for a normal APK
|
||||
```
|
||||
|
||||
Measured on a 4.7 MB APK (4,070 classes / 30k methods): `info` ~0.13 s, `findrefs`
|
||||
~0.11 s, one class ~0.25 s, full decompile ~2.8 s producing ~4,000 files.
|
||||
|
||||
Why the query subcommands matter more than the speed: **string cross-referencing
|
||||
becomes a lookup instead of a crawl.** Asking "which class mentions this config
|
||||
field name" is a sub-second command here and easily an hour of smali grepping by
|
||||
hand. That single property is what turns "find the convergence point" from
|
||||
exploration into a query.
|
||||
|
||||
`info` also **prevents a specific, costly mistake**: reading the package identity
|
||||
out of the binary manifest by hand. Hand-extracted AXML strings are ambiguous —
|
||||
class-name fragments look exactly like package names, and picking the wrong one
|
||||
sends every later `pm`/`dumpsys`/data-dir query to a package that does not exist.
|
||||
Let the tool report `package`, `label` and `launcher`, and cross-check with
|
||||
`aapt2 dump badging` when available.
|
||||
|
||||
Limits to plan around: types are erased (no generics); R8 short names stay short,
|
||||
so you still need string cross-references to infer meaning; output is a **reading
|
||||
aid, not compilable source** (occasional declaration/use ordering is inverted, and
|
||||
numeric resource ids appear as decimal integers); very large methods produce
|
||||
thousands of lines and are better approached via `findrefs`/`getmethod` first.
|
||||
|
||||
**Classpath gotcha.** `baksmali`/`smali` need their dependency jars on the classpath together
|
||||
(`smali`, `antlr-runtime`, `stringtemplate`, `baksmali`, `dexlib2`, `util`, `jcommander`, `guava`).
|
||||
Missing one produces `ClassNotFoundException` that reads like a broken target. `scripts/smtool.py`
|
||||
carries the classpath so you pass it once.
|
||||
|
||||
**Entry-point gotcha.** The main class has moved between versions — `org.jf.*` in older builds,
|
||||
`com.android.tools.smali.*` in newer ones. If `ClassNotFoundException` names the **main class**, it
|
||||
is a version mismatch, not a missing jar.
|
||||
|
||||
**jadx is for reading, not for concluding.** Decompiled Java reorders and rewrites control flow;
|
||||
line numbers and even which branch is which can differ from the bytecode. When a decision depends on
|
||||
it, verify in smali or at runtime. `jadx` writing `(unknown)`/empty method bodies means it failed,
|
||||
not that the method is empty.
|
||||
|
||||
**`smali` assembling can abort silently** — the tree produces no dex while the process still exits
|
||||
0. Never treat exit code as proof of a build. Assert the artifact exists, is fresh, and is non-empty
|
||||
(`patch-audit.md`).
|
||||
|
||||
## Tier 2 — native
|
||||
|
||||
| Tool | Invoke | Notes |
|
||||
|---|---|---|
|
||||
| `radare2` / `rizin` | `r2 -q -c '<cmds>' file` | scriptable disassembly/analysis; the practical choice when no GUI is available |
|
||||
| `Ghidra` (headless) | `analyzeHeadless <proj> <name> -import <file> -postScript <s>` | decompiler without a GUI; slower to script but far better output than a raw disassembler |
|
||||
| `capstone` (python) | library | decoding in your own scripts — see the silent-stop trap below |
|
||||
| `keystone` (python) | library | assembling a short patch when you are editing bytes by hand |
|
||||
| `pyelftools` (python) | library | **section-based — unreliable on hardened targets.** Prefer hand-walking `PT_LOAD`/`PT_DYNAMIC`, as `scripts/elf_plt.py` does |
|
||||
| IDA Pro | GUI, **or headless via `idalib-mcp`** | the strongest decompiler output. Do not assume it needs a human in front of it — a headless MCP server exists (see *MCP tool servers* below). Ask for a human only when that setup is genuinely unavailable |
|
||||
| `x64dbg` | GUI, Windows | human-driven live debugging of a native Windows target |
|
||||
| `gdb` / `lldb` | CLI | live debugging where a device or emulator allows it |
|
||||
|
||||
**capstone can stop silently.** Decoding a buffer that does not begin at an instruction boundary may
|
||||
return a few instructions and then nothing, with no error. A scan built on that reports "no matches"
|
||||
for a library full of matches. Use byte-pattern search or a resynchronising scan for anything where
|
||||
completeness matters (`native-tamper-and-suicide.md` §Scanner traps).
|
||||
|
||||
**Disassembler output is a hypothesis.** Fixed-width architectures (aarch64) decode almost any
|
||||
4-byte window into *some* instruction, so a wrong start offset yields plausible-looking garbage.
|
||||
Bound your window with a known entry point or a known call site.
|
||||
|
||||
## MCP tool servers — an external dependency, not a tool on the shelf
|
||||
|
||||
An MCP server is neither a CLI tool nor one of the scripts here. It is a **separate installation plus
|
||||
a running process**: something to install, a service to start, usually an extension to load, often an
|
||||
authorization step. Listing one beside `readelf` would imply it is already present. Declare it as a
|
||||
dependency with its prerequisites, and check whether it is actually available *before* planning work
|
||||
that needs it — discovering this mid-task is the "missing tool" failure again.
|
||||
|
||||
### IDA Pro, headless
|
||||
|
||||
IDA does **not** require a human at a GUI. `mrexodia/ida-pro-mcp` ships `idalib-mcp`, a headless MCP
|
||||
server that drives an IDA database with no GUI process at all:
|
||||
|
||||
```sh
|
||||
uv run idalib-mcp --host 127.0.0.1 --port 8745 path/to/executable # open a binary up front
|
||||
uv run idalib-mcp --host 127.0.0.1 --port 8745 # open databases on demand
|
||||
uv run idalib-mcp --stdio # for stdio-based clients
|
||||
```
|
||||
|
||||
Prerequisites, all of which must be arranged before the first call: IDA Pro 8.3+ (9 recommended;
|
||||
**IDA Free is not supported**), a Python 3.11+ that `idapyswitch` can select, `uv`, and an `idalib`
|
||||
activated globally via `py-activate-idalib.py`. Each open database lives in a worker process that
|
||||
outlives the supervisor and is adopted transparently by a later supervisor on the same host, so
|
||||
several sessions can share one analysis. Every tool call carries an explicit `database` argument —
|
||||
there is no implicit "current database" — and `idb_open` returns the session id you must pass.
|
||||
|
||||
The GUI-plugin variant of the same project is deprecated upstream in favour of `idalib-mcp`; do not
|
||||
set that up for agent work.
|
||||
|
||||
### Ghidra
|
||||
|
||||
`LaurieWired/GhidraMCP` is a Ghidra **extension** plus a separate Python bridge, not a headless
|
||||
analysis server: Ghidra must be running with the plugin loaded (its HTTP server defaults to
|
||||
`127.0.0.1:8080`) and the bridge is another process your client starts. Treat it as requiring an
|
||||
interactive GUI session. For unattended work the shape that actually runs without a GUI is
|
||||
`analyzeHeadless` with a post-script.
|
||||
|
||||
### The boundary: deobfuscate before you hand the binary to a model
|
||||
|
||||
Both are LLM-driven, and they inherit the model's weaknesses. The IDA MCP authors say it plainly in
|
||||
their own README: **"LLMs will not perform well on obfuscated code"**, and they advise removing
|
||||
string encryption, import hashing, control flow flattening, code encryption and anti-decompilation
|
||||
tricks *before* asking a model to solve anything.
|
||||
|
||||
That matters more here than in most domains, because it is precisely the shape of the targets this
|
||||
skill deals with. An OLLVM-style or virtualized binary is not a job for a model reading decompiler
|
||||
output; the deobfuscated version is a *different binary*, and producing it is the work already
|
||||
described in `code-virtualization-and-custom-linkers.md` and
|
||||
`native-tamper-and-suicide.md`. The same advice has a second half: resolve library code first
|
||||
(FLIRT/Lumina) so the model is not asked to reason about `memcpy` as if it were the program.
|
||||
|
||||
Two consequences worth carrying into the plan:
|
||||
|
||||
- Ask a model for **navigation and reading** — rename, comment, summarise a function, convert an
|
||||
immediate — and verify anything that decides the patch against the disassembly yourself.
|
||||
- If the server is not installed, that is a **missing dependency to report**, not a licence to present
|
||||
a weaker tool's output as equivalent (`packers.md`).
|
||||
|
||||
## Tier 3 — runtime and network
|
||||
|
||||
| Tool | Invoke | Notes |
|
||||
|---|---|---|
|
||||
| `frida` (host) + `frida-server` (device) | `frida -U -f <pkg> -l script.js` | **host and device versions must match** — skew produces errors that look like a broken target (`pitfalls.md` P15) |
|
||||
| `objection` | `objection -g <pkg> explore` | quick Java-layer poking on top of Frida |
|
||||
| `mitmproxy` | `mitmproxy --mode regular` | request/response inspection; a device proxy is usually faster to set up than a transparent one |
|
||||
| `adb` | everything | the primary device interface |
|
||||
|
||||
Version alignment for Frida is a **hard gate**, not a nicety. Check both sides before writing a
|
||||
script, and check the device architecture — the server binary is per-ABI.
|
||||
|
||||
## Tier 4 — cross-platform runtimes
|
||||
|
||||
| Runtime | Identifier | Tool |
|
||||
|---|---|---|
|
||||
| Flutter / Dart | `libflutter.so` + `libapp.so` | `blutter` (needs the **matching Dart version**) — `dart-aot.md` |
|
||||
| Unity / IL2CPP | `libil2cpp.so` + `global-metadata.dat` | Il2CppDumper + a native decompiler |
|
||||
| React Native | `libhermes.so` / `index.android.bundle` | Hermes bytecode tooling, or plain JS if the bundle is unminified |
|
||||
| Cordova / hybrid | WebView + `assets/www` | read the JS directly; Java layer is usually thin |
|
||||
|
||||
**A version mismatch here wastes the most time of any tool in this file.** A Dart decompiler built
|
||||
for a different engine version produces output that is subtly wrong rather than obviously broken.
|
||||
Pin the version first (`dart-aot.md` §1) and do not "try it and see".
|
||||
|
||||
## "Not on PATH" is not "not installed"
|
||||
|
||||
`doctor.py` and `preflight.py` report whether each tool resolves on `PATH`. That
|
||||
is a statement about `PATH`, not about the machine, and the difference has cost
|
||||
real time: a full custom zip writer was built to work around a missing
|
||||
`apksigner` that was already installed in an SDK directory nothing had added to
|
||||
`PATH`.
|
||||
|
||||
**Before treating a tool as absent, search the filesystem once:**
|
||||
|
||||
```bash
|
||||
# POSIX
|
||||
find / -name apksigner -o -name zipalign -o -name baksmali.jar 2>/dev/null | head
|
||||
|
||||
# Windows (PowerShell) -- list every drive letter first, then search each
|
||||
(Get-PSDrive -PSProvider FileSystem).Root |
|
||||
ForEach-Object { Get-ChildItem -Path $_ -Recurse -Depth 5 -ErrorAction SilentlyContinue `
|
||||
-Include apksigner.bat,zipalign.exe,keytool.exe }
|
||||
```
|
||||
|
||||
Common places that are *not* on `PATH`:
|
||||
|
||||
| Artefact | Typical location |
|
||||
|---|---|
|
||||
| `apksigner`, `zipalign`, `aapt2` | any `build-tools/<ver>/` under an Android SDK, and portable tool bundles |
|
||||
| `apksigner.jar` | inside those same directories (runnable as `java -jar`) |
|
||||
| `keytool`, `jarsigner`, `javac` | a JDK install whose `bin` was never added to `PATH`; `java -XshowSettings:properties -version 2>&1 \| grep java.home` reveals the JDK root even when `keytool` does not resolve |
|
||||
| `uber-apk-signer.jar`, `baksmali*.jar` | bundled with portable APK toolkits |
|
||||
|
||||
Record the resolved absolute paths once, in your running notes, and pass them to
|
||||
the scripts that accept `--apksigner` / `--zipalign` / `--ks` style flags. Every
|
||||
script in this repository takes an explicit path for this reason.
|
||||
|
||||
**A useful asymmetry:** missing `apksigner` is survivable (a v2-only signature
|
||||
block can be appended without reordering the archive), but missing `zipalign` is
|
||||
not a reason to hand-roll alignment either -- write the archive aligned in the
|
||||
first place, as `scripts/repack.py` does. Prefer producing a correct archive over
|
||||
repairing one afterwards: post-hoc alignment tools rewrite the file, which
|
||||
changes every offset and can break a target that fingerprints its own layout.
|
||||
|
||||
## Signing: pick the signer deliberately
|
||||
|
||||
Two signers, and the choice changes the output bytes:
|
||||
|
||||
- **`apksigner`** (build-tools) appends the v2/v3 signature block after the zip
|
||||
content. It does **not** reorder entries, so a carefully aligned archive stays
|
||||
aligned. This is the default choice.
|
||||
- **`jarsigner`** (JDK) rewrites the archive as a side effect of adding the v1 JAR
|
||||
signature, which recompresses entries and **destroys the alignment** that
|
||||
Android R+ requires. A build signed this way can fail to install with
|
||||
`Failure [-124] ... resources.arsc ... aligned on a 4-byte boundary` even though
|
||||
the same archive installed fine moments earlier, and `jarsigner -verify` reports
|
||||
success. If you have run `jarsigner` on an archive and a previously-working
|
||||
install starts failing, re-pack and sign with `apksigner` before investigating
|
||||
anything else.
|
||||
|
||||
Enable **v1 + v2 + v3**. v1 keeps very old devices working; v2/v3 are what modern
|
||||
platforms actually verify, and v1-only builds are rejected in more configurations
|
||||
than people expect.
|
||||
|
||||
## The general trap: a tool's failure is not a finding about the target
|
||||
|
||||
A missing jar, a version skew, a forged section header, and a genuinely absent symbol all produce
|
||||
**empty or partial output**. The output looks the same; the conclusions are completely different.
|
||||
|
||||
Before reporting "there is nothing there", confirm the tool was actually capable of finding it:
|
||||
|
||||
- Did it read the file at all? (entry count, segment count, non-zero output somewhere)
|
||||
- Does a **known-present** item show up? (search for something you already know exists — a symbol
|
||||
you saw in the dynamic table, a string you read in the hex dump)
|
||||
- Would a different method see it? (byte pattern vs decoded scan)
|
||||
|
||||
**This is `pitfalls.md` P25 and P26 in tool form.** A self-built analyser that fails quietly reads
|
||||
exactly like a clean target, and it removes routes from consideration for free.
|
||||
|
||||
## Working without a network
|
||||
|
||||
Assume nothing can be downloaded. What still works, in order of usefulness:
|
||||
|
||||
1. Tier 0 in full, plus the Python standard library — enough for structure, strings, hashing, and
|
||||
most ELF/dex parsing.
|
||||
2. Whatever jars and binaries are already present. **Locate them once and reuse the paths** rather
|
||||
than re-searching on every command.
|
||||
3. A local package cache or an offline mirror, if the environment has one.
|
||||
|
||||
If a tool genuinely cannot be obtained, say which step is blocked and **what a substitute would
|
||||
give up** — do not silently substitute a weaker method and report its result as equivalent.
|
||||
|
||||
## Recording the toolchain actually used
|
||||
|
||||
When you report, name the tools and versions that produced each finding. Two agents with different
|
||||
tool versions will reach different conclusions about the same binary, and without the version that
|
||||
difference is unresolvable later.
|
||||
@@ -0,0 +1,243 @@
|
||||
# Updates and forced upgrade
|
||||
|
||||
Load this whenever the deliverable is a patched build that must **keep working over time** — which is
|
||||
almost always. A build that is correct on the day you ship it and dead a week later has failed, and the
|
||||
cause is nearly always an update path you did not neutralise.
|
||||
|
||||
This is the file that decides whether a patch is *durable*, and it is cheap: the whole job is usually
|
||||
one or two edits.
|
||||
|
||||
## Why this is not optional
|
||||
|
||||
Three independent failure modes, all of which present as "the mod stopped working" with no obvious link
|
||||
to updates:
|
||||
|
||||
1. **Forced upgrade.** The app checks a version endpoint, sees a newer build, and blocks its UI behind a
|
||||
non-dismissible dialog until the user installs the official (unpatched) package. Your patch is gone.
|
||||
2. **Self-update install.** The app downloads an APK and hands it to the package installer. Because the
|
||||
downloaded build is signed differently, the install either fails or — worse — succeeds and replaces
|
||||
your work.
|
||||
3. **Silent "compatibility" downgrade.** The server decides the client version is too old and starts
|
||||
omitting fields or returning an error page. No local code changed, so nothing local looks broken.
|
||||
|
||||
A fourth case is a **resource / hot-update channel**: the app fetches a bundle (JS, a Dart/RN patch, a
|
||||
config blob, a plugin APK) that can reintroduce the behaviour you removed. That is a separate code path
|
||||
from version checking — handle it explicitly if the app has one (see §Step 5 below).
|
||||
|
||||
## Step 1: locate the check
|
||||
|
||||
There is usually exactly **one** update service. Find it before patching anything else.
|
||||
|
||||
**From the client's own vocabulary** (works on any runtime):
|
||||
|
||||
```
|
||||
update / upgrade / new version / check version / force update
|
||||
版本更新 / 检查更新 / 发现新版本 / 立即更新 / 强制更新
|
||||
```
|
||||
|
||||
Search those in the app's string table and in class names; on heavy runtimes search the string pool,
|
||||
remembering its encoding (see `framework-runtimes.md` §Locating logic without symbols — searching only one encoding
|
||||
misses half your hits, and "nothing found" is usually the encoding, not an absence).
|
||||
|
||||
**Signals that a version check exists even if you cannot read the strings:**
|
||||
|
||||
- A network call early in startup whose response contains a version number, a download URL, and
|
||||
sometimes a `force` / `must` / `minimum` flag.
|
||||
- A stored "last update check time" preference (throttling a check implies one exists).
|
||||
- The app ships the package installer path or requests `REQUEST_INSTALL_PACKAGES`.
|
||||
- A permissions/manifest entry for an "unknown sources" install intent.
|
||||
|
||||
**Also look for the *coupling*.** Update checks are frequently run from the same startup routine as ad
|
||||
loading and splash dismissal, and a blocking update dialog often **suspends those siblings** — you may
|
||||
find logging that literally says so ("update dialog showing, skipping X"). That tells you both where the
|
||||
check lives and that your patch must not leave the dialog state machine half-finished.
|
||||
|
||||
## Step 2: classify the shape
|
||||
|
||||
| Shape | How it behaves | Where to cut |
|
||||
|---|---|---|
|
||||
| **Optional update** | a dismissible prompt with a download button | suppressing the dialog is enough |
|
||||
| **Forced update** | non-dismissible; blocks the app | must be cut at the decision, not the dialog |
|
||||
| **Silent version gate** | no dialog; features degrade or the server 400s | client-side is *not* fixable — see §the honest answer |
|
||||
| **Self-update installer** | downloads and installs an APK | cut the check, and ideally the install path too |
|
||||
| **Hot-update / resource patch** | fetches a bundle that can restore behaviour | separate route; treat as a data channel |
|
||||
|
||||
Assume **forced** until you have evidence otherwise, because that is the case that costs the user the
|
||||
most when missed.
|
||||
|
||||
## Step 3: patch the decision, not the dialog
|
||||
|
||||
**Prefer the earliest safe exit over every downstream surface.** Supressing the dialog only hides it;
|
||||
the download may still start, and a later code path may still act on the "new version" verdict.
|
||||
|
||||
Two layers, in this order:
|
||||
|
||||
**Layer 1 — make the check itself a no-op.** Replace the entry of the update routine so it returns
|
||||
immediately. Nothing is requested, nothing is compared, no dialog state is created. This is the root fix
|
||||
and it removes the network call entirely, which also makes verification trivial (Step 4).
|
||||
|
||||
**Layer 2 — neutralise the comparison.** Somewhere the client compares the server version against its
|
||||
own and branches on the result. Force that branch to the "already current" side. This catches any path
|
||||
that reaches the comparison without going through the entry you patched (a second caller, a manual
|
||||
"check for updates" button, a settings screen).
|
||||
|
||||
Layer 2 alone is a valid minimal fix if Layer 1 is awkward; Layer 1 alone is valid if you have confirmed
|
||||
a single entry. **Doing both is cheap insurance and is what makes the claim "this build cannot be
|
||||
upgraded into uselessness" defensible.**
|
||||
|
||||
```
|
||||
target routine: <updateChecker>(...) -> return immediately (no request, no state)
|
||||
target branch: <versionCompare> result -> force the "no update" side
|
||||
```
|
||||
|
||||
**Do not** patch the dialog itself as your primary fix, and **do not** patch the comparison to lie in
|
||||
the *other* direction (claiming an update when there is none) — that produces exactly the blocking
|
||||
dialog you are trying to avoid.
|
||||
|
||||
### What not to touch
|
||||
|
||||
- **Do not rewrite the app's own version number** in the manifest or in a version string. It is the
|
||||
cheapest-looking fix and it breaks things you are not looking at: server-side feature negotiation,
|
||||
analytics, cached asset keys, and the app's own self-comparison. Change the *decision*, not the
|
||||
identity.
|
||||
- **Do not strip the installer permission** unless you have checked nothing else uses it.
|
||||
- **Do not block the update hostname at the transport layer.** That is the same class of mistake as
|
||||
blocking ad hosts (`pitfalls.md` P5): it fails offline/online transitions, needs a helper on the
|
||||
machine, and is not a property of the artifact. It is also not required — the check is local code.
|
||||
|
||||
## Step 4: verify
|
||||
|
||||
Update paths are checked once at launch, so verification is a single clean cold start:
|
||||
|
||||
1. **Clear logs, cold start, and grep for the update vocabulary.** Expect **zero** hits. Not "quieter" —
|
||||
absent. If the routine still runs, the string will still appear.
|
||||
2. **Watch the screen through startup.** The failure mode is a modal, so a sample you did not look at is
|
||||
not evidence (`environment.md` §look at the screen). A blocking dialog is unmistakable and it will be
|
||||
on screen for a long time.
|
||||
3. **Check the network.** With the check disabled there should be **no request** to the version/update
|
||||
endpoint at startup. This is the strongest signal: it distinguishes "dialog suppressed" from "check
|
||||
never happened".
|
||||
4. **Exercise the manual path** if the app has a "check for updates" entry in settings — that is the
|
||||
caller Layer 2 exists for.
|
||||
5. **Confirm what you disabled is only updates.** The update routine sometimes shares a bootstrap with
|
||||
other startup work. If you no-op'd a routine rather than its decision, verify that splash dismissal,
|
||||
first-run setup, and the ad/consent flow still complete.
|
||||
|
||||
**Two-sample rule for the durability claim.** If you are asked whether the build *survives* a server-side
|
||||
version bump, you cannot test that directly. What you can honestly claim is: *(a)* no version request is
|
||||
issued at startup, and *(b)* the comparison no longer reaches its "newer" branch. State it in those terms
|
||||
instead of asserting the future.
|
||||
|
||||
## Step 5: hot-update and resource channels
|
||||
|
||||
If the app can fetch a bundle at runtime, version checking is not the only way your change can be undone.
|
||||
|
||||
- **What to look for**: a startup fetch of a signed bundle/zip/config with a version or hash, a local
|
||||
unpack directory, a dynamic plugin loader, or a JS/Dart/RN patch channel.
|
||||
- **Why it matters**: even with updates disabled, a remotely fetched config can re-enable a feature, and
|
||||
a fetched bundle can overwrite patched logic in the parts it owns.
|
||||
- **Handle it like a data channel, not like an update**: identify what is fetched, whether the patched
|
||||
behaviour is inside that payload, and cut the consumption point if it is. If the patched logic lives in
|
||||
the shipped artifact and the fetched payload cannot override it, say so and move on — that is a
|
||||
finding, not a gap.
|
||||
|
||||
Note the flip side: a **server-issued configuration** is the same category. If the thing you removed was
|
||||
driven by remote config, the client patch holds only while the server keeps sending that config — see
|
||||
`references/server-config-and-updates.md` §6 and `references/membership-and-limits.md` for the general
|
||||
rule that *client-side enforcement can be patched, server-side authority cannot*.
|
||||
|
||||
## The honest answer for silent version gates
|
||||
|
||||
If the app degrades because the **server** decides the client is too old — no local dialog, just missing
|
||||
data or errors on some screens — then there is no client-side fix. The only honest report is:
|
||||
|
||||
- the version the client reports to the server (with evidence of where it is read),
|
||||
- the endpoint that makes the decision (with the observed response),
|
||||
- and a clear statement that this is server-side authority.
|
||||
|
||||
Do not paper over it by forcing the version string at random read sites. If you do change a reported
|
||||
version as an experiment, label it experimental, and remember that a version number is used in more
|
||||
places than the one you are looking at.
|
||||
|
||||
## Delivery note: always state what was disabled
|
||||
|
||||
Update suppression changes behaviour a user can observe ("it never tells me about new versions"). Put it
|
||||
in the delivery notes, in one line, together with anything else you neutralised. If the app also has a
|
||||
legitimate reason to update (security fixes), say that the build will not pick them up automatically.
|
||||
|
||||
## Step 6: when the check is not where you expect
|
||||
|
||||
Three shapes that break the "find the Java comparison and flip it" plan. Recognise them early,
|
||||
because each has a different cheapest remedy.
|
||||
|
||||
### The check is native
|
||||
|
||||
Symptom: you grep the whole dex tree for the version-comparison routine, the update endpoint, or the
|
||||
dialog text and find **the method declared, and zero callers**. A `static native` update entry point
|
||||
with no Java caller means the invocation lives in a `.so` (`registerNatives` from a static block is
|
||||
the usual giveaway — see `code-virtualization-and-custom-linkers.md`).
|
||||
|
||||
Options, cheapest first:
|
||||
|
||||
1. **Attack the response, not the check.** Block or rewrite the update endpoint at the network layer,
|
||||
or empty the version/config response. The native code still runs and still decides "no update".
|
||||
This needs no native work at all and survives a rebuild — check this before reaching for a
|
||||
disassembler.
|
||||
2. **Send the check a version it likes.** If it compares against a value the app itself supplies
|
||||
(a config key, a stored preference, a build field), setting that value is a one-line change.
|
||||
3. **Patch the native comparison.** Last, because it is the most expensive and the most fragile.
|
||||
|
||||
Do not conclude "unpatchable" from "no Java caller". The gate usually reads a value you *can* control.
|
||||
|
||||
### The update hands off to a browser or a WebView
|
||||
|
||||
Very common in this category: the dialog's button fires an `ACTION_VIEW` intent at a download URL,
|
||||
or loads it in an in-app WebView. Two consequences:
|
||||
|
||||
- **You will not find an installer call** in the app, so searching for `PackageInstaller`,
|
||||
`REQUEST_INSTALL_PACKAGES` or a download service finds nothing. That is not evidence the dialog is
|
||||
harmless; the browser does the install.
|
||||
- **Logcat truncates the URL.** `ActivityTaskManager` prints `dat=https://host/...` and elides the
|
||||
rest, so a naive grep gives you a host and no path. Do not build a plan on a truncated URL.
|
||||
|
||||
Ways to get the real URL, cheapest first:
|
||||
|
||||
| Approach | Notes |
|
||||
|---|---|
|
||||
| Hook `Intent` construction / `Context.startActivity` and log `intent.getDataString()` | Most reliable. A truncated log line is a *logging* limit, not a limit on what you can read |
|
||||
| `dumpsys activity activities` / recents while the browser is still in the stack | Free; works only if the activity is still alive |
|
||||
| The browser's own history database (root) | Survives the browser being closed; needs the right DB, and modern browsers may encrypt or prune it |
|
||||
| Read the update *response* instead | Often easier: the URL came from a JSON field you can fetch or hook directly |
|
||||
|
||||
**Deliberately tapping the button is a legitimate probe** — but treat it as a measurement, not a
|
||||
side effect: capture the intent (or the screen) in the same window, and know that on some devices a
|
||||
second tap resumes an already-started download rather than re-issuing the intent.
|
||||
|
||||
### The gate is server-issued with a local fallback
|
||||
|
||||
`fetchEnabled()`-style helpers frequently **default to a local value on any failure** (non-200,
|
||||
timeout, malformed body, signature mismatch). Two things follow:
|
||||
|
||||
- **Read the failure branch before you touch anything.** If failure ⇒ "no update" or "no ad", then
|
||||
merely making the request fail is a complete fix, and it is far cheaper and more robust than
|
||||
patching the comparison.
|
||||
- **The fallback also tells you how to test offline.** Disconnect the device and relaunch: if the
|
||||
gate disappears, the fallback is benign and you have a zero-code workaround as well as a
|
||||
verification signal.
|
||||
|
||||
Conversely, if failure ⇒ "must update", failing the request makes things worse, and you must patch the
|
||||
decision instead.
|
||||
|
||||
## Checklist
|
||||
|
||||
- [ ] Update vocabulary searched in **both** string encodings, in the right layer for the runtime
|
||||
- [ ] The single update entry point identified (or its absence established, with evidence)
|
||||
- [ ] Shape classified: optional / forced / silent / installer / hot-update
|
||||
- [ ] Decision-level patch applied, not just the dialog
|
||||
- [ ] Comparison branch neutralised as a second layer
|
||||
- [ ] Manifest version and identity left alone
|
||||
- [ ] Cold start: **zero** update log lines, no blocking modal, **no version request on the wire**
|
||||
- [ ] Manual "check for updates" entry exercised
|
||||
- [ ] Startup siblings (splash dismissal, ads, consent, first-run) still complete
|
||||
- [ ] Hot-update / remote-config channel considered explicitly
|
||||
- [ ] Delivery note states what is now disabled
|
||||
@@ -0,0 +1,128 @@
|
||||
# Verification — what "done" means
|
||||
|
||||
The difference between a hobby patch and a usable deliverable is verification. "It assembles" and "the log is quiet" are not verification.
|
||||
|
||||
## The claim ladder
|
||||
|
||||
Each rung is stronger evidence. Climb as high as the task requires, and **state clearly which rung you reached**.
|
||||
|
||||
| Rung | Claim | Evidence required |
|
||||
|---|---|---|
|
||||
| 0 | "The dex was edited" | Byte-level diff of the target method |
|
||||
| 1 | "The structure is intact" | `dex_classdiff`: same classes, zero `ACC_INTERFACE` drift, unchanged classes byte-identical |
|
||||
| 2 | "It builds and signs" | Signature verification passes |
|
||||
| 3 | "It installs and launches" | Process alive, `logcat` free of fatal signatures |
|
||||
| 4 | "The target behavior changed" | The specific feature observed changed (screen exercised, endpoint observed, UI confirmed) |
|
||||
| 5 | "Nothing else regressed" | Adjacent features exercised: images, playback, lists, login, settings |
|
||||
| 6 | "The mechanism is proven" | Independent evidence of *why* — e.g. the SDK's domains are never resolved because init never ran, or the SDK never created its working directory under the app's private storage |
|
||||
| 7 | "The *distributed* artifact is the verified one" | Re-download the published file and compare its hash against the local build you tested |
|
||||
|
||||
**Rung 3 is the minimum for any deliverable. Rung 4 for a claim that the patch solved the problem. Rung 5 before handing it to a user. Rung 6 when the claim is "the subsystem is dead", not merely "the ad is hidden". Rung 7 whenever the deliverable leaves your machine — an upload can truncate, a build can be re-signed by a pipeline step, and the person downloading it has no way to know.**
|
||||
|
||||
## The control build rule
|
||||
|
||||
Before blaming a patch, build a control: **the same pipeline with zero patches**.
|
||||
|
||||
```bash
|
||||
python scripts/repack.py --apk original.apk --dexdir <extracted> --out control.apk
|
||||
```
|
||||
|
||||
- Control fails → your pipeline, the environment, or the device is at fault. Stop debugging the patch (`pitfalls.md` P9).
|
||||
- Control passes, patched fails → the patch is implicated. Bisect: revert one dex at a time.
|
||||
|
||||
Do this **whenever something unexpectedly fails**, and at least once per project.
|
||||
|
||||
## Structural verification (automate it)
|
||||
|
||||
After every dex edit:
|
||||
|
||||
```bash
|
||||
python scripts/dex_classdiff.py <original.dex> <patched.dex>
|
||||
```
|
||||
Expect exactly:
|
||||
```
|
||||
only_in_A=0 only_in_B=0
|
||||
ACC_INTERFACE mismatch: 0
|
||||
access_flags diff (same interface-ness): 0
|
||||
```
|
||||
|
||||
Caveat, and it is an important one: **this check cannot detect code-item damage.** A whole-tree smali round-trip can pass every table check and still crash with `IncompatibleClassChangeError` (`pitfalls.md` P3). Passing this check is necessary, not sufficient.
|
||||
|
||||
The checks that *can* see further — instruction-length auditing, the equal-length-replacement blind spot, and verifier-level legality (`move-result*` adjacency) — are in `references/patch-audit.md`. Use them before claiming a patch landed.
|
||||
|
||||
Also confirm you changed what you intended and nothing more:
|
||||
- Reverse the patched dex and inspect the target method.
|
||||
- Compare unmodified classes byte-for-byte against the original where feasible.
|
||||
|
||||
## Runtime verification
|
||||
|
||||
```bash
|
||||
adb -s <serial> logcat -c
|
||||
adb -s <serial> shell "am start -n <pkg>/<activity>"
|
||||
sleep 5; adb -s <serial> shell "pidof <pkg>" # empty == died
|
||||
sleep 20; adb -s <serial> shell "pidof <pkg>" # same pid == stable
|
||||
adb -s <serial> logcat -d -v brief | grep -E 'FATAL|VerifyError|IncompatibleClassChange|uncaughtException|Failure starting process'
|
||||
```
|
||||
|
||||
**Sample the pid twice, spaced apart.** A single reading catches apps that die in a crash loop.
|
||||
|
||||
Failure signature → cause table lives in `references/environment.md`.
|
||||
|
||||
**Logcat is often not enough.** If the app installs a crash handler (友盟/UCrash/Bugly), the Java stack never reaches logcat. A process that dies with only `uncaughtException time: ...` and no stack **has crashed** — treat it as a failure, not as noise. Extraction techniques: `references/environment.md` §signal extraction.
|
||||
|
||||
## Behavioral verification (the part people skip)
|
||||
|
||||
Launching proves nothing about your change. Exercise it.
|
||||
|
||||
- **Ads removed** → open the screens that had ads (splash, home, detail, player, reward button). Confirm absence *and* confirm the screens still function. Use **three independent signals**, not one: the screens look right, the SDK's log tags disappeared, and the SDK never created its working directory under the app's private storage. An SDK that silently failed to fill an ad slot looks exactly like an SDK that was never initialised — only the last two signals tell them apart.
|
||||
- **A gate patched** → walk the gated flow end to end.
|
||||
- **A timeout/limit patched** → trigger it.
|
||||
- **Data patched** → stop the app, clear/re-write the value, cold start, re-check (proves it is not an in-memory artifact).
|
||||
|
||||
**And then test the neighbours.** The most common real-world regression is a patch that fixed its target and quietly broke something unrelated:
|
||||
|
||||
- Images / cover art render?
|
||||
- Video or audio playback works?
|
||||
- Lists scroll and paginate?
|
||||
- Login / session still valid?
|
||||
- Settings screens open?
|
||||
- Downloads still start?
|
||||
|
||||
This is exactly how a "generic image-card composable" patch removed all cover art while the ad still showed (`pitfalls.md` P6).
|
||||
|
||||
## Screenshot discipline
|
||||
|
||||
Capture before/after screenshots for each claim. Text descriptions are not evidence; a screenshot of the screen without the ad, alongside one from the control build with it, is.
|
||||
|
||||
## Reporting
|
||||
|
||||
```
|
||||
Build: <path> <sha256>
|
||||
Base: <original apk name/version>
|
||||
Changes: <dex → what changed>, one line each
|
||||
Structural: dex_classdiff result (per dex)
|
||||
Signature: verified with --min-sdk-version 21 (v1/v2/v3); report the raw command, not just "ok"
|
||||
Device: <model / android / abi / rooted?>
|
||||
Runtime: pid stable over N s; no fatal signatures
|
||||
Behavior: <screens exercised>, <before/after>
|
||||
Regressions: <adjacent features checked>
|
||||
Distribution: <where it was published> re-downloaded, sha256 matches the tested build
|
||||
Rung reached: 0..7
|
||||
Residual: <what is NOT fixed, and the exact reason>
|
||||
```
|
||||
|
||||
**Be explicit about residuals.** "Ad X remains because it is delivered inside the screen's main data payload, and suppressing it at the transport layer takes the whole screen down" is a useful, honest result. Silently omitting it is not.
|
||||
|
||||
**Separate the two audiences.** The artifact goes to an end user; the analysis report goes to whoever asked for the work. User-facing notes stay neutral and practical — package name and version, install prerequisites, the signature-conflict warning (a different signer means the old install must be removed first), the checksum, and a scope/disclaimer line. Keep the mechanism, the patch points, and the reasoning in your own report, not in the file the end user opens.
|
||||
|
||||
## Anti-patterns
|
||||
|
||||
- Declaring success from a successful assembly.
|
||||
- Claiming "no ads" from a quiet logcat when the SDK never printed anything either way.
|
||||
- Concluding from a single launch without exercising the feature.
|
||||
- Quoting emulator results as device results.
|
||||
- Reporting a fixed feature without checking adjacent features.
|
||||
- Hiding a known residual failure.
|
||||
- Blaming your own patch for a failure the **unmodified original** also has — run the control build first.
|
||||
- Accepting a UI automation result as proof when the interaction may never have fired: verify field contents and look for the actual request, not just the screen.
|
||||
- Treating a feature-scoped network error as a patching problem before checking the server's certificate (`references/tls-and-cert.md`).
|
||||
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Entry-level APK diff: what actually changed between two builds.
|
||||
|
||||
Two jobs, both recurring:
|
||||
|
||||
1. **Audit a build you did not produce.** Given an original and a
|
||||
"cracked"/"modded" copy, this lists every entry that differs, every entry
|
||||
the author ADDED, and every entry they REMOVED. Added entries under
|
||||
`lib/`, `assets/`, or new dex files are the interesting ones -- that is
|
||||
where injected payloads live.
|
||||
|
||||
2. **Verify your own build was surgical.** After repacking, the diff against
|
||||
the original must contain exactly the entries you intended to touch and
|
||||
nothing else. A surprise entry is a bug in your pipeline, not in the app.
|
||||
|
||||
It compares *content*, not just sizes: two builds can have identical sizes and
|
||||
different bytes, and a same-size replacement is exactly the case a careless
|
||||
comparison misses.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python apk_diff.py original.apk modified.apk
|
||||
python apk_diff.py original.apk modified.apk --hide-identical
|
||||
python apk_diff.py original.apk modified.apk --only 'classes.*\\.dex|lib/.*'
|
||||
python apk_diff.py original.apk modified.apk --summary
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
# Directories worth naming explicitly -- this is where injected code lives.
|
||||
INTERESTING = ("lib/", "assets/", "META-INF/services/")
|
||||
|
||||
|
||||
def snapshot(path):
|
||||
"""{entry_name: (size, sha256, compress_type, crc)}"""
|
||||
out = {}
|
||||
with zipfile.ZipFile(path) as z:
|
||||
for it in z.infolist():
|
||||
if it.is_dir():
|
||||
continue
|
||||
data = z.read(it.filename)
|
||||
out[it.filename] = (
|
||||
len(data),
|
||||
hashlib.sha256(data).hexdigest(),
|
||||
it.compress_type,
|
||||
it.CRC,
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def classify(name):
|
||||
if re.match(r"^classes\d*\.dex$", name):
|
||||
return "dex"
|
||||
if name.startswith("META-INF/") and name.endswith((".RSA", ".SF", ".MF", ".DSA", ".EC")):
|
||||
return "signature"
|
||||
if name.startswith(INTERESTING):
|
||||
return "code/assets"
|
||||
return "other"
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Entry-level APK diff.")
|
||||
ap.add_argument("original")
|
||||
ap.add_argument("modified")
|
||||
ap.add_argument("--only", help="regex: restrict output to matching entry names")
|
||||
ap.add_argument("--hide-identical", action="store_true",
|
||||
help="omit the identical-count line")
|
||||
ap.add_argument("--summary", action="store_true",
|
||||
help="counts only, no per-entry listing")
|
||||
ap.add_argument("--max", type=int, default=200,
|
||||
help="max entries listed per section (default 200)")
|
||||
args = ap.parse_args()
|
||||
|
||||
try:
|
||||
a = snapshot(args.original)
|
||||
b = snapshot(args.modified)
|
||||
except Exception as e:
|
||||
sys.exit("error reading APK: %s" % e)
|
||||
|
||||
only_a = sorted(set(a) - set(b))
|
||||
only_b = sorted(set(b) - set(a))
|
||||
common = sorted(set(a) & set(b))
|
||||
changed = [n for n in common if a[n][1] != b[n][1]]
|
||||
|
||||
rx = re.compile(args.only) if args.only else None
|
||||
|
||||
def keep(n):
|
||||
return rx.search(n) if rx else True
|
||||
|
||||
def sha(path, n):
|
||||
return a[n][1][:16] if n in a else b[n][1][:16]
|
||||
|
||||
print("A (original) %s entries=%d" % (args.original, len(a)))
|
||||
print("B (modified) %s entries=%d" % (args.modified, len(b)))
|
||||
print("")
|
||||
print("only in A (removed) : %d" % len(only_a))
|
||||
print("only in B (added) : %d" % len(only_b))
|
||||
print("content changed : %d" % len(changed))
|
||||
if not args.hide_identical:
|
||||
print("identical : %d" % (len(common) - len(changed)))
|
||||
print("")
|
||||
|
||||
# Signature entries always differ; say so once instead of listing them.
|
||||
sig_only = [n for n in (only_a + only_b) if classify(n) == "signature"]
|
||||
if sig_only:
|
||||
print("(note: %d signature entries account for most of the add/remove noise)"
|
||||
% len(sig_only))
|
||||
|
||||
if args.summary:
|
||||
return
|
||||
|
||||
if only_b:
|
||||
print("\n=== ADDED in B (injection candidates) ===")
|
||||
shown = 0
|
||||
for n in only_b:
|
||||
if not keep(n) or classify(n) == "signature":
|
||||
continue
|
||||
print(" + %-52s %9d B [%s]" % (n, b[n][0], classify(n)))
|
||||
shown += 1
|
||||
if shown >= args.max:
|
||||
print(" ... (truncated)")
|
||||
break
|
||||
|
||||
if only_a:
|
||||
print("\n=== REMOVED from A ===")
|
||||
shown = 0
|
||||
for n in only_a:
|
||||
if not keep(n) or classify(n) == "signature":
|
||||
continue
|
||||
print(" - %-52s %9d B [%s]" % (n, a[n][0], classify(n)))
|
||||
shown += 1
|
||||
if shown >= args.max:
|
||||
print(" ... (truncated)")
|
||||
break
|
||||
|
||||
if changed:
|
||||
print("\n=== CONTENT CHANGED ===")
|
||||
shown = 0
|
||||
for n in changed:
|
||||
if not keep(n):
|
||||
continue
|
||||
sa, sb = a[n], b[n]
|
||||
cmark = "" if sa[2] == sb[2] else " ctype %d->%d" % (sa[2], sb[2])
|
||||
same_size = " (SAME SIZE)" if sa[0] == sb[0] else ""
|
||||
print(" ~ %-52s A %9d %s B %9d %s%s%s"
|
||||
% (n, sa[0], sa[1][:16], sb[0], sb[1][:16], same_size, cmark))
|
||||
shown += 1
|
||||
if shown >= args.max:
|
||||
print(" ... (truncated)")
|
||||
break
|
||||
if any(a[n][0] == b[n][0] for n in changed if keep(n)):
|
||||
print("\n (SAME SIZE means the change is not a length difference --")
|
||||
print(" a size-only comparison would have missed it entirely)")
|
||||
|
||||
if not (only_a or only_b or changed):
|
||||
print("no differences at all")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,276 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Decode (and re-encode) an opaque single-value blob cached by an app.
|
||||
|
||||
Many apps cache server-issued configuration as ONE opaque string inside a
|
||||
preferences file or a key-value store. The encoding is usually some stack of:
|
||||
outer: base64, base64url, or hex
|
||||
transform: a cyclic rotation of the byte stream (so the compressed stream
|
||||
does not begin at its header), sometimes preceded by a short
|
||||
header to skip
|
||||
inner: raw deflate, zlib, or gzip
|
||||
|
||||
You do not have to guess the parameters. This script searches them and reports
|
||||
every combination that decodes to something structured, then can re-encode your
|
||||
edited payload with the same parameters so it can be written back.
|
||||
|
||||
Why rotation matters: a plain base64->inflate attempt fails on these blobs, and
|
||||
the failure looks like "this value is encrypted". Exhaustively trying cyclic
|
||||
shifts is cheap and frequently succeeds, which turns an opaque blob into an
|
||||
editable JSON/XML document.
|
||||
|
||||
Usage:
|
||||
# decode the value of a key inside a prefs XML
|
||||
python blob_decode.py --prefs-xml prefs.xml --name flutter.remoteConfig
|
||||
|
||||
# decode a blob stored in its own file (or piped on stdin)
|
||||
python blob_decode.py --file value.txt
|
||||
cat value.txt | python blob_decode.py
|
||||
|
||||
# keep searching harder (slower) and write the best result out
|
||||
python blob_decode.py --file value.txt --max-skip 64 --out decoded.bin
|
||||
|
||||
# re-encode an edited payload with the parameters that worked
|
||||
python blob_decode.py --encode --file decoded.bin --outer base64 --inner raw --cut 15435 --out value.txt
|
||||
|
||||
Notes:
|
||||
* Output is written to --out; nothing on device is touched.
|
||||
* The winning parameters are printed as a copy-pasteable line for --encode.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
|
||||
INNERS = [("raw", -15), ("zlib", 15), ("gzip", 31)]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# outer encodings
|
||||
# --------------------------------------------------------------------------- #
|
||||
def outer_decode(text: str, which: str) -> bytes | None:
|
||||
t = text.strip().replace("\n", "").replace("\r", "").replace(" ", "")
|
||||
try:
|
||||
if which == "base64":
|
||||
return base64.b64decode(t + "=" * (-len(t) % 4))
|
||||
if which == "base64url":
|
||||
return base64.urlsafe_b64decode(t + "=" * (-len(t) % 4))
|
||||
if which == "hex":
|
||||
return binascii.unhexlify(re.sub(r"[^0-9a-fA-F]", "", t))
|
||||
except Exception:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def outer_encode(data: bytes, which: str) -> str:
|
||||
if which == "base64":
|
||||
return base64.b64encode(data).decode("ascii")
|
||||
if which == "base64url":
|
||||
return base64.urlsafe_b64encode(data).decode("ascii")
|
||||
if which == "hex":
|
||||
return binascii.hexlify(data).decode("ascii")
|
||||
raise ValueError("unknown outer encoding: %s" % which)
|
||||
|
||||
|
||||
def sniff_outer(text: str) -> list[str]:
|
||||
"""Cheap guess first so the common case is instant."""
|
||||
t = text.strip()
|
||||
guesses = []
|
||||
if re.fullmatch(r"[0-9a-fA-F\s]+", t) and len(t) >= 16:
|
||||
guesses.append("hex")
|
||||
if re.fullmatch(r"[A-Za-z0-9+/\s=]+", t):
|
||||
guesses.append("base64")
|
||||
if re.fullmatch(r"[A-Za-z0-9\-_\s=]+", t):
|
||||
guesses.append("base64url")
|
||||
# always keep base64 last-resort, then everything else
|
||||
for w in ("base64", "base64url", "hex"):
|
||||
if w not in guesses:
|
||||
guesses.append(w)
|
||||
return list(dict.fromkeys(guesses))
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# inner transforms
|
||||
# --------------------------------------------------------------------------- #
|
||||
def try_inflate(body: bytes, max_out: int | None = None) -> tuple[str, bytes] | None:
|
||||
best = None
|
||||
for name, wbits in INNERS:
|
||||
try:
|
||||
if max_out is None:
|
||||
out = zlib.decompress(body, wbits)
|
||||
else:
|
||||
d = zlib.decompressobj(wbits)
|
||||
out = d.decompress(body, max_out)
|
||||
if out:
|
||||
if best is None or len(out) > len(best[1]):
|
||||
best = (name, out)
|
||||
except Exception:
|
||||
continue
|
||||
return best
|
||||
|
||||
|
||||
def inflate_raw(data: bytes) -> bytes:
|
||||
co = zlib.compressobj(9, zlib.DEFLATED, -15)
|
||||
return co.compress(data) + co.flush()
|
||||
|
||||
|
||||
def score(out: bytes) -> float:
|
||||
"""How much does this look like a real document we can edit?"""
|
||||
if not out:
|
||||
return -1.0
|
||||
printable = sum(1 for b in out[:4096] if 32 <= b < 127 or b in (9, 10, 13))
|
||||
ratio = printable / min(len(out), 4096)
|
||||
s = ratio * 10.0
|
||||
head = out[:64].lstrip()
|
||||
if head[:1] in (b"{", b"[", b"<", b"#"):
|
||||
s += 6.0
|
||||
if b'"' in out[:512] or b"=" in out[:512]:
|
||||
s += 2.0
|
||||
if len(out) < 32:
|
||||
s -= 3.0
|
||||
return s
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
def search(blob: bytes, max_skip: int, log) -> list[dict]:
|
||||
hits: list[dict] = []
|
||||
n = len(blob)
|
||||
t0 = time.time()
|
||||
|
||||
for skip in range(0, min(max_skip, n) + 1):
|
||||
base = blob[skip:]
|
||||
m = len(base)
|
||||
if m < 8:
|
||||
break
|
||||
for k in range(m):
|
||||
cand = base[k:] + base[:k]
|
||||
got = try_inflate(cand, max_out=8_000_000)
|
||||
if got:
|
||||
name, out = got
|
||||
hits.append({
|
||||
"skip": skip, "cut": k, "inner": name, "size": len(out),
|
||||
"score": round(score(out), 2), "data": out,
|
||||
})
|
||||
if hits and log and skip == 0:
|
||||
log(" first hit found with skip=0 after %.1fs" % (time.time() - t0))
|
||||
if log and skip and skip % 16 == 0 and time.time() - t0 > 30:
|
||||
log(" ... skip=%d, %.0fs elapsed" % (skip, time.time() - t0))
|
||||
log(" search finished in %.1fs (%d candidate(s))" % (time.time() - t0, len(hits)))
|
||||
return hits
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
src = ap.add_mutually_exclusive_group()
|
||||
src.add_argument("--file", help="file containing the encoded value")
|
||||
src.add_argument("--prefs-xml", help="a preferences XML file to pull the value out of")
|
||||
ap.add_argument("--name", help="key name when using --prefs-xml")
|
||||
ap.add_argument("--outer", choices=["base64", "base64url", "hex", "auto"], default="auto")
|
||||
ap.add_argument("--max-skip", type=int, default=0,
|
||||
help="also try dropping 0..N leading bytes before the rotation search (slower)")
|
||||
ap.add_argument("--min-size", type=int, default=200, help="ignore results smaller than this")
|
||||
ap.add_argument("--top", type=int, default=5, help="how many candidates to print")
|
||||
ap.add_argument("--out", help="write the best decoded result here")
|
||||
|
||||
ap.add_argument("--encode", action="store_true", help="re-encode instead of decoding")
|
||||
ap.add_argument("--inner", choices=[n for n, _ in INNERS], default="raw")
|
||||
ap.add_argument("--cut", type=int, default=0, help="rotation used for write-back")
|
||||
a = ap.parse_args()
|
||||
|
||||
def log(msg: str) -> None:
|
||||
print(msg, file=sys.stderr)
|
||||
|
||||
# ------------------------------------------------------------------ encode
|
||||
if a.encode:
|
||||
if not a.file:
|
||||
log("--encode requires --file (the payload to encode)")
|
||||
return 2
|
||||
payload = open(a.file, "rb").read()
|
||||
body = inflate_raw(payload) if a.inner == "raw" else zlib.compress(payload, 9)
|
||||
if a.inner == "zlib":
|
||||
body = zlib.compress(payload, 9)
|
||||
cut = a.cut % max(len(body), 1)
|
||||
rotated = body[-cut:] + body[:-cut] if cut else body
|
||||
enc = outer_encode(rotated, "base64" if a.outer == "auto" else a.outer)
|
||||
if a.out:
|
||||
open(a.out, "w", encoding="utf-8", newline="\n").write(enc)
|
||||
log("wrote %d chars to %s" % (len(enc), a.out))
|
||||
else:
|
||||
print(enc)
|
||||
log("write-back parameters: outer=%s inner=%s cut=%d"
|
||||
% ("base64" if a.outer == "auto" else a.outer, a.inner, cut))
|
||||
return 0
|
||||
|
||||
# ------------------------------------------------------------------ input
|
||||
if a.prefs_xml:
|
||||
if not a.name:
|
||||
log("--prefs-xml requires --name <key>")
|
||||
return 2
|
||||
xml = open(a.prefs_xml, encoding="utf-8", errors="replace").read()
|
||||
m = re.search(r'name="%s"[^>]*>([^<]*)<' % re.escape(a.name), xml)
|
||||
if not m:
|
||||
log("key not found in XML: %s" % a.name)
|
||||
log("keys present: %s" % ", ".join(re.findall(r'name="([^"]+)"', xml)[:40]))
|
||||
return 2
|
||||
text = m.group(1)
|
||||
log("value length: %d" % len(text))
|
||||
elif a.file:
|
||||
text = open(a.file, encoding="utf-8", errors="replace").read()
|
||||
else:
|
||||
text = sys.stdin.read()
|
||||
|
||||
if not text.strip():
|
||||
log("empty input")
|
||||
return 2
|
||||
|
||||
# ------------------------------------------------------------------ decode
|
||||
candidates = [a.outer] if a.outer != "auto" else sniff_outer(text)
|
||||
for which in candidates:
|
||||
blob = outer_decode(text, which)
|
||||
if blob is None or len(blob) < 8:
|
||||
log("outer=%s -> not decodable, skipping" % which)
|
||||
continue
|
||||
log("outer=%s -> %d bytes; searching rotation (and skip<=%d)" % (which, len(blob), a.max_skip))
|
||||
hits = [h for h in search(blob, a.max_skip, log) if h["size"] >= a.min_size]
|
||||
if not hits:
|
||||
continue
|
||||
hits.sort(key=lambda h: (-h["score"], -h["size"]))
|
||||
print("=" * 66)
|
||||
print("outer=%s candidates=%d" % (which, len(hits)))
|
||||
for h in hits[:a.top]:
|
||||
print(" score=%-6s skip=%-4d cut=%-7d inner=%-5s size=%d"
|
||||
% (h["score"], h["skip"], h["cut"], h["inner"], h["size"]))
|
||||
best = hits[0]
|
||||
print("-" * 66)
|
||||
print("write-back line:")
|
||||
print(" python blob_decode.py --encode --file <edited_payload> --outer %s --inner %s --cut %d"
|
||||
% (which, best["inner"], best["cut"]))
|
||||
print("-" * 66)
|
||||
preview = best["data"][:1200]
|
||||
try:
|
||||
print(preview.decode("utf-8"))
|
||||
except UnicodeDecodeError:
|
||||
print(preview.decode("latin1"))
|
||||
print("(non-UTF-8; first 64 bytes: %s)" % best["data"][:64].hex())
|
||||
if a.out:
|
||||
open(a.out, "wb").write(best["data"])
|
||||
log("wrote %d bytes to %s" % (len(best["data"]), a.out))
|
||||
return 0
|
||||
|
||||
print("no decodable candidate found.", file=sys.stderr)
|
||||
print("Next steps:", file=sys.stderr)
|
||||
print(" * raise --max-skip, or pass --outer explicitly", file=sys.stderr)
|
||||
print(" * the blob may be genuinely encrypted (a keyed cipher) rather than merely", file=sys.stderr)
|
||||
print(" encoded -- confirm before spending time on it: a keyed blob should look", file=sys.stderr)
|
||||
print(" random, whereas an encoded one still has structure once the framing is", file=sys.stderr)
|
||||
print(" removed. See references/runtime-data.md.", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,304 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Cold-launch an app and capture a time line of screenshots plus logcat signals.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
"Did the patch work?" for anything user-visible -- a splash/ad gate, a forced
|
||||
update dialog, a login wall, a crash-on-start -- is answered by looking at the
|
||||
screen over the first seconds of a launch, and by comparison against the
|
||||
unmodified build. Doing that by hand produces two failures that look like
|
||||
findings and are not:
|
||||
|
||||
* **Sampling is not observation.** A dialog that appears and is then occluded
|
||||
can fall entirely between samples, and every frame you happened to take shows
|
||||
something else, which feels like corroboration. This tool captures on a fixed
|
||||
short cadence and, crucially, prints what it captured so a human or agent
|
||||
actually LOOKS at the frames.
|
||||
* **`am start -W` can block past a naive timeout.** It waits for the first
|
||||
frame; on some ROMs that never arrives while another window owns the display
|
||||
and the command simply hangs. This tool launches without `-W` and derives the
|
||||
time line from captures plus logcat instead.
|
||||
|
||||
It also records the two facts that decide whether an install even happened:
|
||||
the installed version, and the on-disk APK hash. "Install succeeded" describes
|
||||
the request, not the app on disk.
|
||||
|
||||
IMPORTANT -- before trusting any screenshot, confirm the foreground activity is
|
||||
your target. A vendor package installer left on screen (a pending confirmation
|
||||
from an earlier `adb install`, for example) will be captured instead of your app
|
||||
and looks completely plausible. `--expect-activity` makes that check automatic.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python coldstart.py --serial <SERIAL> --pkg com.example \\
|
||||
--activity com.example/.MainActivity --duration 14 --interval 0.8 \\
|
||||
--out work/verify/orig --expect-activity com.example/.MainActivity
|
||||
|
||||
Requires: adb. `su` on the device is used when available for version/hash facts,
|
||||
otherwise it degrades to plain `pm`/`dumpsys`.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
|
||||
def run(cmd, timeout=30, serial=None):
|
||||
"""Run a command with a hard timeout; never let a call stall the run."""
|
||||
try:
|
||||
return subprocess.run(cmd, capture_output=True, timeout=timeout,
|
||||
text=True, errors='replace')
|
||||
except subprocess.TimeoutExpired:
|
||||
return subprocess.CompletedProcess(cmd, 124, '', 'timeout after %ss' % timeout)
|
||||
|
||||
|
||||
class Device(object):
|
||||
def __init__(self, serial, use_su=True, timeout=30):
|
||||
self.serial = serial
|
||||
self.timeout = timeout
|
||||
self.adb = shutil.which('adb') or 'adb'
|
||||
self.su = use_su and self._su_works()
|
||||
|
||||
def _su_works(self):
|
||||
if self.serial:
|
||||
r = run(['adb', '-s', self.serial, 'shell', "su -c 'id'"], 15)
|
||||
else:
|
||||
r = run(['adb', 'shell', "su -c 'id'"], 15)
|
||||
return r.returncode == 0 and 'uid=0' in (r.stdout or '')
|
||||
|
||||
def shell(self, cmd, timeout=None):
|
||||
"""Run a device shell command, preferring root when available."""
|
||||
t = timeout or self.timeout
|
||||
if self.serial:
|
||||
base = ['adb', '-s', self.serial, 'shell']
|
||||
else:
|
||||
base = ['adb', 'shell']
|
||||
if self.su:
|
||||
return run(base + ["su -c '%s'" % cmd.replace("'", "'\\''")], t)
|
||||
return run(base + [cmd], t)
|
||||
|
||||
def screencap(self, path, timeout=30):
|
||||
"""Capture one PNG. Returns bytes written, or -1 on failure."""
|
||||
if self.serial:
|
||||
base = ['adb', '-s', self.serial]
|
||||
else:
|
||||
base = ['adb']
|
||||
try:
|
||||
with open(path, 'wb') as fh:
|
||||
r = subprocess.run(base + ['exec-out', 'screencap', '-p'],
|
||||
stdout=fh, timeout=timeout)
|
||||
size = os.path.getsize(path)
|
||||
if size < 8:
|
||||
return -1
|
||||
with open(path, 'rb') as fh:
|
||||
if fh.read(8) != b'\x89PNG\r\n\x1a\n':
|
||||
return -1
|
||||
return size
|
||||
except subprocess.TimeoutExpired:
|
||||
return -1
|
||||
|
||||
|
||||
def foreground_activity(dev):
|
||||
r = dev.shell('dumpsys activity activities | grep -m1 ResumedActivity')
|
||||
m = re.search(r'([A-Za-z0-9_.]+)/([A-Za-z0-9_.$]+)', r.stdout or '')
|
||||
return '%s/%s' % (m.group(1), m.group(2)) if m else None
|
||||
|
||||
|
||||
def installed_facts(dev, pkg):
|
||||
facts = {}
|
||||
r = dev.shell("dumpsys package %s | grep -E 'versionCode|versionName|firstInstallTime|lastUpdateTime'" % pkg)
|
||||
for line in (r.stdout or '').splitlines():
|
||||
m = re.match(r'\s*(versionCode|versionName|firstInstallTime|lastUpdateTime)=(.*)', line)
|
||||
if m:
|
||||
facts[m.group(1)] = m.group(2).strip()
|
||||
r = dev.shell('ls /data/app/*/%s*/base.apk 2>/dev/null' % pkg)
|
||||
apk_path = (r.stdout or '').strip().splitlines()[:1]
|
||||
if apk_path:
|
||||
facts['apk_path'] = apk_path[0]
|
||||
r2 = dev.shell('sha256sum %s' % apk_path[0])
|
||||
m = re.search(r'([0-9a-f]{64})', r2.stdout or '')
|
||||
if m:
|
||||
facts['apk_sha256'] = m.group(1)
|
||||
r = dev.shell('dumpsys package %s | grep -m1 userId=' % pkg)
|
||||
m = re.search(r'userId=(\d+)', r.stdout or '')
|
||||
if m:
|
||||
facts['uid'] = m.group(1)
|
||||
return facts
|
||||
|
||||
|
||||
def signal_counts(log_path, patterns):
|
||||
"""Count occurrences of each pattern in a logcat dump."""
|
||||
try:
|
||||
with open(log_path, encoding='utf-8', errors='replace') as fh:
|
||||
text = fh.read()
|
||||
except OSError:
|
||||
return {}
|
||||
return {name: len(re.findall(rx, text)) for name, rx in patterns.items()}
|
||||
|
||||
|
||||
SIGNAL_PATTERNS = {
|
||||
'FATAL EXCEPTION': r'FATAL EXCEPTION',
|
||||
'VerifyError': r'VerifyError',
|
||||
'Bad checksum': r'Bad checksum',
|
||||
'IncompatibleClassChangeError': r'IncompatibleClassChangeError',
|
||||
'ClassNotFoundException': r'ClassNotFoundException',
|
||||
'uncaughtException': r'uncaughtException',
|
||||
'am_crash': r'am_crash',
|
||||
'ANR': r'ANR in ',
|
||||
'Displayed': r'Displayed .*\+([0-9]+)ms',
|
||||
}
|
||||
|
||||
|
||||
def main(argv):
|
||||
ap = argparse.ArgumentParser(
|
||||
description='Cold-launch an app and capture a screenshot time line plus '
|
||||
'logcat signals, for before/after comparison.',
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__.split('Usage')[-1][:1200])
|
||||
ap.add_argument('--serial', help='adb serial (REQUIRED when several devices are '
|
||||
'online, so the wrong one is not picked at random)')
|
||||
ap.add_argument('--pkg', required=True, help='package name')
|
||||
ap.add_argument('--activity', help='component to start (default: monkey/launcher)')
|
||||
ap.add_argument('--out', default='coldstart', help='output directory')
|
||||
ap.add_argument('--duration', type=float, default=14.0, help='seconds to capture')
|
||||
ap.add_argument('--interval', type=float, default=0.8, help='seconds between frames')
|
||||
ap.add_argument('--expect-activity', help='warn if the foreground activity is not '
|
||||
'this (and not the package at all)')
|
||||
ap.add_argument('--no-su', action='store_true', help='never use device root')
|
||||
ap.add_argument('--keep-old', action='store_true',
|
||||
help='do not clear existing screenshots in the output dir')
|
||||
args = ap.parse_args(argv[1:])
|
||||
|
||||
if not shutil.which('adb'):
|
||||
print('error: adb not found on PATH')
|
||||
return 2
|
||||
|
||||
if not args.serial:
|
||||
r = run(['adb', 'devices'])
|
||||
online = [l.split()[0] for l in (r.stdout or '').splitlines()[1:]
|
||||
if len(l.split()) >= 2 and l.split()[1] == 'device']
|
||||
if len(online) > 1:
|
||||
print('error: %d devices online (%s) and no --serial given. adb would '
|
||||
'pick one at random and you would debug the wrong target.'
|
||||
% (len(online), ', '.join(online)))
|
||||
return 2
|
||||
if online:
|
||||
args.serial = online[0]
|
||||
print('[i] single device online; using %s' % args.serial)
|
||||
|
||||
dev = Device(args.serial, use_su=not args.no_su)
|
||||
print('[i] serial=%s root=%s' % (args.serial, dev.su))
|
||||
|
||||
os.makedirs(args.out, exist_ok=True)
|
||||
shots = os.path.join(args.out, 'shots')
|
||||
os.makedirs(shots, exist_ok=True)
|
||||
if not args.keep_old:
|
||||
for f in os.listdir(shots):
|
||||
if f.endswith('.png'):
|
||||
os.remove(os.path.join(shots, f))
|
||||
|
||||
facts = installed_facts(dev, args.pkg)
|
||||
print('\n== installed build facts')
|
||||
for k in sorted(facts):
|
||||
print(' %-18s %s' % (k, facts[k]))
|
||||
if not facts.get('versionCode'):
|
||||
print(' WARNING: no versionCode found -- the package may not be installed')
|
||||
print(' (install success describes the request, not the app on disk; the '
|
||||
'sha256 above is the on-disk truth)')
|
||||
|
||||
print('\n== clearing logcat')
|
||||
dev.shell('logcat -c', timeout=20)
|
||||
|
||||
print('== force-stopping %s' % args.pkg)
|
||||
dev.shell('am force-stop %s' % args.pkg, timeout=20)
|
||||
|
||||
print('== launching')
|
||||
t0 = time.time()
|
||||
if args.activity:
|
||||
r = dev.shell('am start -n %s' % args.activity, timeout=25)
|
||||
else:
|
||||
r = dev.shell('monkey -p %s -c android.intent.category.LAUNCHER 1' % args.pkg,
|
||||
timeout=25)
|
||||
out = ((r.stdout or '') + (r.stderr or '')).strip()
|
||||
print(' %s' % (out.splitlines()[0] if out else '(no output)'))
|
||||
if 'Error' in out or 'Exception' in out:
|
||||
print(' LAUNCH ERROR -- read the line above before blaming the patch')
|
||||
|
||||
# live logcat into a file while we capture
|
||||
log_path = os.path.join(args.out, 'logcat.txt')
|
||||
if args.serial:
|
||||
log_cmd = ['adb', '-s', args.serial, 'logcat', '-v', 'threadtime']
|
||||
else:
|
||||
log_cmd = ['adb', 'logcat', '-v', 'threadtime']
|
||||
log_fh = open(log_path, 'w', encoding='utf-8', errors='replace')
|
||||
log_proc = subprocess.Popen(log_cmd, stdout=log_fh, stderr=subprocess.DEVNULL)
|
||||
|
||||
frames = []
|
||||
idx = 0
|
||||
try:
|
||||
while True:
|
||||
el = time.time() - t0
|
||||
if el > args.duration:
|
||||
break
|
||||
name = 'f%02d_%05.2fs.png' % (idx, el)
|
||||
path = os.path.join(shots, name)
|
||||
n = dev.screencap(path)
|
||||
frames.append((name, n, el))
|
||||
print(' %-20s %s' % (name, ('%d bytes' % n) if n > 0 else 'CAPTURE FAILED'))
|
||||
idx += 1
|
||||
time.sleep(max(0.0, args.interval))
|
||||
finally:
|
||||
time.sleep(0.5)
|
||||
log_proc.terminate()
|
||||
try:
|
||||
log_proc.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
log_proc.kill()
|
||||
log_fh.close()
|
||||
|
||||
fg = foreground_activity(dev)
|
||||
print('\n== foreground at end: %s' % fg)
|
||||
if args.expect_activity and fg and args.pkg not in fg:
|
||||
print(' *** FOREGROUND IS NOT YOUR APP (%s) ***' % fg)
|
||||
print(' Everything captured above shows something else -- most often a '
|
||||
'vendor package-installer confirmation left over from an install.')
|
||||
print(' Clear it (e.g. close the installer, press HOME) and re-run; do not '
|
||||
'read these frames as evidence about your build.')
|
||||
|
||||
counts = signal_counts(log_path, SIGNAL_PATTERNS)
|
||||
print('\n== logcat signals (%s)' % log_path)
|
||||
for name in SIGNAL_PATTERNS:
|
||||
print(' %-32s %s' % (name, counts.get(name, 0)))
|
||||
|
||||
m = re.findall(r'Displayed ([^:]+): \+([0-9]+)ms', open(log_path, encoding='utf-8',
|
||||
errors='replace').read())
|
||||
if m:
|
||||
print('\n== launch timing (logcat Displayed)')
|
||||
for comp, ms in m:
|
||||
print(' %s %s ms' % (comp.strip(), ms))
|
||||
else:
|
||||
print('\n no "Displayed" line: the launch may not have reached a first '
|
||||
'frame (a hang or a blocking dialog looks exactly like this)')
|
||||
|
||||
zero = sum(1 for _n, n, _e in frames if n <= 0)
|
||||
print('\n== %d frame(s) in %s, %d failed' % (len(frames), shots, zero))
|
||||
|
||||
# the point of the tool: make inspection happen
|
||||
print('\n== INSPECT THE FRAMES. A capture nobody looked at is not evidence.')
|
||||
nonzero = [f for f in sorted(os.listdir(shots)) if f.endswith('.png')]
|
||||
if nonzero:
|
||||
print(' start with: %s' % os.path.join(shots, nonzero[0]))
|
||||
mid = nonzero[len(nonzero) // 2]
|
||||
print(' and: %s' % os.path.join(shots, mid))
|
||||
print(' Byte-identical consecutive frames mean the screen is static -- that '
|
||||
'is a finding (a hang, or a dialog waiting), not a capture problem.')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Annotated, windowed disassembly of a Dart AOT snapshot, plus a caller index.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
Two things make Dart AOT code readable at all:
|
||||
|
||||
1. **Pool annotations.** A raw `ldr x2, [x27, #0x9d0]` is meaningless; annotated with the
|
||||
pool entry it becomes `"vipflag"` and the surrounding code explains itself. This tool
|
||||
resolves those loads and prints what they point at, including how many other sites
|
||||
reference the same entry.
|
||||
2. **Windowed disassembly.** Decoding an entire multi-MB `.text` in one pass is how a host
|
||||
gets pinned at 1-2 GB and the run looks like a hang. Disassemble only the ranges you
|
||||
care about -- that is what this tool does, and it is not a limitation but the method.
|
||||
|
||||
Booleans are annotated too: Dart materialises `true`/`false` as small offsets from the null
|
||||
register, so `add x0, x22, #0x20` is marked TRUE and `#0x30` is marked FALSE. Those are the
|
||||
cheapest patch sites in the whole snapshot.
|
||||
|
||||
The caller index answers the other half of every question -- "what calls this function".
|
||||
It is built from B/BL target arithmetic on the raw words, so it needs no disassembler at all
|
||||
and finishes in seconds.
|
||||
|
||||
USAGE
|
||||
-----
|
||||
# a window around one address (default: 0x180 before, 0x220 after)
|
||||
python dart_disasm.py libapp.so --pp pp.txt --refs pp_refs.json 0x26e390
|
||||
|
||||
# an explicit range
|
||||
python dart_disasm.py libapp.so --pp pp.txt --refs pp_refs.json --range 0x64f310 0x64f3e0
|
||||
|
||||
# widen / narrow the window
|
||||
python dart_disasm.py libapp.so --refs pp_refs.json 0x64f1bc --before 0x80 --after 0x40
|
||||
|
||||
# caller index
|
||||
python dart_disasm.py libapp.so --build-index callers.json
|
||||
python dart_disasm.py libapp.so --index callers.json 0x26e230 0x64f0f0
|
||||
|
||||
INPUTS
|
||||
------
|
||||
* `--pp` is the decompiler's pool listing (blutter `pp.txt`): lines shaped
|
||||
`[pp+0x9d0] String: "vipflag"`. Without it, loads are annotated with the raw offset only.
|
||||
* `--refs` is the pool-offset -> code-site index built by `dart_pprefs.py`.
|
||||
|
||||
Requires `capstone` for disassembly; the caller index works without it.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
POOL_REG = 27
|
||||
BOOL_TRUE, BOOL_FALSE = 0x20, 0x30
|
||||
PP_LINE = re.compile(r'^\[(pp\+0x[0-9a-f]+)\](.*)$')
|
||||
|
||||
|
||||
def text_section(path):
|
||||
blob = open(path, 'rb').read()
|
||||
if blob[:4] != b'\x7fELF':
|
||||
raise SystemExit('not an ELF file: %s' % path)
|
||||
if blob[4] != 2:
|
||||
raise SystemExit('not ELF64: %s' % path)
|
||||
e_shoff = struct.unpack_from('<Q', blob, 0x28)[0]
|
||||
e_shentsize = struct.unpack_from('<H', blob, 0x3A)[0]
|
||||
e_shnum = struct.unpack_from('<H', blob, 0x3C)[0]
|
||||
e_shstrndx = struct.unpack_from('<H', blob, 0x3E)[0]
|
||||
|
||||
def sh(i):
|
||||
return struct.unpack_from('<IIQQQQ', blob, e_shoff + i * e_shentsize)
|
||||
|
||||
_, _, _, _, shstr_off, shstr_size = sh(e_shstrndx)
|
||||
strs = blob[shstr_off:shstr_off + shstr_size]
|
||||
for i in range(e_shnum):
|
||||
name, _t, _f, addr, off, size = sh(i)
|
||||
end = strs.find(b'\x00', name)
|
||||
if strs[name:end].decode('ascii', 'replace') == '.text':
|
||||
return addr, blob[off:off + size]
|
||||
raise SystemExit('.text not found')
|
||||
|
||||
|
||||
def load_pp(path):
|
||||
pool = {}
|
||||
if not path or not os.path.exists(path):
|
||||
return pool
|
||||
for line in open(path, encoding='utf-8', errors='replace'):
|
||||
m = PP_LINE.match(line.rstrip('\n'))
|
||||
if m:
|
||||
pool[int(m.group(1)[5:], 16)] = m.group(2).strip()[:120]
|
||||
return pool
|
||||
|
||||
|
||||
def load_refs(path):
|
||||
if not path or not os.path.exists(path):
|
||||
return {}
|
||||
return {int(k, 16): v for k, v in json.load(open(path, encoding='utf-8')).items()}
|
||||
|
||||
|
||||
def disasm_window(sample, addr, before, after, pp, refs):
|
||||
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN
|
||||
|
||||
text_addr, blob = text_section(sample)
|
||||
end_of_text = text_addr + len(blob)
|
||||
start = max(text_addr, addr - before)
|
||||
stop = min(end_of_text, addr + after)
|
||||
|
||||
md = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN)
|
||||
md.skipdata = True # without this, one undecodable byte silently ends the range
|
||||
md.detail = True # without this, operands are unavailable
|
||||
|
||||
print('range 0x%x..0x%x focus=0x%x' % (start, stop, addr))
|
||||
pending = {}
|
||||
for ins in md.disasm(blob[start - text_addr:stop - text_addr], start):
|
||||
if ins.id == 0: # SKIPDATA pseudo-instruction: no operands
|
||||
print('%x: %s' % (ins.address, ins.mnemonic))
|
||||
continue
|
||||
note = ''
|
||||
ops = ins.operands
|
||||
rn = ins.reg_name
|
||||
if (ins.mnemonic == 'add' and len(ops) == 3 and ops[1].type == 1
|
||||
and rn(ops[1].reg) == 'x27' and ops[2].type == 2
|
||||
and ops[2].shift.value == 12):
|
||||
pending[rn(ops[0].reg)] = ops[2].imm << 12
|
||||
elif (ins.mnemonic == 'add' and len(ops) == 3 and ops[1].type == 1
|
||||
and rn(ops[1].reg) == 'x22' and ops[2].type == 2):
|
||||
note = {BOOL_TRUE: ' ; TRUE', BOOL_FALSE: ' ; FALSE'}.get(ops[2].imm, '')
|
||||
elif ins.mnemonic in ('ldr', 'ldur') and len(ops) == 2 and ops[1].type == 3:
|
||||
base = rn(ops[1].mem.base) if ops[1].mem.base else ''
|
||||
off = None
|
||||
if base == 'x27':
|
||||
off = ops[1].mem.disp
|
||||
elif base in pending:
|
||||
off = pending.pop(base) + ops[1].mem.disp
|
||||
if off is not None:
|
||||
text = pp.get(off, '')
|
||||
sites = refs.get(off, [])
|
||||
note = ' ; pp+0x%x %s [%d refs]' % (off, text, len(sites))
|
||||
mark = ' <<<' if abs(ins.address - addr) < 4 else ''
|
||||
print('%x: %-8s %s%s%s' % (ins.address, ins.mnemonic, ins.op_str, note, mark))
|
||||
|
||||
|
||||
def build_index(sample, out):
|
||||
"""B/BL target -> call sites, decoded arithmetically (no disassembler needed)."""
|
||||
text_addr, blob = text_section(sample)
|
||||
index = {}
|
||||
words = struct.unpack_from('<%dI' % (len(blob) // 4), blob, 0)
|
||||
for i, w in enumerate(words):
|
||||
if w & 0xFC000000 in (0x14000000, 0x94000000):
|
||||
imm = w & 0x03FFFFFF
|
||||
if imm & 0x02000000:
|
||||
imm -= 0x04000000
|
||||
site = text_addr + i * 4
|
||||
index.setdefault(site + (imm << 2), []).append(site)
|
||||
with open(out, 'w', encoding='utf-8') as fh:
|
||||
json.dump({hex(k): v for k, v in index.items()}, fh)
|
||||
print('distinct targets : %d' % len(index))
|
||||
print('call sites : %d' % sum(len(v) for v in index.values()))
|
||||
print('written %s' % out)
|
||||
|
||||
|
||||
def lookup_index(sample, path, addrs):
|
||||
index = {int(k, 16): v for k, v in json.load(open(path, encoding='utf-8')).items()}
|
||||
for spec in addrs:
|
||||
target = int(spec, 16)
|
||||
sites = sorted(index.get(target, []))
|
||||
print('0x%x: %d caller(s)' % (target, len(sites)))
|
||||
for s in sites[:80]:
|
||||
print(' 0x%x' % s)
|
||||
if len(sites) > 80:
|
||||
print(' ... %d more' % (len(sites) - 80))
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description=__doc__.split('\n')[0],
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter, epilog=__doc__)
|
||||
ap.add_argument('sample', help='libapp.so')
|
||||
ap.add_argument('addr', nargs='*', help='hex address(es) to disassemble around')
|
||||
ap.add_argument('--pp', metavar='PP_TXT', help="decompiler pool listing (blutter pp.txt)")
|
||||
ap.add_argument('--refs', metavar='REFS_JSON', help='index from dart_pprefs.py')
|
||||
ap.add_argument('--range', nargs=2, metavar=('START', 'END'))
|
||||
ap.add_argument('--before', default='0x180')
|
||||
ap.add_argument('--after', default='0x220')
|
||||
ap.add_argument('--build-index', metavar='OUT_JSON')
|
||||
ap.add_argument('--index', metavar='CALLERS_JSON')
|
||||
a = ap.parse_args()
|
||||
|
||||
if a.build_index:
|
||||
return build_index(a.sample, a.build_index)
|
||||
if a.index:
|
||||
if not a.addr:
|
||||
raise SystemExit('give at least one hex address to look up')
|
||||
return lookup_index(a.sample, a.index, a.addr)
|
||||
|
||||
pp = load_pp(a.pp)
|
||||
refs = load_refs(a.refs)
|
||||
if a.range:
|
||||
start, stop = int(a.range[0], 16), int(a.range[1], 16)
|
||||
disasm_window(a.sample, start, 0, stop - start, pp, refs)
|
||||
return 0
|
||||
if not a.addr:
|
||||
raise SystemExit('give an address, --range, --build-index, or --index')
|
||||
for spec in a.addr:
|
||||
disasm_window(a.sample, int(spec, 16),
|
||||
int(a.before, 0), int(a.after, 0), pp, refs)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,273 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Recover string literals from a Dart AOT snapshot, and locate them by file offset.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
Strings are the cheapest anchor for locating logic in a stripped AOT snapshot: field
|
||||
names, endpoint paths and labels survive compilation even when every symbol name is gone.
|
||||
Two things this gives you that a decompiler's own listing does not:
|
||||
|
||||
* **file offsets**, where the constant physically sits in the binary (what you need to
|
||||
patch bytes, as opposed to a pool offset);
|
||||
* **identifiers the decompiler's listing omits** -- measured on a real sample, most of
|
||||
what this recovers was absent from the pool listing entirely. Treat the two as
|
||||
complementary, not competitive.
|
||||
|
||||
THE FRAMING
|
||||
-----------
|
||||
[ tag ][ payload ] tag = 0x80 | (len << 1) | <two-byte flag>
|
||||
|
||||
* tag bit 7 set -> a string entry
|
||||
* (tag >> 1) & 0x3F -> payload length in characters (this framing tops out at 63)
|
||||
* the low bit -> nominally "payload is UTF-16LE"
|
||||
|
||||
ENCODING, AND WHY ONE-BYTE IS THE DEFAULT
|
||||
-----------------------------------------
|
||||
The two payload kinds are searched differently, and this is where most people lose time:
|
||||
|
||||
* **one-byte** payloads are ASCII / Latin-1 -> a **UTF-8 byte search finds them**
|
||||
* **two-byte** payloads are **UTF-16LE** -> a UTF-8 search returns *zero hits*
|
||||
|
||||
So search ASCII as UTF-8 and CJK/non-Latin as UTF-16LE; forcing one encoding on both is
|
||||
the classic false negative (`pitfalls.md` P25).
|
||||
|
||||
**But automatic two-byte detection does not work reliably.** The low tag bit is not a
|
||||
dependable discriminator against ordinary data, and UTF-16LE decoding essentially never
|
||||
fails -- *any* byte pair is a legal code unit -- so decoding success filters nothing. On a
|
||||
real sample, two-byte output was ~10k entries of near-pure garbage that happened to form
|
||||
long runs, while one-byte output was almost entirely genuine. Hence:
|
||||
|
||||
* default: one-byte only (reliable; verified against a decompiler listing on a real sample)
|
||||
* `--two-byte`: opt in, and **verify every hit yourself**
|
||||
* to find a *known* non-Latin literal, use `--find` -- a direct search is far more
|
||||
reliable than enumerating candidates
|
||||
|
||||
WHY THE RUN LENGTH IS REPORTED
|
||||
------------------------------
|
||||
A per-byte scan for tag-like bytes hits constantly inside ordinary data; a multi-MB
|
||||
snapshot yields hundreds of thousands of candidates. Most real string tables are laid out
|
||||
consecutively, so a genuine entry usually begins a run of back-to-back entries (each
|
||||
entry's tag+payload ends exactly where the next begins). `--min-chain` uses that to shed
|
||||
the scattered tail.
|
||||
|
||||
Note what the measurement showed: raising this threshold barely changes one-byte
|
||||
precision while steadily destroying recall. It is a **noise filter, not a confidence
|
||||
score** -- do not tune it expecting accuracy to improve.
|
||||
|
||||
USAGE
|
||||
-----
|
||||
python dart_pool_strings.py libapp.so strings.tsv
|
||||
python dart_pool_strings.py libapp.so strings.tsv --pp pp.txt # annotate cross-hits
|
||||
python dart_pool_strings.py libapp.so strings.tsv --min-chain 2 --two-byte
|
||||
python dart_pool_strings.py libapp.so --find /activateVipCode --find vipflag
|
||||
python dart_pool_strings.py libapp.so --stats
|
||||
|
||||
OUTPUT
|
||||
------
|
||||
offset_hex <TAB> text <TAB> run <TAB> form [<TAB> in_pp]
|
||||
|
||||
`in_pp` is present with `--pp`: `1` means the decompiler's own pool listing contains this
|
||||
exact string. Absence is **not** evidence of a false positive -- the decompiler's listing
|
||||
is incomplete by design.
|
||||
|
||||
NOTES
|
||||
-----
|
||||
* `--max` is capped at 63 by the framing; longer literals are serialized differently and
|
||||
will not appear here (a few hundred per sample at most).
|
||||
* Never edit a string without counting its references first: a shared entry changes every
|
||||
consumer at once (`references/dart-aot.md` section 10).
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
import re
|
||||
import sys
|
||||
|
||||
TAG_STR = 0x80
|
||||
BAD = re.compile(r'[\x00-\x08\x0b\x0c\x0e-\x1f]')
|
||||
|
||||
|
||||
def decode_payload(raw, two_byte):
|
||||
if two_byte:
|
||||
if len(raw) % 2:
|
||||
return None
|
||||
try:
|
||||
text = raw.decode('utf-16-le')
|
||||
except UnicodeDecodeError:
|
||||
return None
|
||||
else:
|
||||
try:
|
||||
text = raw.decode('utf-8')
|
||||
except UnicodeDecodeError:
|
||||
return None
|
||||
if BAD.search(text):
|
||||
return None
|
||||
return text
|
||||
|
||||
|
||||
def extract(blob, min_len, max_len, want_two_byte):
|
||||
"""Return {start: (end, text, form)} for every framed candidate of the wanted kind."""
|
||||
n = len(blob)
|
||||
cands = {}
|
||||
for i in range(n - 2):
|
||||
tag = blob[i]
|
||||
if not (tag & TAG_STR):
|
||||
continue
|
||||
ln = (tag >> 1) & 0x3F
|
||||
if not (min_len <= ln <= max_len):
|
||||
continue
|
||||
two = tag & 1
|
||||
if two and not want_two_byte:
|
||||
continue
|
||||
end = i + 1 + (ln * 2 if two else ln)
|
||||
if end > n:
|
||||
continue
|
||||
text = decode_payload(blob[i + 1:end], two)
|
||||
if text is None or len(text.strip()) < min_len:
|
||||
continue
|
||||
cands[i] = (end, text, 'utf16le' if two else 'one-byte')
|
||||
return cands
|
||||
|
||||
|
||||
def run_lengths(cands):
|
||||
"""For each candidate, how many back-to-back entries follow it (inclusive)."""
|
||||
nxt = {s: cands[s][0] for s in cands}
|
||||
lengths = {}
|
||||
closed = set()
|
||||
for start in sorted(cands):
|
||||
if start in closed:
|
||||
continue
|
||||
seq = []
|
||||
cur = start
|
||||
guard = 0
|
||||
while cur in nxt and cur not in closed:
|
||||
seq.append(cur)
|
||||
closed.add(cur)
|
||||
cur = nxt[cur]
|
||||
guard += 1
|
||||
if guard > 1_000_000:
|
||||
break
|
||||
for i, item in enumerate(seq):
|
||||
lengths[item] = len(seq) - i
|
||||
return lengths
|
||||
|
||||
|
||||
def load_pp(path):
|
||||
"""Strings present in a decompiler pool listing, for cross-annotation."""
|
||||
if not path:
|
||||
return set()
|
||||
out = set()
|
||||
pat = re.compile(r'^\[pp\+0x[0-9a-f]+\] String: (.*)$')
|
||||
for line in open(path, encoding='utf-8', errors='replace'):
|
||||
m = pat.match(line.strip())
|
||||
if not m:
|
||||
continue
|
||||
s = m.group(1).strip()
|
||||
if len(s) >= 2 and s[0] == '"' and s[-1] == '"':
|
||||
s = s[1:-1]
|
||||
if s:
|
||||
out.add(s)
|
||||
return out
|
||||
|
||||
|
||||
def histogram(lengths):
|
||||
counts = collections.Counter(lengths.values())
|
||||
for run in sorted(counts)[:10]:
|
||||
print(' run=%-4d %d' % (run, counts[run]))
|
||||
tail = sum(v for k, v in counts.items() if k > 10)
|
||||
if tail:
|
||||
print(' run>%-3d %d' % (10, tail))
|
||||
|
||||
|
||||
def search(blob, needles):
|
||||
total = 0
|
||||
for needle in needles:
|
||||
for label, enc in (('utf-8', needle.encode('utf-8')),
|
||||
('utf-16le', needle.encode('utf-16-le'))):
|
||||
offsets = []
|
||||
start = blob.find(enc)
|
||||
while start != -1 and len(offsets) < 8:
|
||||
offsets.append(start)
|
||||
start = blob.find(enc, start + 1)
|
||||
if offsets:
|
||||
total += len(offsets)
|
||||
print('%-26s %-9s file offset %s' % (
|
||||
needle, label, ' '.join(hex(o) for o in offsets)))
|
||||
if not total:
|
||||
print('no hits in either encoding. Try the shortest distinctive fragment -- text is\n'
|
||||
'often assembled from parts, and a literal may only exist as fragments\n'
|
||||
'(pitfalls.md P25).')
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
|
||||
ap.add_argument('sample', help='libapp.so or any artifact holding the snapshot')
|
||||
ap.add_argument('out', nargs='?', help='output tsv')
|
||||
ap.add_argument('--min', type=int, default=4, help='minimum payload length (default 4)')
|
||||
ap.add_argument('--max', type=int, default=63,
|
||||
help="maximum payload length; 63 is this framing's ceiling (default 63)")
|
||||
ap.add_argument('--min-chain', type=int, default=3,
|
||||
help='noise filter: minimum run of consecutive entries (default 3). '
|
||||
'This does not improve accuracy -- see the module docstring.')
|
||||
ap.add_argument('--two-byte', action='store_true',
|
||||
help='ALSO emit UTF-16 candidates. Detection is unreliable; verify each.')
|
||||
ap.add_argument('--pp', metavar='PP_TXT',
|
||||
help='decompiler pool listing, to mark which strings it also contains')
|
||||
ap.add_argument('--stats', action='store_true',
|
||||
help='print the run-length histogram and exit')
|
||||
ap.add_argument('--keep-isolated', action='store_true',
|
||||
help='also write entries below --min-chain (noisy; triage only)')
|
||||
ap.add_argument('--find', action='append', default=[], metavar='TEXT',
|
||||
help='search a literal in BOTH encodings and print file offsets '
|
||||
'(repeatable; the reliable way to locate a known literal)')
|
||||
a = ap.parse_args()
|
||||
|
||||
blob = open(a.sample, 'rb').read()
|
||||
|
||||
if a.find:
|
||||
return search(blob, a.find)
|
||||
if not a.out and not a.stats:
|
||||
raise SystemExit('give an output path, or --find / --stats')
|
||||
|
||||
cands = extract(blob, a.min, a.max, a.two_byte)
|
||||
lengths = run_lengths(cands)
|
||||
|
||||
if a.stats:
|
||||
print('candidates (two-byte included: %s): %d' % (a.two_byte, len(cands)))
|
||||
print('run-length histogram:')
|
||||
histogram(lengths)
|
||||
return 0
|
||||
|
||||
pp = load_pp(a.pp)
|
||||
kept = [s for s in cands if lengths[s] >= a.min_chain]
|
||||
rows = kept + (sorted(s for s in cands if lengths[s] < a.min_chain)
|
||||
if a.keep_isolated else [])
|
||||
with open(a.out, 'w', encoding='utf-8') as fh:
|
||||
fh.write('# offset_hex\ttext\trun\tform%s\n' % ('\tin_pp' if pp else ''))
|
||||
for s in sorted(rows):
|
||||
_end, text, form = cands[s]
|
||||
flat = text.replace('\n', '\\n').replace('\t', ' ')
|
||||
extra = ('\t%d' % (1 if text in pp else 0)) if pp else ''
|
||||
fh.write('0x%06x\t%s\t%d\t%s%s\n' % (s, flat, lengths[s], form, extra))
|
||||
|
||||
one = sum(1 for s in kept if cands[s][2] == 'one-byte')
|
||||
print('candidates : %d' % len(cands))
|
||||
print('kept (run >= %d) : %d (one-byte %d / utf16le %d)'
|
||||
% (a.min_chain, len(kept), one, len(kept) - one))
|
||||
print('below threshold : %d%s' % (
|
||||
len(cands) - len(kept), '' if a.keep_isolated else ' [--keep-isolated to keep them]'))
|
||||
if pp:
|
||||
hits = sum(1 for s in kept if cands[s][1] in pp)
|
||||
print('also in --pp listing : %d / %d (absence is NOT a false positive: the'
|
||||
% (hits, len(kept)))
|
||||
print(' decompiler listing is incomplete by design)')
|
||||
if a.two_byte:
|
||||
print('WARNING: --two-byte detection is unreliable (see module docstring);')
|
||||
print(' verify each UTF-16 hit before trusting it.')
|
||||
print('written %s' % a.out)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Dart AOT object-pool reference index: pool offset -> the instructions that load it.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
blutter's `pp.txt` tells you what is *in* the object pool (strings, types, closures,
|
||||
field metadata) but not which code reads it. "Who uses this string" is the most frequent
|
||||
question in Dart AOT work, and it needs an index you build once and query constantly.
|
||||
|
||||
Building that index with a general-purpose disassembler is the trap here: decoding every
|
||||
instruction of a multi-MB `.text` with detail enabled and asking for per-instruction
|
||||
register writes costs minutes of CPU and 1-2 GB of peak memory, and on a 16 GB host it is
|
||||
indistinguishable from a hang -- no output, no progress, nothing to interrupt. Only three
|
||||
encodings can reach the pool, so this decodes them from the raw 32-bit words instead:
|
||||
seconds, and a flat memory profile.
|
||||
|
||||
Recognised forms (AArch64, little endian), with x27 = pool base:
|
||||
|
||||
add xD, x27, #imm12, lsl #12 -> xD = x27 + (imm12 << 12)
|
||||
ldr xD, [xN, #imm12 * 8] -> 64-bit or 32-bit variant
|
||||
ldur xD, [xN, #simm9] -> 64-bit or 32-bit variant
|
||||
|
||||
A reference is either a direct load whose base is x27, or a load consuming the register an
|
||||
ADD just derived from x27. The compiler emits that pair back to back, so a small window
|
||||
keeps it exact without full liveness analysis.
|
||||
|
||||
USAGE
|
||||
-----
|
||||
python dart_pprefs.py libapp.so pp_refs.json # build the index
|
||||
python dart_pprefs.py --lookup pp_refs.json 0x1d1a8 0xc9d0
|
||||
python dart_pprefs.py libapp.so out.json --window 5 # widen the ADD->LDR window
|
||||
|
||||
NOTES
|
||||
-----
|
||||
* Offsets are **pool** offsets -- the `pp+0x...` space used by pp.txt -- not file offsets.
|
||||
Keep the two spaces apart in your notes; conflating them costs hours.
|
||||
* One offset commonly has many reference sites. Count them before editing the entry:
|
||||
a shared constant will change behaviour everywhere at once (see references/dart-aot.md).
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
|
||||
POOL_REG = 27 # x27: object-pool base in Dart AOT on arm64
|
||||
DEFAULT_WINDOW = 3 # instructions an ADD-derived address may survive
|
||||
|
||||
|
||||
def text_section(path):
|
||||
"""Return (vaddr, bytes) of .text, parsing ELF64 section headers directly."""
|
||||
blob = open(path, 'rb').read()
|
||||
if blob[:4] != b'\x7fELF':
|
||||
raise SystemExit('not an ELF file: %s' % path)
|
||||
if blob[4] != 2:
|
||||
raise SystemExit('not ELF64: %s' % path)
|
||||
e_shoff = struct.unpack_from('<Q', blob, 0x28)[0]
|
||||
e_shentsize = struct.unpack_from('<H', blob, 0x3A)[0]
|
||||
e_shnum = struct.unpack_from('<H', blob, 0x3C)[0]
|
||||
e_shstrndx = struct.unpack_from('<H', blob, 0x3E)[0]
|
||||
|
||||
def sh(i):
|
||||
return struct.unpack_from('<IIQQQQ', blob, e_shoff + i * e_shentsize)
|
||||
|
||||
_, _, _, _, shstr_off, shstr_size = sh(e_shstrndx)
|
||||
strs = blob[shstr_off:shstr_off + shstr_size]
|
||||
for i in range(e_shnum):
|
||||
name, _typ, _flags, addr, off, size = sh(i)
|
||||
end = strs.find(b'\x00', name)
|
||||
if strs[name:end].decode('ascii', 'replace') == '.text':
|
||||
return addr, blob[off:off + size]
|
||||
raise SystemExit('.text not found; pass --text with its virtual address')
|
||||
|
||||
|
||||
def sx(value, bits):
|
||||
m = 1 << (bits - 1)
|
||||
return (value ^ m) - m
|
||||
|
||||
|
||||
def scan(text_addr, blob, window):
|
||||
refs = {}
|
||||
pending = {}
|
||||
words = struct.unpack_from('<%dI' % (len(blob) // 4), blob, 0)
|
||||
|
||||
for i, w in enumerate(words):
|
||||
addr = text_addr + i * 4
|
||||
|
||||
# add xD, x27, #hi, lsl #12
|
||||
if w & 0xFFC00000 == 0x91400000 and (w >> 5) & 0x1F == POOL_REG:
|
||||
# Keep the shift out of the mask expression: `a & m << n` binds as
|
||||
# `a & (m << n)` in Python, which silently produces a wrong base.
|
||||
imm = (w >> 10) & 0xFFF
|
||||
pending[w & 0x1F] = [imm << 12, i]
|
||||
continue
|
||||
|
||||
ldr64 = w & 0xFFC00000 == 0xF9400000
|
||||
ldr32 = w & 0xFFC00000 == 0xB9400000
|
||||
ldur64 = w & 0xFFE00C00 == 0xF8400000
|
||||
ldur32 = w & 0xFFE00C00 == 0xB8400000
|
||||
|
||||
if ldr64 or ldr32 or ldur64 or ldur32:
|
||||
rn = (w >> 5) & 0x1F
|
||||
rd = w & 0x1F
|
||||
if ldr64 or ldr32:
|
||||
disp = ((w >> 10) & 0xFFF) << 3
|
||||
else:
|
||||
disp = sx((w >> 12) & 0x1FF, 9)
|
||||
if rn == POOL_REG:
|
||||
refs.setdefault(disp, []).append(addr)
|
||||
elif rn in pending:
|
||||
base, seq = pending.pop(rn)
|
||||
if i - seq <= window:
|
||||
refs.setdefault(base + disp, []).append(addr)
|
||||
pending.pop(rd, None) # this load overwrote rd
|
||||
continue
|
||||
|
||||
if w & 0xFFC00000 in (0x91000000, 0x91400000):
|
||||
pending.pop(w & 0x1F, None)
|
||||
for r in [r for r, (_o, s) in pending.items() if i - s > window]:
|
||||
del pending[r]
|
||||
|
||||
return refs
|
||||
|
||||
|
||||
def build(so, out, window):
|
||||
text_addr, blob = text_section(so)
|
||||
refs = scan(text_addr, blob, window)
|
||||
with open(out, 'w', encoding='utf-8') as fh:
|
||||
json.dump({hex(k): v for k, v in refs.items()}, fh)
|
||||
total = sum(len(v) for v in refs.values())
|
||||
print('.text vaddr=0x%x bytes=%d' % (text_addr, len(blob)))
|
||||
print('distinct pool offsets : %d' % len(refs))
|
||||
print('reference sites : %d' % total)
|
||||
for off in sorted(refs, key=lambda k: -len(refs[k]))[:8]:
|
||||
print(' pp+0x%-8x %4d sites' % (off, len(refs[off])))
|
||||
print('written %s' % out)
|
||||
|
||||
|
||||
def lookup(path, offsets):
|
||||
refs = {int(k, 16): v for k, v in json.load(open(path, encoding='utf-8')).items()}
|
||||
for spec in offsets:
|
||||
off = int(spec, 16)
|
||||
sites = sorted(refs.get(off, []))
|
||||
print('pp+0x%x: %d ref site(s)' % (off, len(sites)))
|
||||
for s in sites:
|
||||
print(' 0x%x' % s)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
|
||||
ap.add_argument('sample', nargs='?', help='libapp.so (build mode)')
|
||||
ap.add_argument('out', nargs='?', help='output json (build mode)')
|
||||
ap.add_argument('--lookup', metavar='REFS_JSON', help='query an existing index')
|
||||
ap.add_argument('--window', type=int, default=DEFAULT_WINDOW,
|
||||
help='instructions an ADD-derived address may survive (default %d)'
|
||||
% DEFAULT_WINDOW)
|
||||
a = ap.parse_args()
|
||||
|
||||
if a.lookup:
|
||||
rest = sys.argv[sys.argv.index('--lookup') + 2:]
|
||||
if not rest:
|
||||
raise SystemExit('give at least one hex pool offset')
|
||||
lookup(a.lookup, rest)
|
||||
return 0
|
||||
if not (a.sample and a.out):
|
||||
raise SystemExit('usage: dart_pprefs.py <libapp.so> <out.json>')
|
||||
build(a.sample, a.out, a.window)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,347 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Encode or inject AndroidX DataStore (Preferences) protobuf entries.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
Some feature gates are not decided in code but in a preferences file that the app
|
||||
reads at runtime, e.g. a "free until <timestamp>" value. Changing the code alone can
|
||||
then be pointless, while writing the state directly proves the hypothesis in one
|
||||
shot: if the behavior changes, the key really is the gate; if it does not, the gate
|
||||
is elsewhere (usually server-side).
|
||||
|
||||
WHAT THE FILE IS
|
||||
----------------
|
||||
DataStore/Preferences serializes to a protobuf on disk. On a device it lives under
|
||||
the app's private directory, typically:
|
||||
<app_files_dir>/datastore/<name>.preferences_pb
|
||||
and the container is:
|
||||
message PreferenceMap { map<string, Value> preferences = 1; }
|
||||
message Value { oneof { bool boolean = 1; float float = 2; int32 integer = 3;
|
||||
int64 long = 4; string string = 5; double double = 6;
|
||||
bytes bytes = 8; } }
|
||||
|
||||
The map field is the part people get wrong: every entry needs BOTH the outer
|
||||
0x0A <len> (the map field itself) AND the inner 0x0A <len key> <key> +
|
||||
0x12 <len value> <value>. Writing only the inner form produces a file that
|
||||
deserializes into nothing, and some apps then die on the next read with an
|
||||
exception that is swallowed by their crash reporter -- no stack, no clue.
|
||||
|
||||
Bytes writes here are the exact encoding, so this script doubles as a reference.
|
||||
|
||||
USAGE
|
||||
-----
|
||||
# write a fresh file with one big "never expires" timestamp
|
||||
python datastore_inject.py --file example.preferences_pb \
|
||||
--key example_expiry_epoch_ms --type long --value 4102444800000
|
||||
|
||||
# keep every other key from an existing file and replace/add just this one
|
||||
python datastore_inject.py --in pulled.preferences_pb --file patched.preferences_pb \
|
||||
--key example_expiry_epoch_ms --type long --value 4102444800000
|
||||
|
||||
# add more than one entry
|
||||
python datastore_inject.py --file out.pb --key example_flag --type bool --value true \
|
||||
--extra example_name=hello:string
|
||||
|
||||
# inspect a pulled file (what keys exist, and what they decode to)
|
||||
python datastore_inject.py --in pulled.preferences_pb --list
|
||||
|
||||
Deploying the result: the app must not be running while you overwrite the file
|
||||
(it will rewrite the file on exit), so push, fix ownership/selinux context if
|
||||
needed, then start the app. Verify by reading the key back with --list.
|
||||
|
||||
Pure standard library, Python 3.9+.
|
||||
"""
|
||||
import argparse
|
||||
import struct
|
||||
import sys
|
||||
|
||||
DEFAULT_FILE = 'example.preferences_pb'
|
||||
DEFAULT_KEY = 'example_expiry_epoch_ms'
|
||||
DEFAULT_VALUE = '4102444800000' # ~2100-01-01 in ms: "far future" in either unit
|
||||
TYPES = ('long', 'int', 'bool', 'float', 'double', 'string', 'bytes')
|
||||
|
||||
# tag = (field_number << 3) | wire_type, per the Value oneof above.
|
||||
VALUE_TAG = {
|
||||
'bool': (1, 0),
|
||||
'float': (2, 5),
|
||||
'integer': (3, 0),
|
||||
'long': (4, 0),
|
||||
'string': (5, 2),
|
||||
'double': (6, 1),
|
||||
'bytes': (8, 2),
|
||||
}
|
||||
|
||||
|
||||
def varint(n):
|
||||
"""Unsigned LEB128. Negative int32/int64 are encoded as 64-bit twos complement."""
|
||||
if n < 0:
|
||||
n += 1 << 64
|
||||
out = bytearray()
|
||||
while True:
|
||||
b = n & 0x7F
|
||||
n >>= 7
|
||||
if n:
|
||||
out.append(b | 0x80)
|
||||
else:
|
||||
out.append(b)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def read_varint(buf, pos):
|
||||
result = 0
|
||||
shift = 0
|
||||
while True:
|
||||
if pos >= len(buf):
|
||||
raise ValueError('truncated varint at offset %d' % pos)
|
||||
b = buf[pos]
|
||||
pos += 1
|
||||
result |= (b & 0x7F) << shift
|
||||
if not (b & 0x80):
|
||||
return result, pos
|
||||
shift += 7
|
||||
if shift > 70:
|
||||
raise ValueError('varint too long at offset %d' % pos)
|
||||
|
||||
|
||||
def tag_bytes(field, wire):
|
||||
return varint((field << 3) | wire)
|
||||
|
||||
|
||||
def encode_value(kind, raw):
|
||||
"""Encode the Value payload (the bytes after the inner 0x12 <len>)."""
|
||||
if kind == 'bool':
|
||||
field, wire = VALUE_TAG['bool']
|
||||
truthy = str(raw).strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
return tag_bytes(field, wire) + varint(1 if truthy else 0)
|
||||
if kind in ('long', 'int'):
|
||||
field, wire = VALUE_TAG['long' if kind == 'long' else 'integer']
|
||||
return tag_bytes(field, wire) + varint(int(str(raw), 0))
|
||||
if kind == 'float':
|
||||
field, wire = VALUE_TAG['float']
|
||||
return tag_bytes(field, wire) + struct.pack('<f', float(raw))
|
||||
if kind == 'double':
|
||||
field, wire = VALUE_TAG['double']
|
||||
return tag_bytes(field, wire) + struct.pack('<d', float(raw))
|
||||
if kind == 'string':
|
||||
field, wire = VALUE_TAG['string']
|
||||
data = str(raw).encode('utf-8')
|
||||
return tag_bytes(field, wire) + varint(len(data)) + data
|
||||
if kind == 'bytes':
|
||||
field, wire = VALUE_TAG['bytes']
|
||||
data = bytes.fromhex(str(raw))
|
||||
return tag_bytes(field, wire) + varint(len(data)) + data
|
||||
raise ValueError('unknown type: %s' % kind)
|
||||
|
||||
|
||||
def encode_entry(key, value_payload):
|
||||
"""Encode one PreferenceMap entry.
|
||||
|
||||
Two levels of 0x0A on purpose:
|
||||
outer: 0x0A <len(inner)> <- the map field (field 1)
|
||||
inner: 0x0A <len(key)> <key> 0x12 <len(value)> <value>
|
||||
Dropping the outer tag+length is the classic mistake: DataStore then
|
||||
deserializes an empty map, and the failure surfaces far away from here.
|
||||
"""
|
||||
kb = key.encode('utf-8')
|
||||
inner = (tag_bytes(1, 2) + varint(len(kb)) + kb
|
||||
+ tag_bytes(2, 2) + varint(len(value_payload)) + value_payload)
|
||||
return tag_bytes(1, 2) + varint(len(inner)) + inner
|
||||
|
||||
|
||||
def split_entries(data):
|
||||
"""Split a PreferenceMap into raw top-level field slices."""
|
||||
pos = 0
|
||||
entries = []
|
||||
while pos < len(data):
|
||||
start = pos
|
||||
tag, pos = read_varint(data, pos)
|
||||
wire = tag & 0x07
|
||||
if wire == 2:
|
||||
length, pos = read_varint(data, pos)
|
||||
pos += length
|
||||
elif wire == 0:
|
||||
_, pos = read_varint(data, pos)
|
||||
elif wire == 5:
|
||||
pos += 4
|
||||
elif wire == 1:
|
||||
pos += 8
|
||||
else:
|
||||
raise ValueError('unsupported wire type %d at offset %d' % (wire, start))
|
||||
if pos > len(data):
|
||||
raise ValueError('truncated field at offset %d' % start)
|
||||
entries.append((tag, data[start:pos]))
|
||||
return entries
|
||||
|
||||
|
||||
def decode_entry(raw):
|
||||
"""Return (key, value_payload) of one entry, or (None, None) if malformed."""
|
||||
try:
|
||||
pos = 0
|
||||
tag, pos = read_varint(raw, pos)
|
||||
if (tag >> 3) != 1 or (tag & 7) != 2:
|
||||
return None, None
|
||||
length, pos = read_varint(raw, pos)
|
||||
inner = raw[pos:pos + length]
|
||||
|
||||
p = 0
|
||||
t1, p = read_varint(inner, p)
|
||||
if (t1 >> 3) != 1:
|
||||
return None, None
|
||||
klen, p = read_varint(inner, p)
|
||||
key = inner[p:p + klen].decode('utf-8', 'replace')
|
||||
p += klen
|
||||
|
||||
t2, p = read_varint(inner, p)
|
||||
if (t2 >> 3) != 2:
|
||||
return None, None
|
||||
vlen, p = read_varint(inner, p)
|
||||
return key, inner[p:p + vlen]
|
||||
except Exception:
|
||||
return None, None
|
||||
|
||||
|
||||
def describe_value(payload):
|
||||
"""Best-effort decode of a Value payload for the --list output."""
|
||||
try:
|
||||
pos = 0
|
||||
tag, pos = read_varint(payload, pos)
|
||||
field, wire = tag >> 3, tag & 7
|
||||
if field == 1 and wire == 0:
|
||||
val, _ = read_varint(payload, pos)
|
||||
return 'bool=%s' % bool(val)
|
||||
if field == 3 and wire == 0:
|
||||
val, _ = read_varint(payload, pos)
|
||||
return 'integer=%d' % val
|
||||
if field == 4 and wire == 0:
|
||||
val, _ = read_varint(payload, pos)
|
||||
return 'long=%d' % val
|
||||
if field == 2 and wire == 5:
|
||||
return 'float=%r' % struct.unpack('<f', payload[pos:pos + 4])[0]
|
||||
if field == 6 and wire == 1:
|
||||
return 'double=%r' % struct.unpack('<d', payload[pos:pos + 8])[0]
|
||||
if field == 5 and wire == 2:
|
||||
length, pos = read_varint(payload, pos)
|
||||
return 'string=%r' % payload[pos:pos + length].decode('utf-8', 'replace')
|
||||
if field == 8 and wire == 2:
|
||||
length, pos = read_varint(payload, pos)
|
||||
return 'bytes=%s' % payload[pos:pos + length].hex()
|
||||
except Exception:
|
||||
pass
|
||||
return 'raw=%s' % payload.hex()
|
||||
|
||||
|
||||
def parse_extra(items):
|
||||
"""--extra key=value[:type] -> [(key, type, value)]"""
|
||||
out = []
|
||||
for item in items:
|
||||
if '=' not in item:
|
||||
raise SystemExit('--extra expects key=value[:type], got %r' % item)
|
||||
key, rest = item.split('=', 1)
|
||||
kind = 'string'
|
||||
if ':' in rest:
|
||||
rest, kind = rest.rsplit(':', 1)
|
||||
if kind not in TYPES:
|
||||
raise SystemExit('--extra %s: unknown type %r (choose from %s)'
|
||||
% (key, kind, ', '.join(TYPES)))
|
||||
out.append((key, kind, rest))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='Encode or inject AndroidX DataStore (Preferences) protobuf '
|
||||
'entries, with the correct two-level map encoding.')
|
||||
ap.add_argument('--file', default=DEFAULT_FILE,
|
||||
help='output .pb path (default: %s)' % DEFAULT_FILE)
|
||||
ap.add_argument('--key', default=DEFAULT_KEY,
|
||||
help='preference key to write (default: %s)' % DEFAULT_KEY)
|
||||
ap.add_argument('--value', default=DEFAULT_VALUE,
|
||||
help='value for --key (default: %s)' % DEFAULT_VALUE)
|
||||
ap.add_argument('--type', choices=TYPES, default='long',
|
||||
help='value type (default: long)')
|
||||
ap.add_argument('--in', dest='existing', default=None,
|
||||
help='existing .pb to read: preserves all other keys')
|
||||
ap.add_argument('--extra', action='append', default=[],
|
||||
help='key=value[:type], repeatable, added alongside --key')
|
||||
ap.add_argument('--list', action='store_true',
|
||||
help='list the entries of --in and exit (no writing)')
|
||||
ap.add_argument('--dry-run', action='store_true',
|
||||
help='print what would be written, write nothing')
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.list:
|
||||
if not args.existing:
|
||||
raise SystemExit('--list needs --in <file.preferences_pb>')
|
||||
with open(args.existing, 'rb') as fh:
|
||||
data = fh.read()
|
||||
print('[in] %s (%d bytes)' % (args.existing, len(data)))
|
||||
shown = 0
|
||||
for tag, raw in split_entries(data):
|
||||
key, payload = decode_entry(raw)
|
||||
if key is None:
|
||||
print(' <unparsed field tag=0x%02x, %d bytes>' % (tag, len(raw)))
|
||||
continue
|
||||
print(' %-32s %s (value=%d bytes)' % (key, describe_value(payload), len(payload)))
|
||||
shown += 1
|
||||
print('[ok] %d entry(ies)' % shown)
|
||||
return 0
|
||||
|
||||
# Build the entry list: preserved entries first, then the injected ones.
|
||||
chunks = []
|
||||
if args.existing:
|
||||
with open(args.existing, 'rb') as fh:
|
||||
original = fh.read()
|
||||
replaced = {args.key}
|
||||
replaced.update(k for k, _, _ in parse_extra(args.extra))
|
||||
kept = 0
|
||||
for _tag, raw in split_entries(original):
|
||||
key, _payload = decode_entry(raw)
|
||||
if key is None:
|
||||
chunks.append(raw) # unknown field: keep it verbatim
|
||||
continue
|
||||
if key in replaced:
|
||||
print('[keep-skip] %s is being replaced' % key)
|
||||
continue
|
||||
chunks.append(raw)
|
||||
kept += 1
|
||||
print('[in] preserved %d existing entry(ies) from %s' % (kept, args.existing))
|
||||
|
||||
target = encode_entry(args.key, encode_value(args.type, args.value))
|
||||
chunks.append(target)
|
||||
print('[inject] %s (%s) = %s -> %d bytes' % (args.key, args.type, args.value, len(target)))
|
||||
|
||||
for key, kind, value in parse_extra(args.extra):
|
||||
entry = encode_entry(key, encode_value(kind, value))
|
||||
chunks.append(entry)
|
||||
print('[inject] %s (%s) = %s -> %d bytes' % (key, kind, value, len(entry)))
|
||||
|
||||
data = b''.join(chunks)
|
||||
|
||||
# Self-check: re-parse what we just built. A file that does not parse back is
|
||||
# exactly the failure mode that kills the app with no usable stack.
|
||||
found = {}
|
||||
for _tag, raw in split_entries(data):
|
||||
key, payload = decode_entry(raw)
|
||||
if key is not None:
|
||||
found[key] = describe_value(payload)
|
||||
for key in [args.key] + [k for k, _t, _v in parse_extra(args.extra)]:
|
||||
if key not in found:
|
||||
raise SystemExit('internal error: %r does not parse back; refusing to write' % key)
|
||||
print('[check] re-parsed %d entry(ies); %s = %s' % (len(found), args.key, found[args.key]))
|
||||
print('[hex] %s' % data.hex(' '))
|
||||
|
||||
if args.dry_run:
|
||||
print('[dry-run] nothing written')
|
||||
return 0
|
||||
|
||||
with open(args.file, 'wb') as fh:
|
||||
fh.write(data)
|
||||
print('[ok] wrote %s (%d bytes)' % (args.file, len(data)))
|
||||
print('[note] push it to <app_files_dir>/datastore/<name>.preferences_pb while the app '
|
||||
'is NOT running, then start the app and read the key back with --list')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Quoting-safe ADB helper.
|
||||
|
||||
Why this exists: if you build device commands inside a host shell, the host expands
|
||||
`$`, `|`, `>`, and quotes *before* adb sees them. Symptoms are host-side errors that
|
||||
look like device failures -- "Could not find a part of the path", "no closing quote",
|
||||
"Missing type name after '['", unexpanded variables. Windows PowerShell is the worst
|
||||
offender (it also eats `$var:`, `[^"...`, `$(...)`).
|
||||
|
||||
Calling adb from Python with an argument list avoids all of it.
|
||||
|
||||
Configuration (first match wins):
|
||||
1. CLI flags: --serial / --adb
|
||||
2. env: ADB_SERIAL / ADB_PATH
|
||||
3. defaults below
|
||||
|
||||
Usage
|
||||
-----
|
||||
python devsh.py sh "pm list packages | grep myapp" # as the shell user
|
||||
python devsh.py su "pm grant <pkg> android.permission.X"
|
||||
python devsh.py sh "dumpsys window | grep mCurrentFocus"
|
||||
python devsh.py pull /data/local/tmp/x.apk ./x.apk
|
||||
python devsh.py push ./x.apk /data/local/tmp/x.apk
|
||||
python devsh.py dev # list devices
|
||||
|
||||
`su` wraps the command in `su -c "..."`; internal double quotes are escaped.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
DEFAULT_ADB = 'adb'
|
||||
DEFAULT_SERIAL = None
|
||||
|
||||
|
||||
def resolve():
|
||||
ap = argparse.ArgumentParser(add_help=False)
|
||||
ap.add_argument('--adb')
|
||||
ap.add_argument('--serial')
|
||||
known, _ = ap.parse_known_args()
|
||||
adb = known.adb or os.environ.get('ADB_PATH') or DEFAULT_ADB
|
||||
serial = known.serial or os.environ.get('ADB_SERIAL') or DEFAULT_SERIAL
|
||||
return adb, serial
|
||||
|
||||
|
||||
def run(adb, serial, args, timeout=300):
|
||||
cmd = [adb]
|
||||
if serial:
|
||||
cmd += ['-s', serial]
|
||||
cmd += args
|
||||
r = subprocess.run(cmd, capture_output=True, text=True, errors='replace', timeout=timeout)
|
||||
out = r.stdout or ''
|
||||
if (r.stderr or '').strip():
|
||||
out += '\n[stderr]\n' + r.stderr
|
||||
return r.returncode, out
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
return 2
|
||||
|
||||
adb, serial = resolve()
|
||||
argv = [a for a in sys.argv[1:] if not a.startswith('--adb=') and not a.startswith('--serial=')]
|
||||
# strip flag/value pairs
|
||||
cleaned = []
|
||||
skip = False
|
||||
for a in argv:
|
||||
if skip:
|
||||
skip = False
|
||||
continue
|
||||
if a in ('--adb', '--serial'):
|
||||
skip = True
|
||||
continue
|
||||
cleaned.append(a)
|
||||
argv = cleaned
|
||||
if len(argv) < 2 and argv and argv[0] not in ('dev',):
|
||||
print(__doc__)
|
||||
return 2
|
||||
|
||||
mode = argv[0]
|
||||
|
||||
if mode == 'dev':
|
||||
rc, out = run(adb, None, ['devices', '-l'])
|
||||
elif mode in ('sh', 'shell'):
|
||||
rc, out = run(adb, serial, ['shell', argv[1]])
|
||||
elif mode == 'su':
|
||||
cmd = argv[1].replace('"', '\\"')
|
||||
rc, out = run(adb, serial, ['shell', 'su -c "%s"' % cmd])
|
||||
elif mode == 'suf': # read a device text file
|
||||
cmd = argv[1].replace('"', '\\"')
|
||||
size = argv[2] if len(argv) > 2 else '6000'
|
||||
rc, out = run(adb, serial, ['shell', 'su -c "head -c %s %s"' % (size, cmd)])
|
||||
elif mode == 'pull':
|
||||
rc, out = run(adb, serial, ['pull', argv[1], argv[2]])
|
||||
elif mode == 'push':
|
||||
rc, out = run(adb, serial, ['push', argv[1], argv[2]])
|
||||
else:
|
||||
print(__doc__)
|
||||
return 2
|
||||
|
||||
sys.stdout.write(out)
|
||||
return 0 if rc == 0 else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Tier-3 verifier check: does any branch target a `move-result*` instruction?
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
`move-result*` is not an ordinary instruction. The verifier requires it to be the
|
||||
immediate successor of the invoke that produced the value it copies. A branch that
|
||||
lands on a `move-result` therefore bypasses the producer, and the class fails to
|
||||
load with:
|
||||
|
||||
VerifyError: ... copyRes1 v11 <- result0 type=Undefined
|
||||
|
||||
This matters specifically for byte-level patching. Redirecting a branch
|
||||
(`if-*` -> `goto`) is the intuitive way to force one side of a condition, and it
|
||||
is the way that silently creates this violation. Replacing the branch with a pair
|
||||
of `nop`s cannot: it removes a control-flow edge instead of adding one.
|
||||
|
||||
The check must be done on the control-flow graph, not linearly. A "is the
|
||||
previous instruction the producer?" scan over the instruction list reports clean
|
||||
on a method that has a branch jumping straight onto a `move-result`, because the
|
||||
producer does sit immediately before it in the stream. Only asking "does ANY
|
||||
branch target this offset" sees the problem.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python dex_check_verifier.py app.apk # whole image
|
||||
python dex_check_verifier.py app.apk --class 'Lcom/ex/Foo;'
|
||||
python dex_check_verifier.py before.dex after.dex # compare two builds
|
||||
|
||||
Exit codes: 0 = no findings, 1 = findings present, 2 = usage/parse error. The
|
||||
non-zero-on-findings convention is deliberate so a pipeline can gate on it.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from dexutil import IF_TEST, IF_TESTZ, MOVE_RESULT_OPS, load_dex # noqa: E402
|
||||
|
||||
|
||||
def analyse_method(dex, code_off):
|
||||
"""Return (findings, clean, detail) for one method body.
|
||||
|
||||
findings: list of (branch_offset, move_result_offset, is_conditional)
|
||||
clean: whether the decode consumed exactly insns_size units
|
||||
detail: human string when not clean
|
||||
|
||||
ONLY conditional branches are reported. An unconditional `goto` that lands on
|
||||
a `move-result` is a normal compiler-generated merge point: the producer runs
|
||||
on the incoming path and the goto is a *forward* jump to the shared epilogue,
|
||||
so nothing is bypassed. Reporting those as violations makes the tool unusable
|
||||
-- on a real sample they outnumber genuine findings by 20:1 and are pure
|
||||
compiler output.
|
||||
|
||||
The real hazard is narrower: redirecting a CONDITIONAL branch so that it lands
|
||||
directly on a `move-result`. That skips the producing invoke on the taken path.
|
||||
"""
|
||||
insns = list(dex.decode(code_off))
|
||||
info = dex.code_info(code_off)
|
||||
expected = info["insns_off"] + info["insns_size"] * 2
|
||||
ended = (insns[-1]["off"] + insns[-1]["units"] * 2) if insns else info["insns_off"]
|
||||
clean = (ended == expected)
|
||||
detail = "" if clean else ("decode ended at 0x%x, method body ends at 0x%x"
|
||||
% (ended, expected))
|
||||
|
||||
move_results = {i["off"] for i in insns if i["op"] in MOVE_RESULT_OPS}
|
||||
findings = []
|
||||
for i in insns:
|
||||
if i["op"] not in IF_TEST and i["op"] not in IF_TESTZ:
|
||||
continue
|
||||
t = dex.branch_target(i)
|
||||
if t is not None and t in move_results:
|
||||
findings.append((i["off"], t, True))
|
||||
return findings, clean, detail
|
||||
|
||||
|
||||
def scan_image(path, entry, cls_filter):
|
||||
dex, entry_name = load_dex(path, entry)
|
||||
problems = dex.check()
|
||||
if problems:
|
||||
for p in problems:
|
||||
print(" [structure] %s" % p)
|
||||
raise RuntimeError("structurally broken: %s" % path)
|
||||
|
||||
total_methods = 0
|
||||
total_findings = 0
|
||||
unclean = 0
|
||||
for fqcn in dex.class_names():
|
||||
if cls_filter and cls_filter not in fqcn:
|
||||
continue
|
||||
try:
|
||||
methods = list(dex.methods_of(fqcn))
|
||||
except Exception:
|
||||
continue
|
||||
for _section, _midx, _c, name, desc, code_off in methods:
|
||||
if code_off == 0:
|
||||
continue
|
||||
total_methods += 1
|
||||
findings, clean, detail = analyse_method(dex, code_off)
|
||||
if not clean:
|
||||
unclean += 1
|
||||
if findings:
|
||||
total_findings += len(findings)
|
||||
print(" VIOLATION %s.%s%s" % (fqcn, name, desc))
|
||||
for b_off, mr_off, _cond in findings:
|
||||
b_insn = dex.insn_at(code_off, b_off)
|
||||
mr_insn = dex.insn_at(code_off, mr_off)
|
||||
print(" conditional branch 0x%x (%s)"
|
||||
% (b_off, dex.describe(b_insn)))
|
||||
print(" -> move-result 0x%x (%s)"
|
||||
% (mr_off, dex.describe(mr_insn)))
|
||||
print(" the producing invoke is bypassed on the taken "
|
||||
"path: the class will fail to load")
|
||||
return {"methods": total_methods, "findings": total_findings,
|
||||
"unclean": unclean, "entry": entry_name}
|
||||
|
||||
|
||||
def main(argv):
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Detect branch-into-move-result verifier violations.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__.split("Usage")[-1][:800])
|
||||
ap.add_argument("targets", nargs="+", help="one .dex/.apk, or two to compare")
|
||||
ap.add_argument("--entry", help="archive member (default: first classes*.dex)")
|
||||
ap.add_argument("--class", dest="cls", help="substring filter on the class name")
|
||||
args = ap.parse_args(argv[1:])
|
||||
|
||||
results = []
|
||||
for path in args.targets:
|
||||
print("== %s" % path)
|
||||
try:
|
||||
stats = scan_image(path, args.entry, args.cls)
|
||||
except Exception as exc:
|
||||
print(" error: %s" % exc)
|
||||
return 2
|
||||
results.append(stats)
|
||||
print(" methods checked: %d violations: %d unclean decodes: %d"
|
||||
% (stats["methods"], stats["findings"], stats["unclean"]))
|
||||
print("")
|
||||
|
||||
if len(results) >= 2:
|
||||
before, after = results[0], results[1]
|
||||
print("== comparison")
|
||||
print(" violations %d -> %d" % (before["findings"], after["findings"]))
|
||||
if after["findings"] > before["findings"]:
|
||||
print(" REGRESSION: your patch introduced %d new violation(s). A "
|
||||
"branch now lands on a move-result." % (after["findings"] - before["findings"]))
|
||||
print(" Fix: replace the branch with `nop`s (removes an edge) instead "
|
||||
"of redirecting it (adds one).")
|
||||
return 1
|
||||
if before["findings"] and after["findings"] == before["findings"]:
|
||||
print(" note: violations exist in BOTH builds, so they are pre-existing "
|
||||
"and not caused by the patch. Do not 'fix' them as part of this task.")
|
||||
|
||||
if any(r["unclean"] for r in results):
|
||||
print("== WARNING: unclean decodes reported above. Offsets from those "
|
||||
"methods are unreliable -- widen the instruction format table or "
|
||||
"cross-check against a disassembler before trusting a patch offset.")
|
||||
|
||||
if any(r["findings"] for r in results):
|
||||
return 1
|
||||
print("== no branch-into-move-result violations")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Diff two dex files at the class_defs level: class names + access_flags.
|
||||
The interesting flag is ACC_INTERFACE (0x200).
|
||||
|
||||
Use it to prove that a disassemble -> reassemble round-trip did not damage the dex's
|
||||
interface/class relationships. The classic symptom of that damage is
|
||||
IncompatibleClassChangeError ("Found interface X, but class was expected") at runtime.
|
||||
|
||||
Important limitation: this check compares tables only. It cannot see code-item damage —
|
||||
see references/patch-audit.md for the checks that can.
|
||||
"""
|
||||
import argparse
|
||||
import struct
|
||||
import sys
|
||||
|
||||
ACC_INTERFACE = 0x200
|
||||
|
||||
|
||||
def uleb128(data, off):
|
||||
result = 0
|
||||
shift = 0
|
||||
while True:
|
||||
b = data[off]
|
||||
off += 1
|
||||
result |= (b & 0x7F) << shift
|
||||
if not (b & 0x80):
|
||||
break
|
||||
shift += 7
|
||||
return result, off
|
||||
|
||||
|
||||
def read_strings(data):
|
||||
strings_size = struct.unpack('<I', data[0x38:0x3C])[0]
|
||||
strings_off = struct.unpack('<I', data[0x3C:0x40])[0]
|
||||
out = []
|
||||
for i in range(strings_size):
|
||||
sdata_off = struct.unpack('<I', data[strings_off + i * 4: strings_off + i * 4 + 4])[0]
|
||||
n, p = uleb128(data, sdata_off)
|
||||
raw = data[p:p + n]
|
||||
out.append(raw.decode('utf-8', 'replace'))
|
||||
return out
|
||||
|
||||
|
||||
def class_map(path):
|
||||
data = open(path, 'rb').read()
|
||||
strings = read_strings(data)
|
||||
n_types = struct.unpack('<I', data[0x40:0x44])[0]
|
||||
type_ids_off = struct.unpack('<I', data[0x44:0x48])[0]
|
||||
types = []
|
||||
for i in range(n_types):
|
||||
idx = struct.unpack('<I', data[type_ids_off + i * 4: type_ids_off + i * 4 + 4])[0]
|
||||
types.append(strings[idx] if idx < len(strings) else '')
|
||||
class_defs_size = struct.unpack('<I', data[0x60:0x64])[0]
|
||||
class_defs_off = struct.unpack('<I', data[0x64:0x68])[0]
|
||||
out = {}
|
||||
for i in range(class_defs_size):
|
||||
base = class_defs_off + i * 32
|
||||
class_idx, access_flags = struct.unpack('<II', data[base:base + 8])
|
||||
name = types[class_idx] if class_idx < len(types) else '?'
|
||||
out[name] = access_flags
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='Compare two dex files at class_defs level (names + access_flags). '
|
||||
'Proves a reassembly did not damage interface/class relationships.')
|
||||
ap.add_argument('a', help='first dex (e.g. the original)')
|
||||
ap.add_argument('b', help='second dex (e.g. the rebuilt one)')
|
||||
ap.add_argument('filter', nargs='?', default=None,
|
||||
help='only report names containing this substring')
|
||||
ap.add_argument('--max-list', type=int, default=10,
|
||||
help='how many A-only / B-only names to print (default 10)')
|
||||
ap.add_argument('--max-flags', type=int, default=25,
|
||||
help='how many access_flags differences to print (default 25)')
|
||||
ap.add_argument('--quiet', action='store_true',
|
||||
help='print only the summary counts')
|
||||
args = ap.parse_args()
|
||||
|
||||
A = class_map(args.a)
|
||||
B = class_map(args.b)
|
||||
only_a = sorted(set(A) - set(B))
|
||||
only_b = sorted(set(B) - set(A))
|
||||
|
||||
diff_iface = []
|
||||
diff_flags = []
|
||||
for name in sorted(set(A) & set(B)):
|
||||
fa, fb = A[name], B[name]
|
||||
if bool(fa & ACC_INTERFACE) != bool(fb & ACC_INTERFACE):
|
||||
diff_iface.append((name, fa, fb))
|
||||
elif fa != fb:
|
||||
diff_flags.append((name, fa, fb))
|
||||
|
||||
print('A classes=%d B classes=%d' % (len(A), len(B)))
|
||||
print('only_in_A=%d only_in_B=%d' % (len(only_a), len(only_b)))
|
||||
if not args.quiet:
|
||||
for n in only_a[:args.max_list]:
|
||||
print(' A-only:', n)
|
||||
for n in only_b[:args.max_list]:
|
||||
print(' B-only:', n)
|
||||
|
||||
print('\n*** ACC_INTERFACE mismatch: %d ***' % len(diff_iface))
|
||||
if not args.quiet:
|
||||
for name, fa, fb in diff_iface:
|
||||
if args.filter and args.filter not in name:
|
||||
continue
|
||||
print(' %-70s A=%s B=%s' % (name, hex(fa), hex(fb)))
|
||||
|
||||
print('\naccess_flags diff (same interface-ness): %d' % len(diff_flags))
|
||||
if not args.quiet:
|
||||
shown = 0
|
||||
for name, fa, fb in diff_flags:
|
||||
if args.filter and args.filter not in name:
|
||||
continue
|
||||
if shown >= args.max_flags:
|
||||
print(' ... (%d more suppressed)' % (len(diff_flags) - shown))
|
||||
break
|
||||
print(' %-70s A=%s B=%s' % (name, hex(fa), hex(fb)))
|
||||
shown += 1
|
||||
|
||||
# Exit non-zero when a structural difference exists, so a caller can gate on it.
|
||||
verdict = (len(only_a) == 0 and len(only_b) == 0 and len(diff_iface) == 0)
|
||||
print('\nverdict: %s' % ('class tables identical'
|
||||
if verdict else 'STRUCTURAL DIFFERENCE — inspect above'))
|
||||
return 0 if verdict else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,278 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Locate an instruction by decoded semantics and report its exact byte offset.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
You know what the instruction *does* ("a branch on the config boolean whose target
|
||||
starts the countdown") but you need the *byte offset* to patch it. Two shortcuts
|
||||
fail:
|
||||
|
||||
* baksmali listings give smali line numbers, not code offsets. `.line` tracks
|
||||
source lines, breaks 1:N, and cannot be converted reliably.
|
||||
* a hard-coded offset dies the moment the sample is rebuilt, and a wrong offset
|
||||
in an equal-length patch corrupts the neighbouring instruction silently.
|
||||
|
||||
So this tool decodes the method and filters on semantics. It always prints the
|
||||
surrounding instructions so you can see which side of a branch you are about to
|
||||
change -- the polarity mistake is the most common way a patch does the exact
|
||||
opposite of the goal and still starts cleanly.
|
||||
|
||||
Filter language (all optional; combined with AND, comma = OR within a repeated
|
||||
flag):
|
||||
|
||||
NAME substring match on the class, method or string operand
|
||||
@Member field or method name operand equals/contains Member
|
||||
=literal a const/4 literal equals this integer
|
||||
#Class/member a branch whose TARGET reads this field of this class
|
||||
>kind instruction kind: if-test if-testz invoke return
|
||||
move-result const4 nop goto switch field sfield
|
||||
$name the ENCLOSING method name must contain this
|
||||
|
||||
Examples
|
||||
--------
|
||||
# a boolean gate whose taken path reads Cfg.enabled
|
||||
python dex_find_insn.py app.apk --class 'Lcom/example/SplashActivity;' \\
|
||||
--method u --filter '#Lcom/example/Cfg;*enabled'
|
||||
|
||||
# every invoke of a method named like goHome, with 3 lines of context
|
||||
python dex_find_insn.py app.apk --filter '@goHome' --kind invoke -C 3
|
||||
|
||||
# where a specific literal is compared
|
||||
python dex_find_insn.py app.apk --class 'Lcom/example/PlayerActivity;' --filter '=1' --kind if-testz
|
||||
|
||||
Exit codes: 0 = at least one hit, 1 = no hits (a finding: say so, do not retry the
|
||||
same filter), 2 = usage error.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from dexutil import ( # noqa: E402
|
||||
Dex, IF_TEST, IF_TESTZ, INVOKE_OPS, MOVE_RESULT_OPS, load_dex,
|
||||
)
|
||||
|
||||
_KIND_MAP = {
|
||||
"if-test": IF_TEST,
|
||||
"if-testz": IF_TESTZ,
|
||||
"invoke": INVOKE_OPS,
|
||||
"return": (0x0F, 0x10, 0x11),
|
||||
"move-result": MOVE_RESULT_OPS,
|
||||
"const4": (0x12,),
|
||||
"const16": (0x13,),
|
||||
"goto": (0x27, 0x28, 0x29),
|
||||
"switch": (0x2A, 0x2B),
|
||||
"nop": (0x00,),
|
||||
}
|
||||
_FIELD_READ = tuple(range(0x52, 0x59))
|
||||
_FIELD_WRITE = tuple(range(0x59, 0x60))
|
||||
_SFIELD = tuple(range(0x60, 0x6E))
|
||||
_KIND_MAP["field"] = _FIELD_READ
|
||||
_KIND_MAP["field-write"] = _FIELD_WRITE
|
||||
_KIND_MAP["sfield"] = _SFIELD
|
||||
|
||||
|
||||
class Filter(object):
|
||||
"""One compiled filter expression."""
|
||||
|
||||
def __init__(self, text):
|
||||
self.raw = text
|
||||
self.kind = text[1:] if text.startswith(">") else None
|
||||
self.member = text[1:] if text.startswith("@") else None
|
||||
self.literal = int(text[1:]) if text.startswith("=") else None
|
||||
self.target_field = None
|
||||
self.target_class = None
|
||||
self.enclosing = text[1:] if text.startswith("$") else None
|
||||
self.text = None
|
||||
if text.startswith("#"):
|
||||
spec = text[1:]
|
||||
if "/" in spec and ("*" in spec):
|
||||
cls, mem = spec.split("*", 1)
|
||||
self.target_class, self.target_field = cls, mem
|
||||
elif "*" in spec:
|
||||
self.target_field = spec.split("*", 1)[1]
|
||||
else:
|
||||
self.target_class = spec
|
||||
elif not any(text.startswith(p) for p in ("@", "=", ">", "$")):
|
||||
self.text = text
|
||||
|
||||
def describe(self):
|
||||
return self.raw
|
||||
|
||||
|
||||
def _operand_text(dex, insn):
|
||||
"""All names this instruction mentions (class, method, field, string)."""
|
||||
parts = []
|
||||
op, pos = insn["op"], insn["off"]
|
||||
if op in INVOKE_OPS:
|
||||
cls, nm, ds = dex.method(int.from_bytes(insn["raw"][2:4], "little"))
|
||||
parts += [cls, nm, ds]
|
||||
elif op in _FIELD_READ + _FIELD_WRITE + _SFIELD:
|
||||
cls, nm, ty = dex.field(int.from_bytes(insn["raw"][2:4], "little"))
|
||||
parts += [cls, nm, ty]
|
||||
elif op in (0x19, 0x1A):
|
||||
parts.append(dex.string_safe(int.from_bytes(insn["raw"][2:4], "little")))
|
||||
return parts
|
||||
|
||||
|
||||
def _matches(dex, insn, filters, code_off):
|
||||
"""All filters must hold (AND)."""
|
||||
for f in filters:
|
||||
if f.kind:
|
||||
ops = _KIND_MAP.get(f.kind)
|
||||
if ops is None:
|
||||
raise ValueError("unknown kind: %s" % f.kind)
|
||||
if insn["op"] not in ops:
|
||||
return False
|
||||
if f.literal is not None:
|
||||
if insn["op"] != 0x12:
|
||||
return False
|
||||
val = insn["raw"][1] & 0xF
|
||||
if val > 7:
|
||||
val -= 16
|
||||
if val != f.literal:
|
||||
return False
|
||||
if f.member:
|
||||
if insn["op"] not in INVOKE_OPS:
|
||||
return False
|
||||
_cls, nm, _ds = dex.method(int.from_bytes(insn["raw"][2:4], "little"))
|
||||
if f.member not in nm:
|
||||
return False
|
||||
if f.target_class or f.target_field:
|
||||
tgt = dex.branch_target(insn)
|
||||
if tgt is None:
|
||||
return False
|
||||
t_insn = dex.insn_at(code_off, tgt)
|
||||
if t_insn is None or not (0x52 <= t_insn["op"] <= 0x58):
|
||||
return False
|
||||
cls, nm, _ty = dex.field(int.from_bytes(t_insn["raw"][2:4], "little"))
|
||||
if f.target_class and f.target_class != cls:
|
||||
return False
|
||||
if f.target_field and f.target_field not in nm:
|
||||
return False
|
||||
if f.text:
|
||||
hay = " ".join(_operand_text(dex, insn))
|
||||
if f.text.lower() not in hay.lower():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def scan(dex, filters, kind_only=None, class_pattern=None, method_pattern=None,
|
||||
limit=None):
|
||||
"""Yield (fqcn, method_name, descriptor, code_off, insn, all_insns, idx)."""
|
||||
hits = 0
|
||||
cls_re = re.compile(class_pattern) if class_pattern else None
|
||||
mth_re = re.compile(method_pattern) if method_pattern else None
|
||||
|
||||
for fqcn in dex.class_names():
|
||||
if cls_re and not cls_re.search(fqcn):
|
||||
continue
|
||||
try:
|
||||
methods = list(dex.methods_of(fqcn))
|
||||
except Exception:
|
||||
continue
|
||||
for section, midx, _c, name, desc, code_off in methods:
|
||||
if code_off == 0:
|
||||
continue
|
||||
if mth_re and not mth_re.search(name):
|
||||
continue
|
||||
for f in filters:
|
||||
if f.enclosing and f.enclosing not in name:
|
||||
break
|
||||
insns = list(dex.decode(code_off))
|
||||
# a decode that does not land on the method end means offsets here
|
||||
# cannot be trusted; report the method rather than silent misses
|
||||
info = dex.code_info(code_off)
|
||||
expected = info["insns_off"] + info["insns_size"] * 2
|
||||
clean = (insns[-1]["off"] + insns[-1]["units"] * 2 == expected) if insns else False
|
||||
for i, insn in enumerate(insns):
|
||||
if kind_only and insn["op"] not in _KIND_MAP.get(kind_only, ()):
|
||||
continue
|
||||
if filters and not _matches(dex, insn, filters, code_off):
|
||||
continue
|
||||
yield (fqcn, name, desc, code_off, insn, insns, i, clean)
|
||||
hits += 1
|
||||
if limit and hits >= limit:
|
||||
return
|
||||
|
||||
|
||||
def main(argv):
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Find an instruction by decoded semantics; print its exact "
|
||||
"byte offset and surrounding context.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__.split("Examples")[-1][:1500])
|
||||
ap.add_argument("target", help=".dex or .apk/.zip (use --entry to pick a dex)")
|
||||
ap.add_argument("--entry", help="archive member (default: first classes*.dex)")
|
||||
ap.add_argument("--class", dest="cls", help="regex over the class descriptor")
|
||||
ap.add_argument("--method", help="regex over the method name")
|
||||
ap.add_argument("--filter", action="append", default=[],
|
||||
help="filter expression, repeatable (AND across, OR within a flag "
|
||||
"list). See the module docstring for the language.")
|
||||
ap.add_argument("--kind", help="restrict to one instruction kind (see docstring)")
|
||||
ap.add_argument("-C", "--context", type=int, default=2,
|
||||
help="instructions of context to print (default 2)")
|
||||
ap.add_argument("--limit", type=int, default=40, help="max hits (default 40)")
|
||||
ap.add_argument("--show-unclean", action="store_true",
|
||||
help="also print hits from methods whose decode did not align")
|
||||
args = ap.parse_args(argv[1:])
|
||||
|
||||
dex, entry = load_dex(args.target, args.entry)
|
||||
problems = dex.check()
|
||||
if problems:
|
||||
print("structural problems in %s (%s):" % (args.target, entry))
|
||||
for p in problems:
|
||||
print(" - %s" % p)
|
||||
return 2
|
||||
|
||||
filters = [Filter(a) for a in args.filter]
|
||||
print("== %s (%s) %d classes" % (args.target, entry,
|
||||
dex.header["class_defs_size"]))
|
||||
if filters:
|
||||
print(" filters: %s" % ", ".join(f.describe() for f in filters))
|
||||
|
||||
found = 0
|
||||
for fqcn, name, desc, code_off, insn, insns, idx, clean in scan(
|
||||
dex, filters, args.kind, args.cls, args.method, args.limit):
|
||||
if not clean and not args.show_unclean:
|
||||
print("\n!! %s.%s%s decode did not align; offsets unreliable, "
|
||||
"skipping (use --show-unclean to see anyway)"
|
||||
% (fqcn, name, desc))
|
||||
continue
|
||||
found += 1
|
||||
print("\n-- %s.%s%s" % (fqcn, name, desc))
|
||||
print(" code_off=0x%x insns_off=0x%x (decode clean: %s)"
|
||||
% (code_off, code_off + 16, clean))
|
||||
lo = max(0, idx - args.context)
|
||||
hi = min(len(insns), idx + args.context + 1)
|
||||
for j in range(lo, hi):
|
||||
marker = " <== HIT" if j == idx else ""
|
||||
print(" %s%s" % (dex.describe(insns[j]), marker))
|
||||
print(" >>> file offset of the instruction: 0x%x" % insn["off"])
|
||||
if insn["op"] in IF_TEST or insn["op"] in IF_TESTZ:
|
||||
tgt = dex.branch_target(insn)
|
||||
t_insn = dex.insn_at(code_off, tgt)
|
||||
print(" >>> branch TAKEN target 0x%x: %s"
|
||||
% (tgt, dex.describe(t_insn) if t_insn else "?"))
|
||||
nxt = insn["off"] + insn["units"] * 2
|
||||
n_insn = dex.insn_at(code_off, nxt)
|
||||
print(" >>> branch FALL-THROUGH 0x%x: %s"
|
||||
% (nxt, dex.describe(n_insn) if n_insn else "?"))
|
||||
print(" >>> decide which side you want BEFORE patching; a wrong "
|
||||
"polarity still starts cleanly")
|
||||
|
||||
print("\n== %d hit(s)" % found)
|
||||
if not found:
|
||||
print(" no match. Do not retry the same filter: either the decode is "
|
||||
"unclean (see --show-unclean) or the behaviour lives in another "
|
||||
"layer (native / another dex / another class).")
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -0,0 +1,436 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Apply equal-length byte patches to a dex, with structural and verifier checks.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
The cheap way to change behaviour is to rewrite a few bytes in place rather than
|
||||
rebuild a method body. It is cheap for a reason: nothing moves, so no try/catch
|
||||
block, debug-info pointer or branch displacement can be invalidated by
|
||||
construction. But it has four failure modes that all produce a build which looks
|
||||
fine and misbehaves, and this tool exists to make each one impossible to skip:
|
||||
|
||||
1. **Same-length is not enough** -- the replacement must decode to a valid
|
||||
instruction sequence of exactly the same length. A 4-byte branch replaced by
|
||||
a 4-byte branch is fine; a 2-byte branch replaced by a 4-byte instruction
|
||||
corrupts the next instruction.
|
||||
2. **Polarity** -- the overwhelmingly common error is patching the wrong side of
|
||||
a condition. So a spec can *require* the instruction that follows the edit,
|
||||
and this tool aborts if it is not the one you named. Name the fall-through
|
||||
you expect and the mistake cannot survive.
|
||||
3. **Verifier legality** -- a branch whose target is a `move-result*` bypasses
|
||||
the producing invoke and the class fails to load (`VerifyError`). Checked
|
||||
here before writing.
|
||||
4. **dex header staleness** -- the checksum and signature fields must be
|
||||
recomputed, signature FIRST (the checksum covers it). Skipping this makes
|
||||
Android fall back to interpreting the dex, which surfaces as an unrelated
|
||||
ClassNotFoundException at startup.
|
||||
|
||||
Spec format (JSON; a list, or {"patches": [...]}):
|
||||
|
||||
[{
|
||||
"name": "human label",
|
||||
"reason": "why this edit is correct",
|
||||
"class": "Lpkg/Name;",
|
||||
"method": "someMethod",
|
||||
"desc": "(Lpkg/Arg;)V", // optional: disambiguates overloads
|
||||
"match": {"kind": "if-testz", "target_reads_field_of": "Lpkg/Cfg;",
|
||||
"target_field": "enabled"},
|
||||
"expect_next": {"kind": "invoke", "target_method": "goHome"},
|
||||
"replace": {"kind": "nops"} // or {"bytes": "28060000"}
|
||||
}]
|
||||
|
||||
`match` selects the instruction; `expect_next` (optional but strongly advised)
|
||||
asserts what immediately follows, which is what pins the polarity; `replace`
|
||||
gives the bytes. Run with --dry-run first: it prints the match, the neighbours,
|
||||
the verifier verdict and the predicted byte diff without writing anything.
|
||||
|
||||
Exit codes: 0 ok, 1 failure (structure, match, verifier, or self-verify), 2 usage.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from dexutil import ( # noqa: E402
|
||||
Dex, IF_TEST, IF_TESTZ, INVOKE_OPS, MOVE_RESULT_OPS, RETURN_OPS,
|
||||
fix_dex_header, load_dex, verify_dex_header,
|
||||
)
|
||||
|
||||
|
||||
def _kind_of(insn):
|
||||
"""Coarse semantic kind used by spec matching."""
|
||||
op = insn["op"]
|
||||
if op in IF_TEST:
|
||||
return "if-test"
|
||||
if op in IF_TESTZ:
|
||||
return "if-testz"
|
||||
if op in INVOKE_OPS:
|
||||
return "invoke"
|
||||
if op in RETURN_OPS:
|
||||
return "return"
|
||||
if op in MOVE_RESULT_OPS:
|
||||
return "move-result"
|
||||
if op == 0x12:
|
||||
return "const4"
|
||||
return insn["name"]
|
||||
|
||||
|
||||
def _describe_neighbours(dex, code_off, target_off, span=4):
|
||||
"""Render up to `span` instructions before and after an offset."""
|
||||
insns = list(dex.decode(code_off))
|
||||
idx = None
|
||||
for i, insn in enumerate(insns):
|
||||
if insn["off"] == target_off:
|
||||
idx = i
|
||||
break
|
||||
if idx is None:
|
||||
return [], None, []
|
||||
before = insns[max(0, idx - span):idx]
|
||||
after = insns[idx + 1:idx + 1 + span]
|
||||
return before, insns[idx], after
|
||||
|
||||
|
||||
def _matches(dex, insn, crit, code_off=None):
|
||||
"""Does one instruction satisfy a match/expect criterion?"""
|
||||
if crit is None:
|
||||
return True
|
||||
want = crit.get("kind")
|
||||
if want and _kind_of(insn) != want:
|
||||
return False
|
||||
|
||||
if want in ("if-test", "if-testz"):
|
||||
treg = crit.get("target_reg")
|
||||
if treg is not None:
|
||||
regs, _ = dex.branch_regs(insn)
|
||||
if treg not in regs:
|
||||
return False
|
||||
# The usual way to pin "this is the gate for config X": require that the
|
||||
# branch TARGET instruction reads a field of a named class. This is what
|
||||
# distinguishes the gate you want from the other branches in the method.
|
||||
fcls = crit.get("target_reads_field_of")
|
||||
fname = crit.get("target_field")
|
||||
if fcls or fname:
|
||||
if code_off is None:
|
||||
return False
|
||||
tgt = dex.branch_target(insn)
|
||||
t_insn = dex.insn_at(code_off, tgt)
|
||||
if t_insn is None:
|
||||
return False
|
||||
if not (0x52 <= t_insn["op"] <= 0x58):
|
||||
return False
|
||||
fidx = struct.unpack_from("<H", t_insn["raw"], 2)[0]
|
||||
cls, nm, _ty = dex.field(fidx)
|
||||
if fcls and cls != fcls:
|
||||
return False
|
||||
if fname and nm != fname:
|
||||
return False
|
||||
|
||||
if want == "const4":
|
||||
lit = crit.get("literal")
|
||||
if lit is not None:
|
||||
raw = insn["raw"][1]
|
||||
val = raw & 0xF
|
||||
if val > 7:
|
||||
val -= 16
|
||||
if val != lit:
|
||||
return False
|
||||
|
||||
if want == "invoke":
|
||||
midx = struct.unpack_from("<H", insn["raw"], 2)[0]
|
||||
cls, nm, _ds = dex.method(midx)
|
||||
if crit.get("target_class") and crit["target_class"] not in cls:
|
||||
return False
|
||||
if crit.get("target_method") and crit["target_method"] != nm:
|
||||
return False
|
||||
|
||||
if want in ("return", "move-result", "nop"):
|
||||
pass
|
||||
|
||||
raw_eq = crit.get("bytes")
|
||||
if raw_eq and insn["raw"].hex() != raw_eq.replace(" ", "").lower():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _find_site(dex, code_off, spec):
|
||||
"""Return the single instruction matching spec['match'].
|
||||
|
||||
Exactly one match is required. Ambiguity is treated as failure rather than
|
||||
"take the first": picking the wrong site in a method with several similar
|
||||
branches is a silent, expensive error.
|
||||
"""
|
||||
insns = list(dex.decode(code_off))
|
||||
hits = [i for i in insns if _matches(dex, i, spec.get("match"), code_off)]
|
||||
if len(hits) == 1:
|
||||
return hits[0], insns
|
||||
if not hits:
|
||||
return None, insns
|
||||
|
||||
# allow an ordinal to disambiguate deliberately
|
||||
ordv = spec.get("match", {}).get("ordinal")
|
||||
if ordv is not None and 0 <= ordv < len(hits):
|
||||
return hits[ordv], insns
|
||||
return ("ambiguous", hits), insns
|
||||
|
||||
|
||||
def _verifier_report(dex, code_off, target_off_for_new_edge=None):
|
||||
"""Tier-3 check: does any branch target a move-result instruction?
|
||||
|
||||
`move-result*` must be immediately preceded by its producing invoke. A branch
|
||||
into one bypasses the producer and the class fails to load with
|
||||
`VerifyError ... copyResN v <- result0 type=Undefined`. A linear "is the
|
||||
previous instruction the producer" scan misses this; only the CFG view sees
|
||||
it.
|
||||
"""
|
||||
findings = []
|
||||
for insn in dex.decode(code_off):
|
||||
if insn["op"] not in MOVE_RESULT_OPS:
|
||||
continue
|
||||
tgt = insn["off"]
|
||||
for other in dex.decode(code_off):
|
||||
t = dex.branch_target(other)
|
||||
if t == tgt:
|
||||
findings.append((other["off"], tgt))
|
||||
return findings
|
||||
|
||||
|
||||
def _apply_replace(dex_data, insn, repl):
|
||||
"""Return the new bytes for this instruction, enforcing equal length."""
|
||||
kind = repl.get("kind")
|
||||
if kind == "nops":
|
||||
n = len(insn["raw"])
|
||||
return b"\x00" * n
|
||||
if kind == "bytes":
|
||||
blob = bytes.fromhex(repl["bytes"].replace(" ", ""))
|
||||
return blob
|
||||
raise ValueError("replace must be {'kind':'nops'} or {'kind':'bytes','bytes':...}")
|
||||
|
||||
|
||||
def process_one(dex, data, spec, index, dry_run):
|
||||
"""Apply one spec entry to `data`; return a report dict, or raise."""
|
||||
cls = spec["class"]
|
||||
name = spec["method"]
|
||||
desc = spec.get("desc")
|
||||
label = spec.get("name") or ("patch%d" % index)
|
||||
report = {"name": label, "ok": False}
|
||||
|
||||
if desc:
|
||||
found = dex.find_method(cls, name, desc)
|
||||
if not found:
|
||||
raise RuntimeError("[%s] method not found: %s->%s%s"
|
||||
% (label, cls, name, desc))
|
||||
section, midx, code_off = found
|
||||
else:
|
||||
overloads = dex.find_methods_named(cls, name)
|
||||
if len(overloads) != 1:
|
||||
raise RuntimeError(
|
||||
"[%s] %s->%s has %d overloads; give \"desc\" to disambiguate: %s"
|
||||
% (label, cls, name, len(overloads),
|
||||
[d for _s, _i, d, _c in overloads]))
|
||||
section, midx, dsc, code_off = overloads[0]
|
||||
desc = dsc
|
||||
|
||||
report.update({"class": cls, "method": name, "desc": desc,
|
||||
"section": section, "method_idx": midx, "code_off": code_off})
|
||||
|
||||
site, _insns = _find_site(dex, code_off, spec)
|
||||
if site is None:
|
||||
raise RuntimeError("[%s] no instruction matched spec['match']" % label)
|
||||
if isinstance(site, tuple) and site and site[0] == "ambiguous":
|
||||
cands = ", ".join("0x%x" % h["off"] for h in site[1])
|
||||
raise RuntimeError("[%s] match is ambiguous (%d hits: %s); tighten it or "
|
||||
"set match.ordinal" % (label, len(site[1]), cands))
|
||||
|
||||
before, cur, after = _describe_neighbours(dex, code_off, site["off"])
|
||||
report.update({
|
||||
"site_off": cur["off"],
|
||||
"old_bytes": cur["raw"].hex(),
|
||||
"old_text": dex.describe(cur),
|
||||
"before": [dex.describe(i) for i in before],
|
||||
"after": [dex.describe(i) for i in after],
|
||||
})
|
||||
|
||||
# polarity pin: what must immediately follow?
|
||||
exp = spec.get("expect_next")
|
||||
if exp is not None:
|
||||
nxt = after[0] if after else None
|
||||
if nxt is None or not _matches(dex, nxt, exp, code_off):
|
||||
raise RuntimeError(
|
||||
"[%s] expect_next not satisfied at 0x%x. Expected %r, found %r.\n"
|
||||
" This is the polarity check: the instruction after the branch "
|
||||
"is not the one your spec assumes, so the branch points at the "
|
||||
"wrong side."
|
||||
% (label, cur["off"], exp, dex.describe(nxt) if nxt else None))
|
||||
report["expect_next_ok"] = True
|
||||
|
||||
new = _apply_replace(data, cur, spec.get("replace", {"kind": "nops"}))
|
||||
if len(new) != len(cur["raw"]):
|
||||
raise RuntimeError(
|
||||
"[%s] replacement is %d bytes but the instruction is %d. Equal length "
|
||||
"is required: a longer replacement overwrites the next instruction."
|
||||
% (label, len(new), len(cur["raw"])))
|
||||
report.update({"new_bytes": new.hex(), "size_delta": 0})
|
||||
|
||||
# verifier: simulate the new instruction to see if it adds a branch edge
|
||||
fake = Dex(bytes(data), dex.name)
|
||||
fake_probe = dict(cur)
|
||||
fake_probe["raw"] = new
|
||||
fake_probe["op"] = new[0]
|
||||
report["new_text"] = fake.describe(fake_probe)
|
||||
|
||||
if dry_run:
|
||||
report["ok"] = True
|
||||
return report, data
|
||||
|
||||
data[cur["off"]:cur["off"] + len(new)] = new
|
||||
|
||||
# Re-read the patched dex and confirm the edit landed.
|
||||
#
|
||||
# Compare the BYTE RANGE, not a decoded instruction: replacing a 4-byte branch
|
||||
# with a nop pair yields two 1-unit instructions, so "the instruction at this
|
||||
# offset has length 4" is false even though the patch is perfectly correct.
|
||||
# The byte range is what the patch actually owns.
|
||||
span = slice(cur["off"], cur["off"] + len(new))
|
||||
if bytes(data[span]) != new:
|
||||
raise RuntimeError(
|
||||
"[%s] bytes at 0x%x are %s, expected %s"
|
||||
% (label, cur["off"], bytes(data[span]).hex(), new.hex()))
|
||||
|
||||
patched = Dex(bytes(data), dex.name)
|
||||
insns_after = list(patched.decode(code_off))
|
||||
info = patched.code_info(code_off)
|
||||
expected_end = info["insns_off"] + info["insns_size"] * 2
|
||||
ended = (insns_after[-1]["off"] + insns_after[-1]["units"] * 2
|
||||
if insns_after else info["insns_off"])
|
||||
report["post_instruction_count"] = len(insns_after)
|
||||
report["post_decode_clean"] = (ended == expected_end)
|
||||
|
||||
landed = [i for i in insns_after
|
||||
if cur["off"] <= i["off"] < cur["off"] + len(new)]
|
||||
report["post_text"] = " | ".join(patched.describe(i) for i in landed)
|
||||
|
||||
# the next instruction boundary after the replaced span must still be the
|
||||
# instruction that followed the original one
|
||||
nxt_after = patched.insn_at(code_off, cur["off"] + len(new))
|
||||
report["post_next_text"] = patched.describe(nxt_after) if nxt_after else None
|
||||
if not report["post_decode_clean"]:
|
||||
raise RuntimeError(
|
||||
"[%s] the method no longer decodes to exactly insns_size units after "
|
||||
"the edit -- the replacement changed the instruction stream length. "
|
||||
"Use an equal-length replacement." % label)
|
||||
|
||||
edges = _verifier_report(patched, code_off)
|
||||
report["verifier_edges"] = len(edges)
|
||||
if edges:
|
||||
raise RuntimeError(
|
||||
"[%s] verifier: a branch targets a move-result at %s; the class will "
|
||||
"fail to load (VerifyError). Use a nop pair instead of a branch."
|
||||
% (label, ", ".join("0x%x->0x%x" % e for e in edges)))
|
||||
|
||||
report["ok"] = True
|
||||
return report, data
|
||||
|
||||
|
||||
def main(argv):
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Apply equal-length byte patches to a dex, with structural, "
|
||||
"polarity and verifier checks.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__.split("Spec format")[-1][:1200] if __doc__ else None)
|
||||
ap.add_argument("dex", help="input .dex, or an APK/zip (use --entry to pick)")
|
||||
ap.add_argument("--entry", help="archive member to read (default: classes.dex)")
|
||||
ap.add_argument("--spec", required=True, help="JSON spec file")
|
||||
ap.add_argument("-o", "--out", help="output dex path")
|
||||
ap.add_argument("--dry-run", action="store_true",
|
||||
help="report matches and diffs without writing")
|
||||
ap.add_argument("--report", help="write a machine-readable JSON report here")
|
||||
args = ap.parse_args(argv[1:])
|
||||
|
||||
dex, entry = load_dex(args.dex, args.entry) if os.path.exists(args.dex) else (None, None)
|
||||
if dex is None:
|
||||
# allow raw bytes piped through a path that does not exist yet: fail clearly
|
||||
print("error: no such file: %s" % args.dex)
|
||||
return 2
|
||||
|
||||
problems = dex.check()
|
||||
if problems:
|
||||
print("structural problems in %s (%s):" % (args.dex, entry))
|
||||
for p in problems:
|
||||
print(" - %s" % p)
|
||||
print("refusing to patch a source that does not parse cleanly")
|
||||
return 1
|
||||
|
||||
with open(args.spec, encoding="utf-8") as fh:
|
||||
spec_doc = json.load(fh)
|
||||
specs = spec_doc["patches"] if isinstance(spec_doc, dict) else spec_doc
|
||||
|
||||
ok_before = verify_dex_header(dex.d)
|
||||
print("== source: %s (%s, %d bytes)" % (args.dex, entry, len(dex.d)))
|
||||
print(" header before: checksum_ok=%s signature_ok=%s"
|
||||
% ok_before)
|
||||
if not all(ok_before):
|
||||
print(" note: the SOURCE dex header is already inconsistent. Some")
|
||||
print(" producers ship a zeroed signature field; the patch will fix it.")
|
||||
|
||||
data = bytearray(dex.d)
|
||||
reports = []
|
||||
for i, spec in enumerate(specs):
|
||||
rep, data = process_one(dex, data, spec, i, args.dry_run)
|
||||
reports.append(rep)
|
||||
print("\n-- [%s] %s.%s%s" % (rep["name"], rep["class"], rep["method"], rep["desc"]))
|
||||
print(" site 0x%x %s" % (rep["site_off"], rep["old_text"]))
|
||||
for line in rep["before"][-2:]:
|
||||
print(" (before) %s" % line)
|
||||
print(" -> %s" % rep.get("new_text"))
|
||||
for line in rep["after"][:2]:
|
||||
print(" (after) %s" % line)
|
||||
if rep.get("expect_next_ok"):
|
||||
print(" polarity: expect_next satisfied")
|
||||
|
||||
if args.dry_run:
|
||||
print("\n== dry run: nothing written")
|
||||
if args.report:
|
||||
with open(args.report, "w", encoding="utf-8") as fh:
|
||||
json.dump(reports, fh, indent=2)
|
||||
print(" report: %s" % args.report)
|
||||
return 0
|
||||
|
||||
header = fix_dex_header(data)
|
||||
ok_after = verify_dex_header(data)
|
||||
print("\n== header checksum 0x%08x -> 0x%08x" % (header["before_checksum"],
|
||||
header["after_checksum"]))
|
||||
print(" signature %s -> %s"
|
||||
% (header["before_signature"].hex()[:16],
|
||||
header["after_signature"].hex()[:16]))
|
||||
print(" self-verify: checksum_ok=%s signature_ok=%s" % ok_after)
|
||||
if not all(ok_after):
|
||||
print("FATAL: header does not self-verify; nothing written")
|
||||
return 1
|
||||
|
||||
out = args.out
|
||||
if not out:
|
||||
root, ext = os.path.splitext(args.dex)
|
||||
out = root + ".patched" + (ext or ".dex")
|
||||
with open(out, "wb") as fh:
|
||||
fh.write(bytes(data))
|
||||
print("== wrote %s (%d bytes, delta %d)"
|
||||
% (out, len(data), len(data) - len(dex.d)))
|
||||
|
||||
if args.report:
|
||||
with open(args.report, "w", encoding="utf-8") as fh:
|
||||
json.dump(reports, fh, indent=2)
|
||||
print(" report: %s" % args.report)
|
||||
|
||||
print("\nNext: repack (scripts/repack.py) then sign with apksigner, then run "
|
||||
"the device + screen checks in references/verification.md.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Extract strings, URLs and vendor markers from dex files without a decompiler.
|
||||
|
||||
Fast recon: dex strings are stored as plain MUTF-8, so ASCII substrings can be found
|
||||
by scanning the raw bytes. This answers most classification questions in seconds --
|
||||
which dex holds the app's code, which ad SDKs ship with it, what endpoints it calls.
|
||||
|
||||
Usage
|
||||
-----
|
||||
# all URLs across a directory of dex files
|
||||
python dex_strings.py <dex_dir> --urls
|
||||
|
||||
# find which dex files contain a marker (ASCII substring)
|
||||
python dex_strings.py <dex_dir> --find 'openadsdk|com.qq.e|anythink' --per-file
|
||||
|
||||
# dump a class/package inventory per dex (type descriptors)
|
||||
python dex_strings.py <dex_dir> --classes 'Lcom/example/app/'
|
||||
|
||||
# raw string-table dump, length-filtered
|
||||
python dex_strings.py <dex_dir> --strings --min 8 --max 60
|
||||
|
||||
# compare two dex files' string tables (what changed after a patch)
|
||||
python dex_strings.py --diff a.dex b.dex
|
||||
|
||||
Notes
|
||||
-----
|
||||
* A marker in the string table means the class/URL is *present*, not that the app
|
||||
*uses* that feature. Confirm with runtime behavior before acting.
|
||||
* `--urls` output is the fastest way to see an app's whole API surface and its
|
||||
third-party endpoints at once.
|
||||
* A dex may be a multi-dex set: run this per directory, not per file, to see which
|
||||
split holds a given marker.
|
||||
"""
|
||||
import argparse
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
URL_RE = re.compile(rb'https?://[A-Za-z0-9\.\-_:/%\.\?=&~#]{4,200}')
|
||||
|
||||
|
||||
def uleb128(data, off):
|
||||
r = 0
|
||||
s = 0
|
||||
while True:
|
||||
b = data[off]
|
||||
off += 1
|
||||
r |= (b & 0x7F) << s
|
||||
if not (b & 0x80):
|
||||
break
|
||||
s += 7
|
||||
return r, off
|
||||
|
||||
|
||||
def dex_strings(path):
|
||||
"""Yield the dex string table in table order, as bytes."""
|
||||
data = open(path, 'rb').read()
|
||||
if data[:4] != b'dex\n':
|
||||
return
|
||||
n = struct.unpack('<I', data[0x38:0x3C])[0]
|
||||
off = struct.unpack('<I', data[0x3C:0x40])[0]
|
||||
for i in range(n):
|
||||
sdata = struct.unpack('<I', data[off + i * 4: off + i * 4 + 4])[0]
|
||||
ln, p = uleb128(data, sdata)
|
||||
yield bytes(data[p:p + ln])
|
||||
|
||||
|
||||
def iter_dex(target):
|
||||
if os.path.isdir(target):
|
||||
return sorted(glob.glob(os.path.join(target, '*.dex')))
|
||||
return [target]
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='Extract strings / URLs / class descriptors / vendor markers from dex files '
|
||||
'without a decompiler.')
|
||||
ap.add_argument('target', nargs='?', default=None,
|
||||
help='a .dex file or a directory containing .dex files (omit when using --diff)')
|
||||
ap.add_argument('--urls', action='store_true', help='print only http(s) URLs')
|
||||
ap.add_argument('--strings', action='store_true', help='dump raw string table entries')
|
||||
ap.add_argument('--classes', metavar='PREFIX',
|
||||
help='print only entries starting with this prefix (e.g. Lcom/example/app/)')
|
||||
ap.add_argument('--find', metavar='REGEX',
|
||||
help='only keep entries matching this regex (applied to the decoded text)')
|
||||
ap.add_argument('--per-file', action='store_true',
|
||||
help='with --find: report one line per dex with a hit count, instead of each string')
|
||||
ap.add_argument('--diff', nargs=2, metavar=('A', 'B'),
|
||||
help='compare two dex files string tables')
|
||||
ap.add_argument('--min', type=int, default=6, help='minimum string length (default 6)')
|
||||
ap.add_argument('--max', type=int, default=200, help='maximum string length (default 200)')
|
||||
ap.add_argument('--max-print', type=int, default=5000,
|
||||
help='stop printing after this many lines (default 5000; use 0 for unlimited)')
|
||||
a = ap.parse_args()
|
||||
|
||||
# --diff mode needs no target
|
||||
if a.diff:
|
||||
A = set(dex_strings(a.diff[0]))
|
||||
B = set(dex_strings(a.diff[1]))
|
||||
only_a = sorted(x for x in A - B if a.min <= len(x) <= a.max)
|
||||
only_b = sorted(x for x in B - A if a.min <= len(x) <= a.max)
|
||||
print('A strings=%d B strings=%d' % (len(A), len(B)))
|
||||
print('only in A: %d' % len(only_a))
|
||||
for x in only_a[:40]:
|
||||
print(' -', x.decode('utf-8', 'replace'))
|
||||
print('only in B: %d' % len(only_b))
|
||||
for x in only_b[:40]:
|
||||
print(' +', x.decode('utf-8', 'replace'))
|
||||
return 0
|
||||
|
||||
if not a.target:
|
||||
ap.error('target is required unless --diff is used')
|
||||
|
||||
# Two patterns: the per-file mode scans raw bytes (fast), the per-string mode
|
||||
# matches decoded text. Keeping both avoids the bytes/str mismatch that silently
|
||||
# breaks one of the two paths.
|
||||
pat_text = re.compile(a.find) if a.find else None
|
||||
pat_bytes = re.compile(a.find.encode('utf-8')) if a.find else None
|
||||
files = iter_dex(a.target)
|
||||
|
||||
if a.find and a.per_file:
|
||||
for fp in files:
|
||||
data = open(fp, 'rb').read()
|
||||
hits = len(pat_bytes.findall(data))
|
||||
if hits:
|
||||
print('%-22s hits=%d' % (os.path.basename(fp), hits))
|
||||
return 0
|
||||
|
||||
printed = 0
|
||||
seen = set()
|
||||
for fp in files:
|
||||
for raw in dex_strings(fp):
|
||||
s = raw.decode('utf-8', 'replace')
|
||||
if not (a.min <= len(s) <= a.max):
|
||||
continue
|
||||
if pat_text and not pat_text.search(s):
|
||||
continue
|
||||
if a.classes and not s.startswith(a.classes):
|
||||
continue
|
||||
if a.urls and not raw.startswith((b'http://', b'https://')):
|
||||
continue
|
||||
if s in seen:
|
||||
continue
|
||||
seen.add(s)
|
||||
if a.max_print and printed >= a.max_print:
|
||||
print('[note] output cap reached (%d). Use --max-print 0 to lift.' % a.max_print)
|
||||
return 0
|
||||
if a.classes:
|
||||
print('%-18s %s' % (os.path.basename(fp), s))
|
||||
else:
|
||||
print(s)
|
||||
printed += 1
|
||||
|
||||
if a.urls and not seen:
|
||||
# fall back to a raw byte scan: covers URLs stored outside the string table
|
||||
print('[note] no URLs in string tables; raw scan:')
|
||||
for fp in files:
|
||||
for m in sorted(set(URL_RE.findall(open(fp, 'rb').read()))):
|
||||
print(os.path.basename(fp), m.decode('utf-8', 'replace'))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,133 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Byte-level, in-place patch of a string constant inside a dex — no smali round-trip.
|
||||
|
||||
Why not a smali round-trip: a disassemble -> reassemble of a whole tree can damage
|
||||
R8-optimized output in ways the class table does not show. Observed symptom: a synthetic
|
||||
access bridge lost its interface/class relationship, producing
|
||||
IncompatibleClassChangeError ("Found interface X, but class was expected") at runtime even
|
||||
though class_defs and access_flags looked untouched. See references/pitfalls.md P3.
|
||||
|
||||
What this script does instead (zero structural change to the dex):
|
||||
1. Replaces the target string with another of **exactly equal byte length**. Equal length
|
||||
keeps the string_data_item uleb128 length prefix unchanged, so offsets, indices and
|
||||
every table stay exactly where they were.
|
||||
2. Recomputes the dex header signature (SHA-1, from offset 32) and checksum (adler32,
|
||||
from offset 12).
|
||||
|
||||
Use only when the replacement can be equal-length. Otherwise use a method-level dex API
|
||||
rewrite (references/dex-patching.md, technique 1).
|
||||
|
||||
Usage: python dex_strpatch.py <in.dex> <out.dex> <old_str> <new_str>
|
||||
Requires len(new) == len(old) in UTF-8 bytes, and exactly one occurrence of old in the dex.
|
||||
"""
|
||||
import hashlib
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
|
||||
def _uleb128(data, off):
|
||||
result = 0
|
||||
shift = 0
|
||||
while True:
|
||||
b = data[off]
|
||||
off += 1
|
||||
result |= (b & 0x7F) << shift
|
||||
if not (b & 0x80):
|
||||
break
|
||||
shift += 7
|
||||
return result, off
|
||||
|
||||
|
||||
def _read_strings(data):
|
||||
off = struct.unpack('<I', data[0x3C:0x40])[0]
|
||||
size = struct.unpack('<I', data[0x38:0x3C])[0]
|
||||
out = []
|
||||
for i in range(size):
|
||||
sdata_off = struct.unpack('<I', data[off + i * 4: off + i * 4 + 4])[0]
|
||||
n, p = _uleb128(data, sdata_off)
|
||||
out.append((sdata_off, bytes(data[p:p + n])))
|
||||
return out
|
||||
|
||||
|
||||
def _order_ok(data, off, ob, nb):
|
||||
"""Check whether replacing `ob` with `nb` still satisfies the string_ids ordering rule.
|
||||
|
||||
Note: string_ids stores the offset of each string_data_item — i.e. the position of the
|
||||
**length prefix** (a few bytes ahead of the UTF-8 payload), not of the text itself — so
|
||||
matching by string-data offset directly is not possible; this matches the entry by
|
||||
content instead.
|
||||
"""
|
||||
entries = _read_strings(data)
|
||||
idx = None
|
||||
for i, (_sdata_off, raw) in enumerate(entries):
|
||||
if raw == ob:
|
||||
idx = i
|
||||
break
|
||||
if idx is None:
|
||||
print('[order] target string not found in string_ids, skip check')
|
||||
return True
|
||||
prev = entries[idx - 1][1] if idx > 0 else None
|
||||
nxt = entries[idx + 1][1] if idx + 1 < len(entries) else None
|
||||
if prev is not None and nb <= prev:
|
||||
print('[order] FAIL: new %r <= prev %r' % (nb, prev))
|
||||
return False
|
||||
if nxt is not None and nb >= nxt:
|
||||
print('[order] FAIL: new %r >= next %r' % (nb, nxt))
|
||||
return False
|
||||
print('[order] OK: %r < %r < %r' % (prev, nb, nxt))
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) > 1 and sys.argv[1] in ('-h', '--help'):
|
||||
print(__doc__)
|
||||
return 0
|
||||
if len(sys.argv) < 5:
|
||||
print('error: needs 4 arguments, got %d\n' % (len(sys.argv) - 1))
|
||||
print(__doc__)
|
||||
return 2
|
||||
src, dst, old, new = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
|
||||
ob, nb = old.encode('utf-8'), new.encode('utf-8')
|
||||
if len(ob) != len(nb):
|
||||
print('[FAIL] length mismatch: %d vs %d (must be equal)' % (len(ob), len(nb)))
|
||||
return 1
|
||||
data = bytearray(open(src, 'rb').read())
|
||||
if data[:8] != b'dex\n035\x00' and data[:4] != b'dex\n':
|
||||
print('[warn] unexpected magic: %r' % bytes(data[:8]))
|
||||
n = data.count(ob)
|
||||
print('[info] occurrences of %r = %d' % (old, n))
|
||||
if n != 1:
|
||||
print('[FAIL] expected exactly 1 occurrence')
|
||||
return 1
|
||||
off = data.find(ob)
|
||||
|
||||
# The dex spec requires string_ids to be ordered by string content. An equal-length
|
||||
# replacement moves no offset, but it does change where this entry sits in that ordering
|
||||
# — and once it lands out of order the whole dex is rejected by the ClassLoader
|
||||
# (symptom: ClassNotFoundException naming the Application class). So validate the
|
||||
# interval before writing.
|
||||
if not _order_ok(data, off, ob, nb):
|
||||
print('[FAIL] replacement would break string_ids ordering. '
|
||||
'Pick a string that stays between its two neighbours.')
|
||||
return 1
|
||||
|
||||
data[off:off + len(ob)] = nb
|
||||
print('[ok] patched at offset 0x%x: %r -> %r' % (off, old, new))
|
||||
|
||||
# signature = SHA-1 over data[32:], stored at 12..32
|
||||
sig = hashlib.sha1(bytes(data[32:])).digest()
|
||||
data[12:32] = sig
|
||||
# checksum = adler32 over data[12:], stored at 8..12 (little endian)
|
||||
chk = zlib.adler32(bytes(data[12:])) & 0xFFFFFFFF
|
||||
data[8:12] = struct.pack('<I', chk)
|
||||
print('[ok] signature=%s checksum=0x%08x' % (sig.hex(), chk))
|
||||
|
||||
open(dst, 'wb').write(bytes(data))
|
||||
print('[ok] wrote %s (%d bytes)' % (dst, len(data)))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,97 @@
|
||||
import org.jf.dexlib2.DexFileFactory;
|
||||
import org.jf.dexlib2.Opcode;
|
||||
import org.jf.dexlib2.Opcodes;
|
||||
import org.jf.dexlib2.iface.ClassDef;
|
||||
import org.jf.dexlib2.iface.Method;
|
||||
import org.jf.dexlib2.iface.MethodImplementation;
|
||||
import org.jf.dexlib2.builder.MutableMethodImplementation;
|
||||
import org.jf.dexlib2.immutable.ImmutableMethod;
|
||||
import org.jf.dexlib2.writer.pool.DexPool;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* dexlib2 定点 patch:把指定方法的实现整体替换为 return-void(或 return 常量)。
|
||||
*
|
||||
* 为什么不用 baksmali/smali 整树往返:实测在一个多 dex 应用上,整树往返重建后运行时报
|
||||
* IncompatibleClassChangeError: Found interface io.ktor.client.engine.HttpClientEngine,
|
||||
* but class was expected
|
||||
* (R8 生成的 synthetic access bridge 被破坏)。本工具只改目标方法的 code_item,
|
||||
* 其余类/方法/字符串表原样保留,因此不会有这类损伤。
|
||||
*
|
||||
* 用法: java PatchMethod <in.dex> <out.dex> <descriptor> <methodName> <returnType>
|
||||
* 例: java PatchMethod classes7.dex out.dex Lx6; d V
|
||||
*/
|
||||
public class PatchMethod {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length < 5) {
|
||||
System.err.println("usage: PatchMethod <in.dex> <out.dex> <descriptor> <methodName> <returnType>");
|
||||
System.exit(2);
|
||||
}
|
||||
String inPath = args[0], outPath = args[1], desc = args[2], mName = args[3], ret = args[4];
|
||||
|
||||
org.jf.dexlib2.iface.DexFile dex =
|
||||
DexFileFactory.loadDexFile(new File(inPath), Opcodes.forApi(34));
|
||||
|
||||
List<ClassDef> outClasses = new ArrayList<ClassDef>();
|
||||
int patched = 0;
|
||||
|
||||
for (ClassDef cd : dex.getClasses()) {
|
||||
List<Method> direct = new ArrayList<Method>();
|
||||
for (Method m : cd.getDirectMethods()) direct.add(m);
|
||||
List<Method> virtual = new ArrayList<Method>();
|
||||
for (Method m : cd.getVirtualMethods()) virtual.add(m);
|
||||
boolean isTargetClass = cd.getType().equals(desc);
|
||||
boolean changed = false;
|
||||
|
||||
if (isTargetClass) {
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
List<Method> list = (pass == 0) ? direct : virtual;
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
Method m = list.get(i);
|
||||
if (!m.getName().equals(mName) || !m.getReturnType().equals(ret)) continue;
|
||||
// 用 return-void 替换整个方法体。
|
||||
// 寄存器数必须保留原值:Compose/协程方法体里可能仍被其它指令引用同一寄存器窗口,
|
||||
// 且 dex 校验要求 registers >= 参数寄存器数。
|
||||
int regs = m.getImplementation() != null ? m.getImplementation().getRegisterCount() : 0;
|
||||
MethodImplementation impl = new org.jf.dexlib2.immutable.ImmutableMethodImplementation(
|
||||
regs,
|
||||
java.util.Collections.singletonList(
|
||||
new org.jf.dexlib2.immutable.instruction.ImmutableInstruction10x(Opcode.RETURN_VOID)),
|
||||
null,
|
||||
null);
|
||||
Method nm = new ImmutableMethod(
|
||||
m.getDefiningClass(), m.getName(), m.getParameters(), m.getReturnType(),
|
||||
m.getAccessFlags(), m.getAnnotations(), m.getHiddenApiRestrictions(),
|
||||
impl);
|
||||
list.set(i, nm);
|
||||
patched++;
|
||||
changed = true;
|
||||
System.out.println("[patch] " + desc + "->" + mName + m.getReturnType()
|
||||
+ " registers=" + regs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
outClasses.add(cd);
|
||||
} else {
|
||||
outClasses.add(new org.jf.dexlib2.immutable.ImmutableClassDef(
|
||||
cd.getType(), cd.getAccessFlags(), cd.getSuperclass(),
|
||||
cd.getInterfaces(), cd.getSourceFile(), cd.getAnnotations(),
|
||||
cd.getStaticFields(), cd.getInstanceFields(), direct, virtual));
|
||||
}
|
||||
}
|
||||
|
||||
DexFileFactory.writeDexFile(outPath,
|
||||
new org.jf.dexlib2.immutable.ImmutableDexFile(Opcodes.forApi(34), outClasses));
|
||||
System.out.println("[done] patched=" + patched + " -> " + outPath);
|
||||
if (patched == 0) {
|
||||
System.err.println("[warn] no method matched!");
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import org.jf.dexlib2.DexFileFactory;
|
||||
import org.jf.dexlib2.Opcode;
|
||||
import org.jf.dexlib2.Opcodes;
|
||||
import org.jf.dexlib2.iface.ClassDef;
|
||||
import org.jf.dexlib2.iface.Method;
|
||||
import org.jf.dexlib2.iface.instruction.Instruction;
|
||||
import org.jf.dexlib2.immutable.ImmutableClassDef;
|
||||
import org.jf.dexlib2.immutable.ImmutableDexFile;
|
||||
import org.jf.dexlib2.immutable.ImmutableMethod;
|
||||
import org.jf.dexlib2.immutable.ImmutableMethodImplementation;
|
||||
import org.jf.dexlib2.immutable.instruction.ImmutableInstruction11x;
|
||||
import org.jf.dexlib2.immutable.instruction.ImmutableInstruction22c;
|
||||
import org.jf.dexlib2.immutable.instruction.ImmutableInstruction35c;
|
||||
import org.jf.dexlib2.immutable.instruction.ImmutableInstruction51l;
|
||||
import org.jf.dexlib2.immutable.reference.ImmutableFieldReference;
|
||||
import org.jf.dexlib2.immutable.reference.ImmutableMethodReference;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* dexlib2 surgical rewrites -- worked example: force one lambda's emit() to hand a
|
||||
* constant downstream instead of the value it read from its source.
|
||||
*
|
||||
* WHAT IT PATCHES
|
||||
* <target>$$inlined$map$1$2.emit(Object, Continuation)Object
|
||||
* -> send a fixed wide (long) constant to the downstream collector, unconditionally
|
||||
*
|
||||
* WHY THIS SHAPE
|
||||
* Kotlin's `map { ... }` on a Flow compiles to a synthetic class whose emit()
|
||||
* reads the source value from a field and forwards it to the collector. Replacing
|
||||
* that single forwarding body turns "value read from the data source" into
|
||||
* "constant", without touching the data source itself. Doing it in dex keeps the
|
||||
* change inside the APK, so a fresh install behaves the same way -- writing the
|
||||
* value into the app's runtime state instead would not survive a reinstall.
|
||||
*
|
||||
* ONE READ, ONE WRITE. Never rewrite the same dex twice in the same run: dexlib2
|
||||
* round-trips degrade an R8-optimized dex, and the second pass is where it shows.
|
||||
*
|
||||
* ADAPT TO YOUR TARGET
|
||||
* java PatchMethodExample <in.dex> <out.dex> [targetClass] [fieldOwner:fieldName:fieldType]
|
||||
* [collectorIface] [continuationType]
|
||||
* Every optional argument defaults to an obviously-fake example value below, and
|
||||
* the effective values are printed at startup, so a run is never ambiguous.
|
||||
*
|
||||
* HOW TO FIND THE REAL VALUES
|
||||
* * target class: search the dex strings for the source's field/data key, then read
|
||||
* the call site with baksmali -- see scripts/dex_strings.py and scripts/find_refs.py.
|
||||
* * collector iface / continuation type: read them off the emit() signature in smali.
|
||||
* After R8 they are usually single letters; do not guess, copy them.
|
||||
*
|
||||
* DO NOT PATCH SHARED CODE BY ACCIDENT
|
||||
* A generic card/image composable is commonly shared between ordinary content and
|
||||
* ad slots. Turning such a method into `return-void` breaks normal rendering too.
|
||||
* Before patching anything, count its callers (scripts/find_refs.py).
|
||||
*/
|
||||
public class PatchMethodExample {
|
||||
|
||||
/** Synthetic class that owns the lambda: <Owner>$<member>$$inlined$map$1$2. */
|
||||
private static String TARGET_CLASS =
|
||||
"Lcom/example/app/data/ExampleStore$currentValue$$inlined$map$1$2;";
|
||||
|
||||
/** The field on the lambda that holds the downstream collector. */
|
||||
private static String FIELD_OWNER = "Lcom/example/app/data/ExampleStore$currentValue$$inlined$map$1$2;";
|
||||
private static String FIELD_NAME = "b";
|
||||
private static String FIELD_TYPE = "Lcom/example/app/Collector;";
|
||||
|
||||
/** The collector type and the Continuation type used by emit(). */
|
||||
private static String COLLECTOR_IFACE = "Lcom/example/app/Collector;";
|
||||
private static String CONTINUATION_TYPE = "Lkotlin/coroutines/Continuation;";
|
||||
|
||||
private static final long CONSTANT = 4102444800000L; // ~2100-01-01 (ms)
|
||||
|
||||
private static void usage() {
|
||||
System.out.println("usage: PatchMethodExample <in.dex> <out.dex> "
|
||||
+ "[targetClass] [fieldOwner:fieldName:fieldType] "
|
||||
+ "[collectorIface] [continuationType]");
|
||||
System.out.println(" defaults (example values, replace for your target):");
|
||||
System.out.println(" targetClass " + TARGET_CLASS);
|
||||
System.out.println(" fieldRef " + FIELD_OWNER + ":" + FIELD_NAME + ":" + FIELD_TYPE);
|
||||
System.out.println(" collectorIface " + COLLECTOR_IFACE);
|
||||
System.out.println(" continuationType " + CONTINUATION_TYPE);
|
||||
}
|
||||
|
||||
private static void applyArgs(String[] args) {
|
||||
if (args.length > 2 && !args[2].isEmpty()) {
|
||||
TARGET_CLASS = args[2];
|
||||
}
|
||||
if (args.length > 3 && !args[3].isEmpty()) {
|
||||
String[] parts = args[3].split(":");
|
||||
if (parts.length != 3) {
|
||||
throw new IllegalArgumentException(
|
||||
"fieldRef must be owner:name:type, got " + args[3]);
|
||||
}
|
||||
FIELD_OWNER = parts[0];
|
||||
FIELD_NAME = parts[1];
|
||||
FIELD_TYPE = parts[2];
|
||||
}
|
||||
if (args.length > 4 && !args[4].isEmpty()) {
|
||||
COLLECTOR_IFACE = args[4];
|
||||
}
|
||||
if (args.length > 5 && !args[5].isEmpty()) {
|
||||
CONTINUATION_TYPE = args[5];
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
if (args.length < 2) {
|
||||
usage();
|
||||
System.exit(2);
|
||||
}
|
||||
applyArgs(args);
|
||||
|
||||
String in = args[0], out = args[1];
|
||||
System.out.println("[in ] " + in);
|
||||
System.out.println("[cfg] targetClass=" + TARGET_CLASS);
|
||||
System.out.println("[cfg] fieldRef=" + FIELD_OWNER + ":" + FIELD_NAME + ":" + FIELD_TYPE);
|
||||
System.out.println("[cfg] collectorIface=" + COLLECTOR_IFACE);
|
||||
System.out.println("[cfg] continuationType=" + CONTINUATION_TYPE);
|
||||
System.out.println("[cfg] constant=" + CONSTANT);
|
||||
|
||||
org.jf.dexlib2.iface.DexFile dex =
|
||||
DexFileFactory.loadDexFile(new File(in), Opcodes.forApi(34));
|
||||
|
||||
List<ClassDef> outClasses = new ArrayList<ClassDef>();
|
||||
int patched = 0;
|
||||
|
||||
for (ClassDef cd : dex.getClasses()) {
|
||||
List<Method> direct = new ArrayList<Method>();
|
||||
for (Method m : cd.getDirectMethods()) direct.add(m);
|
||||
List<Method> virtual = new ArrayList<Method>();
|
||||
for (Method m : cd.getVirtualMethods()) virtual.add(m);
|
||||
boolean touched = false;
|
||||
|
||||
if (cd.getType().equals(TARGET_CLASS)) {
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
List<Method> list = (pass == 0) ? direct : virtual;
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
Method m = list.get(i);
|
||||
if (!m.getName().equals("emit")
|
||||
|| !m.getReturnType().equals("Ljava/lang/Object;")
|
||||
|| m.getImplementation() == null) {
|
||||
continue;
|
||||
}
|
||||
// Register layout for emit(Object, Continuation):
|
||||
// v0 scratch (return value)
|
||||
// v1:v2 the wide constant we build
|
||||
// v3 = p0 this (the lambda)
|
||||
// v4 = p1 the value being forwarded (ignored)
|
||||
// v5 = p2 the downstream Continuation
|
||||
List<Instruction> body = new ArrayList<Instruction>();
|
||||
body.add(new ImmutableInstruction22c(Opcode.IGET_OBJECT, 0, 3,
|
||||
new ImmutableFieldReference(FIELD_OWNER, FIELD_NAME, FIELD_TYPE)));
|
||||
body.add(new ImmutableInstruction51l(Opcode.CONST_WIDE, 1, CONSTANT));
|
||||
body.add(new ImmutableInstruction35c(Opcode.INVOKE_STATIC, 2, 1, 2, 0, 0, 0,
|
||||
new ImmutableMethodReference("Ljava/lang/Long;", "valueOf",
|
||||
Collections.singletonList("J"), "Ljava/lang/Long;")));
|
||||
body.add(new ImmutableInstruction11x(Opcode.MOVE_RESULT_OBJECT, 1));
|
||||
body.add(new ImmutableInstruction35c(Opcode.INVOKE_INTERFACE, 3, 0, 1, 5, 0, 0,
|
||||
new ImmutableMethodReference(COLLECTOR_IFACE, "emit",
|
||||
Arrays.asList("Ljava/lang/Object;", CONTINUATION_TYPE),
|
||||
"Ljava/lang/Object;")));
|
||||
body.add(new ImmutableInstruction11x(Opcode.MOVE_RESULT_OBJECT, 0));
|
||||
body.add(new ImmutableInstruction11x(Opcode.RETURN_OBJECT, 0));
|
||||
|
||||
list.set(i, new ImmutableMethod(m.getDefiningClass(), m.getName(),
|
||||
m.getParameters(), m.getReturnType(), m.getAccessFlags(),
|
||||
m.getAnnotations(), m.getHiddenApiRestrictions(),
|
||||
new ImmutableMethodImplementation(6, body, null, null)));
|
||||
patched++;
|
||||
touched = true;
|
||||
System.out.println("[patch] emit -> constant=" + CONSTANT
|
||||
+ " (list=" + pass + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!touched) {
|
||||
outClasses.add(cd);
|
||||
} else {
|
||||
outClasses.add(new ImmutableClassDef(
|
||||
cd.getType(), cd.getAccessFlags(), cd.getSuperclass(), cd.getInterfaces(),
|
||||
cd.getSourceFile(), cd.getAnnotations(), cd.getStaticFields(),
|
||||
cd.getInstanceFields(), direct, virtual));
|
||||
}
|
||||
}
|
||||
|
||||
DexFileFactory.writeDexFile(out, new ImmutableDexFile(Opcodes.forApi(34), outClasses));
|
||||
System.out.println("[out ] " + out + " patched=" + patched);
|
||||
if (patched == 0) {
|
||||
// The usual causes: wrong target class (R8 renamed it), the method is not
|
||||
// emit(Object,Continuation), or the class is not in THIS dex.
|
||||
System.err.println("[fail] target not found in this dex. Check: the exact "
|
||||
+ "TARGET_CLASS descriptor, that emit(Object,Continuation) exists there, "
|
||||
+ "and that you loaded the dex that actually contains this class.");
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
# dexlib2 method-level patcher
|
||||
|
||||
The **preferred** way to change app behavior. It replaces only a target method's
|
||||
implementation and writes a new dex, leaving every other class, method, string and
|
||||
reference untouched.
|
||||
|
||||
Why not whole-tree smali round-trip: `baksmali` → `smali` rebuilds misrepresent R8's
|
||||
synthetic access bridges. The class table still looks perfect — same class count, zero
|
||||
`ACC_INTERFACE` mismatches — but at runtime you get
|
||||
`IncompatibleClassChangeError: Found interface X, but class was expected`.
|
||||
See `../../references/pitfalls.md` P3.
|
||||
|
||||
## Build
|
||||
|
||||
Needs the same eight jars `smtool.py` uses:
|
||||
|
||||
```
|
||||
smali-2.5.2.jar antlr-runtime-3.5.2.jar stringtemplate-3.2.1.jar
|
||||
baksmali-2.5.2.jar util-2.5.2.jar jcommander-1.64.jar
|
||||
guava-27.1-android.jar dexlib2-2.5.2.jar
|
||||
```
|
||||
|
||||
```bash
|
||||
# point at your jars (or reuse ../smali_cp.txt)
|
||||
CP=$(cat ../smali_cp.txt | grep -v '^#' | tr '\n' ';' | sed 's/;$//')
|
||||
|
||||
javac -encoding UTF-8 -cp "$CP" PatchMethod.java
|
||||
```
|
||||
|
||||
**Always pass `-encoding UTF-8`** if the source has non-ASCII comments — `javac`
|
||||
otherwise reads them with the platform default encoding and fails.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
java -cp "$CP;." PatchMethod <in.dex> <out.dex> <descriptor> <methodName> <returnType>
|
||||
|
||||
# example: make Lx6;->d(...)V a no-op
|
||||
java -cp "$CP;." PatchMethod classes7.dex out.dex 'Lx6;' d V
|
||||
```
|
||||
|
||||
`PatchMethod` replaces the body with `return-void`. It scans **both** `directMethods`
|
||||
and `virtualMethods` — a method you cannot find is often in the other list
|
||||
(`static`/`private`/`<init>` are direct; everything else, including `public final`,
|
||||
is virtual).
|
||||
|
||||
Use `PatchMethodExample.java` as the template for anything non-trivial (returning a
|
||||
constant, emitting a fixed value from a Flow lambda, applying **several** edits to the
|
||||
same dex in one pass).
|
||||
|
||||
## Rules that decide success
|
||||
|
||||
1. **One dex, one write pass.** Never chain two patchers over the same dex — the second
|
||||
serialization drops metadata and ART then refuses to start the process
|
||||
(`Failure starting process`, no Java stack). Combine all edits into one program.
|
||||
2. **Preserve the register count.** `registers` must be `>=` the parameter register
|
||||
count. With `registers = N` and `k` parameters (counting `this` for non-static),
|
||||
`p0 = N - k`. For `(Ljava/lang/Object;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;`
|
||||
on an instance method, `k = 3`, so with `registers = 6` you get `p0=3, p1=4, p2=5`.
|
||||
3. **`const-wide` needs the 64-bit instruction form** (`ImmutableInstruction51l`), not
|
||||
the 32-bit one.
|
||||
4. **`invoke` operand order in `35c`** is `(opcode, registerCount, regC, regD, regE, regF, regG, ref)`.
|
||||
`invoke-static {v1, v2}, ...` → `registerCount=2, regC=1, regD=2`.
|
||||
5. **End every body with a return of the correct type.**
|
||||
6. **Check the blast radius first** — `../find_refs.py`. A generic helper with dozens of
|
||||
callers is not your patch point (`../../references/pitfalls.md` P6).
|
||||
|
||||
## Verify
|
||||
|
||||
```bash
|
||||
python ../dex_classdiff.py <original.dex> <patched.dex>
|
||||
python ../smtool.py d <patched.dex> <tmp_tree> # confirm it parses
|
||||
# then read the target method in tmp_tree to confirm it says what you intended
|
||||
```
|
||||
|
||||
Expect `only_in_A=0`, `only_in_B=0`, `ACC_INTERFACE mismatch: 0`. Then install and
|
||||
launch — table checks cannot see code-item damage, so runtime verification is
|
||||
mandatory (`../../references/verification.md`).
|
||||
@@ -0,0 +1,582 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Minimal, dependency-free dex reader: structure walk + exact instruction decode.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
Locating the exact byte offset of one instruction is where byte-level patching
|
||||
either works or wastes an afternoon. Two shortcuts do not work and are worth
|
||||
naming so nobody re-derives them:
|
||||
|
||||
* Reconstructing offsets from a baksmali listing. `.line` directives track
|
||||
SOURCE lines, and one source line can span several instructions, so the
|
||||
values repeat and do not map 1:1 onto code offsets.
|
||||
* Matching a guessed byte sequence. Encodings vary with register numbers and
|
||||
operand widths, and a plausible-looking opcode can belong to a different
|
||||
format than you assume (0x38 is `if-test`, 22t/4 bytes -- not `if-testz`).
|
||||
|
||||
So: walk class -> class_data_item -> method -> code_item, then decode forward with
|
||||
a complete format table, and match on decoded semantics instead of bytes.
|
||||
|
||||
Three details in the walk that silently produce wrong answers:
|
||||
|
||||
* `class_data_item` member indices are DELTAS against the previous entry in the
|
||||
same list. Reading a raw uleb as an absolute index yields real-looking wrong
|
||||
members.
|
||||
* dalvik encodes switch/array payloads as `00 <ident> <size>` with ident 1..3.
|
||||
A plain `00 00` is an ordinary one-unit nop; treating every 00 as a payload
|
||||
swallows the next instruction and desynchronises the rest of the method.
|
||||
* The header field order is easy to mis-remember. See OFFSETS below, and always
|
||||
sanity-check the parsed sizes against the file.
|
||||
|
||||
Pure standard library. Import it, or run it for a per-method dump:
|
||||
|
||||
python dexutil.py <dex-or-apk> <Class/Name;> <method> <descriptor>
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import struct
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
# Verified dex header offsets. After magic(8) + checksum(4) + signature(20):
|
||||
OFFSETS = {
|
||||
"file_size": 0x20, "header_size": 0x24, "endian_tag": 0x28,
|
||||
"link_size": 0x2C, "link_off": 0x30, "map_off": 0x34,
|
||||
"string_ids_size": 0x38, "string_ids_off": 0x3C,
|
||||
"type_ids_size": 0x40, "type_ids_off": 0x44,
|
||||
"proto_ids_size": 0x48, "proto_ids_off": 0x4C,
|
||||
"field_ids_size": 0x50, "field_ids_off": 0x54,
|
||||
"method_ids_size": 0x58, "method_ids_off": 0x5C,
|
||||
"class_defs_size": 0x60, "class_defs_off": 0x64,
|
||||
"data_size": 0x68, "data_off": 0x6C,
|
||||
}
|
||||
|
||||
OP_NAMES = {
|
||||
0x00: "nop", 0x01: "move", 0x02: "move/from16", 0x03: "move/16",
|
||||
0x04: "move-wide", 0x05: "move-wide/from16", 0x06: "move-wide/16",
|
||||
0x07: "move-object", 0x08: "move-object/from16", 0x09: "move-object/16",
|
||||
0x0A: "move-result", 0x0B: "move-result-wide", 0x0C: "move-result-object",
|
||||
0x0D: "move-exception", 0x0E: "return-void", 0x0F: "return",
|
||||
0x10: "return-wide", 0x11: "return-object", 0x12: "const/4",
|
||||
0x13: "const/16", 0x14: "const", 0x15: "const/high16",
|
||||
0x16: "const-wide/high16", 0x17: "const-wide/16", 0x18: "const-wide/32",
|
||||
0x19: "const-string", 0x1A: "const-string/jumbo", 0x1B: "const-class",
|
||||
0x1C: "monitor-enter", 0x1D: "monitor-exit", 0x1E: "check-cast",
|
||||
0x1F: "instance-of", 0x20: "array-length", 0x21: "new-instance",
|
||||
0x22: "new-array", 0x23: "filled-new-array", 0x24: "filled-new-array/range",
|
||||
0x25: "fill-array-data", 0x26: "throw", 0x27: "goto",
|
||||
0x28: "goto/16", 0x29: "goto/32", 0x2A: "packed-switch",
|
||||
0x2B: "sparse-switch",
|
||||
0x32: "if-eq", 0x33: "if-ne", 0x34: "if-lt", 0x35: "if-ge",
|
||||
0x36: "if-gt", 0x37: "if-le",
|
||||
0x38: "if-eqz", 0x39: "if-nez", 0x3A: "if-ltz", 0x3B: "if-gez",
|
||||
0x3C: "if-gtz", 0x3D: "if-lez",
|
||||
0x52: "iget", 0x53: "iget-wide", 0x54: "iget-object", 0x55: "iget-boolean",
|
||||
0x56: "iget-byte", 0x57: "iget-char", 0x58: "iget-short",
|
||||
0x59: "iput", 0x5A: "iput-wide", 0x5B: "iput-object", 0x5C: "iput-boolean",
|
||||
0x5D: "iput-byte", 0x5E: "iput-char", 0x5F: "iput-short",
|
||||
0x60: "sget", 0x61: "sget-wide", 0x62: "sget-object", 0x63: "sget-boolean",
|
||||
0x64: "sget-byte", 0x65: "sget-char", 0x66: "sget-short",
|
||||
0x67: "sput", 0x68: "sput-wide", 0x69: "sput-object", 0x6A: "sput-boolean",
|
||||
0x6B: "sput-byte", 0x6C: "sput-char", 0x6D: "sput-short",
|
||||
0x6E: "invoke-virtual", 0x6F: "invoke-super", 0x70: "invoke-direct",
|
||||
0x71: "invoke-static", 0x72: "invoke-interface",
|
||||
0x74: "invoke-virtual/range", 0x75: "invoke-super/range",
|
||||
0x76: "invoke-direct/range", 0x77: "invoke-static/range",
|
||||
0x78: "invoke-interface/range",
|
||||
}
|
||||
|
||||
# Opcode groups whose operands are a pair of registers plus an int16 offset.
|
||||
IF_TEST = set(range(0x32, 0x38)) # 22t: 2 register nibbles + int16
|
||||
IF_TESTZ = set(range(0x38, 0x3E)) # 21t: 1 register nibble + int16
|
||||
RETURN_OPS = (0x0F, 0x10, 0x11)
|
||||
MOVE_RESULT_OPS = (0x0A, 0x0B, 0x0C)
|
||||
INVOKE_OPS = tuple(range(0x6E, 0x73)) + tuple(range(0x74, 0x79))
|
||||
# opcodes that read an instance field: (dest_reg, object_reg, field_idx)
|
||||
IFIELD_OPS = tuple(range(0x52, 0x59))
|
||||
# opcodes that write an instance field: (value_reg, object_reg, field_idx)
|
||||
PFIELD_OPS = tuple(range(0x59, 0x60))
|
||||
SFIELD_OPS = tuple(range(0x60, 0x6E))
|
||||
|
||||
|
||||
def u16(b, o):
|
||||
return b[o] | (b[o + 1] << 8)
|
||||
|
||||
|
||||
def u32(b, o):
|
||||
return b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)
|
||||
|
||||
|
||||
def s16(v):
|
||||
return v - 0x10000 if v > 0x7FFF else v
|
||||
|
||||
|
||||
def read_uleb(b, o):
|
||||
"""ULEB128 -> (value, new_offset). Member indices in class_data are deltas."""
|
||||
result = 0
|
||||
shift = 0
|
||||
while True:
|
||||
x = b[o]
|
||||
o += 1
|
||||
result |= (x & 0x7F) << shift
|
||||
if (x & 0x80) == 0:
|
||||
break
|
||||
shift += 7
|
||||
return result, o
|
||||
|
||||
|
||||
def insn_units(op, data, pos, end):
|
||||
"""Instruction length in 16-bit code units.
|
||||
|
||||
One wrong width desynchronises everything after it, and the failure is quiet:
|
||||
the decode keeps producing plausible-looking instructions, just shifted, so
|
||||
every offset you derive from that point is wrong. Two width traps are common
|
||||
enough to call out:
|
||||
|
||||
* `0x32`-`0x3D` (if-test 22t / if-testz 21t) are **2** units, not 1. Treating
|
||||
them as 1 invents a fake second instruction at every branch.
|
||||
* `0x1A` (const-string/jumbo) is emitted as a **4-byte** form (op, register,
|
||||
uint16 string index) by real toolchains and read that way by ART and
|
||||
baksmali, even though the reference format for the opcode is 31c. Counting
|
||||
it as 3 units is the single most costly width error -- it shifts the rest
|
||||
of the method by one unit per occurrence.
|
||||
* `0x28` is `goto` (10t, **1** unit), `0x29` is `goto/16` (2 units) and
|
||||
`0x2A` is `goto/32` (3 units). Do not read 0x28 as a two-unit form.
|
||||
|
||||
Whenever a decode is used to derive a patch offset, assert that the walk ends
|
||||
exactly on `insns_off + insns_size*2`. See `decode_all`.
|
||||
"""
|
||||
if op == 0x00:
|
||||
# payload nop: `00 <ident> <size>` with ident 1..3; a plain `00 00` is a
|
||||
# one-unit nop. Never treat every 00 as a payload.
|
||||
if pos + 4 <= end and (data[pos + 1] & 0xFF) in (0x01, 0x02, 0x03):
|
||||
return 1 + int.from_bytes(data[pos + 2:pos + 4], "little")
|
||||
return 1
|
||||
# -- 1 unit -------------------------------------------------------------
|
||||
if op in (0x01, 0x04, 0x07, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10,
|
||||
0x11, 0x12, # 12x / 11x / 11n / 10x
|
||||
0x1C, 0x1D, 0x26, 0x27): # monitor-enter/exit, throw, goto
|
||||
return 1
|
||||
if 0x7B <= op <= 0x8F: # 12x unop
|
||||
return 1
|
||||
if 0xB0 <= op <= 0xCF: # 12x binop/2addr
|
||||
return 1
|
||||
if 0xE3 <= op <= 0xFC: # 10x family
|
||||
return 1
|
||||
# -- 2 units ------------------------------------------------------------
|
||||
if op in (0x02, 0x05, 0x08): # 22x move/from16 variants
|
||||
return 2
|
||||
if op in (0x13, 0x15, 0x16, 0x17, 0x19, 0x1A, 0x1B, 0x1E, 0x1F,
|
||||
0x20, 0x21, 0x23, 0x24): # 21s/21h/21c/22c/35c/3rc
|
||||
return 2
|
||||
if 0x2C <= op <= 0x31: # 23x cmp
|
||||
return 2
|
||||
if op in IF_TEST or op in IF_TESTZ: # 22t / 21t <-- 2, not 1
|
||||
return 2
|
||||
if 0x44 <= op <= 0x51: # 23x aget/aput
|
||||
return 2
|
||||
if 0x52 <= op <= 0x5F: # 22c iget/iput
|
||||
return 2
|
||||
if 0x60 <= op <= 0x6D: # 21c sget/sput
|
||||
return 2
|
||||
if 0x90 <= op <= 0xAF: # 23x binop
|
||||
return 2
|
||||
if 0xD0 <= op <= 0xD7: # 22s binop/lit16
|
||||
return 2
|
||||
if 0xD8 <= op <= 0xE2: # 22b binop/lit8
|
||||
return 2
|
||||
if op == 0x29: # goto/16 (20t)
|
||||
return 2
|
||||
# -- 3 units ------------------------------------------------------------
|
||||
if op in (0x03, 0x06, 0x09, # 32x
|
||||
0x14, 0x18, # 31i const, const-wide/32
|
||||
0x22, 0x25, # 22c new-array, 31t fill-array
|
||||
0x2A, 0x2B, # 31t packed/sparse-switch
|
||||
0x6E, 0x6F, 0x70, 0x71, 0x72, # 35c invoke
|
||||
0x74, 0x75, 0x76, 0x77, 0x78): # 3rc invoke/range
|
||||
return 3
|
||||
# -- payloads / unknown -------------------------------------------------
|
||||
return 1
|
||||
|
||||
|
||||
class Dex(object):
|
||||
"""Structural reader for one dex image."""
|
||||
|
||||
def __init__(self, data, name="classes.dex"):
|
||||
self.d = data
|
||||
self.name = name
|
||||
self.header = {k: u32(data, v) for k, v in OFFSETS.items()}
|
||||
|
||||
# ---- sanity -----------------------------------------------------------
|
||||
def check(self):
|
||||
"""Return a list of structural complaints; empty means it parses."""
|
||||
problems = []
|
||||
size = len(self.d)
|
||||
if self.d[:4] != b"dex\n":
|
||||
problems.append("not a dex: magic=%r" % self.d[:4])
|
||||
for key in ("string_ids_off", "type_ids_off", "proto_ids_off",
|
||||
"field_ids_off", "method_ids_off", "class_defs_off"):
|
||||
off = self.header[key]
|
||||
if not (0 < off < size):
|
||||
problems.append("%s=0x%x out of range (file size %d)"
|
||||
% (key, off, size))
|
||||
declared = self.header["file_size"]
|
||||
if declared and declared != size:
|
||||
problems.append("header file_size=%d but actual=%d" % (declared, size))
|
||||
return problems
|
||||
|
||||
# ---- index tables -----------------------------------------------------
|
||||
def string(self, idx):
|
||||
p = u32(self.d, self.header["string_ids_off"] + idx * 4)
|
||||
_utf16_len, p = read_uleb(self.d, p)
|
||||
end = self.d.index(b"\x00", p)
|
||||
return self.d[p:end].decode("utf-8", "replace")
|
||||
|
||||
def string_safe(self, idx):
|
||||
"""Like string() but never raises -- a desynced decode passes junk index.
|
||||
|
||||
A renderer that throws on a bad index hides the very symptom the caller is
|
||||
looking for (a decode that has drifted), so return a marker instead.
|
||||
"""
|
||||
try:
|
||||
if idx >= self.header["string_ids_size"]:
|
||||
return "<string_idx %d out of range>" % idx
|
||||
return self.string(idx)
|
||||
except Exception:
|
||||
return "<string_idx %d unreadable>" % idx
|
||||
|
||||
def type_(self, idx):
|
||||
return self.string(u32(self.d, self.header["type_ids_off"] + idx * 4))
|
||||
|
||||
def proto(self, idx):
|
||||
o = self.header["proto_ids_off"] + idx * 12
|
||||
ret = self.type_(u32(self.d, o + 4))
|
||||
poff = u32(self.d, o + 8)
|
||||
params = []
|
||||
if poff:
|
||||
n = u32(self.d, poff)
|
||||
p = poff + 4
|
||||
for _ in range(n):
|
||||
params.append(self.type_(u16(self.d, p)))
|
||||
p += 2
|
||||
return "(" + "".join(params) + ")" + ret
|
||||
|
||||
def field(self, idx):
|
||||
o = self.header["field_ids_off"] + idx * 8
|
||||
return (self.type_(u16(self.d, o)), self.string(u32(self.d, o + 4)),
|
||||
self.type_(u16(self.d, o + 2)))
|
||||
|
||||
def method(self, idx):
|
||||
o = self.header["method_ids_off"] + idx * 8
|
||||
return (self.type_(u16(self.d, o)), self.string(u32(self.d, o + 4)),
|
||||
self.proto(u16(self.d, o + 2)))
|
||||
|
||||
def find_class(self, fqcn):
|
||||
"""Return the class_def_item offset for a 'Lpkg/Name;' FQCN, or None."""
|
||||
for i in range(self.header["class_defs_size"]):
|
||||
o = self.header["class_defs_off"] + i * 32
|
||||
if self.type_(u32(self.d, o)) == fqcn:
|
||||
return o
|
||||
return None
|
||||
|
||||
def methods_of(self, fqcn):
|
||||
"""Yield (section, method_idx, class, name, descriptor, code_off)."""
|
||||
cd = self.find_class(fqcn)
|
||||
if cd is None:
|
||||
raise KeyError("class not found: %s" % fqcn)
|
||||
p = u32(self.d, cd + 24)
|
||||
if p == 0:
|
||||
return
|
||||
sf, p = read_uleb(self.d, p)
|
||||
inf, p = read_uleb(self.d, p)
|
||||
dm, p = read_uleb(self.d, p)
|
||||
vm, p = read_uleb(self.d, p)
|
||||
for _ in range(sf + inf): # skip field lists
|
||||
_i, p = read_uleb(self.d, p)
|
||||
_a, p = read_uleb(self.d, p)
|
||||
for section, count in (("direct", dm), ("virtual", vm)):
|
||||
running = 0
|
||||
for _ in range(count):
|
||||
diff, p = read_uleb(self.d, p)
|
||||
running += diff # indices are delta-encoded
|
||||
_acc, p = read_uleb(self.d, p)
|
||||
code_off, p = read_uleb(self.d, p)
|
||||
cls, name, desc = self.method(running)
|
||||
yield section, running, cls, name, desc, code_off
|
||||
|
||||
def find_method(self, fqcn, name, desc):
|
||||
"""Return (section, method_idx, code_off) or None."""
|
||||
for section, idx, _cls, nm, ds, code_off in self.methods_of(fqcn):
|
||||
if nm == name and ds == desc:
|
||||
return section, idx, code_off
|
||||
return None
|
||||
|
||||
def find_methods_named(self, fqcn, name):
|
||||
"""All overloads of a name -> list of (section, idx, desc, code_off)."""
|
||||
out = []
|
||||
for section, idx, _cls, nm, ds, code_off in self.methods_of(fqcn):
|
||||
if nm == name:
|
||||
out.append((section, idx, ds, code_off))
|
||||
return out
|
||||
|
||||
def class_names(self):
|
||||
for i in range(self.header["class_defs_size"]):
|
||||
o = self.header["class_defs_off"] + i * 32
|
||||
yield self.type_(u32(self.d, o))
|
||||
|
||||
# ---- code -------------------------------------------------------------
|
||||
def code_info(self, code_off):
|
||||
return {
|
||||
"registers": u16(self.d, code_off),
|
||||
"ins": u16(self.d, code_off + 2),
|
||||
"outs": u16(self.d, code_off + 4),
|
||||
"tries": u16(self.d, code_off + 6),
|
||||
"debug_info_off": u32(self.d, code_off + 8),
|
||||
"insns_size": u32(self.d, code_off + 12),
|
||||
"insns_off": code_off + 16,
|
||||
}
|
||||
|
||||
def decode(self, code_off):
|
||||
"""Yield dicts describing each instruction of one method body.
|
||||
|
||||
Callers should assert the walk ends exactly on insns_off+insns_size*2;
|
||||
landing short or long means the format table is wrong somewhere.
|
||||
"""
|
||||
info = self.code_info(code_off)
|
||||
pos = info["insns_off"]
|
||||
end = pos + info["insns_size"] * 2
|
||||
while pos < end:
|
||||
op = self.d[pos]
|
||||
units = insn_units(op, self.d, pos, end)
|
||||
if units < 1 or pos + units * 2 > end:
|
||||
return
|
||||
yield {
|
||||
"off": pos, "op": op, "units": units,
|
||||
"name": OP_NAMES.get(op, "op_%02x" % op),
|
||||
"raw": bytes(self.d[pos:pos + units * 2]),
|
||||
"registers": info["registers"],
|
||||
}
|
||||
pos += units * 2
|
||||
|
||||
def decode_all(self, code_off):
|
||||
"""Full listing as a list, plus a verdict on whether it ended cleanly."""
|
||||
insns = list(self.decode(code_off))
|
||||
info = self.code_info(code_off)
|
||||
expected = info["insns_off"] + info["insns_size"] * 2
|
||||
ended = insns[-1]["off"] + insns[-1]["units"] * 2 if insns else info["insns_off"]
|
||||
return insns, (ended == expected), expected
|
||||
|
||||
def insn_at(self, code_off, target_off):
|
||||
for insn in self.decode(code_off):
|
||||
if insn["off"] == target_off:
|
||||
return insn
|
||||
return None
|
||||
|
||||
# ---- operand helpers --------------------------------------------------
|
||||
def branch_target(self, insn):
|
||||
"""Absolute target of a branch, or None if the instruction is not one."""
|
||||
op, pos, raw = insn["op"], insn["off"], insn["raw"]
|
||||
if op in IF_TEST or op in IF_TESTZ:
|
||||
return pos + s16(u16(self.d, pos + 2)) * 2
|
||||
if op == 0x27: # goto (10t, signed byte)
|
||||
off = raw[1]
|
||||
if off > 127:
|
||||
off -= 256
|
||||
return pos + off * 2
|
||||
if op == 0x28:
|
||||
return pos + s16(u16(self.d, pos + 2)) * 2
|
||||
if op == 0x29:
|
||||
off = u32(self.d, pos + 2)
|
||||
if off > 0x7FFFFFFF:
|
||||
off -= 0x100000000
|
||||
return pos + off * 2
|
||||
return None
|
||||
|
||||
def branch_regs(self, insn):
|
||||
"""(regs_read, kind) for a conditional branch."""
|
||||
if insn["op"] in IF_TEST:
|
||||
return [insn["raw"][1] >> 4, insn["raw"][1] & 0xF], "if-test"
|
||||
if insn["op"] in IF_TESTZ:
|
||||
return [insn["raw"][1] & 0xF], "if-testz"
|
||||
return [], None
|
||||
|
||||
def all_targets(self, code_off):
|
||||
"""Set of every absolute branch target in one method."""
|
||||
targets = set()
|
||||
for insn in self.decode(code_off):
|
||||
t = self.branch_target(insn)
|
||||
if t is not None:
|
||||
targets.add(t)
|
||||
return targets
|
||||
|
||||
# ---- description ------------------------------------------------------
|
||||
def describe(self, insn):
|
||||
"""One-line human rendering with resolved field/method/string names."""
|
||||
op, pos, raw = insn["op"], insn["off"], insn["raw"]
|
||||
text = "0x%x: %-14s %s" % (pos, raw.hex(), insn["name"])
|
||||
if op in IF_TEST:
|
||||
text += " v%d,v%d -> 0x%x" % (raw[1] >> 4, raw[1] & 0xF,
|
||||
self.branch_target(insn))
|
||||
elif op in IF_TESTZ:
|
||||
text += " v%d -> 0x%x" % (raw[1] & 0xF, self.branch_target(insn))
|
||||
elif op in (0x27, 0x28, 0x29):
|
||||
text += " -> 0x%x" % self.branch_target(insn)
|
||||
elif op in IFIELD_OPS:
|
||||
cls, nm, ty = self.field(u16(self.d, pos + 2))
|
||||
text += " v%d <- v%d.%s:%s" % (raw[1] & 0xF, raw[1] >> 4, nm, ty)
|
||||
elif op in PFIELD_OPS:
|
||||
cls, nm, ty = self.field(u16(self.d, pos + 2))
|
||||
text += " v%d -> v%d.%s:%s" % (raw[1] & 0xF, raw[1] >> 4, nm, ty)
|
||||
elif op in SFIELD_OPS:
|
||||
cls, nm, ty = self.field(u16(self.d, pos + 2))
|
||||
text += " %s.%s:%s" % (cls, nm, ty)
|
||||
elif op in INVOKE_OPS:
|
||||
cls, nm, ds = self.method(u16(self.d, pos + 2))
|
||||
text += " %s.%s%s" % (cls, nm, ds)
|
||||
elif op in (0x19, 0x1A):
|
||||
# Both forms carry the string index as a uint16 at byte offset 2.
|
||||
# Reading a uint32 here gives a huge index that walks off the table.
|
||||
text += ' "%s"' % self.string_safe(u16(self.d, pos + 2))
|
||||
elif op == 0x12:
|
||||
lit = raw[1] & 0xF
|
||||
text += " v%d, %d" % (raw[1] >> 4, lit - 16 if lit > 7 else lit)
|
||||
return text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# dex header integrity
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def fix_dex_header(data):
|
||||
"""Recompute a dex header's checksum and signature IN THE CORRECT ORDER.
|
||||
|
||||
Order is not cosmetic:
|
||||
bytes 12..32 = sha1(data[32:]) -- signature first
|
||||
bytes 8..12 = adler32(data[12:]) -- checksum last, covers the signature
|
||||
|
||||
Reversed, the adler32 is taken while the signature field is still zeroed, so
|
||||
the header never verifies. Android logs
|
||||
`Failure to verify dex file ...: Bad checksum (computed, expected)` -- the
|
||||
real value shows up as "expected" -- and falls back to interpreting the dex,
|
||||
which can surface as an unrelated ClassNotFoundException at startup.
|
||||
|
||||
Accepts and returns a bytearray; also returns the before/after values so a
|
||||
caller can print them.
|
||||
"""
|
||||
before_checksum = int.from_bytes(data[8:12], "little")
|
||||
before_signature = bytes(data[12:32])
|
||||
|
||||
data[12:32] = hashlib.sha1(bytes(data[32:])).digest()
|
||||
after_signature = bytes(data[12:32])
|
||||
|
||||
import zlib
|
||||
after_checksum = zlib.adler32(bytes(data[12:])) & 0xFFFFFFFF
|
||||
data[8:12] = after_checksum.to_bytes(4, "little")
|
||||
|
||||
return {
|
||||
"before_checksum": before_checksum, "after_checksum": after_checksum,
|
||||
"before_signature": before_signature, "after_signature": after_signature,
|
||||
}
|
||||
|
||||
|
||||
def verify_dex_header(data):
|
||||
"""Return (checksum_ok, signature_ok) for a bytearray/bytes dex."""
|
||||
import zlib
|
||||
stored_c = int.from_bytes(data[8:12], "little")
|
||||
calc_c = zlib.adler32(bytes(data[12:])) & 0xFFFFFFFF
|
||||
return stored_c == calc_c, bytes(data[12:32]) == hashlib.sha1(bytes(data[32:])).digest()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# loading
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def load_dex(source, entry=None):
|
||||
"""Load a Dex from a .dex path, an .apk/.zip path, or raw bytes.
|
||||
|
||||
For an archive, `entry` picks a member (default: the first classes*.dex).
|
||||
Returns (Dex, entry_name).
|
||||
"""
|
||||
if isinstance(source, (bytes, bytearray)):
|
||||
return Dex(bytes(source), entry or "<bytes>"), entry or "<bytes>"
|
||||
path = str(source)
|
||||
if path.lower().endswith((".apk", ".zip", ".jar", ".xapk", ".apks", ".apkm")):
|
||||
with zipfile.ZipFile(path) as z:
|
||||
if entry:
|
||||
return Dex(z.read(entry), entry), entry
|
||||
candidates = sorted(n for n in z.namelist()
|
||||
if n.startswith("classes") and n.endswith(".dex"))
|
||||
if not candidates:
|
||||
raise ValueError("no classes*.dex in %s" % path)
|
||||
name = candidates[0]
|
||||
return Dex(z.read(name), name), name
|
||||
with open(path, "rb") as fh:
|
||||
return Dex(fh.read(), path), path
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 5:
|
||||
print(__doc__)
|
||||
return 2
|
||||
target, fqcn, name, desc = argv[1:5]
|
||||
dex, entry = load_dex(target)
|
||||
print("== %s (entry %s, %d bytes)" % (target, entry, len(dex.d)))
|
||||
problems = dex.check()
|
||||
for p in problems:
|
||||
print(" [structure] %s" % p)
|
||||
if problems:
|
||||
print(" refusing to continue on a structurally broken read")
|
||||
return 1
|
||||
|
||||
found = dex.find_method(fqcn, name, desc)
|
||||
if not found:
|
||||
print("method not found: %s->%s%s" % (fqcn, name, desc))
|
||||
print("methods in class:")
|
||||
for section, idx, _c, nm, ds, code_off in dex.methods_of(fqcn):
|
||||
print(" [%s] %s%s code_off=0x%x" % (section, nm, ds, code_off))
|
||||
return 1
|
||||
|
||||
section, idx, code_off = found
|
||||
info = dex.code_info(code_off)
|
||||
insns, clean, expected = dex.decode_all(code_off)
|
||||
print("== %s.%s%s [%s] method_idx=%d" % (fqcn, name, desc, section, idx))
|
||||
print(" code_off=0x%x insns_off=0x%x insns_size=%d registers=%d"
|
||||
% (code_off, info["insns_off"], info["insns_size"], info["registers"]))
|
||||
print(" decoded %d instructions; ended cleanly: %s" % (len(insns), clean))
|
||||
if not clean:
|
||||
print(" WARNING: decode did not land on 0x%x -- offsets below are suspect"
|
||||
% expected)
|
||||
|
||||
regs = info["registers"]
|
||||
over = [i for i in insns if _max_reg(i) >= regs]
|
||||
if over:
|
||||
print(" WARNING: %d instruction(s) reference a register >= %d; "
|
||||
"desync likely" % (len(over), regs))
|
||||
|
||||
targets = dex.all_targets(code_off)
|
||||
print(" branch targets: %s" % ", ".join(sorted("0x%x" % t for t in targets)))
|
||||
print("-- listing --")
|
||||
for insn in insns:
|
||||
mark = " <== branch target" if insn["off"] in targets else ""
|
||||
print(" " + dex.describe(insn) + mark)
|
||||
return 0
|
||||
|
||||
|
||||
def _max_reg(insn):
|
||||
"""Highest register number named by an instruction (rough but sufficient)."""
|
||||
raw, op = insn["raw"], insn["op"]
|
||||
if op in IF_TEST or op in IFIELD_OPS or op in PFIELD_OPS:
|
||||
return max(raw[1] >> 4, raw[1] & 0xF)
|
||||
if op in IF_TESTZ:
|
||||
return raw[1] & 0xF
|
||||
if op == 0x12:
|
||||
return raw[1] >> 4
|
||||
if op in (0x01, 0x04, 0x07, 0x0A, 0x0B, 0x0C, 0x0D, 0x0F, 0x10, 0x11,
|
||||
0x1C, 0x1D, 0x1E):
|
||||
return raw[1] & 0xF
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
@@ -0,0 +1,428 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Environment doctor: what can actually run here, and what is missing.
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
This skill ships a lot of scripts, and the most common failure mode reported by
|
||||
users is not "the script is wrong" but "the script would not start and I could not
|
||||
tell why" - a missing jar, a Python module that does not exist on this interpreter,
|
||||
a device that is not connected. That wastes a whole round before any reverse
|
||||
engineering happens.
|
||||
|
||||
Run this once before a work block. It answers three questions:
|
||||
|
||||
1. Which capabilities are available right now (static / native / dynamic / device)?
|
||||
2. For every script, is it runnable as-is, or what exactly is missing?
|
||||
3. Are there environment facts that will silently poison experiments
|
||||
(clock skew, a leftover proxy, a dead device server, a wrong-ABI device)?
|
||||
|
||||
It never installs anything and never touches a target. Read the report, then go.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python doctor.py # short capability report
|
||||
python doctor.py --scripts # per-script runnability table
|
||||
python doctor.py --device <serial> # include device checks
|
||||
python doctor.py --json # machine-readable
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# ---------------------------------------------------------------- probing
|
||||
|
||||
def extra_tool_dirs():
|
||||
"""Directories to search beyond PATH.
|
||||
|
||||
Tools like jadx and apktool are frequently installed into a project-local or
|
||||
versioned directory and invoked by full path, so a pure PATH probe reports them
|
||||
missing and the capability table lies. Point APKREV_TOOLS at one or more
|
||||
directories (os.pathsep-separated) and they are searched too.
|
||||
"""
|
||||
dirs = []
|
||||
env = os.environ.get('APKREV_TOOLS')
|
||||
if env:
|
||||
dirs.extend(d for d in env.split(os.pathsep) if d)
|
||||
# a tools/ dir beside the skill is a common convention and safe to probe
|
||||
dirs.append(os.path.join(os.path.dirname(HERE), 'tools'))
|
||||
return [d for d in dirs if os.path.isdir(d)]
|
||||
|
||||
|
||||
def which(name: str):
|
||||
hit = shutil.which(name)
|
||||
if hit:
|
||||
return hit
|
||||
exts = ['']
|
||||
if os.name == 'nt':
|
||||
exts = ['.exe', '.bat', '.cmd', '.ps1', '']
|
||||
for d in extra_tool_dirs():
|
||||
for root, _dirs, files in os.walk(d):
|
||||
if root.count(os.sep) - d.count(os.sep) > 3:
|
||||
continue
|
||||
for f in files:
|
||||
stem, ext = os.path.splitext(f)
|
||||
if stem.lower() == name.lower() and ext.lower() in exts:
|
||||
return os.path.join(root, f)
|
||||
return None
|
||||
|
||||
|
||||
def run(cmd, timeout=15):
|
||||
"""Run a command, returning (rc, stdout+stderr). Never raises, always bounded."""
|
||||
try:
|
||||
p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
||||
timeout=timeout)
|
||||
return p.returncode, p.stdout.decode('utf-8', 'replace').strip()
|
||||
except FileNotFoundError:
|
||||
return 127, 'not found'
|
||||
except subprocess.TimeoutExpired:
|
||||
return 124, 'TIMEOUT after %ss' % timeout
|
||||
except Exception as e: # pragma: no cover
|
||||
return 1, '%s: %s' % (type(e).__name__, e)
|
||||
|
||||
|
||||
def have_module(name: str) -> bool:
|
||||
try:
|
||||
return importlib.util.find_spec(name) is not None
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- capability matrix
|
||||
|
||||
def python_info():
|
||||
v = sys.version_info
|
||||
ok = (v.major, v.minor) >= (3, 9)
|
||||
return {
|
||||
'version': '%d.%d.%d' % (v.major, v.minor, v.micro),
|
||||
'ok': ok,
|
||||
'note': '' if ok else 'scripts target 3.9+; older interpreters may fail on syntax',
|
||||
}
|
||||
|
||||
|
||||
def tool_info():
|
||||
"""name -> (found_path, version_string)"""
|
||||
out = {}
|
||||
probes = [
|
||||
('java', ['java', '-version']),
|
||||
('javac', ['javac', '-version']),
|
||||
('adb', ['adb', 'version']),
|
||||
('frida', ['frida', '--version']),
|
||||
('frida-ps', ['frida-ps', '--version']),
|
||||
('objection', ['objection', '--version']),
|
||||
('apktool', ['apktool', '--version']),
|
||||
('jadx', ['jadx', '--version']),
|
||||
('python', [sys.executable, '--version']),
|
||||
('unzip', ['unzip', '-v']),
|
||||
('git', ['git', '--version']),
|
||||
('sqlite3', ['sqlite3', '--version']),
|
||||
('node', ['node', '--version']),
|
||||
('tshark', ['tshark', '-v']),
|
||||
('mitmdump', ['mitmdump', '--version']),
|
||||
('rizin', ['rizin', '-v']),
|
||||
('rabin2', ['rabin2', '-v']),
|
||||
('gdb', ['gdb', '--version']),
|
||||
('readelf', ['readelf', '--version']),
|
||||
('adb-devices', ['adb', 'devices']),
|
||||
]
|
||||
for name, cmd in probes:
|
||||
if which(cmd[0]) is None and cmd[0] != sys.executable:
|
||||
# A tool that ships as a runnable .jar is not on PATH but is still usable
|
||||
# via `java -jar`. Reporting it as missing makes the capability table lie.
|
||||
jar_hit = None
|
||||
for d in [HERE, os.path.dirname(HERE)] + extra_tool_dirs():
|
||||
if not os.path.isdir(d):
|
||||
continue
|
||||
for root, _dirs, files in os.walk(d):
|
||||
if root.count(os.sep) - d.count(os.sep) > 3:
|
||||
continue
|
||||
for f in files:
|
||||
if f.lower() == (name + '.jar').lower():
|
||||
jar_hit = os.path.join(root, f)
|
||||
break
|
||||
if jar_hit:
|
||||
break
|
||||
if jar_hit:
|
||||
break
|
||||
if jar_hit:
|
||||
out[name] = {'path': jar_hit,
|
||||
'version': 'runnable as: java -jar %s' % os.path.basename(jar_hit),
|
||||
'note': 'jar-only (not a PATH command)'}
|
||||
else:
|
||||
out[name] = {'path': None, 'version': None, 'note': 'not on PATH'}
|
||||
continue
|
||||
rc, txt = run(cmd)
|
||||
first = ''
|
||||
for line in txt.splitlines():
|
||||
line = line.strip()
|
||||
if line:
|
||||
first = line
|
||||
break
|
||||
out[name] = {
|
||||
'path': which(cmd[0]) or cmd[0],
|
||||
'version': first[:160],
|
||||
'note': '' if rc == 0 else 'exit %d: %s' % (rc, txt[:120]),
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
# jar/libraries the dex tooling needs; kept as a list so doctor can name them
|
||||
JAR_HINTS = ['baksmali', 'smali', 'dexlib2', 'apksigner', 'uber-apk-signer', 'd2j']
|
||||
|
||||
|
||||
def java_toolchain():
|
||||
"""Find the jars a smali round-trip needs, wherever they live."""
|
||||
found = {}
|
||||
roots = [os.path.join(HERE, 'dexpatch'), HERE,
|
||||
os.path.join(HERE, 'libs'), os.path.join(HERE, 'jar')]
|
||||
extra = os.environ.get('APKREV_JARS')
|
||||
if extra:
|
||||
roots.extend(extra.split(os.pathsep))
|
||||
for r in roots:
|
||||
if not os.path.isdir(r):
|
||||
continue
|
||||
for dirpath, _dirs, files in os.walk(r):
|
||||
for f in files:
|
||||
if f.lower().endswith('.jar'):
|
||||
found.setdefault(f, os.path.join(dirpath, f))
|
||||
return found
|
||||
|
||||
|
||||
def script_dependencies():
|
||||
"""Static, best-effort dependency map: script -> (required_modules, required_bins)."""
|
||||
return {
|
||||
'smtool.py': ([], ['java']),
|
||||
'patch_smali.py': ([], []),
|
||||
'find_refs.py': ([], []),
|
||||
'dex_strings.py': ([], []),
|
||||
'dex_classdiff.py': ([], []),
|
||||
'dex_strpatch.py': ([], []),
|
||||
'repack.py': ([], ['java']),
|
||||
'install_test.py': ([], ['adb']),
|
||||
'preflight.py': ([], ['adb']),
|
||||
'lib_map.py': ([], ['adb']),
|
||||
'apk_diff.py': ([], []),
|
||||
'snap.py': ([], ['adb']),
|
||||
'native_crash.py': ([], []),
|
||||
'grab_crash.py': ([], ['adb']),
|
||||
'blob_decode.py': ([], []),
|
||||
'datastore_inject.py': ([], []),
|
||||
'sig_probe.py': ([], ['java']),
|
||||
'probe_api.py': ([], []),
|
||||
'tls_check.py': ([], []),
|
||||
'usb_net_proxy.py': ([], ['adb']),
|
||||
'devsh.py': ([], ['adb']),
|
||||
'elf_plt.py': ([], []),
|
||||
'so_constpatch.py': ([], []),
|
||||
'dart_pool_strings.py': ([], []),
|
||||
'dart_pprefs.py': ([], []),
|
||||
'dart_disasm.py': ([], []),
|
||||
'run_probe.py': (['frida'], ['adb']),
|
||||
'frida_probe.js': ([], []), # needs a frida host, checked separately
|
||||
}
|
||||
|
||||
|
||||
def script_report(tools, jars):
|
||||
deps = script_dependencies()
|
||||
rows = []
|
||||
for name in sorted(deps):
|
||||
path = os.path.join(HERE, name)
|
||||
mods, bins = deps[name]
|
||||
missing_mods = [m for m in mods if not have_module(m)]
|
||||
missing_bins = [b for b in bins if which(b) is None]
|
||||
# scripts that shell out to the frida host
|
||||
if name in ('run_probe.py', 'frida_probe.js') and which('frida') is None:
|
||||
if 'frida' not in missing_bins:
|
||||
missing_bins.append('frida')
|
||||
ok = os.path.isfile(path) and not missing_mods and not missing_bins
|
||||
rows.append({
|
||||
'script': name,
|
||||
'present': os.path.isfile(path),
|
||||
'runnable': ok,
|
||||
'missing': missing_mods + missing_bins,
|
||||
})
|
||||
return rows, deps
|
||||
|
||||
|
||||
def device_report(serial=None):
|
||||
if which('adb') is None:
|
||||
return {'available': False, 'reason': 'adb not on PATH'}
|
||||
cmd = ['adb'] + (['-s', serial] if serial else []) + ['devices', '-l']
|
||||
rc, txt = run(cmd, timeout=20)
|
||||
if rc != 0:
|
||||
return {'available': False, 'reason': txt[:200]}
|
||||
devices = []
|
||||
for line in txt.splitlines()[1:]:
|
||||
line = line.strip()
|
||||
if not line or line.startswith('*'):
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) >= 2:
|
||||
devices.append({'serial': parts[0], 'state': parts[1],
|
||||
'info': ' '.join(parts[2:])[:160]})
|
||||
out = {'available': True, 'devices': devices, 'raw': txt[:400]}
|
||||
if not devices:
|
||||
out['reason'] = 'no device/emulator attached'
|
||||
return out
|
||||
|
||||
tgt = serial or devices[0]['serial']
|
||||
props = {}
|
||||
for key in ('ro.product.cpu.abi', 'ro.product.cpu.abilist', 'ro.build.version.release',
|
||||
'ro.build.version.sdk', 'ro.product.model'):
|
||||
rc, v = run(['adb', '-s', tgt, 'shell', 'getprop', key], timeout=15)
|
||||
props[key] = v if rc == 0 else ''
|
||||
out['target'] = tgt
|
||||
out['props'] = props
|
||||
|
||||
# root?
|
||||
rc, v = run(['adb', '-s', tgt, 'shell', 'su -c id'], timeout=15)
|
||||
out['root'] = (rc == 0 and 'uid=0' in v)
|
||||
out['root_raw'] = v[:120]
|
||||
|
||||
# clock skew: a classic silent experiment-poisoner
|
||||
rc, dev_epoch = run(['adb', '-s', tgt, 'shell', 'date +%s'], timeout=15)
|
||||
try:
|
||||
dev_t = int(dev_epoch.strip())
|
||||
out['clock_skew_s'] = abs(time.time() - dev_t)
|
||||
except Exception:
|
||||
out['clock_skew_s'] = None
|
||||
|
||||
# leftover forwards and proxies
|
||||
rc, fwd = run(['adb', '-s', tgt, 'forward', '--list'], timeout=15)
|
||||
out['forwards'] = [l for l in fwd.splitlines() if l.strip()][:10]
|
||||
rc, prox = run(['adb', '-s', tgt, 'shell', 'settings get global http_proxy'], timeout=15)
|
||||
out['http_proxy'] = prox.strip()[:120]
|
||||
|
||||
# is a frida server already running on device? (a common source of "the app
|
||||
# suddenly detects instrumentation" while you believe nothing is attached)
|
||||
rc, ps = run(['adb', '-s', tgt, 'shell', 'ps -A'], timeout=20)
|
||||
hits = [l for l in ps.splitlines()
|
||||
if 'frida' in l.lower() and 'grep' not in l.lower()]
|
||||
out['device_frida_processes'] = [h.strip()[:140] for h in hits[:6]]
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- reporting
|
||||
|
||||
def capability_summary(tools, dev, py):
|
||||
caps = {}
|
||||
caps['static (dex/zip/strings)'] = py['ok']
|
||||
caps['repack + sign'] = bool(tools['java']['path']) and py['ok']
|
||||
caps['smali round-trip'] = bool(tools['java']['path']) and py['ok']
|
||||
caps['native ELF patching'] = py['ok']
|
||||
caps['jadx decompile'] = bool(tools['jadx']['path'])
|
||||
caps['apktool unpack'] = bool(tools['apktool']['path'])
|
||||
caps['device work'] = bool(dev.get('available') and dev.get('devices'))
|
||||
caps['root on device'] = bool(dev.get('root'))
|
||||
caps['frida dynamic'] = bool(tools['frida']['path'])
|
||||
caps['emulator/home'] = bool(tools['adb']['path'])
|
||||
return caps
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description='Check what this environment can actually do.')
|
||||
ap.add_argument('--device', default=None, metavar='SERIAL', help='probe this device')
|
||||
ap.add_argument('--scripts', action='store_true', help='per-script runnability table')
|
||||
ap.add_argument('--json', action='store_true', help='emit JSON')
|
||||
args = ap.parse_args()
|
||||
|
||||
py = python_info()
|
||||
tools = tool_info()
|
||||
jars = java_toolchain()
|
||||
dev = device_report(args.device)
|
||||
rows, _deps = script_report(tools, jars)
|
||||
caps = capability_summary(tools, dev, py)
|
||||
|
||||
if args.json:
|
||||
print(json.dumps({'python': py, 'tools': tools, 'jars': jars,
|
||||
'device': dev, 'capabilities': caps, 'scripts': rows},
|
||||
indent=2, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
print('=' * 74)
|
||||
print('apk-reverse environment doctor')
|
||||
print('=' * 74)
|
||||
print('platform : %s %s / %s' % (platform.system(), platform.release(), platform.machine()))
|
||||
print('python : %s %s' % (py['version'], '' if py['ok'] else '<-- ' + py['note']))
|
||||
|
||||
print('\n--- capabilities ---')
|
||||
for k, v in caps.items():
|
||||
print(' [%s] %s' % ('OK ' if v else '-- ', k))
|
||||
|
||||
print('\n--- tools ---')
|
||||
for name, info in tools.items():
|
||||
if name in ('adb-devices',):
|
||||
continue
|
||||
mark = 'OK ' if info['path'] else '-- '
|
||||
ver = info['version'] or info['note']
|
||||
print(' [%s] %-12s %s' % (mark, name, (ver or '')[:96]))
|
||||
|
||||
print('\n--- java jars found near this skill ---')
|
||||
if jars:
|
||||
for k, v in sorted(jars.items()):
|
||||
print(' %s' % k)
|
||||
else:
|
||||
print(' (none) - a smali round-trip needs baksmali/smali/dexlib2 jars.')
|
||||
print(' Set APKREV_JARS=<dir-with-jars> to point this script at them.')
|
||||
|
||||
print('\n--- device ---')
|
||||
if not dev.get('available'):
|
||||
print(' unavailable: %s' % dev.get('reason'))
|
||||
elif not dev.get('devices'):
|
||||
print(' no device attached (adb works)')
|
||||
else:
|
||||
print(' target : %s' % dev.get('target'))
|
||||
for k, v in (dev.get('props') or {}).items():
|
||||
print(' %-9s: %s' % (k.replace('ro.', ''), v))
|
||||
print(' root : %s' % ('yes' if dev.get('root') else 'no'))
|
||||
skew = dev.get('clock_skew_s')
|
||||
if skew is not None:
|
||||
flag = ' <-- FIX THIS, clock drift poisons time-based checks' if skew > 30 else ''
|
||||
print(' clock skew: %ss%s' % (skew, flag))
|
||||
if dev.get('forwards'):
|
||||
print(' leftovers : adb forward entries still present: %s' % dev['forwards'])
|
||||
if dev.get('http_proxy', '').strip() not in ('', 'null', ':0'):
|
||||
print(' leftovers : device http_proxy = %s' % dev['http_proxy'])
|
||||
if dev.get('device_frida_processes'):
|
||||
print(' WARNING : a frida process is already running on device:')
|
||||
for p in dev['device_frida_processes']:
|
||||
print(' %s' % p)
|
||||
print(' If the target dies only while this is up, you are looking at')
|
||||
print(' a probe aimed at YOU. Stop it before concluding anything.')
|
||||
|
||||
if args.scripts:
|
||||
print('\n--- scripts ---')
|
||||
ready = [r for r in rows if r['runnable']]
|
||||
notready = [r for r in rows if not r['runnable']]
|
||||
for r in ready:
|
||||
print(' [OK ] %s' % r['script'])
|
||||
for r in notready:
|
||||
why = []
|
||||
if not r['present']:
|
||||
why.append('file missing')
|
||||
if r['missing']:
|
||||
why.append('missing: ' + ', '.join(r['missing']))
|
||||
print(' [-- ] %-24s %s' % (r['script'], '; '.join(why)))
|
||||
print('\n runnable: %d / %d' % (len(ready), len(rows)))
|
||||
else:
|
||||
ready = sum(1 for r in rows if r['runnable'])
|
||||
print('\n scripts runnable here: %d / %d (use --scripts for the table)'
|
||||
% (ready, len(rows)))
|
||||
|
||||
print('\nRead references/long-task-discipline.md before a long block:')
|
||||
print(' bound every wait, look at the screen while you wait, and record the '
|
||||
'time-to-death before patching.')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,457 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PLT stub -> imported symbol mapping, and byte-level .so diffing.
|
||||
|
||||
Built for hardened/rebuilt native libraries where the usual paths lie:
|
||||
* section headers are often forged, so tools that walk sections (readelf -x,
|
||||
objdump -d on named sections, pyelftools' section API) return confidently
|
||||
wrong or empty results;
|
||||
* a linear disassembler can stop silently on a buffer that does not start at
|
||||
an instruction boundary, so "no matches" from it is not evidence.
|
||||
|
||||
Therefore this tool walks PT_LOAD / PT_DYNAMIC by hand and decodes the two
|
||||
stub shapes with its own decoders (no capstone dependency, no silent stops).
|
||||
|
||||
Why you need the stub -> symbol map: when a hardening library terminates the
|
||||
process, it does so through a PLT stub. To suppress it safely you must know
|
||||
*which* symbol a given stub resolves to -- inferring from position or from a
|
||||
comment is how you end up freezing `snprintf` or `pthread_exit` and reporting
|
||||
it as "the patch did not work".
|
||||
|
||||
Usage
|
||||
-----
|
||||
# full stub table
|
||||
python elf_plt.py libfoo.so
|
||||
|
||||
# what do these stubs call?
|
||||
python elf_plt.py libfoo.so --query 0x9920 0x9950
|
||||
|
||||
# find the stub for one symbol (and every caller of it)
|
||||
python elf_plt.py libfoo.so --symbol kill --callers
|
||||
|
||||
# what changed between the original and a rebuilt library?
|
||||
python elf_plt.py original.so --diff rebuilt.so
|
||||
|
||||
# same, but also name the symbol each changed stub belongs to
|
||||
python elf_plt.py original.so --diff rebuilt.so --name-regions
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
PT_LOAD = 1
|
||||
PT_DYNAMIC = 2
|
||||
|
||||
DT_PLTRELSZ = 2
|
||||
DT_PLTGOT = 3
|
||||
DT_STRTAB = 5
|
||||
DT_SYMTAB = 6
|
||||
DT_RELA = 7
|
||||
DT_RELASZ = 8
|
||||
DT_STRSZ = 10
|
||||
DT_SYMENT = 11
|
||||
DT_PLTREL = 20
|
||||
DT_JMPREL = 23
|
||||
|
||||
EM_X86_64 = 62
|
||||
EM_AARCH64 = 183
|
||||
|
||||
ARCH_NAME = {EM_X86_64: "x86_64", EM_AARCH64: "aarch64"}
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# ELF parsing (program headers only -- never trust the section table here)
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
class Elf:
|
||||
def __init__(self, data, path=""):
|
||||
self.data = data
|
||||
self.path = path
|
||||
if data[:4] != b"\x7fELF":
|
||||
raise ValueError("not an ELF file")
|
||||
if data[4] != 2:
|
||||
raise ValueError("only 64-bit ELF is supported")
|
||||
self.machine = struct.unpack_from("<H", data, 18)[0]
|
||||
self.phoff = struct.unpack_from("<Q", data, 32)[0]
|
||||
self.phentsize = struct.unpack_from("<H", data, 54)[0]
|
||||
self.phnum = struct.unpack_from("<H", data, 56)[0]
|
||||
self.loads = [] # (vaddr, offset, filesz, memsz, flags)
|
||||
self.dynamic = None # (offset, size)
|
||||
self.gnu_eh_frame = None
|
||||
for i in range(self.phnum):
|
||||
off = self.phoff + i * self.phentsize
|
||||
p_type, p_flags = struct.unpack_from("<II", data, off)
|
||||
p_offset, p_vaddr, _pa, p_filesz, p_memsz, _al = struct.unpack_from(
|
||||
"<QQQQQQ", data, off + 8)
|
||||
if p_type == PT_LOAD:
|
||||
self.loads.append((p_vaddr, p_offset, p_filesz, p_memsz, p_flags))
|
||||
elif p_type == PT_DYNAMIC:
|
||||
self.dynamic = (p_offset, p_filesz)
|
||||
elif p_type == 0x6474e550:
|
||||
self.gnu_eh_frame = (p_vaddr, p_filesz)
|
||||
|
||||
@property
|
||||
def arch(self):
|
||||
return ARCH_NAME.get(self.machine, "machine=%d" % self.machine)
|
||||
|
||||
def exec_segment(self):
|
||||
for seg in self.loads:
|
||||
if seg[4] & 1:
|
||||
return seg
|
||||
raise ValueError("no executable PT_LOAD segment")
|
||||
|
||||
def vaddr_to_off(self, vaddr):
|
||||
for va, fo, _fs, ms, _fl in self.loads:
|
||||
if va <= vaddr < va + ms:
|
||||
return fo + (vaddr - va)
|
||||
return None
|
||||
|
||||
def dynamic_tags(self):
|
||||
if self.dynamic is None:
|
||||
raise ValueError("no PT_DYNAMIC segment")
|
||||
tags = {}
|
||||
off, size = self.dynamic
|
||||
for j in range(size // 16):
|
||||
t, v = struct.unpack_from("<qQ", self.data, off + j * 16)
|
||||
if t == 0:
|
||||
break
|
||||
tags[t] = v
|
||||
return tags
|
||||
|
||||
|
||||
def reloc_map(elf):
|
||||
"""{GOT vaddr: imported symbol name} from DT_JMPREL (+ DT_RELA when present)."""
|
||||
tags = elf.dynamic_tags()
|
||||
if DT_STRTAB not in tags or DT_SYMTAB not in tags:
|
||||
return {}
|
||||
strtab_o = elf.vaddr_to_off(tags[DT_STRTAB])
|
||||
symtab_o = elf.vaddr_to_off(tags[DT_SYMTAB])
|
||||
strsz = tags.get(DT_STRSZ, 0)
|
||||
if strtab_o is None or symtab_o is None:
|
||||
return {}
|
||||
|
||||
def symname(idx):
|
||||
so = symtab_o + idx * 24
|
||||
if so + 4 > len(elf.data):
|
||||
return "?"
|
||||
(st_name,) = struct.unpack_from("<I", elf.data, so)
|
||||
if st_name >= strsz:
|
||||
return "?"
|
||||
start = strtab_o + st_name
|
||||
end = elf.data.find(b"\x00", start)
|
||||
if end < 0:
|
||||
return "?"
|
||||
return elf.data[start:end].decode("utf-8", "replace")
|
||||
|
||||
out = {}
|
||||
for tag_off, tag_sz in ((DT_JMPREL, DT_PLTRELSZ), (DT_RELA, DT_RELASZ)):
|
||||
if tag_off not in tags:
|
||||
continue
|
||||
base = elf.vaddr_to_off(tags[tag_off])
|
||||
if base is None:
|
||||
continue
|
||||
n = tags.get(tag_sz, 0) // 24
|
||||
for k in range(n):
|
||||
if base + k * 24 + 16 > len(elf.data):
|
||||
break
|
||||
r_offset, r_info = struct.unpack_from("<QQ", elf.data, base + k * 24)
|
||||
out[r_offset] = symname(r_info >> 32)
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Stub decoders -- written out rather than delegated, so nothing stops early
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def find_stubs(elf, relocs):
|
||||
"""{stub_vaddr: (symbol, got_vaddr)} for the library's stub table."""
|
||||
base, foff, fsz, _ms, _fl = elf.exec_segment()
|
||||
if elf.machine == EM_X86_64:
|
||||
return _stubs_x86(elf.data, base, foff, fsz, relocs)
|
||||
if elf.machine == EM_AARCH64:
|
||||
return _stubs_arm64(elf.data, base, foff, fsz, relocs)
|
||||
return {}
|
||||
|
||||
|
||||
def _stubs_x86(data, base, foff, fsz, relocs):
|
||||
"""x86_64 PLT stub: `ff 25 <disp32>` == jmp qword ptr [rip+disp32]."""
|
||||
out = {}
|
||||
i = 0
|
||||
while i < fsz - 6:
|
||||
if data[foff + i] == 0xFF and data[foff + i + 1] == 0x25:
|
||||
disp = struct.unpack_from("<i", data, foff + i + 2)[0]
|
||||
va = base + i
|
||||
target = va + 6 + disp
|
||||
if target in relocs:
|
||||
out[va] = (relocs[target], target)
|
||||
i += 1
|
||||
return out
|
||||
|
||||
|
||||
def _stubs_arm64(data, base, foff, fsz, relocs):
|
||||
"""aarch64 PLT stub: adrp x16 / ldr x17,[x16,#off] / add x16,x16,#off / br x17.
|
||||
|
||||
Note the stub is FOUR instructions (16 bytes), not four bytes. Assuming the
|
||||
shorter form leads to "borrowing" the next slot, which belongs to a
|
||||
different symbol.
|
||||
"""
|
||||
out = {}
|
||||
off = 0
|
||||
while off < fsz - 16:
|
||||
w0, w1, w2, w3 = struct.unpack_from("<IIII", data, foff + off)
|
||||
dec = _decode_adrp(w0, base + off)
|
||||
if dec is not None:
|
||||
page, rd0 = dec
|
||||
ldr = _decode_ldr_unsigned(w1)
|
||||
add = _decode_add_imm(w2)
|
||||
br = _decode_br(w3)
|
||||
if (ldr is not None and add is not None and br is not None
|
||||
and rd0 == 16 and ldr[0] == 16 and ldr[1] == 17
|
||||
and add[0] == 16 and add[1] == 16
|
||||
and ldr[2] == add[2] and br == 17):
|
||||
got = page + add[2]
|
||||
if got in relocs:
|
||||
out[base + off] = (relocs[got], got)
|
||||
off += 4
|
||||
return out
|
||||
|
||||
|
||||
def _sign_extend(value, bits):
|
||||
if value & (1 << (bits - 1)):
|
||||
value -= (1 << bits)
|
||||
return value
|
||||
|
||||
|
||||
def _decode_adrp(word, pc):
|
||||
"""adrp Rd, #imm -> (target_page, Rd). None if not an adrp."""
|
||||
if (word >> 31) & 1 != 1:
|
||||
return None
|
||||
if ((word >> 24) & 0x1F) != 0x10:
|
||||
return None
|
||||
immlo = (word >> 29) & 0x3
|
||||
immhi = (word >> 5) & 0x7FFFF
|
||||
imm = (immhi << 2) | immlo
|
||||
imm = _sign_extend(imm, 21)
|
||||
return (pc & ~0xFFF) + (imm << 12), (word & 0x1F)
|
||||
|
||||
|
||||
def _decode_ldr_unsigned(word):
|
||||
"""ldr Rt, [Rn, #imm] (64-bit unsigned offset) -> (Rn, Rt, byte_offset)."""
|
||||
if (word >> 30) != 0b11: # size == 64-bit
|
||||
return None
|
||||
if ((word >> 27) & 0x7) != 0b111:
|
||||
return None
|
||||
if ((word >> 24) & 0x3) != 0b01:
|
||||
return None
|
||||
imm12 = (word >> 10) & 0xFFF
|
||||
rn = (word >> 5) & 0x1F
|
||||
rt = word & 0x1F
|
||||
return rn, rt, imm12 * 8
|
||||
|
||||
|
||||
def _decode_add_imm(word):
|
||||
"""add Rd, Rn, #imm -> (Rn, Rd, imm).
|
||||
|
||||
Encoding: sf op S 100010 sh imm12 Rn Rd
|
||||
bits[31]=sf bits[30]=op bits[29]=S bits[28:23]=100010 (6 bits, not 9)
|
||||
"""
|
||||
if (word >> 31) & 1 != 1: # sf must be 1 (64-bit form)
|
||||
return None
|
||||
if ((word >> 23) & 0x3F) != 0b100010:
|
||||
return None
|
||||
if (word >> 22) & 1: # shifted form -- not what stubs use
|
||||
return None
|
||||
imm12 = (word >> 10) & 0xFFF
|
||||
rn = (word >> 5) & 0x1F
|
||||
rd = word & 0x1F
|
||||
return rn, rd, imm12
|
||||
|
||||
|
||||
def _decode_br(word):
|
||||
"""br Rn -> Rn, or None."""
|
||||
if (word & 0xFFFFFC1F) == 0xD61F0000:
|
||||
return (word >> 5) & 0x1F
|
||||
return None
|
||||
|
||||
|
||||
def find_branch_callers(elf, target_vaddr, limit=500):
|
||||
"""Addresses of BL/B instructions that branch to target_vaddr."""
|
||||
base, foff, fsz, _ms, _fl = elf.exec_segment()
|
||||
hits = []
|
||||
if elf.machine == EM_AARCH64:
|
||||
off = 0
|
||||
while off < fsz - 4:
|
||||
(w,) = struct.unpack_from("<I", data_slice(elf.data, foff + off, 4))
|
||||
if (w & 0xFC000000) in (0x94000000, 0x14000000): # BL / B
|
||||
imm = _sign_extend(w & 0x03FFFFFF, 26) << 2
|
||||
if base + off + imm == target_vaddr:
|
||||
hits.append(base + off)
|
||||
if len(hits) >= limit:
|
||||
break
|
||||
off += 4
|
||||
elif elf.machine == EM_X86_64:
|
||||
i = 0
|
||||
while i < fsz - 5:
|
||||
if elf.data[foff + i] == 0xE8:
|
||||
disp = struct.unpack_from("<i", elf.data, foff + i + 1)[0]
|
||||
if base + i + 5 + disp == target_vaddr:
|
||||
hits.append(base + i)
|
||||
if len(hits) >= limit:
|
||||
break
|
||||
i += 1
|
||||
return hits
|
||||
|
||||
|
||||
def data_slice(data, off, n):
|
||||
return data[off:off + n]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Commands
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
def load(path):
|
||||
with open(path, "rb") as fh:
|
||||
return Elf(fh.read(), path)
|
||||
|
||||
|
||||
def cmd_list(elf, args):
|
||||
relocs = reloc_map(elf)
|
||||
stubs = find_stubs(elf, relocs)
|
||||
base, foff, fsz, _ms, _fl = elf.exec_segment()
|
||||
print("== %s" % elf.path)
|
||||
print(" arch=%s exec seg: vaddr=0x%x file=0x%x size=0x%x" % (elf.arch, base, foff, fsz))
|
||||
print(" imported relocations=%d stubs resolved=%d" % (len(relocs), len(stubs)))
|
||||
if not stubs:
|
||||
print(" NOTE: zero stubs resolved. Either the library has no PLT, or the")
|
||||
print(" hardening removed/forged the relocation tables. Do not read")
|
||||
print(" this as 'the library imports nothing'.")
|
||||
for va in sorted(stubs):
|
||||
sym, got = stubs[va]
|
||||
print(" 0x%08x -> %-34s (GOT 0x%x)" % (va, sym, got))
|
||||
return stubs
|
||||
|
||||
|
||||
def cmd_query(elf, args):
|
||||
relocs = reloc_map(elf)
|
||||
stubs = find_stubs(elf, relocs)
|
||||
for a in args.query:
|
||||
va = int(a, 0)
|
||||
hit = stubs.get(va)
|
||||
if hit:
|
||||
print("0x%x -> %s (GOT 0x%x)" % (va, hit[0], hit[1]))
|
||||
else:
|
||||
print("0x%x -> not a resolved stub" % va)
|
||||
|
||||
|
||||
def cmd_symbol(elf, args):
|
||||
relocs = reloc_map(elf)
|
||||
stubs = find_stubs(elf, relocs)
|
||||
wanted = args.symbol
|
||||
found = [(va, sym, got) for va, (sym, got) in stubs.items() if sym == wanted]
|
||||
if not found:
|
||||
near = sorted({s for _v, (s, _g) in stubs.items()
|
||||
if wanted in s or s in wanted})[:10]
|
||||
print("no stub resolves to %r" % wanted)
|
||||
if near:
|
||||
print(" similar: %s" % ", ".join(near))
|
||||
return
|
||||
for va, sym, got in sorted(found):
|
||||
print("stub 0x%x -> %s (GOT 0x%x)" % (va, sym, got))
|
||||
if args.callers:
|
||||
callers = find_branch_callers(elf, va)
|
||||
print(" callers of the stub: %d" % len(callers))
|
||||
for c in callers:
|
||||
print(" 0x%x" % c)
|
||||
print(" NOTE: a stub-level patch covers all of these. A call-site-level")
|
||||
print(" patch must cover every one of them, plus any caller reached")
|
||||
print(" through a cached function pointer (not listed here).")
|
||||
|
||||
|
||||
def cmd_diff(elf_a, args):
|
||||
path_b = args.diff
|
||||
elf_b = load(path_b)
|
||||
a, b = elf_a.data, elf_b.data
|
||||
print("== diff")
|
||||
print(" A %s %d bytes sha256=%s" % (elf_a.path, len(a), hashlib.sha256(a).hexdigest()[:16]))
|
||||
print(" B %s %d bytes sha256=%s" % (path_b, len(b), hashlib.sha256(b).hexdigest()[:16]))
|
||||
if len(a) != len(b):
|
||||
print(" SIZE DIFFERS: %d vs %d -- a length change is itself a finding"
|
||||
% (len(a), len(b)))
|
||||
n = min(len(a), len(b))
|
||||
runs = []
|
||||
i = 0
|
||||
while i < n:
|
||||
if a[i] != b[i]:
|
||||
j = i
|
||||
while j < n and a[j] != b[j]:
|
||||
j += 1
|
||||
runs.append((i, j - i))
|
||||
i = j
|
||||
else:
|
||||
i += 1
|
||||
total = sum(r[1] for r in runs)
|
||||
print(" differing bytes=%d in %d run(s)" % (total, len(runs)))
|
||||
|
||||
regions = {}
|
||||
if args.name_regions:
|
||||
relocs_a = reloc_map(elf_a)
|
||||
stubs_a = find_stubs(elf_a, relocs_a)
|
||||
|
||||
def describe(off):
|
||||
for va, (sym, _got) in stubs_a.items():
|
||||
size = 16 if elf_a.machine == EM_AARCH64 else 16
|
||||
if va <= off < va + size:
|
||||
return "PLT stub for %s" % sym
|
||||
return ""
|
||||
|
||||
regions = {"describe": describe}
|
||||
|
||||
for off, ln in runs:
|
||||
note = ""
|
||||
if regions:
|
||||
note = regions["describe"](off)
|
||||
if note:
|
||||
note = " <- " + note
|
||||
print(" off=0x%06x len=%-4d A: %s" % (off, ln, a[off:off + ln].hex(" ")))
|
||||
print(" %s B: %s%s" % (" " * 14, b[off:off + ln].hex(" "), note))
|
||||
if args.name_regions and not runs:
|
||||
print(" (identical)")
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description="PLT stub -> symbol mapping and .so diffing for hardened libraries.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("so", help="path to the ELF (.so)")
|
||||
ap.add_argument("--query", nargs="+", metavar="ADDR",
|
||||
help="resolve specific stub addresses (hex ok)")
|
||||
ap.add_argument("--symbol", metavar="NAME",
|
||||
help="find the stub that resolves to this symbol")
|
||||
ap.add_argument("--callers", action="store_true",
|
||||
help="with --symbol: also list branch call sites")
|
||||
ap.add_argument("--diff", metavar="OTHER_SO",
|
||||
help="byte-compare against another library")
|
||||
ap.add_argument("--name-regions", action="store_true",
|
||||
help="with --diff: name the symbol each changed stub belongs to")
|
||||
args = ap.parse_args()
|
||||
|
||||
try:
|
||||
elf = load(args.so)
|
||||
except Exception as e:
|
||||
sys.exit("error: %s" % e)
|
||||
|
||||
if args.diff:
|
||||
cmd_diff(elf, args)
|
||||
elif args.query:
|
||||
cmd_query(elf, args)
|
||||
elif args.symbol:
|
||||
cmd_symbol(elf, args)
|
||||
else:
|
||||
cmd_list(elf, args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Find every reference to a method/field/class, so you can judge blast radius
|
||||
BEFORE patching it.
|
||||
|
||||
This is the check that prevents the classic mistake: patching something that looked
|
||||
ad-specific but is actually a general utility with dozens of callers.
|
||||
|
||||
Usage
|
||||
-----
|
||||
# references to a method, from a smali tree or a directory of dex files
|
||||
python find_refs.py <tree_or_dex_dir> 'Lcom/pkg/Helper;->showAd(Landroid/app/Activity;)V'
|
||||
|
||||
# a whole class (all of its members)
|
||||
python find_refs.py <tree_or_dex_dir> 'Lcom/pkg/Helper;'
|
||||
|
||||
# a field
|
||||
python find_refs.py <tree_or_dex_dir> 'Lcom/pkg/Helper;->count:I'
|
||||
|
||||
# just the counts, no listing
|
||||
python find_refs.py <tree_or_dex_dir> 'Lcom/pkg/Helper;->showAd' --count-only
|
||||
|
||||
Reading the result
|
||||
------------------
|
||||
few callers, all inside one feature area -> safe to patch
|
||||
many callers, or callers in unrelated pkgs -> general utility. DO NOT patch it.
|
||||
Go one level up and patch the
|
||||
specific caller instead.
|
||||
|
||||
Also inspect the signature. If it mentions Modifier / ContentScale / Shape / View /
|
||||
ColorScheme or a content-generic model type, it is shared UI, not your target.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
TEXT_EXT = ('.smali',)
|
||||
REF_RE_TMPL = r'invoke[^\n]*%s|sget[^\n]*%s|sput[^\n]*%s|new-instance[^\n]*%s|check-cast[^\n]*%s'
|
||||
|
||||
|
||||
def iter_files(root):
|
||||
if os.path.isdir(root):
|
||||
for dp, _, fs in os.walk(root):
|
||||
for fn in fs:
|
||||
if fn.endswith(TEXT_EXT):
|
||||
yield os.path.join(dp, fn)
|
||||
else:
|
||||
yield root
|
||||
|
||||
|
||||
def method_owner(text, idx):
|
||||
"""Map a character offset to the enclosing .method declaration."""
|
||||
head = text.rfind('.method ', 0, idx)
|
||||
if head < 0:
|
||||
return '?'
|
||||
end = text.find('\n', head)
|
||||
return text[head:end].strip()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(add_help=True)
|
||||
ap.add_argument('root')
|
||||
ap.add_argument('needle')
|
||||
ap.add_argument('--count-only', action='store_true')
|
||||
ap.add_argument('--max-print', type=int, default=60)
|
||||
a = ap.parse_args()
|
||||
|
||||
esc = re.escape(a.needle)
|
||||
# match the needle plus one more char so we do not match a longer prefix
|
||||
pat = re.compile(REF_RE_TMPL % (esc, esc, esc, esc, esc))
|
||||
|
||||
total = 0
|
||||
per_file = []
|
||||
printed = 0
|
||||
for fp in iter_files(a.root):
|
||||
try:
|
||||
t = open(fp, encoding='utf-8', errors='replace').read()
|
||||
except Exception:
|
||||
continue
|
||||
hits = list(pat.finditer(t))
|
||||
if not hits:
|
||||
continue
|
||||
total += len(hits)
|
||||
per_file.append((len(hits), fp, hits, t))
|
||||
|
||||
per_file.sort(reverse=True)
|
||||
print('[total refs] %d across %d files' % (total, len(per_file)))
|
||||
print()
|
||||
for cnt, fp, hits, t in per_file:
|
||||
rel = fp
|
||||
print('%-70s %d' % (rel, cnt))
|
||||
if a.count_only:
|
||||
continue
|
||||
for m in hits:
|
||||
if printed >= a.max_print:
|
||||
print(' ... (truncated)')
|
||||
return 0
|
||||
owner = method_owner(t, m.start())
|
||||
print(' in %s' % owner)
|
||||
print(' %s' % m.group(0).strip())
|
||||
printed += 1
|
||||
|
||||
if total == 0:
|
||||
print('[note] no references found. Check the descriptor prefix "L...;" and '
|
||||
'exact obfuscated names, or disassemble the dex first with smtool.py.')
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,572 @@
|
||||
/*
|
||||
* frida_probe.js -- four-layer full-chain network probe for a hardened Android app.
|
||||
*
|
||||
* WHY THIS SHAPE
|
||||
* --------------
|
||||
* When you cannot tell why a request never reaches the server (or why it fails
|
||||
* silently), a single-layer hook always leaves you guessing. This script hooks
|
||||
* FOUR independent layers at once, so *whichever* layer the app actually uses
|
||||
* produces evidence:
|
||||
*
|
||||
* [APP] the app's own network wrapper class(es) -> what business method asked
|
||||
* [OKHTTP] OkHttp full chain -> newCall/build/execute/async/proceed
|
||||
* [RAW-URL] java.net.URL.openConnection -> HttpsURLConnection, which uses the
|
||||
* SYSTEM trust store and therefore
|
||||
* fails differently from OkHttp
|
||||
* [THROW] java.lang.Throwable.getMessage -> recovers the exception text that an
|
||||
* upper layer swallowed with catch {}
|
||||
*
|
||||
* The RAW-URL vs OKHTTP distinction is the single most valuable signal here: an app
|
||||
* commonly has two unrelated trust chains, so "login fails but browsing works" is
|
||||
* explained by which of the two fired. See LESSONS G3.
|
||||
*
|
||||
* Every hook is installed inside its own try/catch. One missing class (a different
|
||||
* OkHttp major version, a renamed obfuscated class) never disables the other three
|
||||
* layers. Failures are reported as HOOK-FAIL lines instead of killing the script.
|
||||
*
|
||||
* ADAPT TO YOUR TARGET (only this block matters)
|
||||
* ---------------------------------------------
|
||||
* 1) APP_NET_CLASSES -> replace with the app's own network wrapper class name(s)
|
||||
* 2) APP_PKG_PREFIX -> the app's package prefix, used only to filter noise
|
||||
* 3) ENABLE_* flags -> turn layers off if they are too noisy
|
||||
* Everything else is target-independent.
|
||||
*
|
||||
* HOW TO RUN
|
||||
* ----------
|
||||
* Prefer the bundled injector, which also writes a log file and stays resident:
|
||||
* python run_probe.py frida_probe.js 10 --pkg com.example.app
|
||||
* Or by hand against a remote device:
|
||||
* frida -H 127.0.0.1:27042 -p <pid> -l frida_probe.js
|
||||
*
|
||||
* OUTPUT FORMAT
|
||||
* -------------
|
||||
* Every line is <ISO-ish local timestamp> <TAG> <key=value ...>
|
||||
* TAGS: READY | HOOK-FAIL | FATAL | APP | OKHTTP-NEWCALL | OKHTTP-BUILD |
|
||||
* OKHTTP-EXEC | OKHTTP-ASYNC | OKHTTP-PROCEED | RAW-URL | DNS | THROW
|
||||
* Add STACK to a line only where a call chain is genuinely useful (APP, RAW-URL),
|
||||
* because it is the expensive part.
|
||||
*/
|
||||
|
||||
/* ===================================================================
|
||||
* 1. ADAPT THESE LINES
|
||||
* =================================================================== */
|
||||
// The app's own network wrapper / API helper class(es). Enumerate ALL declared
|
||||
// methods at runtime, so you do not have to know the obfuscated method names.
|
||||
// Example: 'com.example.app.net.HttpHelper', 'com.example.app.api.ApiClient'
|
||||
var APP_NET_CLASSES = ['com.example.app.net.HttpHelper'];
|
||||
|
||||
// Used only to filter THROW noise: messages from classes whose name contains this
|
||||
// prefix are always kept. Leave as-is if you do not care.
|
||||
var APP_PKG_PREFIX = 'com.example.app';
|
||||
|
||||
// Layer switches. Turn a layer off if it produces more noise than signal.
|
||||
var ENABLE_APP = true; // [APP] app's own wrapper classes (needs APP_NET_CLASSES)
|
||||
var ENABLE_OKHTTP = true; // [OKHTTP] OkHttp newCall/build/execute/AsyncCall/proceed
|
||||
var ENABLE_RAW_URL = true; // [RAW-URL] java.net.URL.openConnection (HttpsURLConnection)
|
||||
var ENABLE_THROWABLE = true; // [THROW] Throwable.getMessage, deduplicated
|
||||
var ENABLE_DNS = true; // [DNS] InetAddress.getAllByName, one line per unique host
|
||||
var STACK_ON_APP = true; // attach a stack to [APP] hits
|
||||
var STACK_ON_RAW_URL = true; // attach a stack to [RAW-URL] hits
|
||||
var STACK_LINES = 12; // how many stack frames to keep
|
||||
|
||||
// Safety valves: this probe must never become the thing that kills the app.
|
||||
var MAX_STRING = 3000; // truncate any single value
|
||||
var THROWABLE_MAX_LINES = 400;// hard cap on THROW lines
|
||||
var THROWABLE_STACK = false; // stacks on every Throwable line are usually too much
|
||||
|
||||
/* ===================================================================
|
||||
* 2. Plumbing (target-independent)
|
||||
* =================================================================== */
|
||||
|
||||
function pad(n, w) {
|
||||
var s = '' + n;
|
||||
while (s.length < w) s = '0' + s;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Local wall-clock with milliseconds. Local, not UTC, because you will be
|
||||
// comparing these lines against logcat and your own shell history.
|
||||
function stamp() {
|
||||
var d = new Date();
|
||||
return d.getFullYear() + '-' + pad(d.getMonth() + 1, 2) + '-' + pad(d.getDate(), 2) + ' ' +
|
||||
pad(d.getHours(), 2) + ':' + pad(d.getMinutes(), 2) + ':' + pad(d.getSeconds(), 2) + '.' +
|
||||
pad(d.getMilliseconds(), 3);
|
||||
}
|
||||
|
||||
function str(v, max) {
|
||||
if (v === null) return 'null';
|
||||
if (v === undefined) return 'undefined';
|
||||
var s;
|
||||
try { s = '' + v; } catch (e) { s = '<unprintable>'; }
|
||||
max = max || MAX_STRING;
|
||||
if (s.length > max) s = s.substring(0, max) + '...<+' + (s.length - max) + ' chars>';
|
||||
return s;
|
||||
}
|
||||
|
||||
function sendLine(tag, fields) {
|
||||
var parts = [];
|
||||
if (fields) {
|
||||
for (var k in fields) {
|
||||
if (!fields.hasOwnProperty(k)) continue;
|
||||
if (fields[k] === null || fields[k] === undefined || fields[k] === '') continue;
|
||||
parts.push(k + '=' + str(fields[k]));
|
||||
}
|
||||
}
|
||||
var line = { t: stamp(), tag: tag, msg: parts.join(' ') };
|
||||
try { send(line); } catch (e) { /* transport gone; nothing sane to do */ }
|
||||
}
|
||||
|
||||
// Call-chain capture. Expensive, so it is opt-in per hook.
|
||||
function stackText(lines) {
|
||||
try {
|
||||
var Log = Java.use('android.util.Log');
|
||||
var Throwable = Java.use('java.lang.Throwable');
|
||||
var full = Log.getStackTraceString(Throwable.$new());
|
||||
var rows = ('' + full).split('\n');
|
||||
var kept = [];
|
||||
// Drop the probe's own frames at the top; they are never the interesting part.
|
||||
for (var i = 0; i < rows.length && kept.length < (lines || STACK_LINES); i++) {
|
||||
if (rows[i].indexOf('frida') >= 0) continue;
|
||||
if (rows[i].indexOf('java.lang.Throwable') >= 0) continue;
|
||||
if (rows[i].indexOf('android.util.Log') >= 0) continue;
|
||||
kept.push(rows[i].replace(/^\s+/, ''));
|
||||
}
|
||||
return kept.join(' <- ');
|
||||
} catch (e) {
|
||||
return '<stack unavailable: ' + e + '>';
|
||||
}
|
||||
}
|
||||
|
||||
// The whole point: a failure to install one hook must not affect the others.
|
||||
function guard(label, fn) {
|
||||
try {
|
||||
fn();
|
||||
return true;
|
||||
} catch (e) {
|
||||
sendLine('HOOK-FAIL', { where: label, err: e });
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Run one whole layer and return how many hooks it really installed.
|
||||
// > 0 that many hooks are live
|
||||
// = 0 the layer installed nothing (its classes were not found); NOT a success
|
||||
// =-1 the layer is switched off in the config header
|
||||
// Returning a count instead of a boolean matters: a layer whose classes are absent
|
||||
// still returns normally (each inner hook catches its own error), so a boolean
|
||||
// "did not throw" would report a layer as installed when it hooked nothing at all.
|
||||
function runLayer(label, fn) {
|
||||
try {
|
||||
return fn();
|
||||
} catch (e) {
|
||||
sendLine('HOOK-FAIL', { where: 'install ' + label, err: e });
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* ===================================================================
|
||||
* 3. Layer [APP]: the app's own network wrapper
|
||||
* =================================================================== */
|
||||
// Why getDeclaredMethods: obfuscated wrappers routinely expose the same name with
|
||||
// several overloads, and a decompiler's short names (a, b, c) are not reliable
|
||||
// enough to enumerate by hand. Enumerate at runtime, wrap each overload, and let
|
||||
// the stack tell you which one the business code called.
|
||||
// Build a replacement of a fixed arity that reports the hit and then delegates.
|
||||
//
|
||||
// Two deliberate choices here, both about not breaking the app:
|
||||
// * The original is NOT cached in a variable. Frida does not hand out the pre-hook
|
||||
// implementation through `overload.implementation` (it is undefined until you
|
||||
// replace it), so `var orig = ov.implementation; ... orig.apply(...)` would
|
||||
// throw a TypeError on the first real call and propagate straight into the app's
|
||||
// network path. Calling the same name on `this` from inside the replacement is
|
||||
// the documented way to reach the original, and it re-resolves the overload from
|
||||
// the runtime argument types.
|
||||
// * The delegate call is written out per arity instead of spread/apply, so no
|
||||
// engine-specific behaviour is involved. Methods with more than 8 parameters are
|
||||
// reported and left alone rather than bound incorrectly.
|
||||
function appReplacement(className, methodName, arity) {
|
||||
var label = className + '.' + methodName;
|
||||
var note = function (argc) {
|
||||
sendLine('APP', {
|
||||
call: label,
|
||||
argc: argc,
|
||||
stack: STACK_ON_APP ? stackText() : null
|
||||
});
|
||||
};
|
||||
switch (arity) {
|
||||
case 0: return function () {
|
||||
note(arguments.length); return this[methodName]();
|
||||
};
|
||||
case 1: return function (a0) {
|
||||
note(arguments.length); return this[methodName](a0);
|
||||
};
|
||||
case 2: return function (a0, a1) {
|
||||
note(arguments.length); return this[methodName](a0, a1);
|
||||
};
|
||||
case 3: return function (a0, a1, a2) {
|
||||
note(arguments.length); return this[methodName](a0, a1, a2);
|
||||
};
|
||||
case 4: return function (a0, a1, a2, a3) {
|
||||
note(arguments.length); return this[methodName](a0, a1, a2, a3);
|
||||
};
|
||||
case 5: return function (a0, a1, a2, a3, a4) {
|
||||
note(arguments.length); return this[methodName](a0, a1, a2, a3, a4);
|
||||
};
|
||||
case 6: return function (a0, a1, a2, a3, a4, a5) {
|
||||
note(arguments.length); return this[methodName](a0, a1, a2, a3, a4, a5);
|
||||
};
|
||||
case 7: return function (a0, a1, a2, a3, a4, a5, a6) {
|
||||
note(arguments.length); return this[methodName](a0, a1, a2, a3, a4, a5, a6);
|
||||
};
|
||||
case 8: return function (a0, a1, a2, a3, a4, a5, a6, a7) {
|
||||
note(arguments.length); return this[methodName](a0, a1, a2, a3, a4, a5, a6, a7);
|
||||
};
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
|
||||
function installAppLayer() {
|
||||
if (!ENABLE_APP) return -1;
|
||||
if (!APP_NET_CLASSES.length) {
|
||||
sendLine('HOOK-FAIL', { where: 'APP', err: 'APP_NET_CLASSES is empty; edit the header' });
|
||||
return 0;
|
||||
}
|
||||
var wrappedTotal = 0;
|
||||
APP_NET_CLASSES.forEach(function (className) {
|
||||
guard('APP ' + className, function () {
|
||||
var Cls = Java.use(className);
|
||||
var declared = Cls.class.getDeclaredMethods();
|
||||
var total = declared.length;
|
||||
var wrapped = 0;
|
||||
var skipped = 0;
|
||||
for (var i = 0; i < total; i++) {
|
||||
(function (idx) {
|
||||
var methodName;
|
||||
try { methodName = '' + declared[idx].getName(); } catch (e) { return; }
|
||||
guard('APP ' + className + '.' + methodName, function () {
|
||||
var overloads = Cls[methodName];
|
||||
if (!overloads || !overloads.overloads) return;
|
||||
overloads.overloads.forEach(function (ov) {
|
||||
var argTypes;
|
||||
try { argTypes = ov.argumentTypes; } catch (e) { argTypes = null; }
|
||||
var arity = (argTypes && typeof argTypes.length === 'number') ? argTypes.length : -1;
|
||||
var label = className + '.' + methodName + '(' + (argTypes ? argTypes.join(',') : '?') + ')';
|
||||
guard('APP bind ' + label, function () {
|
||||
var replacement = appReplacement(className, methodName, arity);
|
||||
if (replacement === null) {
|
||||
skipped++;
|
||||
sendLine('APP', {
|
||||
call: label,
|
||||
skipped: 'arity ' + arity + ' exceeds 8; left unwrapped on purpose'
|
||||
});
|
||||
return;
|
||||
}
|
||||
ov.implementation = replacement;
|
||||
wrapped++;
|
||||
});
|
||||
});
|
||||
});
|
||||
})(i);
|
||||
}
|
||||
wrappedTotal += wrapped;
|
||||
sendLine('APP', {
|
||||
call: className,
|
||||
declared_methods: total,
|
||||
overloads_wrapped: wrapped,
|
||||
overloads_skipped: skipped
|
||||
});
|
||||
});
|
||||
});
|
||||
return wrappedTotal;
|
||||
}
|
||||
|
||||
/* ===================================================================
|
||||
* 4. Layer [OKHTTP]: the whole OkHttp chain
|
||||
* =================================================================== */
|
||||
// Five independent anchors on purpose. Any single one can be missing depending on
|
||||
// the OkHttp major version and on R8 inlining, and each still answers a different
|
||||
// question:
|
||||
// newCall -> a request object reached OkHttp (earliest reliable URL)
|
||||
// build -> the URL existed even if the call was never executed
|
||||
// execute -> synchronous call actually ran, with status code and duration
|
||||
// AsyncCall.run-> asynchronous call actually ran (enqueue path)
|
||||
// proceed -> every actual network step, including redirects and retries
|
||||
function installOkHttpLayer() {
|
||||
if (!ENABLE_OKHTTP) return -1;
|
||||
|
||||
var installed = 0;
|
||||
var can = function (label, fn) { if (guard(label, fn)) installed++; };
|
||||
|
||||
can('OKHTTP newCall', function () {
|
||||
var Client = Java.use('okhttp3.OkHttpClient');
|
||||
Client.newCall.overload('okhttp3.Request').implementation = function (req) {
|
||||
var url = '<unknown>';
|
||||
try { url = '' + req.url().toString(); } catch (e) { url = '<url error: ' + e + '>'; }
|
||||
sendLine('OKHTTP-NEWCALL', { url: url });
|
||||
return this.newCall(req);
|
||||
};
|
||||
});
|
||||
|
||||
can('OKHTTP Request$Builder.build', function () {
|
||||
var Builder = Java.use('okhttp3.Request$Builder');
|
||||
Builder.build.implementation = function () {
|
||||
var req = this.build();
|
||||
var url = '<unknown>';
|
||||
try { url = '' + req.url().toString(); } catch (e) { url = '<url error: ' + e + '>'; }
|
||||
sendLine('OKHTTP-BUILD', { url: url });
|
||||
return req;
|
||||
};
|
||||
});
|
||||
|
||||
can('OKHTTP RealCall.execute', function () {
|
||||
var RealCall = Java.use('okhttp3.internal.connection.RealCall');
|
||||
RealCall.execute.implementation = function () {
|
||||
var url = '<unknown>';
|
||||
try { url = '' + this.request().url().toString(); } catch (e) { url = '<url error: ' + e + '>'; }
|
||||
var t0 = Date.now();
|
||||
var resp = this.execute();
|
||||
var code = '?';
|
||||
try { code = '' + resp.code(); } catch (e) { code = '<code error>'; }
|
||||
sendLine('OKHTTP-EXEC', { url: url, ms: Date.now() - t0, code: code });
|
||||
return resp;
|
||||
};
|
||||
});
|
||||
|
||||
can('OKHTTP RealCall$AsyncCall.run', function () {
|
||||
var AsyncCall = Java.use('okhttp3.internal.connection.RealCall$AsyncCall');
|
||||
AsyncCall.run.implementation = function () {
|
||||
// The URL is not reliably reachable from here across OkHttp versions; the
|
||||
// newCall/build hooks above supply it. This hook proves *when* the async
|
||||
// path actually started and finished, which is what matters for timing.
|
||||
var t0 = Date.now();
|
||||
this.run();
|
||||
sendLine('OKHTTP-ASYNC', { phase: 'done', ms: Date.now() - t0 });
|
||||
};
|
||||
});
|
||||
|
||||
can('OKHTTP RealInterceptorChain.proceed', function () {
|
||||
var Chain = Java.use('okhttp3.internal.http.RealInterceptorChain');
|
||||
Chain.proceed.overload('okhttp3.Request').implementation = function (req) {
|
||||
var url = '<unknown>';
|
||||
try { url = '' + req.url().toString(); } catch (e) { url = '<url error: ' + e + '>'; }
|
||||
var t0 = Date.now();
|
||||
var resp = this.proceed(req);
|
||||
var code = '?';
|
||||
try { code = '' + resp.code(); } catch (e) { code = '<code error>'; }
|
||||
sendLine('OKHTTP-PROCEED', { url: url, ms: Date.now() - t0, code: code });
|
||||
return resp;
|
||||
};
|
||||
});
|
||||
return installed;
|
||||
}
|
||||
|
||||
/* ===================================================================
|
||||
* 5. Layer [RAW-URL]: HttpsURLConnection -> the SYSTEM trust store
|
||||
* =================================================================== */
|
||||
// Many apps route login/registration through java.net.URL.openConnection instead
|
||||
// of OkHttp. That path validates against the system trust store, so an expired or
|
||||
// untrusted server certificate breaks it while the OkHttp path keeps working.
|
||||
// If this layer fires but the OkHttp layer stays silent, you are on the other
|
||||
// trust chain -- check the certificate out-of-band with tls_check.py.
|
||||
function installRawUrlLayer() {
|
||||
if (!ENABLE_RAW_URL) return -1;
|
||||
|
||||
var URL;
|
||||
try {
|
||||
URL = Java.use('java.net.URL');
|
||||
} catch (e) {
|
||||
sendLine('HOOK-FAIL', { where: 'RAW-URL java.net.URL', err: e });
|
||||
return 0;
|
||||
}
|
||||
var installed = 0;
|
||||
var can = function (label, fn) { if (guard(label, fn)) installed++; };
|
||||
|
||||
can('RAW-URL openConnection()', function () {
|
||||
// Report AFTER the original returns, so we can also name the concrete connection
|
||||
// class (HttpURLConnection vs HttpsURLConnection) -- that distinction is what
|
||||
// tells you which trust chain the request is about to use.
|
||||
// As in the APP layer, the original is reached via `this.openConnection(...)`
|
||||
// rather than a cached function reference.
|
||||
URL.openConnection.overload().implementation = function () {
|
||||
var url = '<unknown>';
|
||||
try { url = '' + this.toString(); } catch (e) { url = '<url error: ' + e + '>'; }
|
||||
var conn = this.openConnection();
|
||||
var connCls = '?';
|
||||
try { connCls = '' + conn.getClass().getName(); } catch (e) { connCls = '<class error>'; }
|
||||
sendLine('RAW-URL', {
|
||||
url: url,
|
||||
kind: 'no-arg',
|
||||
conn: connCls,
|
||||
stack: STACK_ON_RAW_URL ? stackText() : null
|
||||
});
|
||||
return conn;
|
||||
};
|
||||
});
|
||||
|
||||
can('RAW-URL openConnection(Proxy)', function () {
|
||||
URL.openConnection.overload('java.net.Proxy').implementation = function (proxy) {
|
||||
var url = '<unknown>';
|
||||
try { url = '' + this.toString(); } catch (e) { url = '<url error: ' + e + '>'; }
|
||||
var conn = this.openConnection(proxy);
|
||||
var connCls = '?';
|
||||
try { connCls = '' + conn.getClass().getName(); } catch (e) { connCls = '<class error>'; }
|
||||
sendLine('RAW-URL', {
|
||||
url: url,
|
||||
kind: 'proxy',
|
||||
conn: connCls,
|
||||
stack: STACK_ON_RAW_URL ? stackText() : null
|
||||
});
|
||||
return conn;
|
||||
};
|
||||
});
|
||||
return installed;
|
||||
}
|
||||
|
||||
/* ===================================================================
|
||||
* 6. Layer [THROW]: recover swallowed exception text
|
||||
* =================================================================== */
|
||||
// An upper-layer `catch (Exception e) { }` hides exactly the message you need.
|
||||
// Hooking Throwable.getMessage is the cheapest way to get it back, but it is a
|
||||
// very hot method, so: only concrete Exception/Error subclasses, deduplicated by
|
||||
// class+message, hard-capped, and stacks off by default.
|
||||
function installThrowableLayer() {
|
||||
if (!ENABLE_THROWABLE) return -1;
|
||||
|
||||
// Returns 1 only when the hook is really bound to the runtime.
|
||||
return guard('THROWABLE getMessage', function () {
|
||||
var seen = {};
|
||||
var printed = 0;
|
||||
var suppressed = 0;
|
||||
var Throwable = Java.use('java.lang.Throwable');
|
||||
|
||||
Throwable.getMessage.implementation = function () {
|
||||
var msg;
|
||||
try {
|
||||
msg = this.getMessage();
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
var cls = '' + this.getClass().getName();
|
||||
var looksLikeError = (cls.indexOf('Exception') >= 0 || cls.indexOf('Error') >= 0);
|
||||
var isAppClass = (cls.indexOf(APP_PKG_PREFIX) === 0);
|
||||
if (looksLikeError || isAppClass) {
|
||||
var key = cls + '|' + msg;
|
||||
if (seen[key]) {
|
||||
seen[key]++;
|
||||
} else if (printed < THROWABLE_MAX_LINES) {
|
||||
seen[key] = 1;
|
||||
printed++;
|
||||
sendLine('THROW', {
|
||||
cls: cls,
|
||||
msg: msg,
|
||||
stack: THROWABLE_STACK ? stackText() : null
|
||||
});
|
||||
} else {
|
||||
suppressed++;
|
||||
if (suppressed === 1 || suppressed % 200 === 0) {
|
||||
sendLine('THROW', { note: 'cap reached, further unique messages suppressed', printed: printed });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Never let the reporting path throw: this hook is on a very hot path.
|
||||
}
|
||||
return msg;
|
||||
};
|
||||
}) ? 1 : 0;
|
||||
}
|
||||
|
||||
/* ===================================================================
|
||||
* 7. Optional layer [DNS]: which hosts the app really resolves
|
||||
* =================================================================== */
|
||||
// Cheap, high-signal: if an SDK's domains are never resolved, that subsystem never
|
||||
// started -- much stronger evidence than "logcat was quiet". Deduplicated per host
|
||||
// so a retry loop cannot flood the log.
|
||||
function installDnsLayer() {
|
||||
if (!ENABLE_DNS) return -1;
|
||||
|
||||
return guard('DNS getAllByName', function () {
|
||||
var seen = {};
|
||||
var Inet = Java.use('java.net.InetAddress');
|
||||
Inet.getAllByName.overload('java.lang.String').implementation = function (host) {
|
||||
var first = false;
|
||||
try {
|
||||
var key = '' + host;
|
||||
if (!seen[key]) { seen[key] = 1; first = true; }
|
||||
} catch (e) { /* ignore */ }
|
||||
if (first) sendLine('DNS', { host: host });
|
||||
return this.getAllByName(host);
|
||||
};
|
||||
}) ? 1 : 0;
|
||||
}
|
||||
|
||||
/* ===================================================================
|
||||
* 8. Boot
|
||||
* =================================================================== */
|
||||
var JAVA_BRIDGE_HINT =
|
||||
'align the host frida package and the on-device frida-server to the same 16.x version; ' +
|
||||
'17.x can fail to locate the Android dynamic linker and removes the built-in Java bridge';
|
||||
|
||||
function main() {
|
||||
if (typeof Java === 'undefined' || Java === null) {
|
||||
// frida 17+ removed the built-in Java bridge.
|
||||
sendLine('FATAL', {
|
||||
err: 'Java bridge is not available in this frida runtime',
|
||||
fix: JAVA_BRIDGE_HINT
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Java.perform can fail BEFORE the callback ever runs: on a non-Android host, and
|
||||
// on frida 17.x, where it throws "Java API not available". Without this catch the
|
||||
// whole script dies as an opaque `type: error` message with a stack pointing into
|
||||
// frida-java-bridge, which tells you nothing about the version mismatch that
|
||||
// actually caused it.
|
||||
try {
|
||||
Java.perform(function () {
|
||||
var installed = [];
|
||||
var failed = [];
|
||||
var disabled = [];
|
||||
[
|
||||
['APP', installAppLayer],
|
||||
['OKHTTP', installOkHttpLayer],
|
||||
['RAW-URL', installRawUrlLayer],
|
||||
['THROW', installThrowableLayer],
|
||||
['DNS', installDnsLayer]
|
||||
].forEach(function (pair) {
|
||||
var count = runLayer(pair[0], pair[1]);
|
||||
if (count === -1) disabled.push(pair[0]);
|
||||
else if (count > 0) installed.push(pair[0] + ':' + count);
|
||||
else failed.push(pair[0]);
|
||||
});
|
||||
sendLine('READY', {
|
||||
installed: installed.join(',') || 'none',
|
||||
failed: failed.join(',') || 'none',
|
||||
disabled: disabled.join(',') || 'none',
|
||||
note: 'hooks are live; now drive the app UI'
|
||||
});
|
||||
if (failed.length) {
|
||||
sendLine('READY-HINT', {
|
||||
failed: failed.join(','),
|
||||
fix: 'a layer reporting 0 hooks means its classes were not found: the app may '
|
||||
+ 'not use that library, R8 may have renamed the class, or the classloader '
|
||||
+ 'differs. Layers that installed keep working -- debug the failed ones by '
|
||||
+ 'their HOOK-FAIL line, not the working ones.'
|
||||
});
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
sendLine('FATAL', {
|
||||
err: 'Java.perform failed: ' + e,
|
||||
fix: JAVA_BRIDGE_HINT
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Last-resort net: any unexpected top-level error still leaves a readable line in
|
||||
// the log instead of only a raw frida script error.
|
||||
try {
|
||||
main();
|
||||
} catch (e) {
|
||||
sendLine('FATAL', { err: 'probe aborted: ' + e, note: 'no hooks were installed' });
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Capture a crash stack when the app's crash-reporter SDK is hiding it.
|
||||
|
||||
Problem this solves
|
||||
-------------------
|
||||
Many apps install a global uncaught-exception handler (友盟/UCrash, Bugly, Firebase
|
||||
Crashlytics in some configs). The Java stack then never reaches `logcat` -- you only
|
||||
see something like:
|
||||
|
||||
W/UCrash.Java: uncaughtException time: <ts>
|
||||
|
||||
...and the process dies. Without a stack you are guessing.
|
||||
|
||||
Three ways to get it, in order of reliability:
|
||||
1. Frida: hook Thread.setDefaultUncaughtExceptionHandler (use references/dynamic-frida.md)
|
||||
2. Race the reporter's own log file (this script): it writes a file under the app's
|
||||
data dir, then zips, uploads, and deletes it. Poll fast and copy on sight.
|
||||
3. Use a build with the reporter disabled.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python grab_crash.py --pkg com.example.app --activity .MainActivity
|
||||
python grab_crash.py --pkg com.example.app --activity .MainActivity \
|
||||
--scan-dir /data/data/com.example.app --wait 25
|
||||
|
||||
Notes
|
||||
-----
|
||||
* `--scan-dir` defaults to /data/data/<pkg>; the script searches a few levels deep for
|
||||
newly appeared *.log / *.txt / *.stacktrace files, so you do not have to know which
|
||||
SDK is installed.
|
||||
* The watcher loop self-terminates after ~80 s, so nothing is left running on device.
|
||||
* Requires root (the app's data dir is private).
|
||||
"""
|
||||
import argparse
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
CAPTURE = '/data/local/tmp/_skill_crash_capture.log'
|
||||
|
||||
|
||||
def adb(args, serial=None, timeout=180):
|
||||
cmd = ['adb']
|
||||
if serial:
|
||||
cmd += ['-s', serial]
|
||||
cmd += args
|
||||
r = subprocess.run(cmd, capture_output=True, text=True, errors='replace', timeout=timeout)
|
||||
return (r.stdout or '') + (('\n[stderr]\n' + r.stderr) if (r.stderr or '').strip() else '')
|
||||
|
||||
|
||||
def su(cmd, serial=None):
|
||||
return adb(['shell', 'su -c "%s"' % cmd.replace('"', '\\"')], serial)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(add_help=True)
|
||||
ap.add_argument('--pkg', required=True)
|
||||
ap.add_argument('--activity', required=True)
|
||||
ap.add_argument('--serial')
|
||||
ap.add_argument('--scan-dir')
|
||||
ap.add_argument('--wait', type=int, default=25)
|
||||
a = ap.parse_args()
|
||||
|
||||
scan = a.scan_dir or ('/data/data/%s' % a.pkg)
|
||||
s = a.serial
|
||||
|
||||
# On-device watcher: copy any *.log/*.txt that appears under the app dir.
|
||||
watch = (
|
||||
"i=0; while [ $i -lt 400 ]; do "
|
||||
" find {d} -maxdepth 5 -type f \\( -name '*.log' -o -name '*.txt' -o -name '*.stacktrace' "
|
||||
" -o -name '*.crash' \\) -newermt '-3 minutes' -exec cp -f {{}} {c} \\; 2>/dev/null; "
|
||||
" i=$((i+1)); sleep 0.2; "
|
||||
"done"
|
||||
).format(d=scan, c=CAPTURE)
|
||||
|
||||
su('am force-stop %s' % a.pkg, s)
|
||||
su('rm -f %s' % CAPTURE, s)
|
||||
print('[grab] arming on-device watcher over %s' % scan)
|
||||
subprocess.Popen(['adb'] + (['-s', s] if s else []) +
|
||||
['shell', "su -c '%s'" % watch],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
time.sleep(1.5)
|
||||
|
||||
print('[grab] starting app')
|
||||
print(adb(['shell', 'am start -n %s/%s' % (a.pkg, a.activity)], s))
|
||||
time.sleep(a.wait)
|
||||
|
||||
pid = adb(['shell', 'pidof %s' % a.pkg], s).strip()
|
||||
print('[grab] pid: %s' % (pid or '(dead -> likely crashed)'))
|
||||
|
||||
print('[grab] ==== captured file ====')
|
||||
out = su('head -c 6000 %s' % CAPTURE, s)
|
||||
if 'No such file' in out or not out.strip():
|
||||
print('(nothing captured)')
|
||||
print('[hint] the reporter may have deleted it faster than 0.2 s, or it writes '
|
||||
'outside --scan-dir. Use the Frida approach instead.')
|
||||
else:
|
||||
print(out)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Install an APK and run a launch health check, extracting the signals that matter.
|
||||
|
||||
Automates the verification loop from references/verification.md:
|
||||
install -> clear logcat -> launch -> sample pid twice -> scan for fatal signatures
|
||||
-> capture a screenshot.
|
||||
|
||||
Why the pid is sampled TWICE: a crash loop shows a live pid at any single instant.
|
||||
The second sample catches it.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python install_test.py --apk out/app.apk --pkg com.example.app --activity .MainActivity
|
||||
python install_test.py --apk out/app.apk --pkg com.example.app --activity .MainActivity \
|
||||
--shots out/shot.png --uninstall-first --grant READ_PHONE_STATE --grant ACCESS_FINE_LOCATION
|
||||
|
||||
Useful flags
|
||||
------------
|
||||
--uninstall-first wipe app data (needed when the signing key changed, and the only
|
||||
way to test "does this survive a fresh install")
|
||||
--keep-data reinstall over the existing app (requires the same signing key;
|
||||
preserves login state -- valuable when the feature under test
|
||||
needs auth)
|
||||
--grant NAME runtime permission to grant (repeatable). Must be granted as
|
||||
root: the shell user gets SecurityException.
|
||||
--wait N seconds between the two pid samples (default 18)
|
||||
|
||||
Exit code is 0 only when the app launched AND both pid samples agree.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
FATAL = re.compile(
|
||||
r'FATAL EXCEPTION|VerifyError|IncompatibleClassChangeError|'
|
||||
r'ClassNotFoundException|NoClassDefFoundError|LinkageError|'
|
||||
r'Failure starting process|uncaughtException',
|
||||
re.I)
|
||||
|
||||
|
||||
def adb(args, serial=None, timeout=600):
|
||||
cmd = ['adb']
|
||||
if serial:
|
||||
cmd += ['-s', serial]
|
||||
cmd += args
|
||||
r = subprocess.run(cmd, capture_output=True, text=True, errors='replace', timeout=timeout)
|
||||
return (r.stdout or '') + (('\n[stderr]\n' + r.stderr) if (r.stderr or '').strip() else '')
|
||||
|
||||
|
||||
def sh(cmd, serial=None):
|
||||
return adb(['shell', cmd], serial)
|
||||
|
||||
|
||||
def su(cmd, serial=None):
|
||||
return adb(['shell', 'su -c "%s"' % cmd.replace('"', '\\"')], serial)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(add_help=True)
|
||||
ap.add_argument('--apk', required=True)
|
||||
ap.add_argument('--pkg', required=True)
|
||||
ap.add_argument('--activity', required=True, help='e.g. .MainActivity or fully qualified')
|
||||
ap.add_argument('--serial')
|
||||
ap.add_argument('--uninstall-first', action='store_true')
|
||||
ap.add_argument('--keep-data', action='store_true')
|
||||
ap.add_argument('--grant', action='append', default=[])
|
||||
ap.add_argument('--wait', type=int, default=18)
|
||||
ap.add_argument('--shots')
|
||||
a = ap.parse_args()
|
||||
|
||||
s = a.serial
|
||||
print('[0] devices:'); print(adb(['devices', '-l']))
|
||||
|
||||
if a.uninstall_first:
|
||||
print('[1] uninstall'); print(su('am force-stop %s; pm uninstall %s' % (a.pkg, a.pkg), s))
|
||||
stage = '/data/local/tmp/_skill_stage.apk'
|
||||
print('[2] push'); print(adb(['push', a.apk, stage], s))
|
||||
print('[3] install'); print(su('pm install -r -t -d %s' % stage, s))
|
||||
|
||||
for perm in a.grant:
|
||||
p = perm if perm.startswith('android.permission.') else 'android.permission.' + perm
|
||||
su('pm grant %s %s' % (a.pkg, p), s)
|
||||
|
||||
print('[4] clear logcat'); adb(['logcat', '-c'], s)
|
||||
comp = '%s/%s' % (a.pkg, a.activity if a.activity.startswith('.') or '.' in a.activity
|
||||
else a.activity)
|
||||
print('[5] launch'); print(sh('am start -n %s' % comp, s))
|
||||
|
||||
time.sleep(6)
|
||||
p1 = sh('pidof %s' % a.pkg, s).strip()
|
||||
print('[6] pid @+6s : %s' % (p1 or '(dead)'))
|
||||
time.sleep(a.wait)
|
||||
p2 = sh('pidof %s' % a.pkg, s).strip()
|
||||
print('[7] pid @+%ds : %s' % (6 + a.wait, p2 or '(dead)'))
|
||||
|
||||
print('[8] focus : %s' % sh('dumpsys window | grep mCurrentFocus', s).strip())
|
||||
|
||||
if a.shots:
|
||||
su('screencap -p /sdcard/_skill_shot.png', s)
|
||||
print(adb(['pull', '/sdcard/_skill_shot.png', a.shots], s))
|
||||
|
||||
print('[9] fatal signatures:')
|
||||
log = adb(['logcat', '-d', '-v', 'brief'], s)
|
||||
hits = [ln for ln in log.splitlines() if FATAL.search(ln)]
|
||||
if hits:
|
||||
for ln in hits[-25:]:
|
||||
print(' ', ln)
|
||||
else:
|
||||
print(' none')
|
||||
|
||||
ok = bool(p1) and p1 == p2 and not hits
|
||||
print()
|
||||
print('[result] %s' % ('OK (launched, stable, no fatal signatures)'
|
||||
if ok else 'CHECK (see above)'))
|
||||
print('[note] stability is NOT proof the patch worked. Exercise the changed '
|
||||
'feature and its neighbours -- see references/verification.md.')
|
||||
return 0 if ok else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,218 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Report which native libraries are ACTUALLY mapped into a live process.
|
||||
|
||||
`getprop ro.product.cpu.abi` tells you what the device claims to be. It does not
|
||||
tell you what is executing. Those differ more often than people expect:
|
||||
|
||||
* an x86_64 emulator running an app whose only native libraries are arm64,
|
||||
because an ARM translation layer is present;
|
||||
* a hardened app whose real libraries are materialized into its data
|
||||
directory at runtime, so the paths you see are not the paths inside the APK;
|
||||
* a fat APK where the package manager picked a different ABI than you assumed,
|
||||
so you patch a `.so` that never loads.
|
||||
|
||||
This script reads the live mapping table and reports, per library: the path, the
|
||||
base address, and the architecture of the actual ELF on disk. It classifies each
|
||||
path so the interesting ones stand out (system / from-APK / runtime-materialized).
|
||||
|
||||
Requires root to read another process's maps.
|
||||
|
||||
Usage:
|
||||
python lib_map.py --pkg com.example.app
|
||||
python lib_map.py --pkg com.example.app --app-only
|
||||
python lib_map.py --pid 1234 --all
|
||||
python lib_map.py --pkg com.example.app --json
|
||||
python lib_map.py --pkg com.example.app --grep ssl
|
||||
|
||||
Reading it:
|
||||
* A library whose path sits under the app's data dir (not under the APK's
|
||||
lib/<abi> dir) was written at runtime. That is a packer/dropper fingerprint
|
||||
and it will not be present in a repacked APK -- patch or replace with care.
|
||||
* If app libraries are 64-bit ARM but the device primary ABI is x86_64,
|
||||
a translator is in play. Timing and some native checks will differ.
|
||||
* If the library you patched does not appear here at all, your patch cannot
|
||||
matter. That is a plan problem, not a patch problem.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
E_MACHINE = {
|
||||
0x03: "x86", 0x3E: "x86_64", 0x28: "arm", 0xB7: "aarch64",
|
||||
0x08: "mips", 0xF3: "riscv", 0x16: "s390", 0x15: "ppc",
|
||||
}
|
||||
TRANSLATOR_MARKERS = ("houdini", "libndk", "native_bridge", "libntv", "armtrans",
|
||||
"libhoudini", "ndk_translation", "libarm", "exagear", "box64")
|
||||
|
||||
|
||||
def run(cmd: list[str], timeout: int = 60) -> str:
|
||||
try:
|
||||
p = subprocess.run(cmd, capture_output=True, text=True, errors="replace", timeout=timeout)
|
||||
return (p.stdout or "") + (p.stderr or "")
|
||||
except Exception as e:
|
||||
return "ERROR: %s" % e
|
||||
|
||||
|
||||
def classify(path: str, pkg: str | None) -> str:
|
||||
if path.startswith(("/system/", "/apex/", "/vendor/", "/product/", "/odm/", "/system_ext/")):
|
||||
return "system"
|
||||
if re.search(r"/data/app/", path):
|
||||
return "apk-lib"
|
||||
if pkg and (("/data/data/%s" % pkg) in path or ("/data/user/0/%s" % pkg) in path):
|
||||
return "materialized"
|
||||
if "/data/" in path:
|
||||
return "data-other"
|
||||
return "other"
|
||||
|
||||
|
||||
def read_elf_arch(sh_fn, path: str) -> str:
|
||||
"""Read the ELF header on the device and name the machine. '?' means the read failed."""
|
||||
hdr = sh_fn("dd if='%s' bs=20 count=1 2>/dev/null | od -An -tx1 2>/dev/null" % path)
|
||||
hexs = re.sub(r"[^0-9a-fA-F]", "", hdr)
|
||||
if len(hexs) < 40:
|
||||
return "?"
|
||||
b = bytes.fromhex(hexs[:40])
|
||||
if b[:4] != b"\x7fELF":
|
||||
return "not-elf"
|
||||
cls = {1: 32, 2: 64}.get(b[4], 0)
|
||||
little = b[5] == 1
|
||||
mach = int.from_bytes(b[18:20], "little" if little else "big")
|
||||
if mach in E_MACHINE:
|
||||
return E_MACHINE[mach] # the machine name already implies the width
|
||||
return "0x%02x/%db" % (mach, cls or 0)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
tgt = ap.add_mutually_exclusive_group(required=True)
|
||||
tgt.add_argument("--pkg", help="target package name")
|
||||
tgt.add_argument("--pid", type=int, help="target pid")
|
||||
ap.add_argument("--adb", default=os.environ.get("ADB", "adb"))
|
||||
ap.add_argument("--serial", default=None)
|
||||
ap.add_argument("--all", action="store_true", help="include system libraries")
|
||||
ap.add_argument("--app-only", action="store_true", help="only APK libs and runtime-materialized libs")
|
||||
ap.add_argument("--grep", default=None, help="only paths matching this regex")
|
||||
ap.add_argument("--no-arch", action="store_true", help="skip reading ELF headers (faster)")
|
||||
ap.add_argument("--max-libs", type=int, default=120, help="cap how many libraries get an arch probe")
|
||||
ap.add_argument("--json", action="store_true", dest="as_json")
|
||||
a = ap.parse_args()
|
||||
|
||||
def sh(cmd: str, timeout: int = 60) -> str:
|
||||
base = [a.adb] + (["-s", a.serial] if a.serial else []) + ["shell", cmd]
|
||||
return run(base, timeout)
|
||||
|
||||
def su(cmd: str, timeout: int = 90) -> str:
|
||||
base = [a.adb] + (["-s", a.serial] if a.serial else []) + ["shell", 'su -c "%s"' % cmd]
|
||||
return run(base, timeout)
|
||||
|
||||
pid = a.pid
|
||||
if a.pkg and not pid:
|
||||
out = sh("pidof %s" % a.pkg).strip()
|
||||
if not out:
|
||||
print("no running process for %s -- launch it and let it settle first" % a.pkg, file=sys.stderr)
|
||||
return 2
|
||||
pid = int(out.split()[0])
|
||||
|
||||
maps = su("cat /proc/%d/maps" % pid)
|
||||
if not maps.strip() or "No such file" in maps:
|
||||
print("cannot read /proc/%d/maps (root required, or the process is gone)" % pid, file=sys.stderr)
|
||||
return 2
|
||||
|
||||
entries: dict[str, dict] = {}
|
||||
for line in maps.splitlines():
|
||||
m = re.match(r"^([0-9a-f]+)-([0-9a-f]+)\s+(\S+)\s+([0-9a-f]+)\s+\S+\s+\S+\s*(.*)$", line)
|
||||
if not m:
|
||||
continue
|
||||
start, end, perms, off, path = m.groups()
|
||||
path = path.strip()
|
||||
if not path or path.startswith("["):
|
||||
continue
|
||||
if not path.endswith(".so") and ".so." not in path:
|
||||
continue
|
||||
e = entries.setdefault(path, {"path": path, "perms": set(), "base": start, "count": 0})
|
||||
e["perms"].add(perms)
|
||||
e["count"] += 1
|
||||
if perms.startswith("r-x") or perms.startswith("r--"):
|
||||
e["base"] = min(e["base"], start)
|
||||
|
||||
dev_abi = sh("getprop ro.product.cpu.abi").strip()
|
||||
abilist = sh("getprop ro.product.cpu.abilist").strip()
|
||||
pkg = a.pkg
|
||||
if not pkg:
|
||||
cmdline = su("cat /proc/%d/cmdline" % pid).split("\x00")[0].strip()
|
||||
pkg = cmdline or None
|
||||
|
||||
rows = []
|
||||
probed = 0
|
||||
for path, e in sorted(entries.items()):
|
||||
kind = classify(path, pkg)
|
||||
if a.app_only and kind not in ("apk-lib", "materialized"):
|
||||
continue
|
||||
# --grep is an explicit narrow request, so honour it across all kinds
|
||||
if not a.all and not a.app_only and not a.grep and kind == "system":
|
||||
continue
|
||||
if a.grep and not re.search(a.grep, path):
|
||||
continue
|
||||
rows.append({"path": path, "base": e["base"], "kind": kind,
|
||||
"perms": "/".join(sorted(e["perms"])), "maps": e["count"], "arch": "?"})
|
||||
|
||||
if not a.no_arch:
|
||||
for r in rows[:a.max_libs]:
|
||||
r["arch"] = read_elf_arch(su, r["path"])
|
||||
probed += 1
|
||||
|
||||
# translation markers
|
||||
markers = sorted({p for p in entries if any(t in p.lower() for t in TRANSLATOR_MARKERS)})
|
||||
app_archs = sorted({r["arch"] for r in rows if r["kind"] in ("apk-lib", "materialized") and r["arch"] not in ("?", "not-elf")})
|
||||
host_is_x86 = "x86" in dev_abi
|
||||
translated = bool(markers) or (host_is_x86 and any(x.startswith(("arm", "aarch64")) for x in app_archs))
|
||||
|
||||
if a.as_json:
|
||||
print(json.dumps({"pid": pid, "pkg": pkg, "device_abi": dev_abi, "abilist": abilist,
|
||||
"translation_suspected": translated, "translator_markers": markers,
|
||||
"libs": rows}, indent=2, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
print("pid=%s pkg=%s" % (pid, pkg or "?"))
|
||||
print("device primary abi=%s abilist=[%s]" % (dev_abi, abilist))
|
||||
print("%-13s %-9s %-6s %-6s %s" % ("arch", "kind", "perms", "maps", "path"))
|
||||
print("-" * 100)
|
||||
for r in rows:
|
||||
print("%-13s %-9s %-6s %-6d %s" % (r["arch"], r["kind"], r["perms"], r["maps"], r["path"]))
|
||||
print("-" * 100)
|
||||
print("mapped libraries shown: %d" % len(rows))
|
||||
if not a.no_arch and probed < len(rows):
|
||||
print("(architecture probed for the first %d; raise --max-libs to cover the rest -- '?' means not probed)"
|
||||
% probed)
|
||||
|
||||
if markers:
|
||||
print("\nTRANSLATOR MARKERS PRESENT:")
|
||||
for mk in markers:
|
||||
print(" " + mk)
|
||||
print(" -> native ARM code is being translated. Timing differs from a real ARM device,")
|
||||
print(" and native integrity checks may behave differently. Verify the final artifact")
|
||||
print(" on the ABI the user actually runs.")
|
||||
if app_archs:
|
||||
print("\napp library architectures: %s" % ", ".join(app_archs))
|
||||
if translated:
|
||||
print("translation suspected: YES")
|
||||
mat = [r["path"] for r in rows if r["kind"] == "materialized"]
|
||||
if mat:
|
||||
print("\nRUNTIME-MATERIALIZED libraries (not inside the APK):")
|
||||
for p in mat[:20]:
|
||||
print(" " + p)
|
||||
print(" -> written at runtime by the app or its shell. A repacked APK will not contain")
|
||||
print(" them in this location; account for that before assuming your patch is loaded.")
|
||||
if not rows:
|
||||
print("\nnothing matched. Widen with --all, or check that the process is the one that draws the UI.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,279 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Extract native crash blocks from a log or tombstone and locate the fault.
|
||||
|
||||
Native deaths are the expensive kind: no Java stack, often no obvious cause, and
|
||||
the interesting question ("which library, which offset, is this a real fault or
|
||||
an arranged one?") is buried in a debug dump that is tedious to read by hand.
|
||||
|
||||
This reads a saved `logcat` capture or a tombstone file and reports, per crash:
|
||||
|
||||
* the signal, fault address, and cause
|
||||
* the register state that matters (the faulting pointer)
|
||||
* the backtrace, split into your own libraries vs system libraries
|
||||
* a verdict hint when the fault address looks *arranged* rather than accidental
|
||||
|
||||
With `--lib NAME=PATH` it also resolves a frame to a local copy of the library
|
||||
and prints the bytes at that offset, plus a disassembly window when a decoder is
|
||||
available.
|
||||
|
||||
Why the verdict hint matters: a hardening layer that decides the environment is
|
||||
hostile rarely calls `kill`. It more often arranges a fault -- load a small
|
||||
constant, use it as a pointer -- so the death looks like an ordinary bug. The
|
||||
tell is a fault address that is a small integer combined with a register holding
|
||||
that same integer. This script flags that shape so you look at the right place
|
||||
instead of hunting a bug that is not there.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python native_crash.py capture.txt
|
||||
python native_crash.py tombstone_07
|
||||
python native_crash.py capture.txt --lib libfoo.so=/path/to/local/libfoo.so
|
||||
python native_crash.py capture.txt --lib libfoo.so=./libfoo.so --disasm 16
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
SIGNAL_RE = re.compile(
|
||||
r"signal\s+(\d+)\s+\((\w+)\)\s*,?\s*code\s+(\d+)\s*\(([^)]+)\)\s*,?\s*fault addr\s+(0x[0-9a-fA-F]+)")
|
||||
PID_RE = re.compile(r"pid:\s*(\d+),\s*tid:\s*(\d+),\s*name:\s*(\S+)\s*>>>\s*(\S+)")
|
||||
PROC_RE = re.compile(r"Cmdline:\s*(\S+)")
|
||||
UPTIME_RE = re.compile(r"Process uptime:\s*(\d+)")
|
||||
FRAME_RE = re.compile(r"#(\d+)\s+pc\s+([0-9a-fA-F]+)\s+(\S+)")
|
||||
REG_RE = re.compile(r"^\s*([xX]\d{1,2}|sp|lr|pc|pst)\s+([0-9a-fA-F]{8,16})")
|
||||
SYSTEM_LIB_RE = re.compile(r"^/(apex|system|vendor|data/dalvik-cache|memfd)")
|
||||
|
||||
|
||||
def is_system_lib(path):
|
||||
if not path.startswith("/"):
|
||||
return True
|
||||
return bool(SYSTEM_LIB_RE.match(path))
|
||||
|
||||
|
||||
def parse(text):
|
||||
"""Yield crash dicts."""
|
||||
lines = text.splitlines()
|
||||
crashes = []
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
m = SIGNAL_RE.search(lines[i])
|
||||
# some ROMs print the signal line without "F DEBUG"; accept both
|
||||
if not m:
|
||||
i += 1
|
||||
continue
|
||||
block = {"signal": int(m.group(1)), "signame": m.group(2),
|
||||
"si_code": m.group(4), "fault": m.group(5),
|
||||
"frames": [], "regs": {}, "raw": []}
|
||||
# walk up a little to pick up pid/cmdline/uptime printed just before
|
||||
for j in range(max(0, i - 25), i):
|
||||
l = lines[j]
|
||||
mm = PID_RE.search(l)
|
||||
if mm and "pid" not in block:
|
||||
block["pid"], block["tid"], block["tname"], block["proc"] = mm.groups()
|
||||
mm = PROC_RE.search(l)
|
||||
if mm and "proc" not in block:
|
||||
block["proc"] = mm.group(1)
|
||||
mm = UPTIME_RE.search(l)
|
||||
if mm:
|
||||
block["uptime"] = mm.group(1)
|
||||
if "Cause:" in l and "cause" not in block:
|
||||
block["cause"] = l.split("Cause:", 1)[1].strip()
|
||||
# walk down through the dump
|
||||
j = i
|
||||
while j < len(lines) and j < i + 120:
|
||||
l = lines[j]
|
||||
if j > i + 3 and SIGNAL_RE.search(l) and j > i + 3:
|
||||
break
|
||||
block["raw"].append(l.strip())
|
||||
mm = PID_RE.search(l)
|
||||
if mm and "pid" not in block:
|
||||
block["pid"], block["tid"], block["tname"], block["proc"] = mm.groups()
|
||||
mm = PROC_RE.search(l)
|
||||
if mm and "proc" not in block:
|
||||
block["proc"] = mm.group(1)
|
||||
mm = UPTIME_RE.search(l)
|
||||
if mm:
|
||||
block["uptime"] = mm.group(1)
|
||||
if "Cause:" in l and "cause" not in block:
|
||||
block["cause"] = l.split("Cause:", 1)[1].strip()
|
||||
mm = FRAME_RE.search(l)
|
||||
if mm:
|
||||
# Backtrace lines look like either of:
|
||||
# #00 pc 00000000000128cc /data/app/.../lib/arm64/libfoo.so
|
||||
# #02 pc 00000000000cccd0 /apex/.../libc.so (__pthread_start+256)
|
||||
# The path is group(3); anything after it is a symbol in parens.
|
||||
path = mm.group(3)
|
||||
rest = l.split(path, 1)[1].strip() if path in l else ""
|
||||
sym = ""
|
||||
m2 = re.search(r"\(([^)]+)\)", rest)
|
||||
if m2:
|
||||
sym = m2.group(1)
|
||||
block["frames"].append({
|
||||
"n": mm.group(1), "pc": int(mm.group(2), 16),
|
||||
"path": path, "symbol": sym,
|
||||
})
|
||||
# Register dumps put several registers on one line, so collect all of
|
||||
# them rather than only the leading one.
|
||||
for k, v in re.findall(r"\b([xX]\d{1,2}|sp|lr|pc|pst)\s+([0-9a-fA-F]{8,16})\b",
|
||||
l.replace("F DEBUG :", " ")):
|
||||
block["regs"][k] = int(v, 16)
|
||||
if "backtrace:" in l:
|
||||
pass
|
||||
j += 1
|
||||
i = j if j > i else i + 1
|
||||
crashes.append(block)
|
||||
return crashes
|
||||
|
||||
|
||||
def verdict_hint(crash):
|
||||
hints = []
|
||||
fault = int(crash["fault"], 16)
|
||||
regs = crash["regs"]
|
||||
if fault <= 0x100:
|
||||
holder = [k for k, v in regs.items() if v == fault]
|
||||
hints.append("fault address is a small integer (%s)." % crash["fault"])
|
||||
if holder:
|
||||
hints.append("register(s) %s hold exactly that value -- this is the shape of an "
|
||||
"ARRANGED fault, not an accident." % ", ".join(sorted(holder)))
|
||||
hints.append("check whether the instruction at the faulting pc loaded that constant "
|
||||
"a few instructions earlier and used it as a pointer.")
|
||||
if crash["signame"] == "SIGKILL":
|
||||
hints.append("SIGKILL with no tombstone: this is a deliberate termination, not a bug. "
|
||||
"No crash dump exists because nothing faulted.")
|
||||
if crash.get("cause") and "null pointer" in crash["cause"] and fault > 0x100:
|
||||
hints.append("a genuine null-ish dereference; treat as an ordinary bug unless a small "
|
||||
"constant is involved.")
|
||||
return hints
|
||||
|
||||
|
||||
def load_libs(specs):
|
||||
out = {}
|
||||
for s in specs or []:
|
||||
if "=" not in s:
|
||||
sys.exit("--lib expects NAME=PATH, got %r" % s)
|
||||
name, path = s.split("=", 1)
|
||||
with open(path, "rb") as fh:
|
||||
out[name] = fh.read()
|
||||
return out
|
||||
|
||||
|
||||
def maybe_disasm(data, offset, count):
|
||||
try:
|
||||
from capstone import Cs, CS_ARCH_ARM64, CS_MODE_ARM, CS_ARCH_X86, CS_MODE_64
|
||||
except Exception:
|
||||
return None
|
||||
# guess arch from ELF e_machine
|
||||
if data[:4] != b"\x7fELF":
|
||||
return None
|
||||
machine = struct.unpack_from("<H", data, 18)[0]
|
||||
if machine == 183:
|
||||
md = Cs(CS_ARCH_ARM64, CS_MODE_ARM)
|
||||
start = offset & ~3
|
||||
elif machine == 62:
|
||||
md = Cs(CS_ARCH_X86, CS_MODE_64)
|
||||
start = max(0, offset - 16)
|
||||
else:
|
||||
return None
|
||||
out = []
|
||||
for ins in md.disasm(data[start:start + count * 8], start):
|
||||
mark = " <<<" if ins.address <= offset < ins.address + ins.size else ""
|
||||
out.append(" 0x%06x %-10s %s%s" % (ins.address, ins.mnemonic, ins.op_str, mark))
|
||||
if len(out) >= count:
|
||||
break
|
||||
if not out:
|
||||
# capstone stopped immediately -- say so rather than implying emptiness
|
||||
return [" (decoder produced nothing from this offset; a silent stop is not "
|
||||
"evidence there is no code here)"]
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Locate native crashes from a log or tombstone.")
|
||||
ap.add_argument("logfile", help="logcat capture or tombstone file")
|
||||
ap.add_argument("--lib", action="append", metavar="NAME=PATH",
|
||||
help="resolve frames for this library name to a local file")
|
||||
ap.add_argument("--disasm", type=int, default=0, metavar="N",
|
||||
help="disassemble N instructions around the faulting pc")
|
||||
ap.add_argument("--frames", type=int, default=12, help="how many frames to print")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not os.path.exists(args.logfile):
|
||||
sys.exit("no such file: %s" % args.logfile)
|
||||
with open(args.logfile, "r", encoding="utf-8", errors="replace") as fh:
|
||||
text = fh.read()
|
||||
|
||||
crashes = parse(text)
|
||||
if not crashes:
|
||||
print("no native crash block found in %s" % args.logfile)
|
||||
print("")
|
||||
print("This is a real negative only if the capture covers the death. Check:")
|
||||
print(" - was the crash buffer cleared *after* the build under test was installed?")
|
||||
print(" - does the capture include the tombstone? (a SIGKILL leaves none)")
|
||||
print(" - did the process die at all, or did it merely restart?")
|
||||
return
|
||||
|
||||
libs = load_libs(args.lib)
|
||||
|
||||
for idx, c in enumerate(crashes, 1):
|
||||
print("=" * 72)
|
||||
print("CRASH %d" % idx)
|
||||
print(" process : %s" % c.get("proc", "?"))
|
||||
print(" pid/tid : %s / %s" % (c.get("pid", "?"), c.get("tid", "?")))
|
||||
if c.get("uptime"):
|
||||
print(" uptime : %ss <-- time from launch to death; your test window must "
|
||||
"exceed this" % c["uptime"])
|
||||
print(" signal : %s (%d), si_code=%s" % (c["signame"], c["signal"], c["si_code"]))
|
||||
print(" fault addr: %s" % c["fault"])
|
||||
if c.get("cause"):
|
||||
print(" cause : %s" % c["cause"])
|
||||
|
||||
hints = verdict_hint(c)
|
||||
if hints:
|
||||
print(" HINTS")
|
||||
for h in hints:
|
||||
print(" - %s" % h)
|
||||
|
||||
app_frames = [f for f in c["frames"] if not is_system_lib(f["path"])]
|
||||
if app_frames:
|
||||
print(" backtrace (your libraries):")
|
||||
for f in app_frames[:args.frames]:
|
||||
print(" #%s pc 0x%x %s%s"
|
||||
% (f["n"], f["pc"], os.path.basename(f["path"]),
|
||||
(" (%s)" % f["symbol"]) if f["symbol"] else ""))
|
||||
else:
|
||||
print(" backtrace: no frame inside an app library")
|
||||
print(" -> the fault is in the runtime or a system library; an app-side")
|
||||
print(" patch is unlikely to be the cause. Look at what called in.")
|
||||
|
||||
if c["frames"]:
|
||||
print(" full backtrace:")
|
||||
for f in c["frames"][:args.frames]:
|
||||
tag = "system" if is_system_lib(f["path"]) else "APP"
|
||||
print(" #%s [%s] pc 0x%x %s%s"
|
||||
% (f["n"], tag, f["pc"], (f["path"] or "?"),
|
||||
(" (%s)" % f["symbol"]) if f["symbol"] else ""))
|
||||
|
||||
# resolve against local libraries
|
||||
for f in c["frames"]:
|
||||
base = os.path.basename(f["path"])
|
||||
for name, data in libs.items():
|
||||
if name in base or base in name:
|
||||
print(" local %s @ 0x%x:" % (name, f["pc"]))
|
||||
if args.disasm and f is c["frames"][0]:
|
||||
for line in maybe_disasm(data, f["pc"], args.disasm) or []:
|
||||
print(line)
|
||||
else:
|
||||
print(" raw: %s" % data[f["pc"]:f["pc"] + 16].hex(" "))
|
||||
print("")
|
||||
|
||||
print("=" * 72)
|
||||
print("RECORD THIS: signal, fault addr, and the time-to-death above. They are the")
|
||||
print("baseline an attempted fix must be measured against -- without them a later")
|
||||
print("run cannot distinguish 'fixed' from 'the timing changed'.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Method-level smali patcher.
|
||||
|
||||
Design notes (each one earned the hard way):
|
||||
- Only the instruction body is replaced: from the line after the `.method` declaration up to
|
||||
(but not including) `.end method`. The `.method` / `.end method` / `.annotation` sections are
|
||||
left untouched, so modifiers and annotations survive.
|
||||
- The patch manifest must state a self-consistent `.registers` value: the assembler rejects
|
||||
out-of-range registers, so `registers` must be >= the number of parameter registers and
|
||||
>= the highest register index used by any instruction + 1. Parameter registers:
|
||||
static method = number of parameters; instance method = number of parameters + 1 (this).
|
||||
- The manifest is a JSON list; each entry:
|
||||
{
|
||||
"file": "com/example/Helper.smali", # path relative to the smali tree root
|
||||
"method": ".method public final show(Landroid/app/Activity;)V", # exact .method line
|
||||
"registers": 3,
|
||||
"body": ["invoke-interface {p3}, ...;", "return-void"],
|
||||
"note": "why this patch exists" # optional, report only
|
||||
}
|
||||
|
||||
A literal-match tool: whitespace, operand punctuation and instruction names must match the
|
||||
source exactly, and the anchor must be unique. See references/patch-audit.md section 3.
|
||||
|
||||
Usage:
|
||||
python patch_smali.py <smali_tree> <patch.json> [--dry-run]
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
|
||||
|
||||
def split_methods(text):
|
||||
"""Split smali text into [(method_decl, start_idx, end_idx)] using line indices."""
|
||||
lines = text.split('\n')
|
||||
out = []
|
||||
start = None
|
||||
decl = None
|
||||
for i, ln in enumerate(lines):
|
||||
s = ln.strip()
|
||||
if s.startswith('.method ') and start is None:
|
||||
start, decl = i, s
|
||||
elif s == '.end method' and start is not None:
|
||||
out.append((decl, start, i))
|
||||
start, decl = None, None
|
||||
return lines, out
|
||||
|
||||
|
||||
def patch_one(path, decl_wanted, registers, body):
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
text = f.read()
|
||||
lines, methods = split_methods(text)
|
||||
hits = [m for m in methods if m[0] == decl_wanted.strip()]
|
||||
if not hits:
|
||||
return False, 'method not found: %s' % decl_wanted
|
||||
if len(hits) > 1:
|
||||
return False, 'ambiguous (%d matches): %s' % (len(hits), decl_wanted)
|
||||
_, start, end = hits[0]
|
||||
# Keep the .method line; rewrite the interior: .registers + body
|
||||
new_inner = [' .registers %d' % registers, '']
|
||||
for b in body:
|
||||
new_inner.append(' ' + b)
|
||||
new_lines = lines[:start + 1] + new_inner + [''] + lines[end:]
|
||||
with open(path, 'w', encoding='utf-8', newline='\n') as f:
|
||||
f.write('\n'.join(new_lines))
|
||||
return True, 'ok'
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 3:
|
||||
print(__doc__)
|
||||
return 2
|
||||
tree = sys.argv[1]
|
||||
spec = sys.argv[2]
|
||||
dry = '--dry-run' in sys.argv
|
||||
with open(spec, 'r', encoding='utf-8') as f:
|
||||
patches = json.load(f)
|
||||
ok = fail = 0
|
||||
for p in patches:
|
||||
full = os.path.join(tree, p['file'].replace('/', os.sep))
|
||||
if not os.path.isfile(full):
|
||||
print('[MISS-FILE] %s' % p['file'])
|
||||
fail += 1
|
||||
continue
|
||||
if dry:
|
||||
with open(full, 'r', encoding='utf-8') as f:
|
||||
_, methods = split_methods(f.read())
|
||||
found = any(m[0] == p['method'].strip() for m in methods)
|
||||
print('[%s] %s :: %s' % ('DRY-OK' if found else 'DRY-MISS', p['file'], p['method']))
|
||||
ok += 1 if found else 0
|
||||
fail += 0 if found else 1
|
||||
continue
|
||||
okk, msg = patch_one(full, p['method'], p['registers'], p['body'])
|
||||
print('[%s] %s :: %s (%s)' % ('OK' if okk else 'FAIL', p['file'], p['method'].split('(')[0].replace('.method ', ''), msg))
|
||||
ok += 1 if okk else 0
|
||||
fail += 0 if okk else 1
|
||||
print('\npatched=%d failed=%d%s' % (ok, fail, ' [dry-run]' if dry else ''))
|
||||
return 0 if fail == 0 else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,250 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Preflight: prove the environment is sane BEFORE you blame your patch.
|
||||
|
||||
Run this at the start of every experiment block, and again whenever something
|
||||
fails in a way you did not expect. A large share of "my patch broke the app"
|
||||
turns out to be device state, a dead device server, a leftover proxy setting, or
|
||||
a clock skew -- all of which look exactly like a broken artifact.
|
||||
|
||||
It is deliberately read-only: it changes nothing except optional cleanup of a
|
||||
device-wide proxy setting and port forwards it created itself.
|
||||
|
||||
Usage:
|
||||
python preflight.py
|
||||
python preflight.py --serial <serial> --pkg com.example.app
|
||||
python preflight.py --pkg com.example.app --expect-root
|
||||
python preflight.py --cleanup # remove proxy + frida port forwards it finds
|
||||
python preflight.py --json # machine-readable summary
|
||||
|
||||
Exit code is 0 when no BLOCKER was found, 1 otherwise. WARN never fails the run.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
BLOCKER, WARN, OK, INFO = "BLOCKER", "WARN", "OK", "INFO"
|
||||
|
||||
|
||||
class Report:
|
||||
def __init__(self) -> None:
|
||||
self.rows: list[tuple[str, str, str, str]] = []
|
||||
|
||||
def add(self, level: str, area: str, detail: str, fix: str = "") -> None:
|
||||
self.rows.append((level, area, detail, fix))
|
||||
|
||||
def worst(self) -> str:
|
||||
for lv in (BLOCKER, WARN, OK, INFO):
|
||||
if any(r[0] == lv for r in self.rows):
|
||||
return lv
|
||||
return OK
|
||||
|
||||
|
||||
def run(cmd: list[str], timeout: int = 60) -> tuple[int, str]:
|
||||
try:
|
||||
p = subprocess.run(cmd, capture_output=True, text=True, errors="replace", timeout=timeout)
|
||||
return p.returncode, (p.stdout or "") + (p.stderr or "")
|
||||
except FileNotFoundError:
|
||||
return 127, "not found: %s" % cmd[0]
|
||||
except subprocess.TimeoutExpired:
|
||||
return 124, "TIMEOUT after %ss: %s" % (timeout, " ".join(cmd[:4]))
|
||||
except Exception as e: # pragma: no cover - defensive
|
||||
return 1, "error: %s" % e
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--adb", default=os.environ.get("ADB", "adb"), help="adb executable (default: $ADB or 'adb')")
|
||||
ap.add_argument("--serial", default=None, help="device serial; required when more than one is attached")
|
||||
ap.add_argument("--pkg", default=None, help="target package to check (optional)")
|
||||
ap.add_argument("--expect-root", action="store_true", help="treat missing root as a BLOCKER")
|
||||
ap.add_argument("--cleanup", action="store_true", help="remove leftover proxy setting and frida forwards")
|
||||
ap.add_argument("--json", action="store_true", dest="as_json")
|
||||
a = ap.parse_args()
|
||||
|
||||
r = Report()
|
||||
ADB = a.adb
|
||||
|
||||
# ---- host tools -------------------------------------------------------
|
||||
for tool, why in (
|
||||
("java", "dexlib2 patcher, apksigner"),
|
||||
("python", "all scripts"),
|
||||
):
|
||||
found = shutil.which(tool)
|
||||
r.add(OK if found else WARN, "host:" + tool, found or "not on PATH", "" if found else "install it if you need " + why)
|
||||
for tool in ("apksigner", "zipalign", "aapt", "aapt2"):
|
||||
found = shutil.which(tool)
|
||||
r.add(OK if found else INFO, "host:" + tool, found or "not on PATH",
|
||||
"" if found else "only needed for signing/manifest work; build-tools on PATH helps")
|
||||
|
||||
# ---- adb + device selection ------------------------------------------
|
||||
if shutil.which(ADB) is None and not os.path.exists(ADB):
|
||||
r.add(BLOCKER, "adb", "executable not found: %s" % ADB, "pass --adb <path> or set $ADB")
|
||||
return finish(r, a.as_json)
|
||||
|
||||
rc, out = run([ADB, "devices", "-l"])
|
||||
if rc != 0:
|
||||
r.add(BLOCKER, "adb", "adb devices failed: %s" % out.strip()[:160], "start the adb server; check USB/emulator")
|
||||
return finish(r, a.as_json)
|
||||
|
||||
devices = []
|
||||
for line in out.splitlines()[1:]:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
parts = line.split()
|
||||
if len(parts) >= 2:
|
||||
devices.append((parts[0], parts[1], line))
|
||||
online = [d for d in devices if d[1] == "device"]
|
||||
|
||||
if not devices:
|
||||
r.add(BLOCKER, "device", "no device attached", "boot the emulator/connect the device, then re-run")
|
||||
return finish(r, a.as_json)
|
||||
if len(online) > 1 and not a.serial:
|
||||
r.add(BLOCKER, "device", "%d devices online but no --serial given" % len(online),
|
||||
"pass --serial explicitly, or adb will pick one at random and you will debug the wrong target")
|
||||
if not online:
|
||||
bad = ", ".join("%s(%s)" % (d[0], d[1]) for d in devices)
|
||||
r.add(BLOCKER, "device", "attached but not usable: %s" % bad,
|
||||
"unauthorized -> accept the USB debugging prompt; offline -> reconnect/reboot the emulator")
|
||||
return finish(r, a.as_json)
|
||||
|
||||
serial = a.serial or online[0][0]
|
||||
r.add(OK, "device", "using %s (of %d online)" % (serial, len(online)), "")
|
||||
|
||||
def sh(cmd: str, timeout: int = 60) -> str:
|
||||
return run([ADB, "-s", serial, "shell", cmd], timeout=timeout)[1]
|
||||
|
||||
def su(cmd: str, timeout: int = 90) -> str:
|
||||
return run([ADB, "-s", serial, "shell", 'su -c "%s"' % cmd], timeout=timeout)[1]
|
||||
|
||||
# ---- device facts -----------------------------------------------------
|
||||
abi = sh("getprop ro.product.cpu.abi").strip()
|
||||
abilist = sh("getprop ro.product.cpu.abilist").strip()
|
||||
rel = sh("getprop ro.build.version.release").strip()
|
||||
sdk = sh("getprop ro.build.version.sdk").strip()
|
||||
model = sh("getprop ro.product.model").strip()
|
||||
sec = sh("getenforce").strip()
|
||||
|
||||
r.add(OK, "device:os", "Android %s (sdk %s) %s" % (rel, sdk, model), "")
|
||||
r.add(OK, "device:abi", "%s abilist=[%s]" % (abi, abilist), "")
|
||||
r.add(OK if sec.lower() in ("permissive", "") else INFO, "device:selinux", sec or "?", "")
|
||||
|
||||
# translation layer / emulator hints -- these change how native code behaves
|
||||
trans = []
|
||||
for probe in ("ro.dalvik.vm.native.bridge", "ro.enable.native.bridge.exec", "ro.boot.native_bridge"):
|
||||
v = sh("getprop " + probe).strip()
|
||||
if v and v != "0":
|
||||
trans.append("%s=%s" % (probe, v))
|
||||
r.add(WARN if trans else OK, "device:translation",
|
||||
"; ".join(trans) if trans else "no ARM translation declared",
|
||||
"native arm libraries run through a translator here: timing differs and some native checks misbehave" if trans else "")
|
||||
if re.search(r"^1$", sh("getprop ro.kernel.qemu").strip()):
|
||||
r.add(INFO, "device:type", "emulator (ro.kernel.qemu=1)",
|
||||
"final verification belongs on the real ABI the user will run")
|
||||
|
||||
# ---- root -------------------------------------------------------------
|
||||
idout = su("id")
|
||||
has_root = "uid=0" in idout
|
||||
lvl = OK if has_root else (BLOCKER if a.expect_root else WARN)
|
||||
r.add(lvl, "root", "available" if has_root else "NOT available (%s)" % idout.strip()[:60],
|
||||
"" if has_root else "anything beyond static analysis needs root: data dirs, Frida, file locks")
|
||||
|
||||
# ---- clock (silently breaks TLS work) --------------------------------
|
||||
dev_epoch = sh("date +%s").strip()
|
||||
if dev_epoch.isdigit():
|
||||
drift = abs(int(dev_epoch) - int(__import__("time").time()))
|
||||
r.add(OK if drift < 120 else WARN, "clock",
|
||||
"device/host drift %ds" % drift,
|
||||
"" if drift < 120 else "an expired/wrong certificate can be nothing but this clock; fix before TLS triage")
|
||||
|
||||
# ---- leftover state that fakes a failure -----------------------------
|
||||
proxy = sh("settings get global http_proxy").strip()
|
||||
if proxy and proxy not in ("null", ":0"):
|
||||
r.add(WARN, "state:proxy", "device-wide http_proxy=%s" % proxy,
|
||||
"a leftover proxy makes every request fail; clear with: settings put global http_proxy :0")
|
||||
if a.cleanup:
|
||||
sh("settings put global http_proxy :0")
|
||||
r.add(INFO, "state:proxy", "cleared (--cleanup)", "")
|
||||
else:
|
||||
r.add(OK, "state:proxy", "not set", "")
|
||||
|
||||
rc_f, fwd = run([ADB, "-s", serial, "forward", "--list"])
|
||||
if fwd.strip():
|
||||
r.add(INFO, "state:forwards", fwd.strip().replace("\n", " | ")[:200],
|
||||
"stale forwards point frida at the wrong place; 'adb forward --remove-all' resets them")
|
||||
if a.cleanup:
|
||||
run([ADB, "-s", serial, "forward", "--remove-all"])
|
||||
r.add(INFO, "state:forwards", "removed (--cleanup)", "")
|
||||
|
||||
# ---- frida server reachability ---------------------------------------
|
||||
srv = su("pgrep -f frida-server || pgrep -f kwork")
|
||||
if srv.strip().isdigit() or srv.strip().split("\n")[0].strip().isdigit():
|
||||
r.add(OK, "frida:server", "device server process alive (pid %s)" % srv.strip().split("\n")[0].strip(), "")
|
||||
else:
|
||||
r.add(INFO, "frida:server", "no device server process found",
|
||||
"only needed for dynamic work; see references/dynamic-frida.md (name it out of obvious paths)")
|
||||
|
||||
# ---- target package ---------------------------------------------------
|
||||
if a.pkg:
|
||||
pm = sh("pm list packages | grep -F %s" % a.pkg)
|
||||
installed = ("package:" + a.pkg) in pm or a.pkg in pm
|
||||
r.add(OK if installed else INFO, "target", "installed" if installed else "not installed", "")
|
||||
if installed:
|
||||
path = sh("pm path %s" % a.pkg).strip()
|
||||
uid = su("dumpsys package %s | grep -m1 userId=" % a.pkg).strip()
|
||||
r.add(INFO, "target:apk", path[:160] or "?", "")
|
||||
r.add(INFO, "target:uid", uid or "?", "re-check after every reinstall: uid increments")
|
||||
# the native library dir the package manager will use for this device
|
||||
nat = sh("dumpsys package %s | grep -m3 primaryCpuAbi" % a.pkg).strip()
|
||||
if nat:
|
||||
r.add(INFO, "target:abi", nat.replace("\n", " | ")[:160],
|
||||
"this is the ABI the package manager chose for THIS device")
|
||||
maps = su("cat /proc/$(pidof %s | awk '{print $1}')/maps 2>/dev/null | head -1" % a.pkg)
|
||||
if maps.strip():
|
||||
r.add(INFO, "target:running", "process is running", "prefer a clean cold start before measuring anything")
|
||||
else:
|
||||
r.add(OK, "target:running", "not running", "")
|
||||
|
||||
# ---- free space -------------------------------------------------------
|
||||
# Report by device node, not by the mount-point column: a block device can be
|
||||
# mounted at more than one path (an ARM translation shim does exactly this on
|
||||
# some emulators), and `df` will then label /data with an unrelated path.
|
||||
space = ""
|
||||
for line in sh("df -h /data 2>/dev/null").splitlines()[1:]:
|
||||
cols = line.split()
|
||||
if len(cols) >= 5:
|
||||
space = "%s: %s available of %s (%s used)" % (cols[0], cols[3], cols[1], cols[4])
|
||||
break
|
||||
if space:
|
||||
r.add(INFO, "device:space", space, "")
|
||||
|
||||
return finish(r, a.as_json)
|
||||
|
||||
|
||||
def finish(r: Report, as_json: bool) -> int:
|
||||
if as_json:
|
||||
print(json.dumps({"worst": r.worst(),
|
||||
"rows": [dict(level=l, area=ar, detail=d, fix=f) for l, ar, d, f in r.rows]},
|
||||
indent=2, ensure_ascii=False))
|
||||
return 1 if r.worst() == BLOCKER else 0
|
||||
|
||||
width = max(len(x[1]) for x in r.rows) if r.rows else 10
|
||||
for level, area, detail, fix in r.rows:
|
||||
print("%-8s %-*s %s" % ("[" + level + "]", width, area, detail))
|
||||
if fix:
|
||||
print(" " * 9 + "%-*s -> %s" % (width, "", fix))
|
||||
print("\nworst: %s" % r.worst())
|
||||
if r.worst() == BLOCKER:
|
||||
print("Fix every BLOCKER before running another experiment. Do not attribute a failure to your patch yet.")
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Probe an app's HTTP API the way the app does.
|
||||
|
||||
Purpose-built for the common frustration: your request gets 403 while the app
|
||||
works fine. Almost always the app sends a header you are not sending (frequently
|
||||
one custom header), or your egress IP differs from the device's.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python probe_api.py --base https://api.example.com --path /health
|
||||
python probe_api.py --base https://api.example.com --path /adverts \
|
||||
--param position=banner --header 'X-App-Name: myapp'
|
||||
python probe_api.py --base https://api.example.com \
|
||||
--path "/items?page=1" --raw
|
||||
|
||||
Options
|
||||
-------
|
||||
--base Base URL (required)
|
||||
--path Path, may already contain a query string (required)
|
||||
--param k=v Repeatable; appended as query parameters
|
||||
--header k=v Repeatable; sent as-is. Always send the app's real headers.
|
||||
--token T Convenience: adds 'Authorization: Bearer T'
|
||||
--ua UA User-Agent (default: okhttp/4.12.0)
|
||||
--no-proxy Ignore environment proxy settings (recommended)
|
||||
--show Print the first N bytes of the body (default 800)
|
||||
|
||||
Interpreting results
|
||||
--------------------
|
||||
200 + data -> alive; read the envelope shape
|
||||
200 + empty list -> valid input, nothing to return. Do NOT assume "ad removed":
|
||||
it may simply be that no item is configured.
|
||||
400 + message -> input is validated; the message often lists valid values
|
||||
401/403, no creds -> auth-gated (server-side ownership)
|
||||
401/403, forged -> token is verified server-side; client patching cannot mint one
|
||||
403 + HTML body -> a WAF/CDN refused your *request shape* or egress, not the endpoint
|
||||
404 -> exact path mismatch
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
|
||||
def build_opener(no_proxy):
|
||||
if no_proxy:
|
||||
return urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
return urllib.request.build_opener()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(add_help=True)
|
||||
ap.add_argument('--base', required=True)
|
||||
ap.add_argument('--path', required=True)
|
||||
ap.add_argument('--param', action='append', default=[])
|
||||
ap.add_argument('--header', action='append', default=[])
|
||||
ap.add_argument('--token')
|
||||
ap.add_argument('--ua', default='okhttp/4.12.0')
|
||||
ap.add_argument('--no-proxy', action='store_true')
|
||||
ap.add_argument('--show', type=int, default=800)
|
||||
a = ap.parse_args()
|
||||
|
||||
url = a.base.rstrip('/') + a.path
|
||||
if a.param:
|
||||
params = []
|
||||
for p in a.param:
|
||||
if '=' not in p:
|
||||
print('[FAIL] --param expects k=v, got %r' % p)
|
||||
return 2
|
||||
k, v = p.split('=', 1)
|
||||
params.append((k, v))
|
||||
sep = '&' if '?' in url else '?'
|
||||
url += sep + urllib.parse.urlencode(params)
|
||||
|
||||
headers = {
|
||||
'User-Agent': a.ua,
|
||||
'Accept': 'application/json',
|
||||
}
|
||||
for h in a.header:
|
||||
if ':' not in h:
|
||||
print('[FAIL] --header expects "Name: value", got %r' % h)
|
||||
return 2
|
||||
k, v = h.split(':', 1)
|
||||
headers[k.strip()] = v.strip()
|
||||
if a.token:
|
||||
headers['Authorization'] = 'Bearer %s' % a.token
|
||||
|
||||
print('[req] GET %s' % url)
|
||||
for k, v in headers.items():
|
||||
shown = v if k.lower() != 'authorization' else v[:24] + '...'
|
||||
print(' %s: %s' % (k, shown))
|
||||
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
op = build_opener(a.no_proxy)
|
||||
try:
|
||||
with op.open(req, timeout=30) as r:
|
||||
body = r.read().decode('utf-8', 'replace')
|
||||
print('[res] %s %s' % (r.status, r.headers.get('Content-Type', '')))
|
||||
print(body[:a.show])
|
||||
if body.strip().startswith(('{', '[')):
|
||||
try:
|
||||
parsed = json.loads(body)
|
||||
if isinstance(parsed, dict) and 'data' in parsed:
|
||||
d = parsed['data']
|
||||
if isinstance(d, dict) and 'list' in d:
|
||||
print('[shape] data.list length=%s' % len(d['list'] or []))
|
||||
except Exception:
|
||||
pass
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode('utf-8', 'replace')
|
||||
print('[res] HTTP %s' % e.code)
|
||||
print(body[:a.show])
|
||||
except Exception as e:
|
||||
print('[ERR] %s' % e)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,666 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Repack an APK with replaced dex files, drop ONLY the signature entries, and re-sign.
|
||||
|
||||
Pipeline: replace dex files -> drop signature artifacts -> zip, keeping
|
||||
AndroidManifest.xml and resources.arsc STORED -> zipalign + sign -> verify.
|
||||
|
||||
Everything machine-specific is a parameter or resolved from PATH. No JDK path is
|
||||
baked in, no keystore password is baked in, no target app is assumed.
|
||||
|
||||
Keystore handling:
|
||||
--ks <path> is where the keystore lives. If it does not exist, one is generated
|
||||
with keytool and its password is stored next to it as <ks>.pass.txt, so the next
|
||||
run reuses it. Passwords are never hardcoded in this script. That file is a local
|
||||
artifact -- do not commit it.
|
||||
|
||||
Usage examples:
|
||||
# roundtrip: reuse the original dexes unchanged, proves the pipeline itself works
|
||||
python repack.py --apk work/orig.apk --dexdir work/x_orig --out work/out/roundtrip.apk
|
||||
|
||||
# real patch: swap a single dex (name=path), other dexes kept from the apk
|
||||
python repack.py --apk work/orig.apk --dex classes8.dex=work/patch/classes8.dex \
|
||||
--out work/out/patched.apk
|
||||
|
||||
# no signing, no java tooling required at all
|
||||
python repack.py --apk work/orig.apk --dexdir work/x_orig --out work/unsigned.apk --no-sign
|
||||
|
||||
Notes:
|
||||
* All java tooling is invoked through python subprocess, never through a host
|
||||
shell (PowerShell drops arguments in ways that look like tool failures).
|
||||
* uber-apk-signer silently skips already-signed apks (reports 0 processed), which
|
||||
is why signature entries are always dropped before signing.
|
||||
* uber-apk-signer is used for SIGNING to keep the verified path unchanged;
|
||||
apksigner is used for VERIFYING when present, with an explicit sdk range.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
STORE_ONLY = ('AndroidManifest.xml', 'resources.arsc')
|
||||
|
||||
|
||||
def log(msg):
|
||||
print(msg, flush=True)
|
||||
|
||||
|
||||
def run(cmd, **kw):
|
||||
return subprocess.run(cmd, capture_output=True, text=True, errors='replace', **kw)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tool resolution: PATH first, explicit flag second, never a baked-in path.
|
||||
# ---------------------------------------------------------------------------
|
||||
def sibling_tool(exe, name):
|
||||
"""Look for `name` next to `exe`, for JDKs whose bin dir is not on PATH."""
|
||||
if not exe:
|
||||
return None
|
||||
folder = os.path.dirname(exe)
|
||||
for cand in (name, name + '.exe', name + '.bat'):
|
||||
path = os.path.join(folder, cand)
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def resolve_tool(name, explicit=None, hint_exe=None):
|
||||
if explicit:
|
||||
return explicit
|
||||
found = shutil.which(name)
|
||||
if found:
|
||||
return found
|
||||
return sibling_tool(hint_exe, name)
|
||||
|
||||
|
||||
def resolve_tools(args):
|
||||
"""Locate java/keytool/jarsigner/zipalign/apksigner. Missing ones stay None."""
|
||||
java = resolve_tool('java', args.java)
|
||||
tools = {
|
||||
'java': java,
|
||||
'keytool': resolve_tool('keytool', args.keytool, java),
|
||||
'jarsigner': resolve_tool('jarsigner', args.jarsigner, java),
|
||||
'zipalign': resolve_tool('zipalign', args.zipalign),
|
||||
'apksigner': resolve_tool('apksigner', args.apksigner),
|
||||
}
|
||||
return tools
|
||||
|
||||
|
||||
def require(tools, key, why):
|
||||
if tools.get(key):
|
||||
return tools[key]
|
||||
raise SystemExit(
|
||||
"error: '%s' was not found on PATH, and it is needed to %s.\n"
|
||||
" install a JDK (17+ recommended) / Android build-tools and put them on PATH,\n"
|
||||
" or pass the path explicitly (--%s <path>).\n"
|
||||
" Path lookup is deliberate: a machine-specific absolute path must never be\n"
|
||||
" baked into this script." % (key, why, key))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Keystore
|
||||
# ---------------------------------------------------------------------------
|
||||
def read_pwd_file(path):
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, encoding='utf-8') as fh:
|
||||
txt = fh.read().strip()
|
||||
return txt or None
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def ensure_keystore(ks_path, alias, password, keytool):
|
||||
"""Return the keystore password, generating the keystore on first use."""
|
||||
pwd_file = ks_path + '.pass.txt'
|
||||
|
||||
if os.path.exists(ks_path):
|
||||
pwd = password or read_pwd_file(pwd_file)
|
||||
if not pwd:
|
||||
raise SystemExit(
|
||||
'error: keystore %s exists but its password is unknown.\n'
|
||||
' pass --ks-pass <pw>, or write the password into %s' % (ks_path, pwd_file))
|
||||
log('[ks] reuse %s (alias=%s)' % (ks_path, alias))
|
||||
return pwd
|
||||
|
||||
pwd = password or read_pwd_file(pwd_file)
|
||||
generated = pwd is None
|
||||
if generated:
|
||||
# keytool rejects passwords shorter than 6 characters.
|
||||
pwd = secrets.token_urlsafe(12)
|
||||
|
||||
folder = os.path.dirname(ks_path)
|
||||
if folder:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
cmd = [keytool, '-genkeypair', '-keystore', ks_path, '-alias', alias,
|
||||
'-keyalg', 'RSA', '-keysize', '2048', '-validity', '10000',
|
||||
'-storepass', pwd, '-keypass', pwd,
|
||||
'-dname', 'CN=apkreverse, OU=dev, O=dev, L=NA, ST=NA, C=NA']
|
||||
r = run(cmd)
|
||||
if r.returncode != 0:
|
||||
log('[ks] keytool failed rc=%d\n%s\n%s' % (r.returncode, r.stdout, r.stderr))
|
||||
raise SystemExit(1)
|
||||
|
||||
try:
|
||||
with open(pwd_file, 'w', encoding='utf-8') as fh:
|
||||
fh.write(pwd + '\n')
|
||||
os.chmod(pwd_file, 0o600)
|
||||
except OSError as exc:
|
||||
log('[ks] could not persist the password: %s' % exc)
|
||||
|
||||
log('[ks] generated %s (alias=%s)' % (ks_path, alias))
|
||||
if generated:
|
||||
log('[ks] password stored in %s -- local artifact, do not commit it' % pwd_file)
|
||||
return pwd
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Packing
|
||||
# ---------------------------------------------------------------------------
|
||||
def collect_replacement_dex(dexdir=None, dex_pairs=None):
|
||||
repl = {}
|
||||
if dexdir:
|
||||
for name in sorted(os.listdir(dexdir)):
|
||||
if re.match(r'^classes\d*\.dex$', name):
|
||||
repl[name] = os.path.join(dexdir, name)
|
||||
for pair in (dex_pairs or []):
|
||||
if '=' not in pair:
|
||||
raise SystemExit('--dex expects name=path, got %r' % pair)
|
||||
name, path = pair.split('=', 1)
|
||||
repl[name] = path
|
||||
return repl
|
||||
|
||||
|
||||
def is_signature_entry(name):
|
||||
"""True ONLY for JAR/APK signature artifacts directly under META-INF/.
|
||||
|
||||
META-INF/services/**, META-INF/androidx/**, META-INF/native-image/** and every
|
||||
other subdirectory are RUNTIME RESOURCES and must survive repacking. Anything
|
||||
that is not directly under META-INF/ is kept by construction.
|
||||
"""
|
||||
if not name.upper().startswith('META-INF/'):
|
||||
return False
|
||||
rest = name[len('META-INF/'):]
|
||||
if '/' in rest:
|
||||
return False
|
||||
up = rest.upper()
|
||||
if up == 'MANIFEST.MF':
|
||||
return True
|
||||
return up.endswith(('.SF', '.RSA', '.DSA', '.EC'))
|
||||
|
||||
|
||||
def build_unsigned(apk, repl, out_apk, drop_signatures=True):
|
||||
"""Write a new apk with dex replaced and only signature entries dropped.
|
||||
|
||||
IMPORTANT (root cause of a startup crash, do not regress):
|
||||
Stripping the WHOLE META-INF/ breaks ServiceLoader-based runtime wiring. Android
|
||||
reads these registries at runtime, and they live in the APK:
|
||||
META-INF/services/kotlinx.coroutines.internal.MainDispatcherFactory
|
||||
META-INF/services/io.ktor.client.HttpClientEngineContainer
|
||||
META-INF/services/<lib>.core.* (third-party SDK registries)
|
||||
META-INF/services/<obfuscated-class-name> (R8-renamed providers)
|
||||
Deleting them makes the app die at startup with something like:
|
||||
IllegalStateException: Module with the Main dispatcher is missing ...
|
||||
and the message never points at META-INF, so the cause is very hard to find.
|
||||
Therefore: drop signature artifacts only, keep every META-INF subdirectory.
|
||||
|
||||
ALIGNMENT. Writing the entries with a plain zipfile writer produces an archive
|
||||
Android R+ refuses to install:
|
||||
|
||||
Failure [-124: Failed parse during installPackageLI: Targeting R+ (version
|
||||
30 and above) requires the resources.arsc of installed APKs to be stored
|
||||
uncompressed and aligned on a 4-byte boundary]
|
||||
|
||||
Two independent requirements hide in that message: `resources.arsc` must be
|
||||
STORED (not deflated), and its data must start at a 4-byte boundary. The same
|
||||
applies to uncompressed `lib/*.so`. Python's zipfile cannot express an entry
|
||||
offset, so this writer emits the local headers itself and pads the local extra
|
||||
field to hit the boundary.
|
||||
"""
|
||||
seen = set()
|
||||
replaced_names = set(repl)
|
||||
|
||||
# Collect (name, source, data, keep_stored) in output order.
|
||||
plan = []
|
||||
with zipfile.ZipFile(apk, 'r') as zin:
|
||||
for item in zin.infolist():
|
||||
name = item.filename
|
||||
base = os.path.basename(name)
|
||||
if item.is_dir():
|
||||
continue
|
||||
if drop_signatures and is_signature_entry(name):
|
||||
log('[zip] - %s (signature artifact)' % name)
|
||||
continue
|
||||
if name in replaced_names:
|
||||
continue
|
||||
plan.append((name, item, zin.read(name),
|
||||
name in STORE_ONLY or base in STORE_ONLY))
|
||||
for name, path in sorted(repl.items()):
|
||||
with open(path, 'rb') as fh:
|
||||
data = fh.read()
|
||||
info = zipfile.ZipInfo(name, date_time=(2024, 1, 1, 0, 0, 0))
|
||||
plan.append((name, info, data, False))
|
||||
log('[zip] + %s (%d bytes <- %s)' % (name, len(data), path))
|
||||
|
||||
_write_aligned_zip(out_apk, plan)
|
||||
seen.update(name for name, _i, _d, _k in plan)
|
||||
return seen
|
||||
|
||||
|
||||
ALIGN = 4
|
||||
# Entries Android requires to be STORED, and (for some) 4-byte aligned.
|
||||
ALIGNED_STORED = ('resources.arsc',)
|
||||
ALIGNED_PATTERNS = (re.compile(r'^lib/[^/]+\.so$'),)
|
||||
FILLER_NAME = 'META-INF/ALIGN.RSV'
|
||||
|
||||
|
||||
def _needs_alignment(name):
|
||||
if name in ALIGNED_STORED:
|
||||
return True
|
||||
return any(p.match(name) for p in ALIGNED_PATTERNS)
|
||||
|
||||
|
||||
def _dos_word(dt):
|
||||
"""(time, date) MS-DOS words for a zip local header."""
|
||||
y, mo, d, h, mi, s = dt
|
||||
if y < 1980:
|
||||
y, mo, d, h, mi, s = 1980, 1, 1, 0, 0, 0
|
||||
return (h << 11) | (mi << 5) | (s // 2), ((y - 1980) << 9) | (mo << 5) | d
|
||||
|
||||
|
||||
def _local_header(nlen, method, crc, csize, usize, dt, flags=0, extralen=0):
|
||||
t, dd = _dos_word(dt)
|
||||
import struct
|
||||
return struct.pack('<IHHHHHIIIHH', 0x04034B50, 20, flags, method,
|
||||
t, dd, crc, csize, usize, nlen, extralen)
|
||||
|
||||
|
||||
def _deflate_raw(data):
|
||||
"""Raw deflate (no zlib wrapper), which is what a zip method-8 entry holds.
|
||||
|
||||
zlib.compress() prepends a 2-byte zlib header. Some readers tolerate it, some
|
||||
do not, and the failure reads as a corrupt entry rather than a bad compressor
|
||||
call, so use wbits=-15 and get it right the first time.
|
||||
"""
|
||||
import zlib
|
||||
c = zlib.compressobj(9, zlib.DEFLATED, -15)
|
||||
return c.compress(data) + c.flush()
|
||||
|
||||
|
||||
def _write_aligned_zip(out_path, plan):
|
||||
"""Write a zip whose STORED entries can be relied on for offset alignment.
|
||||
|
||||
Padding rule, and why it is not just `(-offset) % 4`: a zip extra area is a
|
||||
sequence of (id, size, payload) records, so its minimum useful length is 4
|
||||
bytes. A required pad of 1-3 bytes therefore CANNOT be expressed in the extra
|
||||
field. When that happens this writer inserts a stored filler entry of exactly
|
||||
the needed size instead -- the filler has a computable size, so the following
|
||||
entry still lands on the boundary.
|
||||
"""
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
order = []
|
||||
meta = {}
|
||||
offset = 0
|
||||
scratch = out_path + '.tmp'
|
||||
|
||||
with open(scratch, 'wb') as out:
|
||||
for name, info, data, keep_stored in plan:
|
||||
name_b = name.encode('utf-8')
|
||||
if keep_stored:
|
||||
method, payload = 0, data
|
||||
else:
|
||||
method, payload = 8, _deflate_raw(data)
|
||||
crc = zlib.crc32(data) & 0xFFFFFFFF
|
||||
|
||||
# reach the boundary before the local header of an aligned entry
|
||||
if _needs_alignment(name):
|
||||
need = (ALIGN - ((offset + 30 + len(name_b)) % ALIGN)) % ALIGN
|
||||
if need in (1, 2, 3):
|
||||
off2, fill_meta = _emit_filler(out, offset, need)
|
||||
order.append(FILLER_NAME)
|
||||
meta[FILLER_NAME] = fill_meta
|
||||
offset = off2
|
||||
|
||||
extra, extralen = b'', 0
|
||||
if _needs_alignment(name):
|
||||
head = 30 + len(name_b)
|
||||
if (offset + head) % ALIGN != 0:
|
||||
# expressible pad: one (id,size,payload) record >= 4 bytes
|
||||
pad = (ALIGN - ((offset + head) % ALIGN)) % ALIGN
|
||||
if pad < 4:
|
||||
pad += ALIGN
|
||||
extra = b'\xfe\xca' + struct.pack('<H', pad - 4) + b'\x00' * (pad - 4)
|
||||
extralen = len(extra)
|
||||
|
||||
flags = getattr(info, 'flag_bits', 0)
|
||||
local_header_offset = offset # the CD points at the HEADER
|
||||
out.write(_local_header(len(name_b), method, crc, len(payload),
|
||||
len(data), info.date_time, flags, extralen))
|
||||
out.write(name_b)
|
||||
out.write(extra)
|
||||
data_off = offset + 30 + len(name_b) + extralen
|
||||
if out.tell() != data_off:
|
||||
raise RuntimeError('offset bookkeeping drift for %s' % name)
|
||||
if _needs_alignment(name) and data_off % ALIGN != 0:
|
||||
raise RuntimeError('%s not aligned: data at 0x%x' % (name, data_off))
|
||||
out.write(payload)
|
||||
offset = out.tell()
|
||||
|
||||
order.append(name)
|
||||
meta[name] = {'name_b': name_b, 'method': method, 'crc': crc,
|
||||
'csize': len(payload), 'usize': len(data),
|
||||
'local_offset': local_header_offset,
|
||||
'date_time': info.date_time, 'flag_bits': flags,
|
||||
'external_attr': getattr(info, 'external_attr', 0)}
|
||||
|
||||
cd_start = out.tell()
|
||||
for name in order:
|
||||
m = meta[name]
|
||||
t, dd = _dos_word(m['date_time'])
|
||||
# central directory: sig, ver_made, ver_need, flags, method, time,
|
||||
# date, crc, csize, usize, namelen, extralen, commentlen, disk,
|
||||
# int_attr, ext_attr, local_header_offset
|
||||
out.write(struct.pack(
|
||||
'<IHHHHHHIIIHHHHHII', 0x02014B50, 20, 20, m.get('flag_bits', 0),
|
||||
m['method'], t, dd, m['crc'], m['csize'], m['usize'],
|
||||
len(m['name_b']), 0, 0, 0, 0,
|
||||
(m['external_attr'] >> 16) & 0xFFFF, m['local_offset']))
|
||||
out.write(m['name_b'])
|
||||
cd_size = out.tell() - cd_start
|
||||
out.write(struct.pack('<IHHHHIIH', 0x06054B50, 0, 0, len(order), len(order),
|
||||
cd_size, cd_start, 0))
|
||||
|
||||
shutil.move(scratch, out_path)
|
||||
return order
|
||||
|
||||
|
||||
def _emit_filler(out, offset, size):
|
||||
"""Insert a stored, zero-filled entry of exactly `size` payload bytes."""
|
||||
import struct
|
||||
import zlib
|
||||
name_b = FILLER_NAME.encode('utf-8')
|
||||
payload = b'\x00' * size
|
||||
crc = zlib.crc32(payload) & 0xFFFFFFFF
|
||||
out.write(_local_header(len(name_b), 0, crc, size, size, (1980, 1, 1, 0, 0, 0)))
|
||||
out.write(name_b)
|
||||
out.write(payload)
|
||||
return out.tell(), {'name_b': name_b, 'method': 0, 'crc': crc,
|
||||
'csize': size, 'usize': size,
|
||||
'local_offset': offset,
|
||||
'date_time': (1980, 1, 1, 0, 0, 0), 'external_attr': 0}
|
||||
|
||||
|
||||
def check_alignment(apk):
|
||||
"""Report storage + 4-byte alignment of the entries Android insists on.
|
||||
|
||||
Returns a list of complaint strings; empty means the install gate is satisfied.
|
||||
"""
|
||||
import struct
|
||||
bad = []
|
||||
with zipfile.ZipFile(apk, 'r') as z, open(apk, 'rb') as fh:
|
||||
for i in z.infolist():
|
||||
if not (i.filename in ALIGNED_STORED or _needs_alignment(i.filename)):
|
||||
continue
|
||||
fh.seek(i.header_offset)
|
||||
lh = fh.read(30)
|
||||
nlen, elen = struct.unpack('<HH', lh[26:30])
|
||||
data_off = i.header_offset + 30 + nlen + elen
|
||||
if i.compress_type != 0:
|
||||
bad.append('%s is compressed (method=%d); Android R+ requires '
|
||||
'STORED' % (i.filename, i.compress_type))
|
||||
if i.filename != FILLER_NAME and data_off % ALIGN != 0:
|
||||
bad.append('%s data offset 0x%x is not %d-byte aligned'
|
||||
% (i.filename, data_off, ALIGN))
|
||||
return bad
|
||||
|
||||
|
||||
def zip_report(apk):
|
||||
"""Entry summary, including the storage/alignment facts Android gates on."""
|
||||
import struct
|
||||
rows = []
|
||||
with zipfile.ZipFile(apk, 'r') as z, open(apk, 'rb') as fh:
|
||||
for i in z.infolist():
|
||||
base = os.path.basename(i.filename)
|
||||
needs = (i.filename in STORE_ONLY or base in STORE_ONLY
|
||||
or _needs_alignment(i.filename))
|
||||
if needs:
|
||||
fh.seek(i.header_offset)
|
||||
lh = fh.read(30)
|
||||
nlen, elen = struct.unpack('<HH', lh[26:30])
|
||||
data_off = i.header_offset + 30 + nlen + elen
|
||||
verdict = 'aligned' if data_off % ALIGN == 0 else 'NOT ALIGNED'
|
||||
stored = 'STORED' if i.compress_type == 0 else \
|
||||
'COMPRESSED(method=%d)' % i.compress_type
|
||||
rows.append('%-40s %-22s offset=0x%-8x %s'
|
||||
% (i.filename, stored, data_off, verdict))
|
||||
if re.match(r'^classes\d*\.dex$', i.filename):
|
||||
rows.append('%s %d bytes method=%d crc=%08x' % (
|
||||
i.filename, i.file_size, i.compress_type, i.CRC))
|
||||
return rows
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Sign / verify
|
||||
# ---------------------------------------------------------------------------
|
||||
def sign_apk(unsigned_apk, workdir, ks, alias, password, tools, signer_jar):
|
||||
java = require(tools, 'java', 'run the signer jar')
|
||||
if not os.path.exists(signer_jar):
|
||||
raise SystemExit(
|
||||
'error: signer jar not found: %s\n'
|
||||
' pass --signer-jar <path>, or set APK_SIGNER_JAR.\n'
|
||||
' Any zipalign+apksigner based signer works here.' % signer_jar)
|
||||
|
||||
outdir = os.path.join(workdir, 'signed')
|
||||
if os.path.isdir(outdir):
|
||||
shutil.rmtree(outdir, ignore_errors=True)
|
||||
os.makedirs(outdir, exist_ok=True)
|
||||
|
||||
cmd = [java, '-jar', signer_jar,
|
||||
'--apks', unsigned_apk,
|
||||
'--ks', ks, '--ksAlias', alias,
|
||||
'--ksPass', password, '--ksKeyPass', password,
|
||||
'-o', outdir, '--verbose']
|
||||
r = run(cmd)
|
||||
log('[sign] rc=%d' % r.returncode)
|
||||
log(r.stdout.strip())
|
||||
if r.stderr.strip():
|
||||
log('[sign][stderr] ' + r.stderr.strip())
|
||||
|
||||
cand = os.path.join(outdir, os.path.basename(unsigned_apk))
|
||||
if not os.path.exists(cand):
|
||||
outs = [os.path.join(outdir, f) for f in os.listdir(outdir)] \
|
||||
if os.path.isdir(outdir) else []
|
||||
if not outs:
|
||||
raise SystemExit('signing produced no output')
|
||||
cand = outs[0]
|
||||
return cand
|
||||
|
||||
|
||||
def verify_apk(apk, tools, signer_jar=None, expect_signed=True):
|
||||
log('== verify: %s' % apk)
|
||||
ok = True
|
||||
sig_checks = 0 # real signature-verification tools that actually ran
|
||||
|
||||
# 1) apksigner -- the authoritative check, but ONLY with an explicit sdk range.
|
||||
#
|
||||
# READ THIS BEFORE CONCLUDING THE SIGNATURE IS BROKEN:
|
||||
# `apksigner verify` with no range checks the signature schemes implied by the
|
||||
# APK's own minSdkVersion. With minSdk >= 24 it prints v1/v2 as false while the
|
||||
# files in META-INF are perfectly fine, which looks exactly like a failed signing
|
||||
# step. Always pass --min-sdk-version / --max-sdk-version so the v1/v2/v3 results
|
||||
# are meaningful.
|
||||
if tools.get('apksigner'):
|
||||
sig_checks += 1
|
||||
r = run([tools['apksigner'], 'verify', '--print-certs', '--verbose',
|
||||
'--min-sdk-version', '21', '--max-sdk-version', '34', apk])
|
||||
log('[verify:apksigner] rc=%d\n%s' % (r.returncode, ((r.stdout or '') +
|
||||
(r.stderr or '')).strip()[:3000]))
|
||||
if r.returncode != 0:
|
||||
ok = False
|
||||
else:
|
||||
log('[verify:apksigner] skipped: apksigner not on PATH.\n'
|
||||
' Do NOT judge the signature from a bare `apksigner verify`: with\n'
|
||||
' minSdk >= 24 its default range reports v1/v2 as false even when the\n'
|
||||
' signature is valid. The correct invocation is:\n'
|
||||
' apksigner verify --print-certs --verbose --min-sdk-version 21 '
|
||||
'--max-sdk-version 34 <apk>')
|
||||
|
||||
# 2) signer jar's own verify (also re-checks alignment)
|
||||
if signer_jar and os.path.exists(signer_jar) and tools.get('java'):
|
||||
sig_checks += 1
|
||||
r = run([tools['java'], '-jar', signer_jar, '-a', apk, '-y'])
|
||||
log('[verify:signer] rc=%d\n%s' % (r.returncode, (r.stdout or '').strip()))
|
||||
if r.returncode != 0 and 'DOES NOT VERIFY' in (r.stdout or ''):
|
||||
ok = False
|
||||
|
||||
# 3) jarsigner (v1 / JAR signature)
|
||||
if tools.get('jarsigner'):
|
||||
sig_checks += 1
|
||||
r = run([tools['jarsigner'], '-verify', '-certs', apk])
|
||||
txt = ((r.stdout or '') + (r.stderr or '')).strip()
|
||||
log('[verify:jarsigner] rc=%d\n%s' % (r.returncode, txt[:2000]))
|
||||
if 'jar verified' not in txt and 'verified' not in txt.lower():
|
||||
log('[verify:jarsigner] note: not reported as verified (see output above)')
|
||||
|
||||
# 4) keytool cert dump
|
||||
if tools.get('keytool'):
|
||||
r = run([tools['keytool'], '-printcert', '-jarfile', apk])
|
||||
log('[verify:keytool] rc=%d\n%s' % (r.returncode, (r.stdout or '').strip()[:1500]))
|
||||
|
||||
# 5) zipalign check
|
||||
if tools.get('zipalign'):
|
||||
r = run([tools['zipalign'], '-c', '-v', '4', apk])
|
||||
log('[verify:zipalign] rc=%d' % r.returncode)
|
||||
if r.returncode != 0:
|
||||
log((r.stdout or '').strip()[:1500])
|
||||
else:
|
||||
log('[verify:zipalign] skipped: zipalign not on PATH')
|
||||
|
||||
# 6) v2/v3 APK Signing Block presence, read straight from the file
|
||||
with open(apk, 'rb') as fh:
|
||||
blob = fh.read()
|
||||
log('[verify:v2block] %s' % ('present' if b'APK Sig Block 42' in blob else 'MISSING'))
|
||||
|
||||
# A build nobody could verify is not a passing build. Saying OK here would
|
||||
# violate the first rule of this skill ("an APK is not done until it is
|
||||
# verified"): report UNVERIFIED and fail instead.
|
||||
if expect_signed and sig_checks == 0:
|
||||
log('[result] UNVERIFIED: no signature verification tool was available '
|
||||
'(apksigner / jarsigner / signer jar). This is NOT an OK result.')
|
||||
return False
|
||||
return ok
|
||||
|
||||
|
||||
def fingerprint(apk, tools):
|
||||
if not tools.get('keytool'):
|
||||
return []
|
||||
r = run([tools['keytool'], '-printcert', '-jarfile', apk])
|
||||
return re.findall(r'(SHA1|SHA256):\s*([0-9A-F:]+)', r.stdout or '')
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='Repack an APK with replaced dex files, drop only the signature '
|
||||
'entries, re-sign and verify.')
|
||||
ap.add_argument('--apk', required=True, help='source apk to use as the template')
|
||||
ap.add_argument('--out', required=True, help='output apk path')
|
||||
ap.add_argument('--dexdir', help='directory of classes*.dex to swap in')
|
||||
ap.add_argument('--dex', action='append', default=[],
|
||||
help='name=path, repeatable, e.g. classes8.dex=work/patch/classes8.dex')
|
||||
ap.add_argument('--workdir', default=None,
|
||||
help='scratch directory (default: next to --out)')
|
||||
ap.add_argument('--ks', default=None, help='keystore path (created on first use)')
|
||||
ap.add_argument('--ks-alias', default='apkreverse', help='keystore alias')
|
||||
ap.add_argument('--ks-pass', default=None,
|
||||
help='keystore password; default: <ks>.pass.txt, else generated')
|
||||
ap.add_argument('--signer-jar', default=None,
|
||||
help='jar used for zipalign+sign (default: $APK_SIGNER_JAR or '
|
||||
'uber-apk-signer.jar)')
|
||||
ap.add_argument('--no-sign', action='store_true', help='stop after writing the apk')
|
||||
ap.add_argument('--java', default=None, help='path to java (default: from PATH)')
|
||||
ap.add_argument('--keytool', default=None, help='path to keytool (default: from PATH)')
|
||||
ap.add_argument('--jarsigner', default=None, help='path to jarsigner (default: from PATH)')
|
||||
ap.add_argument('--zipalign', default=None, help='path to zipalign (default: from PATH)')
|
||||
ap.add_argument('--apksigner', default=None, help='path to apksigner (default: from PATH)')
|
||||
args = ap.parse_args()
|
||||
|
||||
tools = resolve_tools(args)
|
||||
signer_jar = args.signer_jar or os.environ.get('APK_SIGNER_JAR', 'uber-apk-signer.jar')
|
||||
|
||||
apk = os.path.abspath(args.apk)
|
||||
out = os.path.abspath(args.out)
|
||||
if not os.path.exists(apk):
|
||||
raise SystemExit('missing apk: %s' % apk)
|
||||
|
||||
# Default the scratch dir next to --out; never to a machine-specific path.
|
||||
workdir = os.path.abspath(args.workdir) if args.workdir else os.path.dirname(out)
|
||||
if not workdir:
|
||||
workdir = os.getcwd()
|
||||
os.makedirs(workdir, exist_ok=True)
|
||||
out_folder = os.path.dirname(out)
|
||||
if out_folder:
|
||||
os.makedirs(out_folder, exist_ok=True)
|
||||
|
||||
repl = collect_replacement_dex(args.dexdir, args.dex)
|
||||
log('[in ] %s (%d bytes)' % (apk, os.path.getsize(apk)))
|
||||
log('[tools] java=%s keytool=%s apksigner=%s zipalign=%s'
|
||||
% (tools['java'], tools['keytool'], tools['apksigner'], tools['zipalign']))
|
||||
log('[repl] %s' % (', '.join('%s<-%s' % (k, v) for k, v in sorted(repl.items())) or '<none>'))
|
||||
|
||||
unsigned = os.path.join(workdir, 'unsigned.apk')
|
||||
if os.path.exists(unsigned):
|
||||
os.remove(unsigned)
|
||||
build_unsigned(apk, repl, unsigned)
|
||||
log('[zip] unsigned written: %d bytes' % os.path.getsize(unsigned))
|
||||
for row in zip_report(unsigned):
|
||||
log('[zip] ' + row)
|
||||
|
||||
if args.no_sign:
|
||||
shutil.copy2(unsigned, out)
|
||||
else:
|
||||
if not args.ks:
|
||||
raise SystemExit(
|
||||
"error: --ks is required when signing (there is no default keystore).\n"
|
||||
" e.g. --ks work/out/release.keystore")
|
||||
keytool = require(tools, 'keytool', 'create the keystore on first use')
|
||||
password = ensure_keystore(os.path.abspath(args.ks), args.ks_alias,
|
||||
args.ks_pass, keytool)
|
||||
signed = sign_apk(unsigned, workdir, os.path.abspath(args.ks), args.ks_alias,
|
||||
password, tools, signer_jar)
|
||||
shutil.copy2(signed, out)
|
||||
|
||||
log('[out] %s (%d bytes)' % (out, os.path.getsize(out)))
|
||||
log('== zip layout of final apk')
|
||||
for row in zip_report(out):
|
||||
log(' ' + row)
|
||||
alignment_problems = check_alignment(out)
|
||||
if alignment_problems:
|
||||
log('== ALIGNMENT/STORAGE GATE FAILED -- do not ship this build:')
|
||||
for p in alignment_problems:
|
||||
log(' - %s' % p)
|
||||
log(' Android R+ (targetSdk 30+) refuses to install an APK whose '
|
||||
'resources.arsc is compressed or not 4-byte aligned.')
|
||||
else:
|
||||
log('== alignment gate: resources.arsc STORED and 4-byte aligned (OK)')
|
||||
|
||||
ok = verify_apk(out, tools, signer_jar, expect_signed=not args.no_sign)
|
||||
if not args.no_sign:
|
||||
for algo, val in fingerprint(out, tools):
|
||||
log('[cert] %s %s' % (algo, val))
|
||||
log('[result] %s' % ('OK' if ok else 'CHECK-FAILED'))
|
||||
else:
|
||||
log('[result] UNSIGNED (--no-sign): good for inspection, not installable as-is')
|
||||
log('[reminder] repacking is not done until the app launches and the changed '
|
||||
'behavior is exercised on a device: see scripts/install_test.py')
|
||||
return 0 if ok else 2
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,360 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Inject a Frida probe script into a running Android app and stay resident.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
`frida -U -f <pkg> -l script.js` has two failure modes that cost real debugging time:
|
||||
1. With a real device AND an emulator both attached, the USB auto-selection picks
|
||||
the emulator, so you attach to the wrong process and see nothing. This tool
|
||||
prefers an explicit remote device over `adb forward`, which cannot be hijacked.
|
||||
2. Probe output that only goes to a terminal is lost the moment the terminal
|
||||
scrolls, the session detaches, or the app crashes. Here every message is
|
||||
written to a log file *and* to stdout, with both the device timestamp and the
|
||||
host arrival timestamp -- that pair is itself evidence when you suspect a
|
||||
clock skew problem.
|
||||
|
||||
It also answers the three questions that otherwise produce a bare traceback:
|
||||
* is the `frida` python module importable, and which version?
|
||||
* is `adb` reachable, and is the target process actually running?
|
||||
* is an on-device frida-server answering on the forwarded port?
|
||||
|
||||
USAGE
|
||||
-----
|
||||
python run_probe.py frida_probe.js 10 --pkg com.example.app
|
||||
python run_probe.py frida_probe.js 5 --pkg com.example.app --device <serial>
|
||||
python run_probe.py frida_probe.js 5 --pkg com.example.app --via usb
|
||||
python run_probe.py frida_probe.js 2 --pkg com.example.app --spawn
|
||||
python run_probe.py frida_probe.js 10 --pkg com.example.app --log my.log --port 27043
|
||||
|
||||
<script.js> the probe to inject (e.g. frida_probe.js, see its header to adapt)
|
||||
<minutes> how long to stay attached (default 10)
|
||||
|
||||
NOTES
|
||||
-----
|
||||
* The host `frida` package and the on-device `frida-server` must be the SAME
|
||||
version, and 16.x is the version to align on: 17.x can fail to locate the
|
||||
Android dynamic linker and removes the built-in Java bridge.
|
||||
* `--spawn` is the right choice when the problem happens at startup: attach-only
|
||||
misses init and the first network calls. Hooks are installed before resume.
|
||||
* Log file: a timestamped name is generated unless --log is given.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
DEFAULT_PORT = 27042
|
||||
DEFAULT_MINUTES = 10
|
||||
DEFAULT_SERVER_PORT = 27042 # the port frida-server listens on, on the device
|
||||
|
||||
FRIDA_INSTALL_HINT = (
|
||||
'install the matching host package and the matching device server, e.g.\n'
|
||||
' pip install frida==16.7.19\n'
|
||||
' # then push frida-server-16.7.19-android-<abi> to the device and run it as root'
|
||||
)
|
||||
|
||||
|
||||
def host_ts():
|
||||
return datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
|
||||
|
||||
|
||||
class Logger(object):
|
||||
"""Write every line to stdout AND to a file, flushing both immediately."""
|
||||
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
self.fh = open(path, 'a', encoding='utf-8', errors='replace')
|
||||
|
||||
def line(self, text):
|
||||
print(text, flush=True)
|
||||
self.fh.write(text + '\n')
|
||||
self.fh.flush()
|
||||
|
||||
def close(self):
|
||||
try:
|
||||
self.fh.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def adb_run(adb, serial, args, timeout=30):
|
||||
cmd = [adb]
|
||||
if serial:
|
||||
cmd += ['-s', serial]
|
||||
cmd += args
|
||||
return subprocess.run(cmd, capture_output=True, text=True,
|
||||
errors='replace', timeout=timeout)
|
||||
|
||||
|
||||
def find_adb(explicit=None):
|
||||
if explicit:
|
||||
return explicit
|
||||
return shutil.which('adb') or shutil.which('adb.exe')
|
||||
|
||||
|
||||
def get_pid(adb, serial, pkg):
|
||||
"""Return (pid, raw_output). pid is None when the process is not running."""
|
||||
try:
|
||||
r = adb_run(adb, serial, ['shell', 'pidof', pkg])
|
||||
except subprocess.TimeoutExpired:
|
||||
return None, 'adb timed out'
|
||||
raw = ((r.stdout or '') + (r.stderr or '')).strip()
|
||||
if r.returncode != 0 or not raw:
|
||||
return None, raw
|
||||
first = raw.split()[0]
|
||||
if not first.isdigit():
|
||||
return None, raw
|
||||
return int(first), raw
|
||||
|
||||
|
||||
def attach_remote(frida, port, logger):
|
||||
mgr = frida.get_device_manager()
|
||||
logger.line('[host %s] registering remote device 127.0.0.1:%d' % (host_ts(), port))
|
||||
return mgr.add_remote_device('127.0.0.1:%d' % port)
|
||||
|
||||
|
||||
def attach_usb(frida, device_id, logger):
|
||||
if device_id:
|
||||
logger.line('[host %s] selecting usb device %s' % (host_ts(), device_id))
|
||||
return frida.get_device(device_id, timeout=5)
|
||||
logger.line('[host %s] selecting usb device (auto; an emulator can win this race)'
|
||||
% host_ts())
|
||||
return frida.get_usb_device(timeout=5)
|
||||
|
||||
|
||||
def format_message(message):
|
||||
"""Turn a frida message into one log line. Never raises."""
|
||||
kind = message.get('type')
|
||||
if kind == 'send':
|
||||
payload = message.get('payload')
|
||||
if isinstance(payload, dict):
|
||||
dev = payload.get('t') or '-'
|
||||
tag = payload.get('tag') or 'SEND'
|
||||
msg = payload.get('msg')
|
||||
if msg is None:
|
||||
msg = payload
|
||||
return dev, '%s %s' % (tag, msg)
|
||||
return '-', 'SEND %r' % (payload,)
|
||||
if kind == 'error':
|
||||
desc = message.get('description') or ''
|
||||
where = '%s:%s' % (message.get('fileName') or '?', message.get('lineNumber') or '?')
|
||||
stack = message.get('stack') or ''
|
||||
out = 'FRIDA-ERROR %s (%s)' % (desc, where)
|
||||
if stack:
|
||||
out += '\n ' + stack.replace('\n', '\n ')
|
||||
return '-', out
|
||||
return '-', '%s %r' % (kind, message)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='Inject a Frida probe into a running Android app, log everything '
|
||||
'to stdout and a file, and stay attached for N minutes.')
|
||||
ap.add_argument('script', help='path to the frida JS probe, e.g. frida_probe.js')
|
||||
ap.add_argument('minutes', nargs='?', type=float, default=DEFAULT_MINUTES,
|
||||
help='how long to stay attached (default %d)' % DEFAULT_MINUTES)
|
||||
ap.add_argument('--pkg', default=None, help='target package name, e.g. com.example.app')
|
||||
ap.add_argument('--device', default=None,
|
||||
help='adb serial (remote mode) or frida device id (usb mode)')
|
||||
ap.add_argument('--via', choices=['remote', 'usb'], default='remote',
|
||||
help='remote = adb forward + explicit remote device (default, '
|
||||
'cannot be hijacked by an emulator); usb = frida.get_usb_device()')
|
||||
ap.add_argument('--port', type=int, default=DEFAULT_PORT,
|
||||
help='host-side forwarded port (default %d)' % DEFAULT_PORT)
|
||||
ap.add_argument('--server-port', type=int, default=DEFAULT_SERVER_PORT,
|
||||
help='port frida-server listens on, on the device (default %d)'
|
||||
% DEFAULT_SERVER_PORT)
|
||||
ap.add_argument('--spawn', action='store_true',
|
||||
help='spawn the app instead of attaching, so hooks are live before '
|
||||
'the first network call')
|
||||
ap.add_argument('--log', default=None, help='log file path (default: auto-named)')
|
||||
ap.add_argument('--adb', default=None, help='path to adb (default: from PATH)')
|
||||
ap.add_argument('--script-timeout', type=float, default=30.0,
|
||||
help='seconds to wait for the script to load')
|
||||
ap.add_argument('--keep-forward', action='store_true',
|
||||
help='leave the adb forward in place after exit')
|
||||
args = ap.parse_args()
|
||||
|
||||
if not os.path.isfile(args.script):
|
||||
print('probe script not found: %s' % args.script)
|
||||
return 2
|
||||
if args.spawn and not args.pkg:
|
||||
print('--spawn needs --pkg (there is no pid to attach to)')
|
||||
return 2
|
||||
|
||||
log_name = args.log or ('probe-%s-%s.log'
|
||||
% (args.pkg or 'target', datetime.now().strftime('%Y%m%d-%H%M%S')))
|
||||
logger = Logger(log_name)
|
||||
logger.line('# probe log %s' % os.path.abspath(log_name))
|
||||
logger.line('# script=%s minutes=%s via=%s pkg=%s'
|
||||
% (os.path.abspath(args.script), args.minutes, args.via, args.pkg))
|
||||
|
||||
# 1) frida python package
|
||||
try:
|
||||
import frida
|
||||
except ImportError:
|
||||
logger.line(host_ts() + ' FATAL cannot import the frida python module.\n' +
|
||||
FRIDA_INSTALL_HINT)
|
||||
logger.close()
|
||||
return 3
|
||||
logger.line('[host %s] frida python %s' % (host_ts(), getattr(frida, '__version__', '?')))
|
||||
|
||||
# 2) adb
|
||||
adb = find_adb(args.adb)
|
||||
if not adb:
|
||||
logger.line(host_ts() + ' FATAL adb not found.\n'
|
||||
' put platform-tools on PATH, or pass --adb <path>')
|
||||
logger.close()
|
||||
return 3
|
||||
logger.line('[host %s] adb %s' % (host_ts(), adb))
|
||||
|
||||
pid = None
|
||||
forward_added = False
|
||||
device = None
|
||||
session = None
|
||||
script = None
|
||||
counts = {}
|
||||
deadline = time.monotonic() + max(args.minutes, 0) * 60.0
|
||||
|
||||
try:
|
||||
# 3) remote device over adb forward (default), or plain USB selection
|
||||
if args.via == 'remote':
|
||||
try:
|
||||
r = adb_run(adb, args.device,
|
||||
['forward', 'tcp:%d' % args.port, 'tcp:%d' % args.server_port])
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.line(host_ts() + ' FATAL adb forward timed out; is the device responsive?')
|
||||
return 3
|
||||
if r.returncode != 0:
|
||||
msg = ((r.stdout or '') + (r.stderr or '')).strip()
|
||||
logger.line(host_ts() + ' FATAL adb forward failed.\n'
|
||||
' adb said: %s\n'
|
||||
' if it mentions more than one device, pass --device <serial>;\n'
|
||||
' check the device is visible with: adb devices' % msg)
|
||||
return 3
|
||||
forward_added = True
|
||||
logger.line('[host %s] forwarded tcp:%d -> device tcp:%d'
|
||||
% (host_ts(), args.port, args.server_port))
|
||||
device = attach_remote(frida, args.port, logger)
|
||||
else:
|
||||
device = attach_usb(frida, args.device, logger)
|
||||
|
||||
# 4) pid: spawn when asked, otherwise attach to the running process
|
||||
if args.spawn:
|
||||
try:
|
||||
pid = device.spawn([args.pkg])
|
||||
except Exception as exc:
|
||||
logger.line(host_ts() + ' FATAL spawn failed for %s: %s\n'
|
||||
' check the package is installed: adb shell pm list packages | grep %s'
|
||||
% (args.pkg, exc, args.pkg))
|
||||
return 3
|
||||
logger.line('[device] spawned %s pid=%s' % (args.pkg, pid))
|
||||
else:
|
||||
if not args.pkg:
|
||||
logger.line(host_ts() + ' FATAL --pkg is required when attaching '
|
||||
'(or use --spawn with --pkg)')
|
||||
return 3
|
||||
pid, raw = get_pid(adb, args.device, args.pkg)
|
||||
if pid is None:
|
||||
logger.line(host_ts() + ' FATAL process not found: %s\n'
|
||||
' adb output: %s\n'
|
||||
' start the app first, or use --spawn to launch it under the probe;\n'
|
||||
' if pidof is unavailable on this ROM, try: adb shell ps -A'
|
||||
% (args.pkg, raw or '<empty>'))
|
||||
return 3
|
||||
logger.line('[device] pid of %s = %d' % (args.pkg, pid))
|
||||
|
||||
# 5) attach + load
|
||||
try:
|
||||
session = device.attach(pid)
|
||||
except Exception as exc:
|
||||
logger.line(host_ts() + ' FATAL attach failed: %s\n'
|
||||
' usual causes: frida-server not running on the device, a\n'
|
||||
' host/server version mismatch, or an anti-instrumentation check.\n'
|
||||
' %s' % (exc, FRIDA_INSTALL_HINT))
|
||||
return 3
|
||||
|
||||
with open(args.script, encoding='utf-8') as fh:
|
||||
source = fh.read()
|
||||
|
||||
def on_message(message, data):
|
||||
dev, text = format_message(message)
|
||||
tag = 'OTHER'
|
||||
if isinstance(message.get('payload'), dict):
|
||||
tag = message['payload'].get('tag') or 'SEND'
|
||||
elif message.get('type') == 'error':
|
||||
tag = 'FRIDA-ERROR'
|
||||
counts[tag] = counts.get(tag, 0) + 1
|
||||
logger.line('[host %s] [dev %s] %s' % (host_ts(), dev, text))
|
||||
if message.get('type') == 'error':
|
||||
desc = message.get('description') or ''
|
||||
if 'Java API not available' in desc or 'Java is not defined' in desc:
|
||||
logger.line('[hint] the script loaded but this runtime has no Java bridge. '
|
||||
'That is a version problem, not a hook problem: align the host '
|
||||
'frida package and the on-device frida-server to the same 16.x '
|
||||
'version, then retry. Do not debug the hooks until READY appears.')
|
||||
|
||||
script = session.create_script(source)
|
||||
script.on('message', on_message)
|
||||
try:
|
||||
script.load()
|
||||
except Exception as exc:
|
||||
logger.line(host_ts() + ' FATAL script load failed: %s\n'
|
||||
' if this says "Java is not defined", the runtime has no Java\n'
|
||||
' bridge: align host frida and on-device frida-server to 16.x.'
|
||||
% exc)
|
||||
return 3
|
||||
|
||||
if args.spawn:
|
||||
device.resume(pid)
|
||||
logger.line('[device] resumed pid=%d (hooks were installed before resume)' % pid)
|
||||
|
||||
logger.line('[host %s] attached; staying resident for %s minute(s). '
|
||||
'Now drive the app UI.' % (host_ts(), args.minutes))
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.line('[host %s] interrupted; detaching' % host_ts())
|
||||
finally:
|
||||
if script is not None:
|
||||
try:
|
||||
script.unload()
|
||||
except Exception:
|
||||
pass
|
||||
if session is not None:
|
||||
try:
|
||||
session.detach()
|
||||
except Exception:
|
||||
pass
|
||||
if forward_added and not args.keep_forward:
|
||||
try:
|
||||
adb_run(adb, args.device, ['forward', '--remove', 'tcp:%d' % args.port])
|
||||
logger.line('[host %s] removed adb forward tcp:%d' % (host_ts(), args.port))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
logger.line('')
|
||||
logger.line('== summary: %d message(s)' % sum(counts.values()))
|
||||
for tag in sorted(counts):
|
||||
logger.line(' %-16s %d' % (tag, counts[tag]))
|
||||
if not counts:
|
||||
logger.line(' no probe output at all. Ordered checklist:')
|
||||
logger.line(' 1. did READY appear? if not, the script never loaded')
|
||||
logger.line(' 2. is the class/overload name you configured really present?')
|
||||
logger.line(' 3. ClassLoader: the hooks bind against the app classloader')
|
||||
logger.line(' 4. did the UI action actually reach the business code?')
|
||||
logger.line(' 5. check THROW lines: a local validation may have returned early')
|
||||
logger.line('# log written to %s' % os.path.abspath(log_name))
|
||||
logger.close()
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,274 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
sig_probe.py -- find the exact value Android returns for
|
||||
`PackageInfo.signatures[0].toCharsString()`.
|
||||
|
||||
Why this exists: apps that use their own signing certificate as a *crypto key* need that
|
||||
value hardcoded after a repack. Deriving it offline is unreliable -- it is platform
|
||||
dependent, and on modern Android it is a single certificate from the chain, not the whole
|
||||
`META-INF/*.RSA` blob. Get it from the device, or cross-check offline candidates.
|
||||
|
||||
Usage
|
||||
-----
|
||||
# authoritative: read from a running (or launchable) package on a rooted device
|
||||
python sig_probe.py --live <package>
|
||||
python sig_probe.py --live <package> --serial <adb-serial> --host 127.0.0.1:27042
|
||||
|
||||
# offline: enumerate candidate blobs inside META-INF/*.RSA
|
||||
python sig_probe.py --apk <apk>
|
||||
|
||||
Output is plain hex, ready to paste into a `const-string` smali patch.
|
||||
|
||||
Notes
|
||||
-----
|
||||
* --live needs `frida` (pip install frida) plus a matching frida-server on the device.
|
||||
Host and device versions must match; see references/dynamic-frida.md.
|
||||
* `--serial` is honoured for adb calls. If several devices are attached, pass it -- Frida's
|
||||
USB auto-selection can silently pick the wrong one.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
SIG_EXTS = ('.RSA', '.DSA', '.EC')
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- DER helpers
|
||||
def _tlv(data, off):
|
||||
"""Return (tag, header_len, content_len). Raises on truncation."""
|
||||
if off + 2 > len(data):
|
||||
raise ValueError('truncated TLV at %d' % off)
|
||||
tag = data[off]
|
||||
first = data[off + 1]
|
||||
if first & 0x80:
|
||||
n = first & 0x7F
|
||||
if n == 0 or off + 2 + n > len(data):
|
||||
raise ValueError('bad length at %d' % off)
|
||||
length = int.from_bytes(data[off + 2:off + 2 + n], 'big')
|
||||
return tag, 2 + n, length
|
||||
return tag, 2, first
|
||||
|
||||
|
||||
def _children(data, start, end):
|
||||
"""Yield (tag, header_len, content_len, content_off) for each child in [start, end)."""
|
||||
off = start
|
||||
while off < end:
|
||||
tag, hlen, clen = _tlv(data, off)
|
||||
yield tag, hlen, clen, off + hlen
|
||||
off += hlen + clen
|
||||
|
||||
|
||||
def pkcs7_certificates(blob):
|
||||
"""Extract the DER certificate blobs from a PKCS#7 SignedData structure.
|
||||
|
||||
ContentInfo ::= SEQUENCE { contentType OID, content [0] EXPLICIT SignedData }
|
||||
SignedData ::= SEQUENCE { version, digestAlgorithms, contentInfo,
|
||||
certificates [0] IMPLICIT SET OF Certificate, ... }
|
||||
"""
|
||||
out = []
|
||||
tag, hlen, clen = _tlv(blob, 0)
|
||||
if tag != 0x30:
|
||||
return out
|
||||
content_off = hlen
|
||||
content_end = hlen + clen
|
||||
|
||||
# ContentInfo -> [0] EXPLICIT -> SignedData SEQUENCE
|
||||
signed_data = None
|
||||
for t, h, c, coff in _children(blob, content_off, content_end):
|
||||
if t == 0xA0: # content [0] EXPLICIT
|
||||
for t2, h2, c2, coff2 in _children(blob, coff, coff + c):
|
||||
if t2 == 0x30: # SignedData
|
||||
signed_data = (coff2, coff2 + c2)
|
||||
break
|
||||
if signed_data is None:
|
||||
return out
|
||||
|
||||
sd_start, sd_end = signed_data
|
||||
# children of SignedData: version, digestAlgorithms, contentInfo, certificates [0], ...
|
||||
seen_a0 = 0
|
||||
for t, h, c, coff in _children(blob, sd_start, sd_end):
|
||||
if t == 0xA0: # certificates [0] IMPLICIT
|
||||
seen_a0 += 1
|
||||
if seen_a0 > 1:
|
||||
break
|
||||
for t3, h3, c3, coff3 in _children(blob, coff, coff + c):
|
||||
if t3 == 0x30: # a Certificate
|
||||
out.append(blob[coff3 - h3:coff3 + c3])
|
||||
return out
|
||||
|
||||
|
||||
def candidates_from_apk(path):
|
||||
"""Every plausible hardcode candidate, longest-first, de-duplicated."""
|
||||
results = []
|
||||
with zipfile.ZipFile(path) as z:
|
||||
names = [n for n in z.namelist()
|
||||
if n.upper().startswith('META-INF/') and n.upper().endswith(SIG_EXTS)]
|
||||
for name in names:
|
||||
blob = z.read(name)
|
||||
whole = ('whole ' + name, blob)
|
||||
results.append(whole)
|
||||
for i, cert in enumerate(pkcs7_certificates(blob)):
|
||||
results.append(('%s cert[%d]' % (name, i), cert))
|
||||
|
||||
seen, uniq = set(), []
|
||||
for label, blob in results:
|
||||
if blob not in seen:
|
||||
seen.add(blob)
|
||||
uniq.append((label, blob))
|
||||
return uniq
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- live route
|
||||
LIVE_JS = r"""
|
||||
// Single-shot read. No timers: frida's JS runtime has no setTimeout, and using one
|
||||
// turns a "not ready yet" into a silent no-response. The Python side retries instead.
|
||||
Java.perform(function () {
|
||||
var pkg = PKG_NAME;
|
||||
try {
|
||||
var app = Java.use('android.app.ActivityThread').currentApplication();
|
||||
if (app === null) {
|
||||
send({ ok: false, retry: true, error: 'Application not initialized yet' });
|
||||
return;
|
||||
}
|
||||
var ctx = app.getApplicationContext();
|
||||
var pm = ctx.getPackageManager();
|
||||
var pi = pm.getPackageInfo(pkg, 64);
|
||||
var arr = pi.signatures.value;
|
||||
var out = [];
|
||||
for (var i = 0; i < arr.length; i++) {
|
||||
var s = arr[i].toCharsString();
|
||||
var blen = -1;
|
||||
try { blen = arr[i].toByteArray().length; } catch (e) {}
|
||||
out.push({ i: i, hex: s, len: s.length, bytes: blen });
|
||||
}
|
||||
send({ ok: true, signatures: out });
|
||||
} catch (e) {
|
||||
send({ ok: false, error: String(e) });
|
||||
}
|
||||
});
|
||||
"""
|
||||
|
||||
|
||||
def run_live(pkg, serial, host, timeout):
|
||||
try:
|
||||
import frida
|
||||
except ImportError:
|
||||
print('[!] frida not installed: pip install frida', file=sys.stderr)
|
||||
return 2
|
||||
|
||||
try:
|
||||
dev = frida.get_device_manager().add_remote_device(host)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print('[!] cannot reach frida-server at %s: %s' % (host, exc), file=sys.stderr)
|
||||
print(' is it running, and is the port forwarded? '
|
||||
'adb %sforward tcp:%s tcp:27042'
|
||||
% (('-s %s ' % serial) if serial else '',
|
||||
host.rsplit(':', 1)[-1]), file=sys.stderr)
|
||||
return 2
|
||||
|
||||
# A running process is preferred; fall back to spawning so package data is readable.
|
||||
pid, spawned = None, False
|
||||
for p in dev.enumerate_processes():
|
||||
if p.name == pkg:
|
||||
pid = p.pid
|
||||
break
|
||||
if pid is None:
|
||||
try:
|
||||
pid = dev.spawn([pkg])
|
||||
spawned = True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print('[!] package not running and could not be spawned: %s' % exc, file=sys.stderr)
|
||||
print(' launch it once, then re-run', file=sys.stderr)
|
||||
return 2
|
||||
|
||||
result = {}
|
||||
|
||||
def on_msg(msg, _data):
|
||||
if msg.get('type') == 'error':
|
||||
result['_js_error'] = msg.get('description') or str(msg)
|
||||
else:
|
||||
result.update(msg.get('payload') or {})
|
||||
|
||||
try:
|
||||
session = dev.attach(pid)
|
||||
if spawned:
|
||||
dev.resume(pid)
|
||||
time.sleep(1.0)
|
||||
|
||||
# Retry at the Python level: right after a spawn the Application object may not
|
||||
# exist yet, and the script reports that as retryable rather than failing.
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
result.clear()
|
||||
# V8 is required: on some frida builds the default runtime has no Java bridge,
|
||||
# and the failure looks like "no response" rather than a clear error.
|
||||
script = session.create_script(
|
||||
LIVE_JS.replace('PKG_NAME', repr(pkg).replace("'", '"')), runtime='v8')
|
||||
script.on('message', on_msg)
|
||||
script.load()
|
||||
t0 = time.time()
|
||||
while not result and time.time() - t0 < 1.5:
|
||||
time.sleep(0.1)
|
||||
if result.get('ok') or not result.get('retry'):
|
||||
break
|
||||
time.sleep(0.4)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print('[!] injection failed: %s' % exc, file=sys.stderr)
|
||||
return 2
|
||||
|
||||
if not result.get('ok'):
|
||||
detail = result.get('error') or result.get('_js_error') or 'no response'
|
||||
print('[!] probe failed: %s' % detail, file=sys.stderr)
|
||||
return 2
|
||||
|
||||
for sig in result['signatures']:
|
||||
print('signature[%d] toCharsString length = %d toByteArray bytes = %d'
|
||||
% (sig['i'], sig['len'], sig['bytes']))
|
||||
print(sig['hex'])
|
||||
print()
|
||||
return 0
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- main
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='Find the exact signatures[0].toCharsString() value (for hardcoding '
|
||||
'into a repacked APK).',
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog=__doc__)
|
||||
g = ap.add_mutually_exclusive_group(required=True)
|
||||
g.add_argument('--apk', help='APK to inspect offline (enumerates candidates)')
|
||||
g.add_argument('--live', metavar='PKG', help='package name; read the value from the device')
|
||||
ap.add_argument('--serial', help='adb serial (when several devices are attached)')
|
||||
ap.add_argument('--host', default='127.0.0.1:27042',
|
||||
help='frida-server endpoint for --live (default %(default)s)')
|
||||
ap.add_argument('--timeout', type=float, default=20.0,
|
||||
help='seconds to wait for the live probe (default %(default)s)')
|
||||
args = ap.parse_args()
|
||||
|
||||
if args.live:
|
||||
return run_live(args.live, args.serial, args.host, args.timeout)
|
||||
|
||||
cands = candidates_from_apk(args.apk)
|
||||
if not cands:
|
||||
print('[!] no META-INF/*.RSA|*.DSA|*.EC in %s (is it signed?)' % args.apk,
|
||||
file=sys.stderr)
|
||||
return 1
|
||||
|
||||
print('Candidates in %s' % args.apk)
|
||||
print('(modern Android returns ONE certificate from the chain, not the whole .RSA --')
|
||||
print(' use --live to know which; otherwise build one variant per candidate)\n')
|
||||
for label, blob in cands:
|
||||
print('%-28s %6d bytes %5d hex chars' % (label, len(blob), len(blob) * 2))
|
||||
print(blob.hex())
|
||||
print()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,10 @@
|
||||
# One jar path per line. Adjust the directory to your own tools.
|
||||
# Needed: smali baksmali dexlib2 util antlr-runtime stringtemplate jcommander guava
|
||||
smali-2.5.2.jar
|
||||
antlr-runtime-3.5.2.jar
|
||||
stringtemplate-3.2.1.jar
|
||||
baksmali-2.5.2.jar
|
||||
util-2.5.2.jar
|
||||
jcommander-1.64.jar
|
||||
guava-27.1-android.jar
|
||||
dexlib2-2.5.2.jar
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""baksmali / smali wrapper.
|
||||
|
||||
Assembling and disassembling dex requires smali + baksmali + several runtime jars on
|
||||
the classpath. Getting the set wrong produces a bare `ClassNotFoundException` that
|
||||
looks like a broken tool rather than a missing jar, so this wrapper centralizes it.
|
||||
|
||||
Two ways to configure the classpath, in priority order:
|
||||
1. --cp "jar1;jar2" (explicit, per invocation)
|
||||
2. APK_REVERSE_SMALI_CP env var
|
||||
3. a `smali_cp.txt` next to this script (one jar path per line, '#' comments ok)
|
||||
|
||||
Required jars: smali, baksmali, dexlib2, util, antlr-runtime, stringtemplate,
|
||||
jcommander, guava.
|
||||
|
||||
Usage
|
||||
-----
|
||||
python smtool.py d <in.dex> <out_dir> # disassemble to a smali tree
|
||||
python smtool.py a <in_tree> <out.dex> # assemble a smali tree back to dex
|
||||
python smtool.py check # print the resolved classpath and exit
|
||||
|
||||
Notes
|
||||
-----
|
||||
* Always pass the tree directory as its own argument; do not rely on the shell.
|
||||
* Call java from Python rather than from a shell: PowerShell in particular mangles
|
||||
arguments containing ';' or '$', which silently drops jars from the classpath.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CP_FILE = os.path.join(HERE, 'smali_cp.txt')
|
||||
|
||||
JAR_NAMES = [
|
||||
'smali-2.5.2.jar',
|
||||
'antlr-runtime-3.5.2.jar',
|
||||
'stringtemplate-3.2.1.jar',
|
||||
'baksmali-2.5.2.jar',
|
||||
'util-2.5.2.jar',
|
||||
'jcommander-1.64.jar',
|
||||
'guava-27.1-android.jar',
|
||||
'dexlib2-2.5.2.jar',
|
||||
]
|
||||
|
||||
|
||||
def resolve_cp(explicit=None):
|
||||
if explicit:
|
||||
return explicit
|
||||
env = os.environ.get('APK_REVERSE_SMALI_CP')
|
||||
if env:
|
||||
return env
|
||||
if os.path.isfile(CP_FILE):
|
||||
parts = []
|
||||
for line in open(CP_FILE, encoding='utf-8'):
|
||||
line = line.strip()
|
||||
if line and not line.startswith('#'):
|
||||
parts.append(line)
|
||||
if parts:
|
||||
return os.pathsep.join(parts)
|
||||
# last resort: look for the jars in a 'tools' dir next to this script
|
||||
cand = [os.path.join(HERE, 'tools', n) for n in JAR_NAMES]
|
||||
if all(os.path.isfile(c) for c in cand):
|
||||
return os.pathsep.join(cand)
|
||||
return None
|
||||
|
||||
|
||||
def run(cp, main_class, args):
|
||||
cmd = ['java', '-cp', cp, main_class] + args
|
||||
r = subprocess.run(cmd, capture_output=True, text=True, errors='replace')
|
||||
out = (r.stdout or '') + (('\n[stderr]\n' + r.stderr) if (r.stderr or '').strip() else '')
|
||||
return r.returncode, out
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print(__doc__)
|
||||
return 2
|
||||
|
||||
explicit = None
|
||||
argv = sys.argv[1:]
|
||||
if '--cp' in argv:
|
||||
i = argv.index('--cp')
|
||||
explicit = argv[i + 1]
|
||||
del argv[i:i + 2]
|
||||
|
||||
cp = resolve_cp(explicit)
|
||||
if not cp:
|
||||
print('[FAIL] no classpath. Provide --cp, set APK_REVERSE_SMALI_CP, '
|
||||
'or create smali_cp.txt next to this script.')
|
||||
return 1
|
||||
|
||||
cmd = argv[0]
|
||||
if cmd == 'check':
|
||||
print('classpath: %s' % cp)
|
||||
for j in cp.split(os.pathsep):
|
||||
print(' %s %s' % ('OK ' if os.path.isfile(j) else 'MISSING', j))
|
||||
return 0
|
||||
|
||||
if cmd in ('d', 'dis', 'disassemble'):
|
||||
if len(argv) < 3:
|
||||
print('usage: smtool.py d <in.dex> <out_dir>')
|
||||
return 2
|
||||
rc, out = run(cp, 'org.jf.baksmali.Main', ['d', argv[1], '-o', argv[2]])
|
||||
elif cmd in ('a', 'asm', 'assemble'):
|
||||
if len(argv) < 3:
|
||||
print('usage: smtool.py a <in_tree> <out.dex>')
|
||||
return 2
|
||||
rc, out = run(cp, 'org.jf.smali.Main', ['a', argv[1], '-o', argv[2]])
|
||||
else:
|
||||
print(__doc__)
|
||||
return 2
|
||||
|
||||
print(out.strip()[-4000:])
|
||||
print('rc=%d' % rc)
|
||||
return 0 if rc == 0 else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Capture what is actually on screen -- and say whether the control tree is usable.
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
Driving a UI blind (tap a coordinate, wait, tap again) is the single most
|
||||
expensive habit in device work. A look at the screen resolves in one step what
|
||||
coordinate guessing cannot resolve in five: the layout moved, a different dialog
|
||||
is up, a countdown is frozen, a button is disabled, text says why.
|
||||
|
||||
Two independent kinds of evidence, and they are not interchangeable:
|
||||
|
||||
* the **image** -- always available, always truthful about what is rendered.
|
||||
It is the only evidence for UI drawn by a runtime or a web view, where no
|
||||
real controls exist.
|
||||
* the **control tree** (`uiautomator dump`) -- precise, diffable, gives exact
|
||||
bounds and text. Frequently EMPTY for canvas/webview/cross-platform UI.
|
||||
|
||||
This script grabs both, reports the size and whether the tree had content, so
|
||||
you know which one is actually informative before you rely on it. It never
|
||||
touches app state.
|
||||
|
||||
Usage
|
||||
-----
|
||||
# one look
|
||||
python snap.py --out shots --tag before
|
||||
|
||||
# watch a wait: 6 samples, 3 s apart (bounded: hard cap of 20 samples)
|
||||
python snap.py --out shots --tag waiting --count 6 --interval 3
|
||||
|
||||
# tree only, no images
|
||||
python snap.py --out shots --tag tree --tree-only
|
||||
|
||||
# when nothing is on screen, capture and it will say so rather than guess
|
||||
python snap.py --out shots --tag check --serial <serial>
|
||||
|
||||
Reading the output
|
||||
------------------
|
||||
* `bytes=0` after both capture paths -> the device refused; see the note in the
|
||||
output rather than concluding the screen is blank.
|
||||
* `tree=EMPTY` -> do not plan around accessibility bounds. Use the image and
|
||||
reason from pixels, or drive the app through a non-UI path.
|
||||
* Identical hashes across samples -> nothing is changing. Stop waiting and go
|
||||
find out why (this is the stall detector).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
MAX_SAMPLES = 20 # hard cap so a typo cannot produce an unbounded loop
|
||||
|
||||
|
||||
def run(cmd: list[str], timeout: int) -> tuple[int, str, str]:
|
||||
try:
|
||||
p = subprocess.run(cmd, capture_output=True, text=True, errors="replace", timeout=timeout)
|
||||
return p.returncode, p.stdout or "", p.stderr or ""
|
||||
except subprocess.TimeoutExpired:
|
||||
return 124, "", "TIMEOUT after %ss: %s" % (timeout, " ".join(cmd[:4]))
|
||||
except FileNotFoundError:
|
||||
return 127, "", "not found: %s" % cmd[0]
|
||||
|
||||
|
||||
class Dev:
|
||||
def __init__(self, adb: str, serial: str | None):
|
||||
self.adb = adb
|
||||
self.base = [adb] + (["-s", serial] if serial else [])
|
||||
self.serial = serial
|
||||
|
||||
def sh(self, cmd: str, timeout: int = 60) -> str:
|
||||
return run(self.base + ["shell", cmd], timeout)[1]
|
||||
|
||||
def su(self, cmd: str, timeout: int = 90) -> str:
|
||||
return run(self.base + ["shell", 'su -c "%s"' % cmd], timeout)[1]
|
||||
|
||||
def pull(self, remote: str, local: str, timeout: int = 120) -> bool:
|
||||
rc, _, err = run(self.base + ["pull", remote, local], timeout)
|
||||
return rc == 0 and os.path.exists(local) and os.path.getsize(local) > 0
|
||||
|
||||
|
||||
def tree_stats(dev: Dev, workdir: str) -> tuple[str, int, int]:
|
||||
"""Return (status, node_count, text_count). status in {OK, EMPTY, FAILED}."""
|
||||
xml = "/data/local/tmp/_snap_ui.xml"
|
||||
dev.sh("rm -f " + xml)
|
||||
out = dev.su("uiautomator dump %s" % xml, timeout=90)
|
||||
if "dumped to" not in out and "UI hierchary" not in out and os.sep not in out:
|
||||
# some builds print nothing useful; fall through to the file check anyway
|
||||
pass
|
||||
local = os.path.join(workdir, "_snap_ui.xml")
|
||||
if not dev.pull(xml, local, timeout=120):
|
||||
return "FAILED", 0, 0
|
||||
try:
|
||||
data = open(local, encoding="utf-8", errors="replace").read()
|
||||
except Exception:
|
||||
return "FAILED", 0, 0
|
||||
nodes = len(re.findall(r"<node", data))
|
||||
texts = len([t for t in re.findall(r'text="([^"]*)"', data) if t.strip()])
|
||||
if nodes == 0:
|
||||
return "EMPTY", 0, 0
|
||||
# A tree with nodes but almost no text is usually a shell with no real widgets.
|
||||
return ("OK" if texts else "SPARSE"), nodes, texts
|
||||
|
||||
|
||||
def capture_image(dev: Dev, workdir: str, name: str) -> tuple[int, str]:
|
||||
remote = "/data/local/tmp/%s.png" % name
|
||||
dev.su("rm -f " + remote)
|
||||
# on-device write then pull: the streaming form returns 0 bytes on some ROMs
|
||||
dev.su("screencap -p %s" % remote, timeout=90)
|
||||
local = os.path.join(workdir, name + ".png")
|
||||
if dev.pull(remote, local, timeout=120):
|
||||
n = os.path.getsize(local)
|
||||
if n > 0:
|
||||
return n, hashlib.sha256(open(local, "rb").read()).hexdigest()[:12]
|
||||
# fallback: stream to host
|
||||
rc, out, err = run(dev.base + ["exec-out", "screencap -p"], timeout=120)
|
||||
if rc == 0:
|
||||
data = out.encode("latin1", "ignore") if isinstance(out, str) else b""
|
||||
if data:
|
||||
open(local, "wb").write(data)
|
||||
return len(data), hashlib.sha256(data).hexdigest()[:12]
|
||||
return 0, ""
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--adb", default=os.environ.get("ADB", "adb"))
|
||||
ap.add_argument("--serial", default=None, help="device serial; required when several are attached")
|
||||
ap.add_argument("--out", default="snapshots", help="output directory (created if missing)")
|
||||
ap.add_argument("--tag", default="snap", help="label used in filenames")
|
||||
ap.add_argument("--count", type=int, default=1, help="samples to take (capped at %d)" % MAX_SAMPLES)
|
||||
ap.add_argument("--interval", type=float, default=2.0, help="seconds between samples")
|
||||
ap.add_argument("--tree-only", action="store_true", help="skip images; only read the control tree")
|
||||
ap.add_argument("--image-only", action="store_true", help="skip the control tree")
|
||||
a = ap.parse_args()
|
||||
|
||||
if a.count > MAX_SAMPLES:
|
||||
print("count capped at %d (asked for %d)" % (MAX_SAMPLES, a.count), file=sys.stderr)
|
||||
a.count = MAX_SAMPLES
|
||||
|
||||
workdir = os.path.abspath(a.out)
|
||||
os.makedirs(workdir, exist_ok=True)
|
||||
dev = Dev(a.adb, a.serial)
|
||||
|
||||
# cheap reachability gate with a timeout, so we fail fast and informatively
|
||||
rc, out, err = run(dev.base + ["shell", "echo __ok__"], timeout=30)
|
||||
if "__ok__" not in out:
|
||||
print("device not answering: %s%s" % (out.strip()[:120], (" / " + err.strip()[:120]) if err else ""),
|
||||
file=sys.stderr)
|
||||
print("check `adb devices`; if the emulator process is alive but nothing is listening on the adb port,",
|
||||
file=sys.stderr)
|
||||
print("restart the instance through the vendor console (see references/environment.md).", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
tree_status = "skipped"
|
||||
nodes = texts = 0
|
||||
if not a.image_only:
|
||||
tree_status, nodes, texts = tree_stats(dev, workdir)
|
||||
print("control tree: %s (nodes=%d, non-empty text=%d)" % (tree_status, nodes, texts))
|
||||
if tree_status in ("EMPTY", "FAILED"):
|
||||
print(" -> the accessibility tree is not usable here. Do NOT plan around bounds from it.")
|
||||
print(" The image is the primary evidence for this UI. Cross-platform runtimes, web views")
|
||||
print(" and canvas-drawn UI frequently expose no real controls at all.")
|
||||
elif tree_status == "SPARSE":
|
||||
print(" -> tree exists but carries almost no text; treat it as unreliable and read the image.")
|
||||
|
||||
prev_hash = None
|
||||
same_run = 0
|
||||
for i in range(a.count):
|
||||
tag = a.tag if a.count == 1 else "%s_%02d" % (a.tag, i)
|
||||
if a.tree_only:
|
||||
print("%-14s tree-only sample" % tag)
|
||||
else:
|
||||
size, digest = capture_image(dev, workdir, tag)
|
||||
if size == 0:
|
||||
print("%-14s bytes=0 -> device refused the capture. Not evidence that the screen is blank." % tag)
|
||||
else:
|
||||
note = ""
|
||||
if digest == prev_hash:
|
||||
same_run += 1
|
||||
note = " (identical to previous -> nothing changed)"
|
||||
else:
|
||||
same_run = 0
|
||||
prev_hash = digest
|
||||
print("%-14s bytes=%-8d sha=%s%s" % (tag, size, digest, note))
|
||||
print("%-14s %s" % ("", os.path.join(workdir, tag + ".png")))
|
||||
if same_run >= 2:
|
||||
print(" -> %d identical samples in a row. This is a stall, not a slow operation." % (same_run + 1))
|
||||
print(" Stop waiting: inspect the image, or check the app is still alive and in the foreground.")
|
||||
if i < a.count - 1:
|
||||
time.sleep(max(0.0, a.interval))
|
||||
|
||||
print("\nNow LOOK at the image(s) before deciding the next action.")
|
||||
print("Driving blind and waiting is how rounds get wasted; the screen usually states the reason.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,275 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Redirect a native library load by rewriting an isolated string constant in place.
|
||||
|
||||
Why this exists
|
||||
---------------
|
||||
Protected targets frequently name a *checker* library at a single call site
|
||||
(``System.loadLibrary("X")`` reached from a JNI constant pool) rather than through
|
||||
``DT_NEEDED``. When that checker does the integrity validation, deleting the loader
|
||||
deadlocks you: keep it and validation kills the process, delete it and the load
|
||||
throws.
|
||||
|
||||
Rewriting the *name* is the way out. Point that call at a library that is guaranteed
|
||||
already mapped (on Android, ``android`` / ``libandroid.so``): the load succeeds, the
|
||||
checker is never mapped, and **no byte offsets move** because the replacement is
|
||||
exactly the same length. Nothing for an integrity check to notice about layout, and
|
||||
no death path to neutralize.
|
||||
|
||||
Usage
|
||||
-----
|
||||
# inspect: where does this name occur, and is it an isolated constant?
|
||||
python so_constpatch.py libfoo.so --find apkhuan
|
||||
|
||||
# patch a bare .so
|
||||
python so_constpatch.py libfoo.so --replace apkhuan=android -o libfoo.patched.so
|
||||
|
||||
# patch inside an APK (rebuilds the zip, entry order preserved)
|
||||
python so_constpatch.py app.apk --entry lib/arm64-v8a/libfoo.so \
|
||||
--replace apkhuan=android -o app.patched.apk
|
||||
|
||||
# only patch occurrences that sit in an ELF constant-pool section
|
||||
python so_constpatch.py libfoo.so --replace apkhuan=android --section-aware
|
||||
|
||||
Design notes
|
||||
------------
|
||||
* Equal length is mandatory and enforced; there is no padding mode that can be safe
|
||||
when the next constant lives immediately after the NUL.
|
||||
* ``--find`` reports whether each hit is isolated (NUL on both sides). Patching a
|
||||
substring of a longer identifier corrupts that identifier, so non-isolated hits are
|
||||
refused unless ``--allow-nonisolated`` is given explicitly.
|
||||
* The ELF section map is only used for *reporting* which constant pool a hit lives in.
|
||||
It never gates a patch on section validity, because hardened libraries ship forged
|
||||
section headers (see references/native-tamper-and-suicide.md) while the bytes you
|
||||
need are still exactly where the loader reads them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import io
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import zipfile
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- ELF helpers
|
||||
|
||||
def elf_sections(data: bytes):
|
||||
"""Return [(name, sh_type, addr, offset, size)] or [] if unusable.
|
||||
|
||||
Deliberately tolerant: forged/truncated section headers are common in this
|
||||
domain, and a failed parse must not stop the string scan.
|
||||
"""
|
||||
try:
|
||||
if data[:4] != b'\x7fELF':
|
||||
return []
|
||||
e_shoff = struct.unpack_from('<Q', data, 0x28)[0]
|
||||
e_shentsize = struct.unpack_from('<H', data, 0x3a)[0]
|
||||
e_shnum = struct.unpack_from('<H', data, 0x3c)[0]
|
||||
e_shstrndx = struct.unpack_from('<H', data, 0x3e)[0]
|
||||
if e_shoff == 0 or e_shnum == 0 or e_shoff >= len(data):
|
||||
return []
|
||||
raw = []
|
||||
for i in range(e_shnum):
|
||||
o = e_shoff + i * e_shentsize
|
||||
if o + 0x40 > len(data):
|
||||
break
|
||||
name, stype, _flags, addr, offset, size = struct.unpack_from('<IIQQQQ', data, o)
|
||||
raw.append([name, stype, addr, offset, size])
|
||||
if e_shstrndx >= len(raw):
|
||||
return []
|
||||
base = raw[e_shstrndx][3]
|
||||
out = []
|
||||
for name, stype, addr, offset, size in raw:
|
||||
try:
|
||||
end = data.index(b'\x00', base + name)
|
||||
nm = data[base + name:end].decode('ascii', 'replace')
|
||||
except Exception:
|
||||
nm = '?'
|
||||
out.append((nm, stype, addr, offset, size))
|
||||
return out
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def section_of(sections, off: int):
|
||||
for nm, stype, _addr, soff, ssize in sections:
|
||||
if stype != 8 and soff <= off < soff + ssize:
|
||||
return nm
|
||||
return None
|
||||
|
||||
|
||||
POOLS = ('.rodata', '.data', '.data.rel.ro', '.rodata.str1.1', '.dynstr', '.strtab')
|
||||
|
||||
|
||||
def occurrences(data: bytes, needle: bytes):
|
||||
"""Yield (offset, isolated, section_name, context)."""
|
||||
sections = elf_sections(data)
|
||||
start = 0
|
||||
while True:
|
||||
i = data.find(needle, start)
|
||||
if i < 0:
|
||||
return
|
||||
prev = data[i - 1:i]
|
||||
nxt = data[i + len(needle):i + len(needle) + 1]
|
||||
isolated = (prev == b'\x00' or i == 0) and (nxt == b'\x00')
|
||||
yield i, isolated, section_of(sections, i), data[max(0, i - 24):i + len(needle) + 24]
|
||||
start = i + 1
|
||||
|
||||
|
||||
def describe(ctx: bytes) -> str:
|
||||
return ''.join(chr(b) if 32 <= b < 127 else ('\\0' if b == 0 else '.') for b in ctx)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- operations
|
||||
|
||||
def do_find(data: bytes, needle: bytes) -> int:
|
||||
hits = list(occurrences(data, needle))
|
||||
if not hits:
|
||||
print('no occurrence of %r' % needle.decode('utf-8', 'replace'))
|
||||
return 1
|
||||
print('%d occurrence(s) of %r:' % (len(hits), needle.decode('utf-8', 'replace')))
|
||||
for off, iso, sec, ctx in hits:
|
||||
print(' 0x%-8x isolated=%-5s section=%-12s | %s' % (off, iso, sec or '-', describe(ctx)))
|
||||
n_iso = sum(1 for _, iso, _, _ in hits if iso)
|
||||
print('\nisolated (safe to rewrite in place): %d / %d' % (n_iso, len(hits)))
|
||||
return 0
|
||||
|
||||
|
||||
def do_replace(data: bytes, old: bytes, new: bytes, section_aware: bool,
|
||||
allow_nonisolated: bool, force: bool) -> tuple[bytes, list]:
|
||||
if len(old) != len(new):
|
||||
raise SystemExit(
|
||||
'REFUSING: %r (%d bytes) -> %r (%d bytes).\n'
|
||||
'Equal length is mandatory - a different length shifts every byte after it '
|
||||
'and invalidates the ELF.\nPass a same-length name (e.g. pad with a shorter '
|
||||
'already-loaded library name).' % (
|
||||
old.decode('utf-8', 'replace'), len(old),
|
||||
new.decode('utf-8', 'replace'), len(new)))
|
||||
|
||||
hits = list(occurrences(data, old))
|
||||
if not hits:
|
||||
raise SystemExit('REFUSING: %r not present' % old.decode('utf-8', 'replace'))
|
||||
|
||||
selected = []
|
||||
for off, iso, sec, ctx in hits:
|
||||
if not iso and not allow_nonisolated:
|
||||
print(' skip 0x%-8x not an isolated constant (would corrupt a neighbour)' % off)
|
||||
continue
|
||||
if section_aware and (sec not in POOLS):
|
||||
print(' skip 0x%-8x section=%s (not a constant pool; --section-aware)' % (off, sec))
|
||||
continue
|
||||
selected.append(off)
|
||||
|
||||
if not selected:
|
||||
raise SystemExit('REFUSING: no eligible occurrence (see remarks above)')
|
||||
|
||||
if len(selected) > 1 and not force:
|
||||
print('\n%d eligible occurrence(s). Re-run with --force to patch all of them, '
|
||||
'or narrow the search.' % len(selected))
|
||||
for off in selected:
|
||||
print(' 0x%x' % off)
|
||||
raise SystemExit(2)
|
||||
|
||||
out = bytearray(data)
|
||||
applied = []
|
||||
for off in selected:
|
||||
before = bytes(out[off:off + len(old)])
|
||||
out[off:off + len(old)] = new
|
||||
applied.append((off, before, bytes(new)))
|
||||
print(' patched 0x%-8x %r -> %r' % (off, before.decode('utf-8', 'replace'),
|
||||
new.decode('utf-8', 'replace')))
|
||||
|
||||
print('\n%d byte(s) changed, file length unchanged (%d).' % (len(applied) * len(old), len(data)))
|
||||
return bytes(out), applied
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- containers
|
||||
|
||||
def load_target(path: str, entry: str | None):
|
||||
if path.lower().endswith('.apk') or path.lower().endswith('.zip'):
|
||||
if not entry:
|
||||
raise SystemExit('--entry is required when patching an APK '
|
||||
'(e.g. --entry lib/arm64-v8a/libfoo.so)')
|
||||
z = zipfile.ZipFile(path)
|
||||
if entry not in z.namelist():
|
||||
cands = [n for n in z.namelist() if n.endswith('.so')]
|
||||
raise SystemExit('entry %r not in %s\navailable .so entries:\n %s'
|
||||
% (entry, path, '\n '.join(cands[:40])))
|
||||
return z.read(entry), 'apk'
|
||||
with open(path, 'rb') as f:
|
||||
return f.read(), 'file'
|
||||
|
||||
|
||||
def write_target(path: str, kind: str, src_path: str, entry: str | None,
|
||||
new_data: bytes, out_path: str):
|
||||
if kind == 'file':
|
||||
with open(out_path, 'wb') as f:
|
||||
f.write(new_data)
|
||||
return
|
||||
src = zipfile.ZipFile(src_path)
|
||||
total = 0
|
||||
with zipfile.ZipFile(out_path, 'w', zipfile.ZIP_DEFLATED) as dst:
|
||||
for item in src.infolist():
|
||||
blob = new_data if item.filename == entry else src.read(item.filename)
|
||||
dst.writestr(zipfile.ZipInfo(item.filename, date_time=item.date_time),
|
||||
blob, item.compress_type)
|
||||
total += 1
|
||||
print(' rebuilt %s (%d entries)' % (out_path, total))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- main
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='In-place same-length rewrite of a string constant (library-load redirection).',
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog='examples:\n'
|
||||
' so_constpatch.py libfoo.so --find checkername\n'
|
||||
' so_constpatch.py libfoo.so --replace checkername=android -o libfoo.patched.so\n'
|
||||
' so_constpatch.py app.apk --entry lib/arm64-v8a/libfoo.so '
|
||||
'--replace checkername=android -o app.patched.apk\n')
|
||||
ap.add_argument('target', help='.so file or .apk')
|
||||
ap.add_argument('--entry', default=None, help='zip entry path when target is an APK')
|
||||
ap.add_argument('--find', default=None, metavar='STR', help='report occurrences and exit')
|
||||
ap.add_argument('--replace', default=None, metavar='OLD=NEW',
|
||||
help='same-length rewrite of OLD with NEW')
|
||||
ap.add_argument('-o', '--out', default=None, help='output path (required for --replace)')
|
||||
ap.add_argument('--section-aware', action='store_true',
|
||||
help='only patch hits inside known constant-pool sections')
|
||||
ap.add_argument('--allow-nonisolated', action='store_true',
|
||||
help='permit patching a substring of a longer identifier (dangerous)')
|
||||
ap.add_argument('--force', action='store_true', help='patch every eligible occurrence')
|
||||
args = ap.parse_args()
|
||||
|
||||
data, kind = load_target(args.target, args.entry)
|
||||
print('loaded %s (%s, %d bytes)\n' % (args.target, kind, len(data)))
|
||||
|
||||
if args.find:
|
||||
sys.exit(do_find(data, args.find.encode()))
|
||||
|
||||
if not args.replace:
|
||||
ap.error('one of --find or --replace is required')
|
||||
|
||||
if '=' not in args.replace:
|
||||
ap.error('--replace expects OLD=NEW')
|
||||
old_s, new_s = args.replace.split('=', 1)
|
||||
old, new = old_s.encode(), new_s.encode()
|
||||
|
||||
if not args.out and kind == 'file':
|
||||
args.out = args.target + '.patched'
|
||||
if not args.out:
|
||||
ap.error('-o/--out is required when patching an APK')
|
||||
if os.path.abspath(args.out) == os.path.abspath(args.target):
|
||||
ap.error('refusing to overwrite the input in place; choose a different -o')
|
||||
|
||||
patched, applied = do_replace(data, old, new, args.section_aware,
|
||||
args.allow_nonisolated, args.force)
|
||||
write_target(args.out, kind, args.target, args.entry, patched, args.out)
|
||||
print('\nwrote %s' % args.out)
|
||||
print('next: re-sign, then verify the loader\'s log tag count is 0 on a cold start '
|
||||
'(see references/code-virtualization-and-custom-linkers.md).')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,323 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""TLS certificate health check for one or more hosts.
|
||||
|
||||
WHY THIS EXISTS
|
||||
---------------
|
||||
When a repacked app's login/registration fails with
|
||||
`Chain validation failed` / `SSLHandshakeException`, the cause is often the
|
||||
*server* certificate, not your patch. This script answers that question
|
||||
independently of the app, so you can rule the server side in or out **before**
|
||||
touching the APK. It is step 2 of the three-step TLS triage:
|
||||
1. take the real request URL / host out of the runtime probe (see frida_probe.js)
|
||||
2. verify that host's certificate out-of-band <-- this script
|
||||
3. compare with another host of the same app (usually one of them is fine),
|
||||
which proves the failure is host-specific and not your clock/network
|
||||
|
||||
WHY IT STILL PRINTS THE CERTIFICATE WHEN VERIFICATION FAILS
|
||||
-----------------------------------------------------------
|
||||
`ssl.SSLSocket.getpeercert()` returns an empty dict whenever the handshake was
|
||||
not validated, and `verification_mode=CERT_NONE` never validates. So on failure
|
||||
we re-read the peer certificate in DER form and decode it locally. That is what
|
||||
turns "it failed" into "it failed because notAfter is 39 days in the past".
|
||||
|
||||
WHAT IT REPORTS
|
||||
---------------
|
||||
Per host: strict verification result, protocol/cipher, subject, issuer,
|
||||
notBefore, notAfter, days remaining, and a classification of the failure:
|
||||
EXPIRED certificate has expired
|
||||
NOT-YET-VALID certificate is not valid yet
|
||||
HOSTNAME-MISMATCH chain is fine, the name does not match
|
||||
UNTRUSTED-CA self-signed, or issuer not in the trust store
|
||||
CHAIN-BROKEN bad signature / invalid CA / incomplete chain
|
||||
REVOKED revoked by the issuer
|
||||
OTHER anything else, with the raw OpenSSL message
|
||||
|
||||
Exit code: 0 if every host verified strictly, 2 if any host failed.
|
||||
Pure standard library, Python 3.9+.
|
||||
|
||||
USAGE
|
||||
-----
|
||||
python tls_check.py api.example.com
|
||||
python tls_check.py api.example.com cdn.example.com
|
||||
python tls_check.py api.example.com --port 8443
|
||||
python tls_check.py 203.0.113.10 --sni api.example.com # IP + real SNI name
|
||||
python tls_check.py api.example.com --json # machine-readable
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
|
||||
DEFAULT_PORT = 443
|
||||
DEFAULT_TIMEOUT = 10
|
||||
|
||||
# OpenSSL X509_V_ERR_* -> (classification, human readable)
|
||||
VERIFY_CODE_CLASS = {
|
||||
7: ('CHAIN-BROKEN', 'certificate signature failure'),
|
||||
9: ('NOT-YET-VALID', 'certificate is not yet valid'),
|
||||
10: ('EXPIRED', 'certificate has expired'),
|
||||
18: ('UNTRUSTED-CA', 'self-signed certificate'),
|
||||
19: ('UNTRUSTED-CA', 'self-signed certificate in certificate chain'),
|
||||
20: ('UNTRUSTED-CA', 'unable to get local issuer certificate'),
|
||||
21: ('UNTRUSTED-CA', 'unable to verify the first certificate'),
|
||||
24: ('CHAIN-BROKEN', 'invalid CA certificate'),
|
||||
27: ('REVOKED', 'certificate revoked'),
|
||||
62: ('HOSTNAME-MISMATCH', 'hostname mismatch'),
|
||||
}
|
||||
|
||||
# What a failure means for the reverse-engineering workflow.
|
||||
CLASS_ACTION = {
|
||||
'EXPIRED': 'server-side problem: the certificate chain is not trustworthy '
|
||||
'any more. Re-signing the APK cannot fix this, and a client patch '
|
||||
'is the only way to keep the app usable.',
|
||||
'NOT-YET-VALID': 'either the server is misconfigured or the device clock is '
|
||||
'wrong. Check the device date before blaming the app.',
|
||||
'HOSTNAME-MISMATCH': 'the chain is valid but the connection is using the '
|
||||
'wrong name. Check for a proxy, a hosts entry, or a '
|
||||
'hardcoded IP + wrong SNI.',
|
||||
'UNTRUSTED-CA': 'the presented chain is not rooted in the system trust store. '
|
||||
'Expected for a MITM/proxy setup; suspicious for a public API.',
|
||||
'CHAIN-BROKEN': 'the server sent an incomplete or internally inconsistent '
|
||||
'chain. Often a missing intermediate certificate.',
|
||||
'REVOKED': 'the certificate was revoked by its issuer.',
|
||||
'OTHER': 'read the raw OpenSSL message below; this is not one of the '
|
||||
'well-known failure classes.',
|
||||
}
|
||||
|
||||
|
||||
def fmt_name(parts):
|
||||
"""Flatten ((('commonName','x'),),) into 'commonName=x'."""
|
||||
if not parts:
|
||||
return None
|
||||
flat = []
|
||||
for rdn in parts:
|
||||
for key, val in rdn:
|
||||
flat.append('%s=%s' % (key, val))
|
||||
return ', '.join(flat)
|
||||
|
||||
|
||||
def parse_asn1_time(text):
|
||||
"""'Nov 29 23:59:59 2026 GMT' -> aware UTC datetime (or None)."""
|
||||
if not text:
|
||||
return None
|
||||
cleaned = text.strip()
|
||||
if cleaned.endswith(' GMT') or cleaned.endswith(' UTC'):
|
||||
cleaned = cleaned[:-4].rstrip()
|
||||
try:
|
||||
return datetime.strptime(cleaned, '%b %d %H:%M:%S %Y').replace(tzinfo=timezone.utc)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def decode_der(der):
|
||||
"""Decode a DER certificate without ever verifying it.
|
||||
|
||||
Uses the CPython private helper that backs `getpeercert()`; if it is not
|
||||
available we still return what we can (length + fingerprint), because a
|
||||
partially decoded certificate beats no certificate at all.
|
||||
"""
|
||||
info = {'der_bytes': len(der),
|
||||
'sha256': hashlib.sha256(der).hexdigest(),
|
||||
'sha1': hashlib.sha1(der).hexdigest()}
|
||||
helper = getattr(getattr(ssl, '_ssl', None), '_test_decode_cert', None)
|
||||
if helper is None:
|
||||
return info
|
||||
path = None
|
||||
try:
|
||||
pem = ssl.DER_cert_to_PEM_cert(der)
|
||||
with tempfile.NamedTemporaryFile('w', suffix='.pem', delete=False) as fh:
|
||||
path = fh.name
|
||||
fh.write(pem)
|
||||
info.update(helper(path))
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
if path and os.path.exists(path):
|
||||
try:
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
return info
|
||||
|
||||
|
||||
def fetch_peer_cert(host, port, sni, timeout):
|
||||
"""Read the peer certificate even when the chain cannot be validated."""
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
with socket.create_connection((host, port), timeout=timeout) as raw:
|
||||
with ctx.wrap_socket(raw, server_hostname=sni) as tls:
|
||||
der = tls.getpeercert(binary_form=True)
|
||||
return decode_der(der) if der else {}
|
||||
|
||||
|
||||
def strict_connect(host, port, sni, timeout):
|
||||
"""Full strict verification: system trust store + hostname match."""
|
||||
ctx = ssl.create_default_context()
|
||||
with socket.create_connection((host, port), timeout=timeout) as raw:
|
||||
with ctx.wrap_socket(raw, server_hostname=sni) as tls:
|
||||
return {
|
||||
'cert': tls.getpeercert() or {},
|
||||
'protocol': tls.version(),
|
||||
'cipher': (tls.cipher() or ('', '', ''))[0],
|
||||
}
|
||||
|
||||
|
||||
def check_host(host, port, sni, timeout):
|
||||
"""Return one result dict; never raises for network/TLS problems."""
|
||||
res = {
|
||||
'host': host,
|
||||
'port': port,
|
||||
'sni': sni,
|
||||
'ok': False,
|
||||
'classification': None,
|
||||
'reason': None,
|
||||
'verify_code': None,
|
||||
'protocol': None,
|
||||
'cipher': None,
|
||||
'subject': None,
|
||||
'issuer': None,
|
||||
'not_before': None,
|
||||
'not_after': None,
|
||||
'days_remaining': None,
|
||||
'fingerprint_sha256': None,
|
||||
'action': None,
|
||||
'error': None,
|
||||
}
|
||||
|
||||
try:
|
||||
hit = strict_connect(host, port, sni, timeout)
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
code = getattr(exc, 'verify_code', None)
|
||||
cls, human = VERIFY_CODE_CLASS.get(code, ('OTHER', getattr(exc, 'verify_message', str(exc))))
|
||||
res['classification'] = cls
|
||||
res['reason'] = human
|
||||
res['verify_code'] = code
|
||||
res['action'] = CLASS_ACTION.get(cls)
|
||||
res['error'] = '%s: %s' % (type(exc).__name__, exc)
|
||||
except (ssl.SSLError, socket.error, OSError) as exc:
|
||||
res['classification'] = 'OTHER'
|
||||
res['reason'] = 'connection or handshake failed before certificate validation'
|
||||
res['action'] = CLASS_ACTION['OTHER']
|
||||
res['error'] = '%s: %s' % (type(exc).__name__, exc)
|
||||
return res
|
||||
else:
|
||||
cert = hit['cert']
|
||||
res.update({'ok': True, 'protocol': hit['protocol'], 'cipher': hit['cipher'],
|
||||
'subject': fmt_name(cert.get('subject')),
|
||||
'issuer': fmt_name(cert.get('issuer')),
|
||||
'not_before': cert.get('notBefore'),
|
||||
'not_after': cert.get('notAfter')})
|
||||
res['days_remaining'] = days_left(res['not_after'])
|
||||
return res
|
||||
|
||||
# Verification failed: still try to show the real certificate.
|
||||
try:
|
||||
cert = fetch_peer_cert(host, port, sni, timeout)
|
||||
except Exception as exc:
|
||||
res['error'] = (res['error'] or '') + ' | peek failed: %s' % exc
|
||||
return res
|
||||
|
||||
res.update({'subject': fmt_name(cert.get('subject')),
|
||||
'issuer': fmt_name(cert.get('issuer')),
|
||||
'not_before': cert.get('notBefore'),
|
||||
'not_after': cert.get('notAfter'),
|
||||
'fingerprint_sha256': cert.get('sha256')})
|
||||
res['days_remaining'] = days_left(res['not_after'])
|
||||
return res
|
||||
|
||||
|
||||
def days_left(not_after):
|
||||
dt = parse_asn1_time(not_after)
|
||||
if dt is None:
|
||||
return None
|
||||
return (dt - datetime.now(timezone.utc)).days
|
||||
|
||||
|
||||
def report(res, out=sys.stdout):
|
||||
w = out.write
|
||||
w('== %s:%d%s\n' % (res['host'], res['port'],
|
||||
'' if res['sni'] == res['host'] else ' (SNI: %s)' % res['sni']))
|
||||
if res['ok']:
|
||||
w(' status : OK (strict verification passed)\n')
|
||||
else:
|
||||
w(' status : FAIL - %s\n' % res['classification'])
|
||||
w(' reason : %s\n' % res['reason'])
|
||||
if res['verify_code'] is not None:
|
||||
w(' verify_code : %d\n' % res['verify_code'])
|
||||
if res['protocol']:
|
||||
w(' protocol : %s cipher: %s\n' % (res['protocol'], res['cipher']))
|
||||
w(' subject : %s\n' % (res['subject'] or '<undecoded>'))
|
||||
w(' issuer : %s\n' % (res['issuer'] or '<undecoded>'))
|
||||
w(' notBefore : %s\n' % (res['not_before'] or '<unknown>'))
|
||||
w(' notAfter : %s\n' % (res['not_after'] or '<unknown>'))
|
||||
days = res['days_remaining']
|
||||
if days is not None:
|
||||
if days < 0:
|
||||
w(' validity : EXPIRED %d days ago\n' % (-days))
|
||||
else:
|
||||
w(' days remaining : %d\n' % days)
|
||||
if res['fingerprint_sha256']:
|
||||
w(' sha256 : %s\n' % res['fingerprint_sha256'])
|
||||
if res['action'] and not res['ok']:
|
||||
w(' action : %s\n' % res['action'])
|
||||
if res['error']:
|
||||
w(' raw error : %s\n' % res['error'])
|
||||
w('\n')
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(
|
||||
description='Verify TLS certificates for one or more hosts, strictly, '
|
||||
'and classify any failure (expired / hostname mismatch / untrusted CA).')
|
||||
ap.add_argument('hosts', nargs='+', metavar='HOST',
|
||||
help='hostname or IP to check, e.g. api.example.com')
|
||||
ap.add_argument('--port', type=int, default=DEFAULT_PORT,
|
||||
help='TCP port (default %d)' % DEFAULT_PORT)
|
||||
ap.add_argument('--sni', default=None,
|
||||
help='override the SNI/hostname to validate against; useful when '
|
||||
'HOST is a bare IP, e.g. --sni api.example.com')
|
||||
ap.add_argument('--timeout', type=float, default=DEFAULT_TIMEOUT,
|
||||
help='connect timeout in seconds (default %d)' % DEFAULT_TIMEOUT)
|
||||
ap.add_argument('--json', action='store_true', help='emit JSON instead of a report')
|
||||
args = ap.parse_args()
|
||||
|
||||
results = []
|
||||
for host in args.hosts:
|
||||
sni = args.sni or host
|
||||
results.append(check_host(host, args.port, sni, args.timeout))
|
||||
|
||||
if args.json:
|
||||
json.dump(results, sys.stdout, indent=2, sort_keys=True)
|
||||
sys.stdout.write('\n')
|
||||
else:
|
||||
for res in results:
|
||||
report(res)
|
||||
|
||||
bad = [r for r in results if not r['ok']]
|
||||
good = [r for r in results if r['ok']]
|
||||
if len(results) > 1:
|
||||
if bad and good:
|
||||
print('SUMMARY: %d/%d hosts failed. At least one host on this app '
|
||||
'verifies fine, so the failure is host-specific (server side), '
|
||||
'not a clock/network problem on your side.'
|
||||
% (len(bad), len(results)))
|
||||
elif bad:
|
||||
print('SUMMARY: every host failed. Suspect the network path, a proxy, '
|
||||
'or the device/host clock before blaming the app.')
|
||||
else:
|
||||
print('SUMMARY: all %d hosts verified strictly.' % len(results))
|
||||
for r in bad:
|
||||
print('FAIL %s -> %s' % (r['host'], r['classification']))
|
||||
|
||||
return 0 if all(r['ok'] for r in results) else 2
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Minimal HTTP/HTTPS forward proxy for giving an offline Android device network access.
|
||||
|
||||
Situation: the device has no working network interface (DHCP failure, no default route), so
|
||||
every request the app makes fails.
|
||||
|
||||
Why this works: it does not need a network interface on the device at all. `adb reverse`
|
||||
opens a listener on the **device's own loopback**, which exists regardless:
|
||||
|
||||
1) run this proxy on the host (0.0.0.0:8080)
|
||||
2) adb -s <serial> reverse tcp:8080 tcp:8080
|
||||
3) on the device: settings put global http_proxy 127.0.0.1:8080
|
||||
4) the app's HTTP/HTTPS traffic travels over USB and is sent by the host
|
||||
|
||||
Supports:
|
||||
- CONNECT tunnelling (what HTTPS uses)
|
||||
- absolute-URI plain HTTP forwarding
|
||||
|
||||
Forwards only: it does not MITM, does not decrypt TLS and does not modify traffic, so
|
||||
certificate validation is unaffected. See references/environment.md.
|
||||
|
||||
Usage: python usb_net_proxy.py [listen_port] [logfile]
|
||||
"""
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
if len(sys.argv) > 1 and sys.argv[1] in ('-h', '--help'):
|
||||
print(__doc__)
|
||||
sys.exit(0)
|
||||
|
||||
try:
|
||||
PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
|
||||
except ValueError:
|
||||
print('error: listen_port must be a number, got %r\n' % sys.argv[1])
|
||||
print(__doc__)
|
||||
sys.exit(2)
|
||||
LOGF = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
_lock = threading.Lock()
|
||||
_logf = open(LOGF, 'a', encoding='utf-8') if LOGF else None
|
||||
|
||||
|
||||
def log(msg):
|
||||
line = '[%s] %s' % (time.strftime('%H:%M:%S'), msg)
|
||||
print(line, flush=True)
|
||||
if _logf:
|
||||
with _lock:
|
||||
_logf.write(line + '\n')
|
||||
_logf.flush()
|
||||
|
||||
|
||||
def pump(a, b):
|
||||
"""Copy a -> b in one direction until either end closes."""
|
||||
try:
|
||||
while True:
|
||||
r, _, _ = select_select([a], [], [], 30)
|
||||
if not r:
|
||||
break
|
||||
data = a.recv(65536)
|
||||
if not data:
|
||||
break
|
||||
b.sendall(data)
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
for s in (a, b):
|
||||
try:
|
||||
s.shutdown(socket.SHUT_RDWR)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
s.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def select_select(rlist, wlist, xlist, timeout):
|
||||
import select
|
||||
return select.select(rlist, wlist, xlist, timeout)
|
||||
|
||||
|
||||
def read_head(sock, limit=65536):
|
||||
data = b''
|
||||
while b'\r\n\r\n' not in data and len(data) < limit:
|
||||
chunk = sock.recv(4096)
|
||||
if not chunk:
|
||||
return data
|
||||
data += chunk
|
||||
return data
|
||||
|
||||
|
||||
def handle(client, addr):
|
||||
client.settimeout(30)
|
||||
try:
|
||||
head = read_head(client)
|
||||
if not head:
|
||||
client.close()
|
||||
return
|
||||
first = head.split(b'\r\n', 1)[0].decode('latin-1')
|
||||
parts = first.split(' ')
|
||||
if len(parts) < 3:
|
||||
client.close()
|
||||
return
|
||||
method, target = parts[0].upper(), parts[1]
|
||||
rest = head.split(b'\r\n\r\n', 1)[1] if b'\r\n\r\n' in head else b''
|
||||
|
||||
if method == 'CONNECT':
|
||||
host, _, port = target.rpartition(':')
|
||||
port = int(port or 443)
|
||||
log('CONNECT %s:%d' % (host, port))
|
||||
remote = socket.create_connection((host, port), timeout=20)
|
||||
client.sendall(b'HTTP/1.1 200 Connection Established\r\n\r\n')
|
||||
client.settimeout(None)
|
||||
remote.settimeout(None)
|
||||
t = threading.Thread(target=pump, args=(client, remote), daemon=True)
|
||||
t.start()
|
||||
pump(remote, client)
|
||||
else:
|
||||
# Plain HTTP: target is normally an absolute URI
|
||||
if target.startswith('http://'):
|
||||
without = target[len('http://'):]
|
||||
hostport = without.split('/', 1)[0]
|
||||
path = '/' + without.split('/', 1)[1] if '/' in without else '/'
|
||||
else:
|
||||
hostport = None
|
||||
for ln in head.split(b'\r\n'):
|
||||
if ln.lower().startswith(b'host:'):
|
||||
hostport = ln.split(b':', 1)[1].strip().decode()
|
||||
path = target
|
||||
if not hostport:
|
||||
client.close()
|
||||
return
|
||||
host, _, port = hostport.rpartition(':')
|
||||
port = int(port or 80)
|
||||
log('HTTP %s%s' % (hostport, path))
|
||||
remote = socket.create_connection((host, port), timeout=20)
|
||||
req = ('%s %s HTTP/1.1\r\n' % (method, path)).encode()
|
||||
hdrs = head.split(b'\r\n')[1:]
|
||||
for h in hdrs:
|
||||
if h.lower().startswith(b'proxy-connection'):
|
||||
continue
|
||||
req += h + b'\r\n'
|
||||
req += b'\r\n' + rest
|
||||
remote.sendall(req)
|
||||
client.settimeout(None)
|
||||
remote.settimeout(None)
|
||||
t = threading.Thread(target=pump, args=(client, remote), daemon=True)
|
||||
t.start()
|
||||
pump(remote, client)
|
||||
except Exception as e:
|
||||
log('ERR %s %s' % (addr, e))
|
||||
try:
|
||||
client.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main():
|
||||
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
srv.bind(('0.0.0.0', PORT))
|
||||
srv.listen(128)
|
||||
log('proxy listening on 0.0.0.0:%d' % PORT)
|
||||
while True:
|
||||
c, a = srv.accept()
|
||||
threading.Thread(target=handle, args=(c, a), daemon=True).start()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user