mirror of
https://codeberg.org/dabao1955/apk-reverse.git
synced 2026-11-28 03:50:22 +08:00
Compare commits
7
Commits
aa9af54854
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93ec493d02 | ||
|
|
90d9bd3e57 | ||
|
|
068280a180 | ||
|
|
45ba13c0f3 | ||
|
|
f497180e35 | ||
|
|
f3863f070c | ||
|
|
bd6dd0c59c |
No files matched your search
@@ -0,0 +1,74 @@
|
||||
<!--
|
||||
Two things this template asks for are not machine-checkable: whether a claim's label is honest, and
|
||||
whether the change keeps this repository's index in step. The gate output is the cheapest evidence
|
||||
you can give a reviewer; a green run is not approval, and a blank section is not an omission nobody
|
||||
will notice.
|
||||
-->
|
||||
|
||||
## What this changes
|
||||
|
||||
One or two sentences. Name the file or the behaviour, not the intention.
|
||||
|
||||
## What I ran
|
||||
|
||||
```bash
|
||||
python check_repo.py && python check_refs.py && python check_routing.py \
|
||||
&& python check_commands.py && python check_budget.py && python -m pytest -q
|
||||
```
|
||||
|
||||
Paste the output that decides the question, including any gate that was red before the change and
|
||||
why. Report only checks that actually executed — `should pass` is not a result, and a run on one
|
||||
device, one ABI or one sample says so in the line where it is quoted.
|
||||
|
||||
```
|
||||
<decisive output>
|
||||
```
|
||||
|
||||
If `mypy` or `flake8` are not installed locally, say that here: CI runs them, and a contributor
|
||||
without them cannot reproduce that half.
|
||||
|
||||
## Claims
|
||||
|
||||
Every claim carries one of the four labels this repository uses. `observed` requires both the command
|
||||
and its output; `inferred` means it was not run; `unverified` means someone else said so; `unknown`
|
||||
means nobody looked.
|
||||
|
||||
| Claim | Label | Command and result, or what would have to exist for it to be `observed` |
|
||||
|---|---|---|
|
||||
| | observed / inferred / unverified / unknown | |
|
||||
|
||||
- [ ] No chain is labelled above its weakest step.
|
||||
- [ ] A negative result says whether it was `absent`, `unknown` or `present but unreadable`, and names
|
||||
the probe's coverage. Only the first is a finding.
|
||||
- [ ] A measurement names the version, device or ABI it came from.
|
||||
|
||||
## What has to move with it
|
||||
|
||||
Check every line that applies. These are the rows that cost a red CI run when they are missed.
|
||||
|
||||
- [ ] A reference file — named in `references/routing.md`, reachable from `SKILL.md` or the README,
|
||||
with a load-this-when head if it passes 100 lines.
|
||||
- [ ] A script — a row in the routing script table, its capability declared in
|
||||
`scripts/capabilities.py`, and `--help` working on a bare interpreter.
|
||||
- [ ] A symptom-index row — mirrored into `references/routing.md`, which is compared rather than
|
||||
generated.
|
||||
- [ ] A section heading — every section reference that pointed at the old name is updated.
|
||||
- [ ] A documented command — the flags are copied from `--help`, not retyped.
|
||||
- [ ] `SKILL.md` — the budget line is attached above; it is loaded in full on activation.
|
||||
- [ ] A capability claim — the row in `evidence/capability-matrix.json` **and** the line in
|
||||
`references/evidence-summary.md`. No gate compares them; that is why the reviewer reads them.
|
||||
- [ ] A new pitfall — next number, same four headings.
|
||||
- [ ] `README.md` and `README.zh-CN.md` — the two stay in step.
|
||||
- [ ] Documentation only — say so explicitly; a blank list is not the same statement.
|
||||
|
||||
## Boundaries
|
||||
|
||||
Where something could not be exercised here, ship the measured half plus an explicitly labelled
|
||||
template for the rest, and state what would have to exist for the other half to become `observed`.
|
||||
|
||||
- [ ] Anything needing a device, adb, frida, a rooted phone or the network is named as not run here,
|
||||
rather than described as working.
|
||||
- [ ] One variable changed per result: if a result moved, it is attributable to the one thing this
|
||||
change touched.
|
||||
- [ ] The scan in `scripts/scan_leaks.py` was run over the files being published, and its findings
|
||||
are resolved — including names and metadata that no pattern reads.
|
||||
@@ -38,6 +38,10 @@ tools/
|
||||
# resting on "nobody has added them yet".
|
||||
.ref/
|
||||
|
||||
# A public skill clone read by the 2026-11 game-reserve absorption pass. Same rule: the method
|
||||
# and the anonymised record ship, the upstream tree does not.
|
||||
game-reserve/
|
||||
|
||||
# sandbox installs made while testing `npx skills add .` against this repo
|
||||
.claude/
|
||||
.agents/
|
||||
|
||||
@@ -193,6 +193,36 @@ references/ loaded on demand, one topic each
|
||||
Begins with the snapshot-decoding front end it depends on (aotopsy or
|
||||
blutter) because the pool listing is an input, not something this skill
|
||||
produces itself
|
||||
unity-runtime.md Unity from the two files that decide everything: Mono
|
||||
(`Assembly-CSharp.dll`) versus IL2CPP (`libil2cpp.so` plus
|
||||
`global-metadata.dat`), dumping the pair with Il2CppDumper and
|
||||
importing the tables into IDA in the order that works, the
|
||||
dnSpy-Unity-mono patch that makes a retail Mono player accept a
|
||||
debugger, a run-time class lookup over frida-il2cpp-bridge, and
|
||||
the audit probes when the deliverable is a report
|
||||
unity-lua-and-assetbundles.md
|
||||
the Unity that is neither plain Mono nor IL2CPP: Lua logic in a
|
||||
bundle (xLua/tolua/SLua), the Lua 5.1 header-byte tamper, bundle
|
||||
CRC in the manifest the game actually reads, partial-encryption
|
||||
windows, UnityFS rebuild traps (layout loss, stripped dependency
|
||||
null, compressed == raw), TextAsset read-back, and half-encrypted
|
||||
Mono assemblies behind a publisher shell
|
||||
il2cpp-protected-metadata.md
|
||||
when that pair is not readable: absent, 0-byte, encrypted or
|
||||
embedded metadata, the consumer-side dump, version-independent
|
||||
header sizing, XOR/VM/XXTEA container shapes, the live-image dump
|
||||
and the ELF repair that makes it usable
|
||||
linker-and-soinfo-repair.md loading, dumping or repairing a .so by hand: the `dlopen` pipeline
|
||||
as a loader spec, load_bias and segment arithmetic, DT_* parsing,
|
||||
relocation rules and the two biases, minimal `soinfo` repair,
|
||||
anti-dump header XOR, and where a dump is valid
|
||||
vm-protector-analysis.md a native VM protector with virtual eflags: no cmp/sub/jcc, a flags
|
||||
slot, NAND lowering, branchless select, data-anchored breakpoints
|
||||
and trace-then-search-by-constant; handler slicing stays in
|
||||
native-vm-recovery.md
|
||||
python-bytecode-recovery.md Python bytecode behind Pyarmor/PyInstaller: key schedule, AES-CTR
|
||||
nonce rules, the 12-byte VM, version-gated pyc parsing, the
|
||||
extra-section TLV and per-object/per-string decryption
|
||||
native-and-so.md .so hosts, DT_NEEDED vs JNI_OnLoad, relocation limits,
|
||||
relocation-free bootstrapping, replacing Java methods natively,
|
||||
and which ABI/library is *actually loaded and executing*
|
||||
@@ -200,6 +230,10 @@ references/ loaded on demand, one topic each
|
||||
mechanisms, how to tell which one actually fires, how to find the
|
||||
site, forged section headers, function boundaries from
|
||||
PT_GNU_EH_FRAME, scanner traps, and neutralising safely
|
||||
ida-so-debugging.md attaching a real debugger instead of hooking: IDA's `dbgsrv` with
|
||||
the ABI match, `am start -D` plus the JDWP handshake that actually
|
||||
releases the process, and the `extractNativeLibs="false"` failure
|
||||
where the library is mapped from `base.apk` and no breakpoint binds
|
||||
detection-and-anti-analysis.md when the app fights back or the tool cannot run here: telling
|
||||
detection apart from a broken environment, deciding by cost instead
|
||||
of escalating, recognising an environment where dynamic analysis
|
||||
@@ -591,10 +625,12 @@ whose measurements disagreed with them. A **hardware pass** then added the layer
|
||||
software tooling: **hardware watchpoints** with their honest `TracerPid` ledger, **ETE/TRBE
|
||||
differential tracing** with its five gates, and **kernel-side injection templates** — every
|
||||
host-checkable piece measured, every device-bound piece labelled `unverified` until a gate
|
||||
opens. Unity/IL2CPP logic recovery,
|
||||
React Native/Hermes bytecode internals, and defeating a server-side authority are **not**
|
||||
covered, and the skill is written to say so and stop rather than apply the nearest
|
||||
documented procedure to a target it was not written for.
|
||||
opens. Unity/IL2CPP logic recovery (including
|
||||
the protected-metadata case), linker-level `.so` repair, VM-protector idioms, Python/Pyarmor
|
||||
bytecode recovery and attaching a real debugger to a `.so` are **documented routes, not
|
||||
measurements** — absorbed from public write-ups and labelled `unverified` throughout. React Native/Hermes bytecode internals and
|
||||
defeating a server-side authority are **not** covered, and the skill is written to say so and stop
|
||||
rather than apply the nearest documented procedure to a target it was not written for.
|
||||
|
||||
Four qualifications that the Coverage section states in full and that belong here too:
|
||||
|
||||
|
||||
+30
-1
@@ -115,6 +115,31 @@ references/ 按需加载,每个文件一个主题
|
||||
识别业务逻辑的三种签名、定位、打补丁。
|
||||
开篇先讲它所依赖的 snapshot 解码前端(aotopsy 或
|
||||
blutter),因为 pool 列表是输入,不是本 skill 自己产出的东西
|
||||
unity-runtime.md 用两个决定一切的文件进入 Unity:Mono(`Assembly-CSharp.dll`)
|
||||
与 IL2CPP(`libil2cpp.so` + `global-metadata.dat`)的区分、
|
||||
用 Il2CppDumper 导出这一对文件、按能成功的顺序把表导入 IDA、
|
||||
让零售 Mono 播放器接受调试器的 dnSpy-Unity-mono 补丁、
|
||||
基于 frida-il2cpp-bridge 的运行时类查找,以及交付物是报告时的审计探针
|
||||
unity-lua-and-assetbundles.md
|
||||
既不是纯 Mono 也不是 IL2CPP 的 Unity:逻辑在 Lua bundle 里
|
||||
(xLua/tolua/SLua)、Lua 5.1 头字节篡改、游戏真正读取的 manifest
|
||||
CRC、局部加密窗口、UnityFS 重建陷阱(布局丢失、依赖被剥后返回
|
||||
null、压缩大小等于原始大小)、TextAsset 读回,以及发行方壳后面的
|
||||
半加密 Mono 程序集
|
||||
il2cpp-protected-metadata.md
|
||||
当这一对不可读时:缺失、0 字节、加密或内嵌的 metadata、
|
||||
从消费端 dump、不信任版本号的 header 定长、XOR/VM/XXTEA
|
||||
容器形态、活体镜像 dump,以及让 dump 可用的 ELF 修复
|
||||
linker-and-soinfo-repair.md 手工加载、dump 或修复 .so:把 `dlopen` 管线当作 loader
|
||||
规范、load_bias 与段映射算术、DT_* 解析、重定位规则与
|
||||
两个 bias、最小 `soinfo` 修复、反 dump 的 header XOR,
|
||||
以及 dump 在哪个窗口内有效
|
||||
vm-protector-analysis.md 带虚拟 eflags 的 native VM 保护:没有 cmp/sub/jcc、只有
|
||||
flags 槽、NAND 降级、无分支选择、数据锚定断点与
|
||||
「先 trace 再按常量搜索」;handler 切片仍在 native-vm-recovery.md
|
||||
python-bytecode-recovery.md Pyarmor/PyInstaller 之后的 Python 字节码:密钥调度、
|
||||
AES-CTR nonce 规则、12 字节 VM、按版本分支的 pyc 解析、
|
||||
extra section TLV 与按 code object/字符串解密
|
||||
native-and-so.md .so 宿主、DT_NEEDED vs JNI_OnLoad、重定位限制、
|
||||
免重定位的 bootstrap、用 native 替换 Java 方法,
|
||||
以及*实际加载并执行*的是哪个 ABI/库
|
||||
@@ -122,6 +147,10 @@ references/ 按需加载,每个文件一个主题
|
||||
如何判断实际触发的是哪一个、如何定位现场、
|
||||
伪造的 section header、由 PT_GNU_EH_FRAME 推出的
|
||||
函数边界、扫描器陷阱,以及安全地失效化
|
||||
ida-so-debugging.md 接一个真正的调试器而不是 hook:ABI 匹配的 IDA `dbgsrv`、
|
||||
`am start -D` 加真正放行进程的 JDWP 握手,以及
|
||||
`extractNativeLibs="false"`——库直接从 `base.apk` 映射、
|
||||
断点无处可绑的失败
|
||||
detection-and-anti-analysis.md 当 app 反击,或工具在这里跑不起来时:把检测与
|
||||
环境损坏区分开、按成本而不是按升级来决策、认出
|
||||
动态分析根本无效的环境,并把「挡住我的分析」这个问题
|
||||
@@ -454,7 +483,7 @@ export APKREV_TOOLS=<dir>:<dir> # POSIX
|
||||
|
||||
为处理你自己的应用、你被授权分析的样本,以及 CTF/竞赛沙箱而构建。它不含任何内置的第三方二进制,也不含任何目标特定数据。
|
||||
|
||||
它覆盖什么、刻意不覆盖什么,写在 `SKILL.md` 顶部 **Coverage** 一节。简版:仅 Android(不含 iOS),并且在经过真实打磨的层上深入 —— dex 补丁、重打包、壳与自定义加载器、native 篡改响应,以及 Flutter/Dart AOT。一次扩展迭代加入了第二梯队的已记录路线:重打包受阻时的**模块侧交付**、**抽取壳恢复**及其 VMP 边界、用于「调用而不是阅读」的**模拟执行与实时 RPC**、针对 OLLVM 的**指令级追踪**、REST 之外的**协议逆向**、当用户态 hooking 可证明够不到时用的**内核路线**图,以及**设备上工具**。随后一次**基准迭代**把公开目标放到这些路线之下(`tests/benchmark.md`):它加入了 **Java2C 判别**(那种会让 agent 去追一个从不存在的解密 DEX 的误诊)、**split APK / App Bundle 处理**、**无 schema 的 protobuf 解码**、一个 **Dex-VMP 差分**测试台,以及**带版本闸门的内核模块模板** —— 并纠正了先前两条与自身测量结果不一致的说法。随后一次**硬件迭代**加入了软件工具之下的那一层:带诚实 `TracerPid` 账本的**硬件观察点**、带五道闸门的 **ETE/TRBE 差分追踪**,以及**内核侧注入模板** —— 凡是宿主可验证的部分都实测过,凡是设备绑定的部分在闸门打开前一律标注 `unverified`。Unity/IL2CPP 逻辑恢复、React Native/Hermes 字节码内部,以及击败服务端权威**不**在覆盖范围内,skill 的写法就是明说这一点并停下,而不是把最近的一条已记录流程套用到一个它并非为之编写的目标上。
|
||||
它覆盖什么、刻意不覆盖什么,写在 `SKILL.md` 顶部 **Coverage** 一节。简版:仅 Android(不含 iOS),并且在经过真实打磨的层上深入 —— dex 补丁、重打包、壳与自定义加载器、native 篡改响应,以及 Flutter/Dart AOT。一次扩展迭代加入了第二梯队的已记录路线:重打包受阻时的**模块侧交付**、**抽取壳恢复**及其 VMP 边界、用于「调用而不是阅读」的**模拟执行与实时 RPC**、针对 OLLVM 的**指令级追踪**、REST 之外的**协议逆向**、当用户态 hooking 可证明够不到时用的**内核路线**图,以及**设备上工具**。随后一次**基准迭代**把公开目标放到这些路线之下(`tests/benchmark.md`):它加入了 **Java2C 判别**(那种会让 agent 去追一个从不存在的解密 DEX 的误诊)、**split APK / App Bundle 处理**、**无 schema 的 protobuf 解码**、一个 **Dex-VMP 差分**测试台,以及**带版本闸门的内核模块模板** —— 并纠正了先前两条与自身测量结果不一致的说法。随后一次**硬件迭代**加入了软件工具之下的那一层:带诚实 `TracerPid` 账本的**硬件观察点**、带五道闸门的 **ETE/TRBE 差分追踪**,以及**内核侧注入模板** —— 凡是宿主可验证的部分都实测过,凡是设备绑定的部分在闸门打开前一律标注 `unverified`。Unity/IL2CPP 逻辑恢复(含受保护的 metadata 情形)、linker 层的 `.so` 修复、VM 保护器惯用法、Python/Pyarmor 字节码恢复,以及**给 `.so` 接真实调试器**属于**已记录但未实测**的路线 —— 吸收自公开文章,全文标注 `unverified`。React Native/Hermes 字节码内部,以及击败服务端权威**不**在覆盖范围内,skill 的写法就是明说这一点并停下,而不是把最近的一条已记录流程套用到一个它并非为之编写的目标上。
|
||||
|
||||
Coverage 一节完整陈述、同时也应当放在这里的四条限定:
|
||||
|
||||
|
||||
+12
-7
@@ -78,9 +78,10 @@ NAV_LINES = 100 # above this, a reference must open navigably
|
||||
CORPUS_FILES_NOTE = 110 # references + scripts, reported as a note past this
|
||||
CORPUS_LINES_NOTE = 26000 # total lines across the same corpus, same treatment
|
||||
# Characters per token, for the no-tiktoken fallback. **Calibrated on SKILL.md against
|
||||
# tiktoken/cl100k_base** (47,629 chars -> 11,114 tokens = 4.285), so both measurement paths reach
|
||||
# the same verdict. Getting this wrong made the gate answer differently on CI than locally.
|
||||
TOKENS_PER_CHAR = 4.285
|
||||
# tiktoken/cl100k_base** (54,983 chars -> 12,906 tokens = 4.260, re-measured 2026-10-24), so both
|
||||
# measurement paths reach the same verdict. Getting this wrong made the gate answer differently on
|
||||
# CI than locally.
|
||||
TOKENS_PER_CHAR = 4.260
|
||||
# A navigable head: one of these must appear in the first NAV_HEAD_LINES lines.
|
||||
NAV_HEAD_LINES = 40
|
||||
HEDGE_RE = re.compile(
|
||||
@@ -143,9 +144,10 @@ def token_estimate(text):
|
||||
everywhere in this repository, including in this file. When it is not, it falls back to
|
||||
`characters / TOKENS_PER_CHAR`.
|
||||
|
||||
The fallback constant is **calibrated against that measurement** rather than guessed: a
|
||||
markdown-heavy document tokenizes worse per character than the usual /4 rule of thumb, and this
|
||||
file measured 0.30 characters-to-tokens on SKILL.md (67,011 chars -> 19,929 tokens).
|
||||
The fallback constant is **calibrated against that measurement** rather than guessed: this
|
||||
SKILL.md measures 4.260 characters per token (54,983 chars -> 12,906 tokens, cl100k_base).
|
||||
Agreeing with the "about four" rule of thumb to within a few percent is not close enough to rely
|
||||
on, so the number is re-derived when the document changes rather than assumed.
|
||||
|
||||
Why the value matters more than the method: the first version used 3.6 and the gate therefore
|
||||
reached *different verdicts on different machines* -- `WARN over budget` where tiktoken was
|
||||
@@ -307,8 +309,11 @@ def check_corpus():
|
||||
green always-loaded count.
|
||||
"""
|
||||
refs = sorted(glob.glob(os.path.join(REFS, '**', '*.md'), recursive=True))
|
||||
# A bytecode cache is not corpus. It is untracked, it appears the first time the suite runs, and
|
||||
# counting it made this note report 27 scripts where the directory ships 16 -- a measurement that
|
||||
# changes when a *reader* runs a test is not a measurement of the repository.
|
||||
scripts = sorted(p for p in glob.glob(os.path.join(SKILL_DIR, 'scripts', '**', '*'), recursive=True)
|
||||
if os.path.isfile(p))
|
||||
if os.path.isfile(p) and '__pycache__' not in p.split(os.sep))
|
||||
|
||||
def count(paths):
|
||||
total = 0
|
||||
|
||||
@@ -21,7 +21,7 @@ postings; no sample, tool output or target fact from them entered the repository
|
||||
| W1: full arm64 custom-VM recovery (long-form) | 0x00–0x1A method narrative | `references/native-vm-recovery.md` (existence signals, dispatcher separation, partial deflattening, relocation tables, PC proofs, descriptor/ISA cautions, clean-re-VM loop) |
|
||||
| W2: VMP interpreter recovery with trace-driven IR lifting | anchor/trace/lifting narrative | `references/native-vm-recovery.md` (register anchoring + triple verification, nested segment stacks, STORE-backward slicing, byte provenance, IR shape), `vm_handler_slice.py` nested-loop diagnostic |
|
||||
| W3: login-capture war story (packed + MADP/Weex + gomobile) | route-by-route复盘 | `references/pitfalls.md` P43–P46; the stack-ABI note in `references/hardware-watchpoints.md` |
|
||||
| W4: manual OLLVM deflattening | predicate algebra + IDA scripting | cross-checked against existing content; its MOV/MOVK constant-propagation state mapping is referenced as the static counterpart in `native-vm-recovery.md` §11 — no new file |
|
||||
| W4: manual OLLVM deflattening | predicate algebra + IDA scripting | cross-checked against existing content; its MOV/MOVK constant-propagation state mapping is referenced as the static counterpart in `native-vm-recovery.md` §12 — no new file |
|
||||
|
||||
## 2. The one code change, and why — observed
|
||||
|
||||
@@ -54,7 +54,7 @@ spin-loop note on the real code path. Both regressions are now pinned by tests.
|
||||
plaintext boundary; a RegisterNative inventory is one run for a full method table).
|
||||
- W4's full IDA script: the technique is named (state-register MOV/MOVK constant propagation,
|
||||
CMP-site collection, predecessor walk past blocks with no CMP on the state register) and
|
||||
pointed at from `native-vm-recovery.md` §11; writing an IDA-independent implementation is a
|
||||
pointed at from `native-vm-recovery.md` §12; writing an IDA-independent implementation is a
|
||||
future pass, not an absorbed claim.
|
||||
- Every sample identity in all four sources: anonymized by the authors, kept anonymized here;
|
||||
`.ref/` (the local copies) is untracked and git-ignored in effect (never added).
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
# EXTENSION — absorbing the reverse-engineering half of `game-reserve` (2026-11-09)
|
||||
|
||||
A public game-preservation skill was cloned at the repository root (`game-reserve/`). It is
|
||||
mostly a workflow for turning a dead server into an offline build. That workflow is **not** what this
|
||||
pass took. This pass read the case reports and the pitfalls for the reverse-engineering mechanisms
|
||||
they contain and landed only those: how the Unity/Lua script layer is found and repaired, how
|
||||
AssetBundles are checked and rebuilt, how a half-encrypted Mono assembly is read, how LayaAir's Conch
|
||||
cache is recomputed, and what recon should measure before a route is chosen.
|
||||
|
||||
## Sources
|
||||
|
||||
- `game-reserve/` (the clone at the repository root) — its recon reference (logic-layer table,
|
||||
encryption map, CRC log, resource-completeness check), four anonymised case reports (Unity + Lua,
|
||||
LayaAir + JS, Unity Mono + SLua, native Kotlin), and its patch/pitfalls notes (UnityFS rebuild
|
||||
traps, TextAsset read-back, hot-update merge, R8 minSdk branches, `os.date` race).
|
||||
|
||||
All are public secondary sources. Their case reports are `observed` **by their authors**; nothing in
|
||||
this repository executed them. Identifiers, package names, hosts, keys, offsets and the source's own
|
||||
scripts were deliberately not copied.
|
||||
|
||||
## What was added
|
||||
|
||||
One new reference file, because the topic had no owner:
|
||||
|
||||
| File | Covers | Why no existing file owned it |
|
||||
|---|---|---|
|
||||
| `references/unity-lua-and-assetbundles.md` | Unity + Lua (xLua/tolua/SLua) container discovery, script decryption and Lua 5.1 header repair, loader bytecode-only check, AssetBundle CRC source, UnityFS partial-encryption windows, bundle rebuild traps (layout loss, stripped dependency null, compressed == raw), added/replaced TextAsset read-back, half-encrypted Mono assemblies and the publisher shell | `unity-runtime.md` owns Mono/IL2CPP and `il2cpp-protected-metadata.md` owns protected metadata; neither owns a Lua layer or UnityFS container editing. `packers.md` owns generic shell identification, not the Mono-assembly decryptor shape |
|
||||
|
||||
Existing topic files were extended, not duplicated:
|
||||
|
||||
- `references/framework-runtimes.md` — a **LayaAir native (Conch)** section: identification, the
|
||||
path-addressed cache, the DCC filetable checksum, metadata regeneration from shipped content, the
|
||||
loader patch and the startup-delay race, plus the Laya render-loop freeze and poisoned-XHR shapes.
|
||||
- `references/recon.md` — Unity + Lua and LayaAir rows in the code-location table, and a
|
||||
**§1c** for resource completeness and the encryption map (manifest diff, player backup, entropy is
|
||||
not encryption, fixed prefixes, config-table field check, separate "unreadable" from "not in hand").
|
||||
- `references/repack-and-sign.md` — **renaming the package** across binary AXML, the `resources.arsc`
|
||||
package block and the launcher label, with the validation that both builds coexist.
|
||||
- `references/split-apk.md` — the narrow manual resource merge through `apktool` that the source's
|
||||
native case used, with the condition that makes it safe and the collision that stops it.
|
||||
- `references/dex-patching.md` — deleting specific calls from an original smali method instead of
|
||||
hand-rewriting a lifecycle method, removing the argument-preparation instructions, and putting new
|
||||
logic in an extra dex behind one `invoke-static`.
|
||||
- `references/packers.md` — PairIP as a target-selection signal (Play licensing plus partial code
|
||||
virtualization): prefer an older/regional build without it rather than fighting a re-signed suicide.
|
||||
- `references/pitfalls.md` — **P51** (R8 deleted the low-API branch when `minSdk` was lowered),
|
||||
**P52** (a decompiled Lua file does not match its name because the writer's `read()` returns the
|
||||
template/original bytes) and **P53** (a retained AssetBundle returns null after its dependency was
|
||||
stripped).
|
||||
- `SKILL.md` and `references/routing.md` — two symptom rows: a Lua decompiler rejecting every
|
||||
script with `non-standard lua format`, and a re-signed Unity/Mono build exiting cleanly with code
|
||||
4 two seconds in.
|
||||
|
||||
## Deliberately not absorbed
|
||||
|
||||
- **The offline-revival workflow itself**: feasibility verdicts, fake local servers, virtual-clock
|
||||
testing, player-order playtest, save-preserving release, media/OCR recovery, distribution and the
|
||||
unattended-run playbook. It is a legitimate body of work, but it is a product workflow rather than
|
||||
an APK-reverse mechanism, and the first pass that imported it was corrected for exactly that.
|
||||
- **Target-specific constants**: package names, hosts, keys, offsets, counts, paths and the source's
|
||||
scripts.
|
||||
- **The source's local-server implementation**: `RPCWaitSend` handling, entity-property bags and the
|
||||
rest belong to a game-revival project, not to this skill's protocol-reverse files.
|
||||
- **The media/OCR and night-shift stacks**: no script surface is imported that this pass cannot test.
|
||||
|
||||
## Registration surface updated
|
||||
|
||||
- `references/routing.md`: one reference-index row; two symptom rows mirrored from `SKILL.md`.
|
||||
- `README.md` and `README.zh-CN.md`: one entry in the structure block.
|
||||
- `evidence/capability-matrix.json`: `unity-lua-and-assetbundle-recovery` and
|
||||
`layaair-conch-dcc-recovery`, both `partial` / `route_measured: false` / `unverified`.
|
||||
- `references/evidence-summary.md`: the same two rows.
|
||||
- `references/coverage/route-inventory.md` and `coverage-and-limits.md`: two documented-route rows
|
||||
and two bullets.
|
||||
- `evidence/known-limitations.md`: one "never exercised" bullet.
|
||||
- `.gitignore`: the upstream clone is ignored, so a later `git add -A` cannot commit it.
|
||||
|
||||
## Verification
|
||||
|
||||
None of the absorbed reverse-engineering mechanisms is `observed` in this repository. No Unity or
|
||||
LayaAir package was decrypted, no bundle was rebuilt, no Mono assembly was reconstructed, and no
|
||||
device build was installed. The checks performed here are structural: the new file and every changed
|
||||
section resolve, the symptom mirror agrees, and the registration surface names the new capability.
|
||||
|
||||
## What would change a label
|
||||
|
||||
- **Unity + Lua**: decrypt one anonymous Unity+Lua package, decompile a script, patch one anchor,
|
||||
rebuild the bundle, install it and show the changed behaviour after a cold start, with a control
|
||||
build. That moves the Lua half toward `observed`.
|
||||
- **UnityFS**: rebuild one bundle with the same layout and show it loads; then reproduce the
|
||||
compressed-size-equals-raw crash in a control and fix it in one field. The single-field experiment is
|
||||
the cheapest.
|
||||
- **Mono half-encryption**: reconstruct one PE header from the documented landmarks and have a
|
||||
decompiler open it; the shell-recovery half additionally needs the original process.
|
||||
- **LayaAir DCC**: recompute the filetable for a package and show the engine accepts the regenerated
|
||||
metadata offline. The checksum algorithm is arithmetic and can be host-tested on synthetic files;
|
||||
the full route still needs a package.
|
||||
|
||||
## Gate status
|
||||
|
||||
Run after the change:
|
||||
|
||||
```text
|
||||
python check_repo.py && python check_refs.py && python check_routing.py \
|
||||
&& python check_commands.py && python check_budget.py && python -m pytest -q
|
||||
```
|
||||
|
||||
Result on 2026-11-09: `check_repo` 0 problems; `check_refs` 489 reachable references, 0 dangling,
|
||||
0 warnings; `check_routing` coherent (72 symptom rows, 63 reference rows, 64 script rows);
|
||||
`check_commands` 196 checked, 0 drift; `check_budget` 448 lines / ~12,987 tokens, 0 failures,
|
||||
0 warnings; `pytest` 796 passed, 209 skipped, 25 xfailed. A green run proves the inventory resolves
|
||||
and the mirrors agree; it says nothing about whether a decrypted script or a rebuilt bundle works,
|
||||
which is what the labels above are for.
|
||||
@@ -0,0 +1,113 @@
|
||||
# EXTENSION — reference absorption from `ref/*` (2026-10)
|
||||
|
||||
This pass read sixteen public Chinese write-ups dropped in `ref/` at the repository root and
|
||||
absorbed their *mechanisms* into the skill. It did not run any of them. The record exists so a later
|
||||
reader can tell what changed and on what footing.
|
||||
|
||||
## Sources
|
||||
|
||||
Sixteen files in four groups. Titles, authors, product names and package identifiers are omitted;
|
||||
the descriptions are enough to identify the shape without carrying target identity onto the tracked
|
||||
surface.
|
||||
|
||||
| Group | Files | What they are |
|
||||
|---|---|---|
|
||||
| Unity / IL2CPP | `unity1.md`–`unity6.md`, `unity8.md`, `unity10.md`, `unity12.md` | Nine write-ups on protected Unity builds: absent/encrypted/embedded metadata, a custom container VM, a two-stage native loader, HybridCLR IL-body encryption, a version-lying metadata header, live-image dumping and ELF repair, a runtime IL2CPP bridge, an AssetBundle wrapper and a CDN manifest |
|
||||
| SO / linker | `so1.md`, `so2.md`, `so4.md` | Two source-reading walkthroughs of the Android `dlopen` pipeline and packer design (Android 5.0 and 8.x), plus a Frida cookbook for native/Java hooks |
|
||||
| VM protector | `vmp1.md`, `vmp2.md`, `vmp3.md` | A teaching series and a practical crack on x86 VMProtect-style targets: virtualized dispatch, virtual eflags, NAND lowering, trace search |
|
||||
| Python bytecode | `py1.md` | Static unpacking of a Pyarmor build with a modified `pycdc` |
|
||||
|
||||
All sixteen are **public secondary sources**. Their own claims are `observed` by their authors when
|
||||
they show a command and output; nothing in them is reproduced in this repository. The absorbed
|
||||
mechanics are therefore `unverified` here, and the *ordering judgement* built on them is
|
||||
`inferred`. No text, code, key material, offset table or screenshot was copied.
|
||||
|
||||
## What was added
|
||||
|
||||
Four reference files, each with its own claim-strength paragraph and boundary:
|
||||
|
||||
| File | Absorbs | Deliberately does not |
|
||||
|---|---|---|
|
||||
| `references/il2cpp-protected-metadata.md` | Metadata triage (absent/0-byte/encrypted/embedded/version-lie), consumer-side dump, 0x10C header sizing, repeating-key XOR, custom bytecode-VM container, XXTEA, length-derived string keys, live-image dump and ELF repair, HybridCLR IL-body decryption, AssetBundle header transforms | Recover IL2CPP native code or build an opcode map; explain a specific dumper's internals |
|
||||
| `references/linker-and-soinfo-repair.md` | `dlopen` pipeline as a loader spec, `load_size`/`load_bias`, `seg_page_offset`, `DT_HASH`/`DT_GNU_HASH`, relocation targets and the two biases, APS2, minimal `soinfo` repair, anti-dump header XOR, dump points, constructor timing | Implement an unpacker; guarantee `soinfo` offsets across Android versions |
|
||||
| `references/vm-protector-analysis.md` | Envelope triage, VM_DATA/VM_CONTEXT/vEIP/vStack, central vs direct-threaded dispatch, data-anchored breakpoints, forged returns, trace-by-constant, virtual eflags, NAND lowering, branchless select, static rebase caveats | Reconstruct the guest instruction stream; replace handler slicing in `native-vm-recovery.md` |
|
||||
| `references/python-bytecode-recovery.md` | Pyarmor key schedule, AES-CTR nonce rules, the 12-byte nonce-XOR VM, version-gated `pyc` parsing, extra-section TLV, per-code-object and per-string decryption | Run the recovered module; generalise field offsets across Pyarmor versions |
|
||||
|
||||
### Existing files touched
|
||||
|
||||
- `unity-runtime.md` — the "metadata does not parse" branch now hands the protected case to the new
|
||||
file instead of implying that a retry with another dumper is the answer.
|
||||
- `framework-runtimes.md` — Python runtimes (Chaquopy/Kivy/BeeWare) added to the identification
|
||||
table, with the new file as the next step.
|
||||
- `native-vm-recovery.md` — a cross-link for the case where the missing piece is *what a handler
|
||||
computes* (virtual eflags), not *where the dispatcher is*.
|
||||
- `code-virtualization-and-custom-linkers.md` — a cross-link for when the loader itself becomes the
|
||||
object of study rather than its validation check.
|
||||
|
||||
## Registration surface updated
|
||||
|
||||
- `SKILL.md` symptom index and the `routing.md` mirror: five rows, identical first cells.
|
||||
- `routing.md` reference index: four rows.
|
||||
- `evidence/capability-matrix.json`: four rows, all `partial` / `route_measured: false` /
|
||||
`unverified`; the existing Unity row's evidence list now names the companion file.
|
||||
- `references/evidence-summary.md`: four rows.
|
||||
- `references/coverage-and-limits.md` and `references/coverage/route-inventory.md`: four documented
|
||||
routes, and the not-covered statement now names both Unity files.
|
||||
- `README.md` and `README.zh-CN.md`: tree entries and a scope clause.
|
||||
|
||||
## Second pass — gaps found by auditing the first pass
|
||||
|
||||
The first pass kept the four new references at the level of the primary mechanism and left several
|
||||
secondary mechanisms in the sources. An explicit file-by-file audit found these, and they are now
|
||||
absorbed into the files that already own the topic (same `unverified` / `inferred` labels):
|
||||
|
||||
| Missed mechanism | Now in |
|
||||
|---|---|
|
||||
| Staged loader that decrypts a DEX from an asset, selects a payload by ABI, and patches an 8-byte tail | `code-virtualization-and-custom-linkers.md` §staged loaders |
|
||||
| IL2CPP live object graph (`Il2Cpp.gc.choose`, getter invocation) and `Il2Cpp.dump(name, path)` | `unity-runtime.md` §5 |
|
||||
| ARM64 app on an x86 host: translation runs the app but not an ARM64 `frida-server` | `environment.md` §emulator notes |
|
||||
| MessagePack as a self-describing body; mutate request before response | `protocol-reverse.md` §1.1, `server-api.md` |
|
||||
| A delayed detection that is a `sleep`/`nanosleep` timing measurement | `detection-and-anti-analysis.md` §timing-delayed checks |
|
||||
| A dynamically loaded dex visible as a `(deleted)` mapping | `advanced-unpacking.md` §read the map |
|
||||
| `RegisterNatives` table layout, `dlopen` gating, instruction+4 reads, Thumb NOP patch inside `call_function`, JNI argument shapes, OLLVM call-graph triage | `dynamic-frida.md` §native registration |
|
||||
| Trace call-site anchoring, `rel32` resolution, back-edge hot-loop suppression | `vm-protector-analysis.md` §4.1 |
|
||||
| Branchless `max` arithmetic | `vm-protector-analysis.md` §6.2 |
|
||||
| Encoded handler tables (`table[i] + constant`) and the one-register/benign-landing dispatcher invariant | `native-vm-recovery.md` §2.1-2.2 |
|
||||
| The `29.1` `genericMethodPointersCount` misdetection on a large `.so` | `il2cpp-protected-metadata.md` §5 |
|
||||
|
||||
### Deliberately not absorbed
|
||||
|
||||
- **Target-specific constants**: per-sample addresses, AES keys, section names, package ids, CDN
|
||||
hosts, device serials and the write-ups' own scripts. They would be reused wrongly and they carry
|
||||
identity; the reference files say the constants must be re-derived.
|
||||
- **One-target asset pipelines**: Live2D `moc3` parsing, USM video reconstruction, the CDN manifest
|
||||
delta and the Blender import conventions. They are not APK-reversing mechanisms and belong to an
|
||||
asset-extraction skill; `unity-runtime.md` §6 keeps the audit question, not the pipeline.
|
||||
- **Middleware-specific audio decryption** (CRIWARE ACB) and the GUI-only steps of the cited
|
||||
debugger sessions.
|
||||
- **Secure-coding advice** (constant-time comparison) that is not a reverse-engineering route.
|
||||
- **Exact opcode tables** from a challenge VM. The procedure for deriving one is covered in
|
||||
`native-vm-recovery.md`; copying the table would invite applying it to a different ISA.
|
||||
|
||||
## What would change a label
|
||||
|
||||
Per file, one cheap experiment turns the `unverified` mechanism into a local `observed`:
|
||||
|
||||
- **IL2CPP metadata:** decrypt one file to a valid `0xFAB11BAF` and have Il2CppDumper accept it;
|
||||
separately dump one live image and name one function in the disassembler.
|
||||
- **Linker:** load a trivial `.so` from memory with the arithmetic in the file, resolve one symbol
|
||||
through the repaired `soinfo`, and dump one protected image at `LoadSegments`.
|
||||
- **VM protector:** trace one protected comparison, find the virtual flags slot, force the value, and
|
||||
show the failure path disappear while the VM remains intact.
|
||||
- **Python:** parse one `.pyc`, show the extra-section counts matching the file, decrypt one code
|
||||
object, and execute the recovered module to the same output as the original.
|
||||
|
||||
Until one of these is recorded, the capability matrix rows must stay `partial` / `unverified`, and
|
||||
a reader must not cite them as support for a claim about a target.
|
||||
|
||||
## Gate status
|
||||
|
||||
The structural gates were run after the change: `check_repo.py`, `check_refs.py`,
|
||||
`check_routing.py`, `check_commands.py`, `check_budget.py`, and `pytest -q`. A green run proves
|
||||
the inventory resolves and the index mirrors agree; it says nothing about whether the mechanisms
|
||||
work. That distinction is the point of the labels above.
|
||||
@@ -0,0 +1,168 @@
|
||||
# EXTENSION — second reference absorption from `ref/*` (2026-10-25)
|
||||
|
||||
This pass read three public Chinese write-ups dropped in `ref/` and absorbed their *mechanisms* into
|
||||
the files that already own the topics. None was run end to end; a host-level pass (§Verification pass)
|
||||
settles the claims that need no device. The record exists so a later reader can tell what changed and
|
||||
on what footing.
|
||||
|
||||
## Sources
|
||||
|
||||
Three files, described by shape. Titles, authors, product names, package identifiers and every
|
||||
per-build address are omitted; none was copied onto the tracked surface.
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `vm1.md` | A dual-library commercial shell on ARM64: two SOs, one owning Java/ART checks, the other owning an `init_proc` scheduler with inline-shellcode `exit_group`, three watchdog threads and SMC. Covers dump timing, a syscall-level reader, single-predicate patching and a tiered patch order |
|
||||
| `vm2.md` | A white-box VM protecting one signing routine: threaded-code interpreter, tens of thousands of obfuscated nodes, and a devirtualization to a straight-line `(op, args)` program with constant table, output map and fixed template |
|
||||
| `vm3.md` | A native signer behind a JNI shim plus an encrypted body: package/signature checks during `JNI_OnLoad`, an emulator used as an oracle, a differential probe that classifies the cipher, an involution wrapper around a standard stream cipher, and Java/Python encoding drift |
|
||||
|
||||
All three are **public secondary sources**. Their own claims are `observed` by their authors; nothing
|
||||
in them was reproduced here. Mechanisms that need a target are therefore `unverified`, the ordering
|
||||
judgements built on them are `inferred`, and the host-checkable ones are settled in §Verification
|
||||
pass. No text, code, key material, offset table or screenshot was
|
||||
copied.
|
||||
|
||||
## What was added
|
||||
|
||||
No new reference files. Each mechanism was folded into the file that already owns its topic:
|
||||
|
||||
| File | Absorbs | Deliberately does not |
|
||||
|---|---|---|
|
||||
| `references/linker-and-soinfo-repair.md` §6.2–6.3 | the dump window that closes inside `JNI_OnLoad` when self-decryption and watchdog startup share it; the raw-syscall reader outside a self-hooked libc; zero-filling unreadable pages so segment offsets survive repair | claim that a dump taken at `android_dlopen_ext` entry is complete; name a specific reader |
|
||||
| `references/native-tamper-and-suicide.md` §Which site | predicate-first patching (one verdict function versus many kill sites), the tiered grading with the per-tier reason, benign-value selection by caller branch, watchdog enumeration by probe, one tier per run | copy any sample's function table or addresses; assert that a predicate patch covers an unenumerated checker |
|
||||
| `references/detection-and-anti-analysis.md` §Filter signals | module-filtered signal attribution: ART's implicit `SIGSEGV` on `boot*.oat`/`odex`/JIT pages is the runtime's, and a handler must forward anything outside the target module | claim the discrimination is measured; recommend swallowing runtime signals |
|
||||
| `references/native-vm-recovery.md` §11 | devirtualization to a runnable program: symbolic input, constant folding, loop/branch elimination, the four artefacts (program, constant table, output map, template), version binding, per-node validation | claim the route works for a VM that reads device state or time; replace the IR-recovery sections |
|
||||
| `references/protocol-reverse.md` §7 | three black-box probes (header length, determinism, one-byte diffusion width, length law), involution-wrapper algebra, fixed-permutation recognition, and the Java-`URLEncoder` / compression-byte drift that decides the last mile. The probe's original prefix-XOR-only claim was falsified by the host run below and the section now states the corrected discriminator | claim any cipher was classified; assume byte-identical compression is required |
|
||||
| `references/signature-derived-keys.md` §Variant | a certificate-derived salt concatenated *inside* the digest: why black-box hash search cannot find it, how to read the cached buffer, how to verify on three triples, and the per-build consequence | present the captured constant as an algorithm |
|
||||
| `references/pitfalls.md` P49–P50 | extraction length masquerading as an algorithm gap; an involution wrapper that cancels | duplicate P42's decoder-desync case or the §7 method |
|
||||
|
||||
## Registration surface updated
|
||||
|
||||
- `evidence/capability-matrix.json`: three rows — `native-dump-window-and-syscall-reader` and
|
||||
`whitebox-crypto-devirtualization-to-program` are `partial` / `route_measured: false` / `unverified`;
|
||||
`cipher-classification-by-differential-probe` is `partial` / `route_measured: false` / `inferred`
|
||||
after the host checks below; two existing rows
|
||||
(`native-terminate-path-neutralisation`, `signature-derived-keys`) had their `limits` extended
|
||||
rather than duplicated.
|
||||
- `references/evidence-summary.md`: three rows.
|
||||
- `references/coverage/route-inventory.md`: three rows.
|
||||
- `references/coverage-and-limits.md`: three absorbed-route bullets extended.
|
||||
- `SKILL.md`, `routing.md`, both READMEs: unchanged. No file, script or symptom row was added, so the
|
||||
symptom mirror and the reference/script inventories had nothing to learn.
|
||||
|
||||
## Verification pass — host, 2026-10-25
|
||||
|
||||
Purpose: separate what the write-ups report from what this host can show, and label per claim rather
|
||||
than per section. Three tiers were applied: `observed` (a command ran here and its output is below),
|
||||
`inferred` (follows from a mechanism or a neighbouring measurement), `unverified` (reported by
|
||||
someone else, not reproduced). No device, protected sample or server was involved, so **no claim
|
||||
about a target was upgraded**.
|
||||
|
||||
```bash
|
||||
python3 docs/tool-verification/fixtures/verify_absorbed_claims.py
|
||||
```
|
||||
|
||||
```text
|
||||
PASS mask identity (protocol-reverse section 7, involution)
|
||||
65536 eight-bit (x,m) pairs: 0 counterexamples
|
||||
200000 random 16-bit pairs: 0 counterexamples
|
||||
PASS PKCS#7 length law (protocol-reverse section 7, probe 3)
|
||||
b=16, p=0..64: 0 mismatches
|
||||
PASS unreadable page: skip shifts, zero-fill preserves (linker section 6.3)
|
||||
expected offset 8199
|
||||
skip -> 4103
|
||||
zero-fill -> 8199
|
||||
PASS hidden salt defeats a visible-parameter search (signature-derived-keys variant)
|
||||
36 combinations over 3 algorithms and 4 field orders: 0 hits
|
||||
with the salt included: match
|
||||
PASS compressed bytes are implementation/parameter defined (protocol-reverse section 7)
|
||||
level 1 = 49 bytes, level 9 = 48 bytes, identical = False
|
||||
both round-trip to the payload
|
||||
PASS Python percent-encoding differs from Java URLEncoder (protocol-reverse section 7)
|
||||
quote = a%20b~%2A-_.
|
||||
quote_plus = a+b~%2A-_.
|
||||
Java keeps *-._ and encodes ~ as %7E -- not checked here (no JDK)
|
||||
PASS AES mode separation (protocol-reverse section 7, probe 2)
|
||||
ctr prefix-xor dirty=0/32 one-byte-flip changed=1/32
|
||||
cbc prefix-xor dirty=0/32 one-byte-flip changed=32/32
|
||||
ecb prefix-xor dirty=0/32 one-byte-flip changed=16/32
|
||||
all three modes show zero prefix-XOR: that probe cannot separate them
|
||||
|
||||
7 check(s), 0 failed
|
||||
RESULT=ok
|
||||
```
|
||||
|
||||
### What the run falsified
|
||||
|
||||
The absorbed probe said *zeros over the common prefix ⇒ a stream cipher*. Measured on AES-128 with a
|
||||
fixed IV, **CTR, CBC and ECB all produce zero prefix-XOR** (0 of 32 bytes differ): any deterministic
|
||||
mode reproduces the ciphertext of a prefix, so the experiment only proves the absence of a
|
||||
per-message nonce. The discriminator that does work is a one-byte plaintext flip: CTR changes exactly
|
||||
1 byte, CBC changes every block from the flipped one onward (32 of 32 here), ECB changes exactly one
|
||||
block (16 of 32, later blocks untouched). The reference now states the corrected procedure; the
|
||||
capability row records the correction instead of the original claim.
|
||||
|
||||
**A label convention was corrected.** `native-vm-recovery.md`'s claim-strength paragraph called the
|
||||
absorbed mechanics `inferred`. Under the repository's definition (`unverified` = reported by someone
|
||||
else, not reproduced) the mechanics are `unverified`, and only the ordering judgements are
|
||||
`inferred`. The paragraph and the checklist now say that; no capability row changed for it.
|
||||
|
||||
### Claims the run settles (host only)
|
||||
|
||||
| Claim | Where | Now |
|
||||
|---|---|---|
|
||||
| `(x & ~m) \| (~x & m) == x ^ m`, and the composition is an involution | `protocol-reverse.md` §7 | `observed` |
|
||||
| PKCS#7 padded length is `b * ceil((len+1)/b)` | `protocol-reverse.md` §7 | `observed` |
|
||||
| Zero-filling an unreadable page preserves later offsets; skipping shifts them | `linker-and-soinfo-repair.md` §6.3 | `observed` |
|
||||
| An unknown salt inside the digest defeats a search over visible parameters | `signature-derived-keys.md` §Variant | `observed` |
|
||||
| Two compressors/parameters can emit different valid bytes for one payload | `protocol-reverse.md` §7 | `observed` (general) |
|
||||
| Python's encoder treats ` `, `*`, `~` differently from Java's | `protocol-reverse.md` §7 | `observed` (Python side) |
|
||||
| CTR / CBC / ECB are separable by diffusion width, not by prefix-XOR | `protocol-reverse.md` §7 | `observed` |
|
||||
|
||||
### Claims that stay `unverified`, and what would move them
|
||||
|
||||
- **Device-side mechanisms** — the dump window inside `JNI_OnLoad`, watchdog startup, a protector
|
||||
intercepting the dump reader. Needs a device and a protected sample: the experiments are the four
|
||||
already listed under *What would change a label*.
|
||||
- **The Java encoder mapping** — no JDK on the analysis host. One captured parameter from a real
|
||||
request settles it; until then the mapping is quoted from the JDK contract.
|
||||
- **liblz4 versus python-lz4** — no lz4 binding here. The general claim is `observed`; the specific
|
||||
pair is not.
|
||||
- **The devirtualization route** — needs a VM binary; nothing on this host can stand in for one.
|
||||
|
||||
## Deliberately not absorbed
|
||||
|
||||
- **Per-build constants and addresses**: function offsets, unified kill-site addresses, the 32-byte
|
||||
salt value, the signing prefix and template string, the package identifier, the shell's own
|
||||
`sub_*` names. They are only valid for one build and they carry identity.
|
||||
- **Performance and effort claims** ("1 ms", "days to hours") — no measurement exists here to anchor
|
||||
them.
|
||||
- **The AI-assisted-analysis narrative** in one source: it is advice about tool use, not a reversing
|
||||
mechanism, and it is not reproducible as written.
|
||||
- **Thread and watchdog tables as data.** The *method* (enumerate by probe, then prove the set closed)
|
||||
was absorbed; the table itself would invite applying one build's layout to another.
|
||||
|
||||
## What would change a label
|
||||
|
||||
One cheap experiment per row, on a device this record never had. The cipher row's host half is
|
||||
already done (§Verification pass); what remains there is a real body and a real server.
|
||||
|
||||
- **Dump window:** dump one protected image at `android_dlopen_ext` entry, repair it, and open it in a
|
||||
disassembler with the expected functions present; separately dump inside `JNI_OnLoad` and record
|
||||
whether the process survives.
|
||||
- **Patch grading:** run the same target twice — kill sites only, then the predicate only — and show
|
||||
which one survives longer than the observed timer.
|
||||
- **Devirtualization:** extract one program, run it against a device call on ten inputs, and show
|
||||
per-node equality at three checkpoints.
|
||||
- **Cipher classification:** classify one body with the three probes, then reproduce it and have the
|
||||
server accept the request.
|
||||
|
||||
Until one of these is recorded, the matrix rows stay `partial` — `inferred` for the cipher row on the
|
||||
host evidence, `unverified` for the other two — and none may be cited as support for a claim about a
|
||||
target.
|
||||
|
||||
## Gate status
|
||||
|
||||
`check_repo.py`, `check_refs.py`, `check_routing.py`, `check_commands.py`, `check_budget.py` and
|
||||
`pytest -q` were run after the change; the result is in the session record, not in this file. A green
|
||||
run proves the inventory resolves; it says nothing about whether the mechanisms work.
|
||||
@@ -0,0 +1,151 @@
|
||||
# EXTENSION — third audit of the `ref/*` drop folder (2026-10-27)
|
||||
|
||||
`ref/` still held the sixteen write-ups absorbed on 2026-10-24 (`EXTENSION-ref-absorption-2026-10.md`).
|
||||
Their mtimes were unchanged, and nothing in the folder matched the 2026-10-25 set that was absorbed in
|
||||
place. So this pass was **not** a re-absorption: it re-read all sixteen, compared every generalisable
|
||||
mechanism against what the skill already says, and ran the host-checkable part of what it found. Nine
|
||||
mechanisms were still absent, one absorbed sentence turned out to be wrong, and one procedure is now
|
||||
`observed` instead of `unverified`.
|
||||
|
||||
## Sources
|
||||
|
||||
The same sixteen files, in the same four groups as the 2026-10 record (Unity/IL2CPP nine, linker three,
|
||||
x86 VM protector three, Pyarmor one). Titles, authors, product names and package identifiers are omitted
|
||||
here for the same reason as before: they carry identity and nothing in the tracked surface needs them.
|
||||
All are public secondary sources, `unverified` in this repository unless the verification pass below
|
||||
says otherwise.
|
||||
|
||||
## What was added
|
||||
|
||||
No new reference files — every mechanism went into the file that already owns its topic.
|
||||
|
||||
| Mechanism | File | Why the existing text did not cover it |
|
||||
|---|---|---|
|
||||
| The shipped Pyarmor blob is wrapped once more: outer container → per-code-object → per-string, three nonce scopes on one master key, and a live dump is therefore structurally incomplete | `python-bytecode-recovery.md` §2.2 | §3 opened with "the protected file is a normal `.pyc` with extra fields", which is the second layer, not the file you are handed |
|
||||
| Mirror the host register width, not just the register clobbers, when reimplementing the 12-byte key VM | `python-bytecode-recovery.md` §2.1 | §2.1 named the `idiv` clobber; 32-bit wrapping and truncating division were unstated, and they fail the same way |
|
||||
| Python compiled away (Nuitka / Cython / `pyd`): no `.pyc` is not "no Python" | `framework-runtimes.md` identification table | the Python row implied the runtime always arrives as bytecode |
|
||||
| A rebuilt `libil2cpp` announces itself in the ELF tables (`JNI_OnLoad` export, own `DT_INIT`/`init_array`, `SHT_LOUSER` section) | `il2cpp-protected-metadata.md` §1.1 | the triage table sent "registration search returns 0" straight to the live-image dump; the injected entry point is cheaper to find and is what the dumper's refusal is reacting to |
|
||||
| A container VM's block schedule decides what a unit test is: fixed-size blocks with a truncated tail and no cross-block state vs a chained context | `il2cpp-protected-metadata.md` §3.2 | the section specified the container layout and stopped at "replay the program"; the call site is what says whether block 0 is a valid test |
|
||||
| When the literal cipher lives in the VM, drive `String::NewLen` over every index instead of reversing the cipher — and use it as a completeness proof | `il2cpp-protected-metadata.md` §6 | the hook was documented as observation only; enumerating the index space is a different, stronger route |
|
||||
| A VM can live in the managed layer: opcode array + cursor + `Dictionary<int, delegate>`, handler indices enrolled in the constructor | `unity-runtime.md` §when the managed layer is itself the interpreter | every VM file assumed a native interpreter; `native-vm-recovery.md` now says so explicitly and cross-links |
|
||||
| Static array literals are field defaults materialised by `RuntimeHelpers::InitializeArray`, not bytes in `.rodata` | `unity-runtime.md` same section | the absence of a table in `.rodata` was being read as "derived at run time" |
|
||||
| Hook the framework crypto primitive (BCL AES provider, `javax.crypto`), not the app's obfuscated wrapper | `unity-runtime.md` §5 | §5 polled the app's own class; the stability of framework class names under obfuscation is the point |
|
||||
| A comparison gate is a prefix oracle: instrument the comparator's counter, and read the fail-path cost to decide whether the oracle is open | `account-gates.md` Step 2b | the file classified gates by authority and never considered that the comparison itself leaks the expected value |
|
||||
| Debugger-side stop policy: `SIGPWR`/`SIGXCPU` suspend-to-crash, one database per activity, input injection into a paused process | `ida-so-debugging.md` §8 | the debuggable-side failure modes were documented; the failures caused by the debugger's own defaults were not |
|
||||
|
||||
### A claim that was corrected, not added
|
||||
|
||||
`python-bytecode-recovery.md` §5 said an unset `nonce[15]` "produces a stream that decrypts the first
|
||||
block plausibly and then diverges". Counter mode does not have that state: the keystream for block *i*
|
||||
is `E(nonce || counter_i)`, so a different nonce byte changes the output from block 0. Measured below.
|
||||
The paragraph now says what happens (every block wrong; an unset tail makes the result
|
||||
non-reproducible) and tells the reader to check a known prologue rather than "a plausible body".
|
||||
|
||||
## Registration surface updated
|
||||
|
||||
- `evidence/capability-matrix.json`: two rows, `il2cpp-managed-layer-bytecode-vm` (`partial`,
|
||||
`route_measured: false`, `unverified`) and `comparison-cost-oracle` (`partial`,
|
||||
`route_measured: false`, `observed` — the host half only).
|
||||
- `references/evidence-summary.md`: the same two rows, with the same labels.
|
||||
- `references/coverage/route-inventory.md`: one new row (the comparison oracle) and three extended rows
|
||||
(Unity, protected IL2CPP, Python).
|
||||
- `references/coverage-and-limits.md`: three bullets under "Covered by documented routes", each naming
|
||||
which half is measured.
|
||||
- `SKILL.md`, `routing.md`, both READMEs: unchanged. No file, script or symptom row was added, so the
|
||||
symptom mirror and the inventories had nothing to learn. That is also why the token budget did not
|
||||
move.
|
||||
|
||||
## Verification pass — host, 2026-10-27
|
||||
|
||||
```bash
|
||||
python3 docs/tool-verification/fixtures/verify_ref_claims_10c.py
|
||||
```
|
||||
|
||||
```text
|
||||
PASS CTR: nonce tail changes block 0 (python-bytecode-recovery section 5)
|
||||
keystream block 0 differs in 16/16 bytes
|
||||
ciphertext block 0 differs in 16/16 bytes, blocks 1-2 in 32/32
|
||||
negative control, nonce against itself: 0/48 bytes differ
|
||||
so there is no "first block decrypts, rest diverges" state -- every block is wrong
|
||||
PASS comparison cost is a prefix oracle (account-gates Step 2b)
|
||||
prefix 0/15 -> early-exit 1, full pass 15
|
||||
prefix 1/15 -> early-exit 2, full pass 15
|
||||
...
|
||||
prefix 15/15 -> early-exit 15, full pass 15
|
||||
full pass over the same candidates: [15]
|
||||
negative control, identical inputs through the early-exit build: 15 (must be 15)
|
||||
early exit: work grows one unit per correct prefix byte; full pass: constant
|
||||
PASS metadata header size by backward walk (il2cpp-protected-metadata section 2.1)
|
||||
declared 0x1140, forward scan 0x1140, walk from 0x10c -> 0x1140
|
||||
negative control, off-grid start 0x110 -> 0x1120 (must differ)
|
||||
magic/version zeroed in this fixture: the walk uses only offset/count pairs
|
||||
|
||||
3 check(s), 0 skipped, 0 failed
|
||||
RESULT=ok
|
||||
```
|
||||
|
||||
Three labels changed as a result: the counter-mode statement in §5 is now `observed` (and corrected),
|
||||
the comparison-cost separation in `account-gates.md` is `observed` for the synthetic case only, and
|
||||
the backward header walk in §2.1 is `observed` on a synthetic header. **No claim about a target was
|
||||
upgraded** — no device, sample or server was involved.
|
||||
|
||||
### The fixture was audited before it was trusted
|
||||
|
||||
The first draft passed all three checks and was still wrong in one of them: the comparison check
|
||||
incremented its own counter inside the loop it was measuring, so `work == k + 1` restated the Python
|
||||
source and could not fail for any real reason — the repository's "a limit that cannot fail is
|
||||
decorative" defect, in a check that was about to carry an `observed` label. Three changes:
|
||||
|
||||
1. **Measured on compiled code.** The two comparators are now C, built with `-O2` and called through
|
||||
`ctypes`; the question is what a compiler emits for `break` on mismatch, which an interpreted loop
|
||||
cannot answer about itself. Without a compiler the check reports SKIP rather than PASS.
|
||||
2. **Every check carries a negative control** that must come out empty: the same nonce twice (0/48
|
||||
bytes differ), identical inputs through the early-exit build (15, i.e. a full pass), and an
|
||||
off-grid walk start (`0x110` yields `0x1120` instead of `0x1140`).
|
||||
3. **The verdict travels as a return value, not through a global list.** `main()` built its failure
|
||||
count from the list `report()` appended to, so a check that returned False without printing would
|
||||
have been invisible; it now counts the return values and reports skips separately.
|
||||
|
||||
`tests/unit/test_verify_ref_claims_10c.py` injects the wrong claim into each check and requires the
|
||||
failure — full-pass mislabelled as early-exit, early-exit mislabelled as constant, an unchanged nonce,
|
||||
an off-grid walk, a pair table whose declared and scanned lengths disagree — plus the skip semantics
|
||||
(a host with no `openssl`/compiler exits 0 with SKIP) and the exit-code plumbing. The AES probe needs
|
||||
`openssl`; the comparison probe needs a C compiler; the header check needs nothing.
|
||||
|
||||
## Deliberately not absorbed
|
||||
|
||||
- **Per-build constants and identities**: offsets, keys, package ids, function counts, the articles' own
|
||||
scripts. Same rule as the two earlier passes.
|
||||
- **Asset and media pipelines** (Live2D `moc3`, video reconstruction, Blender conventions) and the
|
||||
CDN-manifest delta. One candidate survived this audit — "an index pulled from a device is a cache
|
||||
subset, not the catalogue" — and was dropped deliberately: it is a provenance rule for a download
|
||||
pipeline, and `server-config-and-updates.md` is not an asset-extraction file.
|
||||
- **In-memory patch hygiene** (write the operand, restore `r-x`) from one article: the distinct part is
|
||||
one sentence, and `native-and-so.md` already carries the "which copy is mapped" rule that decides
|
||||
whether a patch matters at all. Recording it would have added a fourth file to a single idea.
|
||||
- **Performance and effort claims**, and the articles' commentary about tooling quality.
|
||||
|
||||
## What would change a label
|
||||
|
||||
One experiment per row, none of which this record could run:
|
||||
|
||||
- **Managed-layer VM**: recover one opcode table from a `dump.cs` interpreter and show an instruction
|
||||
stream that reproduces a known in-game value. That moves the row to `observed`; today only the shape
|
||||
is documented.
|
||||
- **Array literals**: hook `InitializeArray` on a live build and read back a key that the same build's
|
||||
`.rodata` does not contain.
|
||||
- **Comparison oracle**: run the counter against one real serial gate and show the work grows with the
|
||||
correct prefix. On a device, use the comparator's counter, not the clock — a timing-only attempt is
|
||||
expected to fail and would not move the row.
|
||||
- **Pyarmor outer layer**: decrypt one shipped blob, show the pyc magic appearing only after the outer
|
||||
pass, then decrypt one code object and run the recovered module.
|
||||
- **Rebuilt `libil2cpp`**: `readelf` a stock library and the protected one side by side and show the
|
||||
three markers absent/present.
|
||||
|
||||
## Gate status
|
||||
|
||||
`check_repo.py`, `check_refs.py`, `check_routing.py`, `check_commands.py`, `check_budget.py` and
|
||||
`pytest -q` were run after the change and are green (796 passed, 209 skipped, 25 xfailed; eight of
|
||||
those tests are the fixture's own falsifiability cases). A green run
|
||||
proves the inventory resolves and the mirrors agree; it says nothing about whether any mechanism works
|
||||
on a target, which is what the labels above are for.
|
||||
@@ -76,8 +76,8 @@ those are called out in the matrix rather than buried here.
|
||||
## Absorption-pass record
|
||||
|
||||
A later pass absorbed mechanics from external skill repositories (`reverse-skill`,
|
||||
`awesome-game-security`, `android-reverse-engineering-claude-skill`, `MobileRE-Skill`), keeping each
|
||||
project's own discipline: only the phase, the checklist and the command pattern cross over, with the
|
||||
`awesome-game-security`, `android-reverse-engineering-claude-skill`, `MobileRE-Skill`, `game-reserve`),
|
||||
keeping each project's own discipline: only the phase, the checklist and the command pattern cross over, with the
|
||||
source URL and the access date recorded, and nothing vendored as a runtime dependency. These files
|
||||
live here rather than in the skill because two of them corrected a claim the repository had already
|
||||
written down.
|
||||
@@ -88,6 +88,8 @@ written down.
|
||||
| `EXTENSION-dart-aot-formats.md` | Two string-table claims tested against a real dual-ABI Flutter app: the arm64 packed scheme confirmed against literal tag bytes, and the assumed armv7 `len*2`/UTF-16 form **refuted** — the 32-bit record is `[header u32][byte-count u32le][UTF-8]`, and the extractor's zero is a format mismatch rather than an empty table |
|
||||
| `EXTENSION-detection-pipeline.md` | Naming the check that fires: three arms on a public MASTG target (control alive, probe arm dead in ≈300 ms via `strstr("frida")`, with the `TracerPid=0` versus 4-frida-mappings asymmetry), `svc_scan.py`'s two decoders agreeing on an identical 214-site set, the layered Java-to-svc descent, and the ptrace-free dump boundary on targets whose dex is deflated inside the APK |
|
||||
| `EXTENSION-dexsql.md` | The SQL query layer adopted as a **third indexer** beside rasc/droidasc/ddc: identical class-definition sets on four archives (zero differences either way), the string xref agreement and the `=` versus `LIKE` match-semantics trap, `decode` against `ddc disasm` line for line, and the persistent cache measured as **not** a speed switch |
|
||||
| `EXTENSION-ref-absorption-2026-10.md` | Sixteen public write-ups in four groups (Unity/IL2CPP metadata protection, linker-level SO packing, VM protector idioms, Pyarmor bytecode), the four reference files they became, the registration surface that changed, and the one cheap experiment that would move each row off `unverified` |
|
||||
| `EXTENSION-game-reserve-2026-11.md` | The reverse-engineering half of a public game-preservation skill: Unity + Lua script extraction and the Lua 5.1 header tamper, AssetBundle CRC and UnityFS rebuild traps, half-encrypted Mono assemblies, LayaAir Conch DCC checksums, plus recon/repack/split/dex/packer additions — all absorbed as `unverified`, since no package was rebuilt here |
|
||||
|
||||
## Hardware-layer pass record
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Re-run the host-checkable claims absorbed from ref/* on 2026-10-25.
|
||||
|
||||
These are the claims that can be settled without a device, a protected sample or a server. Each
|
||||
check prints what it measured and whether the claim in the reference survived it. The AES probes
|
||||
need `openssl`; without it they report SKIP rather than passing.
|
||||
|
||||
Usage:
|
||||
python3 docs/tool-verification/fixtures/verify_absorbed_claims.py
|
||||
"""
|
||||
import hashlib
|
||||
import math
|
||||
import random
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.parse
|
||||
import zlib
|
||||
|
||||
PAGE = 4096
|
||||
KEY = '000102030405060708090a0b0c0d0e0f'
|
||||
IV = KEY
|
||||
results = []
|
||||
|
||||
|
||||
def report(name, ok, detail):
|
||||
results.append((name, ok))
|
||||
print(('PASS ' if ok else 'FAIL ') + name)
|
||||
for line in detail:
|
||||
print(' ' + line)
|
||||
|
||||
|
||||
def mask_identity():
|
||||
bad = sum(1 for x in range(256) for m in range(256)
|
||||
if ((x & ~m) | (~x & m)) & 0xFF != x ^ m)
|
||||
random.seed(1)
|
||||
bad16 = 0
|
||||
for _ in range(200000):
|
||||
x, m = random.getrandbits(16), random.getrandbits(16)
|
||||
if ((x & ~m) | (~x & m)) & 0xFFFF != x ^ m:
|
||||
bad16 += 1
|
||||
report('mask identity (protocol-reverse section 7, involution)', bad == 0 and bad16 == 0,
|
||||
['65536 eight-bit (x,m) pairs: %d counterexamples' % bad,
|
||||
'200000 random 16-bit pairs: %d counterexamples' % bad16])
|
||||
|
||||
|
||||
def padding_length():
|
||||
bad = [n for n in range(0, 65)
|
||||
if n + (16 - n % 16) != 16 * math.ceil((n + 1) / 16)]
|
||||
report('PKCS#7 length law (protocol-reverse section 7, probe 3)', not bad,
|
||||
['b=16, p=0..64: %d mismatches' % len(bad)])
|
||||
|
||||
|
||||
def zero_fill():
|
||||
img = bytearray(3 * PAGE)
|
||||
img[2 * PAGE + 7] = 0xAB
|
||||
skipped = img[:PAGE] + img[2 * PAGE:]
|
||||
filled = img[:PAGE] + bytearray(PAGE) + img[2 * PAGE:]
|
||||
ok = skipped.index(0xAB) != 2 * PAGE + 7 and filled.index(0xAB) == 2 * PAGE + 7
|
||||
report('unreadable page: skip shifts, zero-fill preserves (linker section 6.3)', ok,
|
||||
['expected offset %d' % (2 * PAGE + 7),
|
||||
'skip -> %d' % skipped.index(0xAB),
|
||||
'zero-fill -> %d' % filled.index(0xAB)])
|
||||
|
||||
|
||||
def hidden_salt():
|
||||
p, b, t = b'api=search', b'{"q":"x"}', b'1729000000'
|
||||
salt = bytes.fromhex('00112233445566778899aabbccddeeff')
|
||||
target = hashlib.md5(p + b + t + salt).hexdigest()
|
||||
tried = hits = 0
|
||||
for alg in (hashlib.md5, hashlib.sha1, hashlib.sha256):
|
||||
for sep in (b'', b'&', b'|'):
|
||||
for parts in ((p, b, t), (t, b, p), (p, t, b), (b, p, t)):
|
||||
tried += 1
|
||||
hits += alg(sep.join(parts)).hexdigest() == target
|
||||
ok = hits == 0 and hashlib.md5(p + b + t + salt).hexdigest() == target
|
||||
report('hidden salt defeats a visible-parameter search (signature-derived-keys variant)', ok,
|
||||
['%d combinations over 3 algorithms and 4 field orders: %d hits' % (tried, hits),
|
||||
'with the salt included: match'])
|
||||
|
||||
|
||||
def compression_drift():
|
||||
data = b'{"items":[' + b'{"id":1,"name":"x"},' * 40 + b']}'
|
||||
a, b = zlib.compress(data, 1), zlib.compress(data, 9)
|
||||
ok = a != b and zlib.decompress(a) == data and zlib.decompress(b) == data
|
||||
report('compressed bytes are implementation/parameter defined (protocol-reverse section 7)', ok,
|
||||
['level 1 = %d bytes, level 9 = %d bytes, identical = %s' % (len(a), len(b), a == b),
|
||||
'both round-trip to the payload'])
|
||||
|
||||
|
||||
def percent_encoding():
|
||||
q = urllib.parse.quote('a b~*-_.')
|
||||
qp = urllib.parse.quote_plus('a b~*-_.')
|
||||
ok = q == 'a%20b~%2A-_.' and qp == 'a+b~%2A-_.'
|
||||
report('Python percent-encoding differs from Java URLEncoder (protocol-reverse section 7)', ok,
|
||||
['quote = ' + q, 'quote_plus = ' + qp,
|
||||
'Java keeps *-._ and encodes ~ as %7E -- not checked here (no JDK)'])
|
||||
|
||||
|
||||
def aes_enc(mode, data):
|
||||
cmd = ['openssl', 'enc', '-aes-128-' + mode, '-K', KEY, '-iv', IV, '-nopad']
|
||||
run = subprocess.run(cmd, input=data, capture_output=True)
|
||||
if run.returncode:
|
||||
raise RuntimeError(run.stderr.decode('utf-8', 'replace'))
|
||||
return run.stdout
|
||||
|
||||
|
||||
def aes_modes():
|
||||
if not shutil.which('openssl'):
|
||||
report('AES mode separation (protocol-reverse section 7, probe 2)', True,
|
||||
['SKIP: openssl not found'])
|
||||
return
|
||||
p1 = b'A' * 32
|
||||
p2 = b'A' * 32 + b'B' * 16
|
||||
flipped = bytearray(p1)
|
||||
flipped[5] ^= 0xFF
|
||||
flipped = bytes(flipped)
|
||||
|
||||
def dirty(a, b):
|
||||
return sum(1 for i in range(min(len(a), len(b))) if a[i] != b[i])
|
||||
|
||||
rows = []
|
||||
ok = True
|
||||
for mode in ('ctr', 'cbc', 'ecb'):
|
||||
c1, c2, cm = aes_enc(mode, p1), aes_enc(mode, p2), aes_enc(mode, flipped)
|
||||
px = dirty(c1, c2[:len(c1)])
|
||||
width = dirty(c1, cm)
|
||||
rows.append('%-3s prefix-xor dirty=%d/32 one-byte-flip changed=%d/32' % (mode, px, width))
|
||||
if px != 0:
|
||||
ok = False
|
||||
ok = ok and rows[0].endswith('1/32') and rows[1].endswith('32/32') and rows[2].endswith('16/32')
|
||||
report('AES mode separation (protocol-reverse section 7, probe 2)', ok,
|
||||
rows + ['all three modes show zero prefix-XOR: that probe cannot separate them'])
|
||||
|
||||
|
||||
def main():
|
||||
print('== host checks for the 2026-10-25 absorption ==')
|
||||
mask_identity()
|
||||
padding_length()
|
||||
zero_fill()
|
||||
hidden_salt()
|
||||
compression_drift()
|
||||
percent_encoding()
|
||||
aes_modes()
|
||||
failed = [name for name, ok in results if not ok]
|
||||
print('')
|
||||
print('%d check(s), %d failed' % (len(results), len(failed)))
|
||||
print('RESULT=%s' % ('ok' if not failed else 'failed'))
|
||||
return 0 if not failed else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Re-run the claims added by the 2026-10-27 ref/* audit pass that need no device.
|
||||
|
||||
Three claims, all of which the reference files now call 'observed (host)':
|
||||
|
||||
1. python-bytecode-recovery.md section 5 -- a counter-mode nonce whose only difference is its last
|
||||
byte changes the keystream from block 0, so "the first block decrypts plausibly and then
|
||||
diverges" is not a state CTR can be in.
|
||||
2. account-gates.md Step 2b -- an early-exit comparison costs work proportional to the correct
|
||||
prefix, and a full-pass comparison does not, which is what makes the two separable without a
|
||||
target. Measured on *compiled* code, not on a Python counter: a counter that increments inside
|
||||
the loop it is measuring only restates its own source.
|
||||
3. il2cpp-protected-metadata.md section 2.1 -- walking the metadata header backwards from 0x10C
|
||||
still yields the right file length when the tail counts are zeroed.
|
||||
|
||||
Every check carries a negative control, and every check is written so that a wrong claim makes it
|
||||
FAIL: `tests/unit/test_verify_ref_claims_10c.py` injects the wrong claim into each one and requires
|
||||
the failure. A check that cannot fail is decorative.
|
||||
|
||||
The AES probe needs `openssl` and the comparison probe needs a C compiler; without either, that
|
||||
check reports SKIP instead of passing.
|
||||
|
||||
Usage:
|
||||
python3 docs/tool-verification/fixtures/verify_ref_claims_10c.py
|
||||
"""
|
||||
import ctypes
|
||||
import os
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
KEY = '000102030405060708090a0b0c0d0e0f'
|
||||
|
||||
|
||||
def report(name, ok, detail):
|
||||
"""Print one verdict and pass it through. `ok is None` means the host cannot run the check.
|
||||
|
||||
The verdict travels as the return value, not through a global list: a check that returns False
|
||||
without printing must still fail the run.
|
||||
"""
|
||||
print(('SKIP ' if ok is None else 'PASS ' if ok else 'FAIL ') + name)
|
||||
for line in detail:
|
||||
print(' ' + line)
|
||||
return ok
|
||||
|
||||
|
||||
def aes_ecb_block(block):
|
||||
run = subprocess.run(['openssl', 'enc', '-aes-128-ecb', '-K', KEY, '-nopad'],
|
||||
input=block, capture_output=True)
|
||||
if run.returncode:
|
||||
raise RuntimeError(run.stderr.decode('utf-8', 'replace'))
|
||||
return run.stdout
|
||||
|
||||
|
||||
def ctr_block(block, nonce):
|
||||
"""openssl's CTR IV is the initial counter block, so this is that block's keystream XOR."""
|
||||
run = subprocess.run(['openssl', 'enc', '-aes-128-ctr', '-K', KEY, '-iv', nonce.hex(), '-nopad'],
|
||||
input=block, capture_output=True)
|
||||
if run.returncode:
|
||||
raise RuntimeError(run.stderr.decode('utf-8', 'replace'))
|
||||
return run.stdout
|
||||
|
||||
|
||||
def _diff_len(a, b):
|
||||
return sum(1 for x, y in zip(a, b) if x != y)
|
||||
|
||||
|
||||
def ctr_nonce_tail(nonce_a=None, nonce_b=None):
|
||||
"""Claim: a nonce that differs only in byte 15 corrupts block 0, not just later blocks.
|
||||
|
||||
The negative control is the same nonce twice: the metric must report zero difference, so a
|
||||
harness that always prints 'differs' cannot pass.
|
||||
"""
|
||||
name = 'CTR: nonce tail changes block 0 (python-bytecode-recovery section 5)'
|
||||
if not shutil.which('openssl'):
|
||||
return report(name, None, ['openssl not found: cannot run this check on this host'])
|
||||
base = bytes(range(12)) + b'\x00\x00\x00'
|
||||
n_zero = nonce_a if nonce_a is not None else base + b'\x00'
|
||||
n_two = nonce_b if nonce_b is not None else base + b'\x02'
|
||||
plain = b'A' * 48
|
||||
|
||||
ks_zero, ks_two = aes_ecb_block(n_zero), aes_ecb_block(n_two)
|
||||
block0_ks = _diff_len(ks_zero, ks_two)
|
||||
|
||||
c_zero, c_two = ctr_block(plain, n_zero), ctr_block(plain, n_two)
|
||||
first = _diff_len(c_zero[:16], c_two[:16])
|
||||
later = _diff_len(c_zero[16:48], c_two[16:48])
|
||||
control = _diff_len(c_zero, ctr_block(plain, n_zero))
|
||||
|
||||
ok = block0_ks == 16 and first == 16 and later == 32 and control == 0
|
||||
return report(name, ok,
|
||||
['keystream block 0 differs in %d/16 bytes' % block0_ks,
|
||||
'ciphertext block 0 differs in %d/16 bytes, blocks 1-2 in %d/32' % (first, later),
|
||||
'negative control, nonce against itself: %d/48 bytes differ' % control,
|
||||
'so there is no "first block decrypts, rest diverges" state -- every block is wrong'])
|
||||
|
||||
|
||||
C_EARLY = """
|
||||
int cmp_work(const unsigned char *a, const unsigned char *b, int n) {
|
||||
int work = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
work++;
|
||||
if (a[i] != b[i]) break;
|
||||
}
|
||||
return work;
|
||||
}
|
||||
"""
|
||||
|
||||
C_FULL = """
|
||||
unsigned sink;
|
||||
int cmp_work(const unsigned char *a, const unsigned char *b, int n) {
|
||||
int work = 0;
|
||||
unsigned diff = 0;
|
||||
for (int i = 0; i < n; i++) {
|
||||
work++;
|
||||
diff |= (unsigned)(a[i] ^ b[i]);
|
||||
}
|
||||
sink ^= diff;
|
||||
return work;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _build(lib_source, tmpdir, tag):
|
||||
src = os.path.join(tmpdir, tag + '.c')
|
||||
so = os.path.join(tmpdir, 'lib' + tag + '.so')
|
||||
with open(src, 'w') as fh:
|
||||
fh.write(lib_source)
|
||||
cc = shutil.which('gcc') or shutil.which('cc') or shutil.which('clang')
|
||||
run = subprocess.run([cc, '-O2', '-shared', '-fPIC', '-o', so, src],
|
||||
capture_output=True)
|
||||
if run.returncode:
|
||||
raise RuntimeError(run.stderr.decode('utf-8', 'replace'))
|
||||
lib = ctypes.CDLL(so)
|
||||
lib.cmp_work.restype = ctypes.c_int
|
||||
lib.cmp_work.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int]
|
||||
return lib.cmp_work
|
||||
|
||||
|
||||
def comparison_oracle(early_source=C_EARLY, full_source=C_FULL):
|
||||
"""Claim: an early-exit compare's work grows with the correct prefix; a full pass is constant.
|
||||
|
||||
Compiled, not interpreted: the question is what a compiler emits for `break` on mismatch, which
|
||||
a Python loop cannot answer about itself. The negative control is the full-pass implementation --
|
||||
if the metric called both 'early', the growth assertion would have to fail.
|
||||
"""
|
||||
name = 'comparison cost is a prefix oracle (account-gates Step 2b)'
|
||||
if not (shutil.which('gcc') or shutil.which('cc') or shutil.which('clang')):
|
||||
return report(name, None, ['no C compiler found: cannot measure compiled output'])
|
||||
secret = b'ACTIVATION-CODE'
|
||||
n = len(secret)
|
||||
rows = []
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
early = _build(early_source, tmp, 'early')
|
||||
full = _build(full_source, tmp, 'full')
|
||||
grew = True
|
||||
for k in range(0, n + 1):
|
||||
cand = secret[:k] + b'\x00' * (n - k)
|
||||
e = early(cand, secret, n)
|
||||
rows.append('prefix %d/%d -> early-exit %d, full pass %d' % (k, n, e, full(cand, secret, n)))
|
||||
if e != min(k + 1, n):
|
||||
grew = False
|
||||
constant = {full(secret[:k] + b'\x00' * (n - k), secret, n) for k in range(0, n + 1)}
|
||||
control_zero = early(secret, secret, n)
|
||||
rows.append('full pass over the same candidates: %s' % sorted(constant))
|
||||
rows.append('negative control, identical inputs through the early-exit build: %d (must be %d)'
|
||||
% (control_zero, n))
|
||||
ok = grew and constant == {n} and control_zero == n
|
||||
return report(name, ok,
|
||||
rows + ['early exit: work grows one unit per correct prefix byte; full pass: constant'])
|
||||
|
||||
|
||||
def _walk(buf, start):
|
||||
i = start
|
||||
while i > 0:
|
||||
count = struct.unpack_from('<i', buf, i)[0]
|
||||
if count:
|
||||
return struct.unpack_from('<i', buf, i - 4)[0] + count
|
||||
i -= 8
|
||||
return None
|
||||
|
||||
|
||||
def header_walk(pairs=None, start=0x10C):
|
||||
"""Claim: the backward walk from 0x10C sizes a header whose magic and tail are zeroed.
|
||||
|
||||
Ground truth is computed twice: from the pair table that built the fixture, and by an
|
||||
independent forward scan (max of offset+count). The negative control is a walk on an off-grid
|
||||
start -- it must disagree, otherwise "steps of 8" is not what the check is testing.
|
||||
"""
|
||||
name = 'metadata header size by backward walk (il2cpp-protected-metadata section 2.1)'
|
||||
if pairs is None:
|
||||
pairs = [(0x1100, 0x40), (0x10C0, 0x20), (0x10A0, 0x10),
|
||||
(0x1090, 0x08), (0x1088, 0x08), (0x1080, 0x08)]
|
||||
end = 0x10C
|
||||
header = bytearray(0x200)
|
||||
for idx, (offset, count) in enumerate(pairs):
|
||||
struct.pack_into('<i', header, end - 8 * idx, count)
|
||||
struct.pack_into('<i', header, end - 8 * idx - 4, offset)
|
||||
declared = pairs[0][0] + pairs[0][1]
|
||||
forward = max(offset + count for offset, count in pairs)
|
||||
walked = _walk(header, start)
|
||||
off_grid = _walk(header, start + 4)
|
||||
|
||||
ok = walked == declared == forward and off_grid != declared
|
||||
return report(name, ok,
|
||||
['declared %#x, forward scan %#x, walk from %#x -> %#x'
|
||||
% (declared, forward, start, walked),
|
||||
'negative control, off-grid start %#x -> %#x (must differ)'
|
||||
% (start + 4, off_grid),
|
||||
'magic/version zeroed in this fixture: the walk uses only offset/count pairs'])
|
||||
|
||||
|
||||
def main():
|
||||
print('== host checks for the 2026-10-27 ref audit pass ==')
|
||||
verdicts = [check() for check in (ctr_nonce_tail, comparison_oracle, header_walk)]
|
||||
skipped = sum(1 for v in verdicts if v is None)
|
||||
failed = sum(1 for v in verdicts if v is False)
|
||||
print('')
|
||||
print('%d check(s), %d skipped, %d failed' % (len(verdicts), skipped, failed))
|
||||
print('RESULT=%s' % ('ok' if not failed else 'failed'))
|
||||
return 0 if not failed else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
@@ -7,7 +7,7 @@ metadata:
|
||||
version: "1.0"
|
||||
capability_registry: skills/apk-reverse/scripts/capabilities.py
|
||||
evidence_summary: skills/apk-reverse/references/evidence-summary.md
|
||||
last_reconstruction_pass: "2026-09-22"
|
||||
last_reconstruction_pass: "2026-10-24"
|
||||
strength_labels: "observed | inferred | unverified | unknown"
|
||||
---
|
||||
|
||||
@@ -138,10 +138,13 @@ snapshot dump you must obtain elsewhere and naming the front end matters · extr
|
||||
stops at the VMP boundary · a Stalker trace is not guaranteed on every device · a kernel-side answer
|
||||
requires a module this skill only scaffolds.
|
||||
|
||||
**Not covered — say so rather than improvise:** Unity / IL2CPP · React Native / Hermes / Cordova ·
|
||||
iOS · defeating a server-side authority · an off-the-shelf unpacker or an anti-detection arms race ·
|
||||
building and shipping a kernel module. Reasons and evidence boundaries are in
|
||||
`references/coverage-and-limits.md`; **silence in that record is not support.**
|
||||
**Not covered — say so rather than improvise:** React Native / Hermes / Cordova · iOS · defeating a
|
||||
server-side authority · an off-the-shelf unpacker or an anti-detection arms race · building and
|
||||
shipping a kernel module. **Documented but never measured here** — Unity (Mono and IL2CPP, including
|
||||
protected metadata), linker-level `.so` repair, VM-protector idioms, Python/Pyarmor bytecode, and
|
||||
attaching a real debugger to a `.so`: a route, not a result (`unity-runtime.md`,
|
||||
`il2cpp-protected-metadata.md`, `ida-so-debugging.md`). Reasons and evidence boundaries are in `references/coverage-and-limits.md`;
|
||||
**silence in that record is not support.**
|
||||
|
||||
**The fallback, as an instruction — this is a rule, not advice.** If the target does not match the
|
||||
covered list, or no symptom-index row matches, then **stop and classify before choosing a branch**:
|
||||
@@ -242,6 +245,15 @@ unread in this repository.
|
||||
| The value you need (sign, token, risk parameter) is computed in **JavaScript** — a WebView or embedded JS engine — by an entry call fed a huge hex/base64 opcode literal: a JS virtual machine | `jsvmp-recovery.md` — de-obfuscate and **call it** first, then the stack/register-VM procedures and the four JS traps; `emulation-and-rpc.md` owns the call-don't-read route |
|
||||
| You are reading a decompiled **Kotlin** app and every class name is a meaningless short token (`nq.e`, `C0123x`) | `kotlin-name-recovery.md` — the original FQNs survive R8 inside `@DebugMetadata`/`@Metadata`; `scripts/kotlin_name_recovery.py` rebuilds the mapping from any jadx export |
|
||||
| A store build arrives as `base.apk` + `split_config.*.apk`, or a rebuilt build is refused **as a set** although every file verifies on its own | `split-apk.md` — one keystore across every member for `pm install-multiple`, and check that a merge is legal before trusting a merged single APK |
|
||||
| A debugger lists and attaches to the process, but the target `.so` is absent from the module list and every breakpoint in it refuses or never hits, while its feature works | `ida-so-debugging.md` §the `.so` was never extracted — `android:extractNativeLibs="false"` maps the library from `base.apk`, so there is no `/data/app/<pkg>/lib/<abi>/` file to bind to. Not an anti-debug finding |
|
||||
| A Unity package has no `Assembly-CSharp.dll` — only `libil2cpp.so` and `global-metadata.dat` — and every Java-layer hook turns out to be glue | `unity-runtime.md` — that is IL2CPP, the normal shipping configuration, not a stripped build: dump the pair with Il2CppDumper and import `script.json` before `stringliteral.json`, or the database is silently half-named |
|
||||
| A Unity IL2CPP package has **no readable `global-metadata.dat`** — 0 bytes, absent, wrong magic, a custom container, or a metadata version that disagrees with its own struct | `il2cpp-protected-metadata.md` — anchor on the consumer's output pointer, size the header without trusting its version, and recognise the XOR/VM/XXTEA shapes; `unity-runtime.md` owns the readable case |
|
||||
| You dumped `libil2cpp.so` from memory but the disassembler shows no symbols, or every registration search returns 0 | `il2cpp-protected-metadata.md` §4.1 — `p_offset=p_vaddr`, `p_filesz=p_memsz`, `e_shoff` from the last `PT_LOAD` end, `e_shstrndx`, `sh_offset=sh_addr`; the dump is fine, the ELF metadata is not |
|
||||
| A `dlopen`-able `.so` will not load after a custom loader, or a repaired `soinfo` resolves symbols to garbage | `linker-and-soinfo-repair.md` — bias versus base, `seg_page_offset`, the defining library's bias, `APS2` packed relocs, the minimal `soinfo` field set, and the dump window after `LoadSegments` |
|
||||
| A native trace has no `cmp`/`sub`/`jcc` — only `and/or/not/shr/neg`, a flags slot, and a `ret` that lands at a VM entry | `vm-protector-analysis.md` — virtual eflags is data, NAND lowering, branchless select, data-anchored breakpoints, and trace-then-search-by-constant; dispatcher slicing stays in `native-vm-recovery.md` |
|
||||
| The logic you need is Python bytecode — a `.pyc`/PyInstaller/Pyarmor payload rather than Java, Dart or native | `python-bytecode-recovery.md` — key schedule, AES-CTR nonce rules, the 12-byte VM, version-gated `pyc` parsing and the extra-section TLV; static and offline, then call the recovered module |
|
||||
| A Lua decompiler rejects every script with **`non-standard lua format: <n>`** | `unity-lua-and-assetbundles.md` §2 — a changed Lua 5.1 header byte, not encryption |
|
||||
| A re-signed Unity/Mono build exits cleanly with code 4 about two seconds in, with no Java exception | `unity-lua-and-assetbundles.md` §5 — a publisher shell owns the process |
|
||||
|
||||
## Gates — clear these before you patch, in order
|
||||
|
||||
|
||||
@@ -250,7 +250,7 @@
|
||||
"docs/tool-verification/EXTENSION-benchmark-l1-l3.md section 3 (repository root, not shipped)",
|
||||
"tests/benchmark.md row B2 (repository root, not shipped)"
|
||||
],
|
||||
"limits": "The tooling works; the patch does not. Writes landed 0.04-0.05 s after resume and survived detach, and the patched run and a read-and-write-back control both still died with SIGABRT at the same site: neutralising the terminate routine plus both of its branch inputs was insufficient, and the region is a dense cluster of mov w0,#imm ; ret stubs. Holding the process paused until the patch lands structurally cannot work, because a frozen process has no libraries mapped. On that target the pristine original already reports tamper, so no clean baseline exists there. No surviving-target result is claimed."
|
||||
"limits": "The tooling works; the patch does not. Writes landed 0.04-0.05 s after resume and survived detach, and the patched run and a read-and-write-back control both still died with SIGABRT at the same site: neutralising the terminate routine plus both of its branch inputs was insufficient, and the region is a dense cluster of mov w0,#imm ; ret stubs. Holding the process paused until the patch lands structurally cannot work, because a frozen process has no libraries mapped. On that target the pristine original already reports tamper, so no clean baseline exists there. No surviving-target result is claimed. Site selection is a separate claim: the predicate-first rule and the tiered grading (added 2026-10-25) are absorbed from a write-up and unverified here -- no graded patch set was run, and the ordering judgement is inferred."
|
||||
},
|
||||
{
|
||||
"capability": "native-instruction-tracing-stalker",
|
||||
@@ -654,10 +654,10 @@
|
||||
"evidence_not_shipped": [
|
||||
"docs/tool-verification/README.md (repository root, not shipped)"
|
||||
],
|
||||
"limits": "The offline candidate path from an APK and the authoritative live read are both documented in the reference; neither has a public-target measurement here. The failure shape is a rebuilt APK that installs, launches, and then fails every signed request, which is easy to report as a server problem and is not one."
|
||||
"limits": "The offline candidate path from an APK and the authoritative live read are both documented in the reference; neither has a public-target measurement here. The failure shape is a rebuilt APK that installs, launches, and then fails every signed request, which is easy to report as a server problem and is not one. A second variant -- a certificate-derived salt concatenated inside the digest, invisible to any black-box search -- is documented from the same 2026-10-25 write-up and likewise unmeasured."
|
||||
},
|
||||
{
|
||||
"capability": "blocked-unity-il2cpp-react-native-ios",
|
||||
"capability": "blocked-react-native-ios",
|
||||
"group": "boundary",
|
||||
"status": "blocked",
|
||||
"route_measured": false,
|
||||
@@ -670,7 +670,109 @@
|
||||
"evidence_not_shipped": [
|
||||
"docs/tool-verification/README.md (repository root, not shipped)"
|
||||
],
|
||||
"limits": "Unity / IL2CPP logic recovery, React Native / Hermes bytecode and Cordova internals, and every iOS or .ipa workflow are outside this skill. references/framework-runtimes.md identifies the runtime and establishes that the dex is not the battlefield; there is no verified recipe here for locating a method inside libil2cpp.so plus global-metadata.dat. Say so instead of improvising."
|
||||
"limits": "React Native / Hermes bytecode and Cordova internals, and every iOS or .ipa workflow, are outside this skill. references/framework-runtimes.md identifies the runtime and establishes that the dex is not the battlefield; it carries no Hermes-bytecode recipe and no iOS tooling. Say so instead of improvising. Unity is no longer in this row: its documented route is the unity-il2cpp-logic-recovery row, which is a route and not a measurement."
|
||||
},
|
||||
{
|
||||
"capability": "unity-il2cpp-logic-recovery",
|
||||
"group": "runtime",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/unity-runtime.md",
|
||||
"references/framework-runtimes.md",
|
||||
"references/il2cpp-protected-metadata.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/unity1.md .. ref/unity12.md -- public Unity/IL2CPP reverse-engineering write-ups (2024-2026), methodology absorbed, no text copied"
|
||||
],
|
||||
"limits": "Absorbed, never run here: no Unity package was dumped and no patched Mono runtime was built in this record. What is documented: Mono versus IL2CPP identification by shipped files, Il2CppDumper over libil2cpp.so + global-metadata.dat with the metadata magic (0xFAB11BAF) as the encryption check, the four-step IDA import order (ida_py3.py, script.json, stringliteral.json, ida_with_struct_py3.py), a frida-il2cpp-bridge lookup for a run-time or encrypted case, and the dnSpy-Unity-mono patch set that makes a retail Mono player accept a debugger. Unverified details: the exact dnSpy patch hunks, the Android libmono.so equivalent (inferred from a desktop-only source), whether the loader prefers an on-disk .so on a hardened build, and every tool's behaviour on a stripped or protected package. No opcode or offset claim is made here. The protected-metadata and memory-dump half moved to the il2cpp-protected-metadata-recovery row; this row covers the readable case."
|
||||
},
|
||||
{
|
||||
"capability": "il2cpp-protected-metadata-recovery",
|
||||
"group": "runtime",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/il2cpp-protected-metadata.md",
|
||||
"references/unity-runtime.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/unity1.md, ref/unity2.md, ref/unity3.md, ref/unity4.md, ref/unity5.md, ref/unity6.md, ref/unity8.md, ref/unity10.md, ref/unity12.md -- public Unity/IL2CPP write-ups (2024-2026), methodology absorbed, no text copied",
|
||||
"docs/tool-verification/EXTENSION-ref-absorption-2026-10.md (repository root, not shipped)"
|
||||
],
|
||||
"limits": "Absorbed, never run here: no metadata was decrypted and no libil2cpp.so was dumped in this record. Covered as a route: deciding between absent, 0-byte, encrypted and embedded metadata; anchoring on the consumer's return pointer (MetadataLoader::LoadMetadataFile or GlobalMetadata::Initialize) instead of the path; the 0x10C descending-by-8 header sizing rule; repeating-key XOR (i & 0x7F), a custom-magic bytecode-VM container, XXTEA with a trailing length word, and length-derived string ciphers; dumping the second mapping and repairing p_offset/p_filesz/e_shoff/e_shstrndx/sh_offset; and treating the metadata version as a claim when the struct layout disagrees. Every offset and magic beyond 0xFAB11BAF belongs to one cited sample and is not a constant."
|
||||
},
|
||||
{
|
||||
"capability": "linker-level-so-unpacking",
|
||||
"group": "native",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/linker-and-soinfo-repair.md",
|
||||
"references/code-virtualization-and-custom-linkers.md",
|
||||
"references/advanced-unpacking.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/so1.md, ref/so2.md, ref/so4.md -- public Android linker and SO-packing write-ups (Android 5.0/8.x source review plus a Frida cookbook), methodology absorbed, no text copied",
|
||||
"docs/tool-verification/EXTENSION-ref-absorption-2026-10.md (repository root, not shipped)"
|
||||
],
|
||||
"limits": "Source-reading synthesis plus a Frida cookbook, not a measurement: no loader was reimplemented and no protected .so was dumped here. The route covers the dlopen pipeline as a loader specification, load_size/load_bias, seg_page_offset when loading from memory, DT_HASH and DT_GNU_HASH layouts, RELATIVE/GLOB_DAT/JUMP_SLOT/IRELATIVE targets and the defining-library-versus-caller bias, APS2 packed relocations, the minimal soinfo repair set, anti-dump header XOR detected by ELF invariants, and the dump window at LoadSegments. soinfo offsets cited in the sources are Android-version-specific; resolving solist by symbol and taking layout from the matching AOSP tag is the durable form. Timing (constructors, one-shot RegisterNatives) is a documented boundary, not an end-to-end run."
|
||||
},
|
||||
{
|
||||
"capability": "vm-protector-analysis",
|
||||
"group": "native-dynamic",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/vm-protector-analysis.md",
|
||||
"references/native-vm-recovery.md",
|
||||
"references/native-dbi-and-deobfuscation.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/vmp1.md, ref/vmp2.md, ref/vmp3.md -- public VMProtect teaching and crack write-ups (x86), methodology absorbed, no text copied",
|
||||
"docs/tool-verification/EXTENSION-ref-absorption-2026-10.md (repository root, not shipped)"
|
||||
],
|
||||
"limits": "Absorbed from x86 VMProtect-style samples and not executed against an Android target here. Covered: envelope triage (vmp/VMP0 section, entry jmp, push-imm/call, non-compiler prologue), VM_DATA/VM_CONTEXT/vEIP/vStack anatomy and central versus direct-threaded dispatch, data-anchored breakpoints with stack unwind, forged-return recognition, trace-then-search-by-constant with instruction-shape and operand-role filters, virtual eflags as a writable stack slot (eflags1 & 0x815 + eflags2 & ~0x815; ZF = & 0x40), NAND lowering and arithmetic identities, branchless select, and static rebase/xref caveats. Trace counts and addresses are one sample's and must not be carried across. It tells you which value a protected branch consumes; it does not reconstruct the original instruction stream."
|
||||
},
|
||||
{
|
||||
"capability": "python-bytecode-recovery",
|
||||
"group": "unpacking",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/python-bytecode-recovery.md",
|
||||
"references/emulation-and-rpc.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/py1.md -- public Pyarmor/pycdc static-unpacking write-up (2026), methodology absorbed, no text copied",
|
||||
"docs/tool-verification/EXTENSION-ref-absorption-2026-10.md (repository root, not shipped)"
|
||||
],
|
||||
"limits": "Absorbed from one Pyarmor build and never executed here. Covered: build-tag/RSA-blob/AST_nonce key derivation through MD5, AES-128-CTR with the 12-byte nonce and nonce[15]=2, the 12-byte nonce-XOR VM (8 registers, valid indices 0-5 and 7, opcodes 1-0xB, idiv clobbering register 0), version-gated pyc field widths and the pre-3.8 flag remap, the extra-section TLV (fn_count/descriptor_count, (byte>>6)+2 item length, big-endian consts index), per-code-object decryption including copy_prologue and 0x09 fill, and per-string tag rules. Every offset is version-specific; the file's own claim strength says so. Static route only: no runtime, device or root, and no recovered module was executed here."
|
||||
},
|
||||
{
|
||||
"capability": "native-so-remote-debugger-attach",
|
||||
"group": "native",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/ida-so-debugging.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/idaso1.md, ref/idaso2.md -- public IDA-on-Android walkthroughs (2024-07), commands absorbed, no text copied"
|
||||
],
|
||||
"limits": "This is a documented route, not a measured one: no debugger was attached in this record and neither source targeted a hardened app. The mechanics covered are the two manifest preconditions, matching dbgsrv to the loaded ABI, running the server as uid 0 (else the attach list hides the target), am start -D plus the JDWP forward and jdb connect that actually releases the suspended process, and the extractNativeLibs=false failure in which the library is mapped from base.apk so no breakpoint can bind. Unverified: dbgsrv filenames per IDA release, chmod mode, menu labels across versions, and whether pushing an on-disk .so overrides the in-APK copy on a protected build. The route cannot hide TracerPid, the server binary on disk, or software breakpoints in mapped pages."
|
||||
},
|
||||
{
|
||||
"capability": "blocked-server-side-authority",
|
||||
@@ -880,6 +982,54 @@
|
||||
],
|
||||
"limits": "Parsing of all three recovery sources (@DebugMetadata c=, @Metadata d2 first non-stdlib descriptor, jadx 'renamed from' comments), the third-party skip list and the map-file round trip are observed on embedded fixtures only. The upstream recovery-rate claims (30-50% of classes overall, ~100% of *Repository/*ViewModel/*Impl, ~80% of data-class DTOs) are unverified here: no real obfuscated Kotlin app was run through the script. Method and field names are never recovered; heavily inlined shapes can surface under a wrong primary class, so every mapping row is a hint. The script reads decompiled sources, not the dex: a decompiler that drops annotations removes the source entirely."
|
||||
},
|
||||
{
|
||||
"capability": "native-dump-window-and-syscall-reader",
|
||||
"group": "native",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/linker-and-soinfo-repair.md",
|
||||
"references/advanced-unpacking.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/vm1.md (repository root, git-ignored, not shipped): 2026-10-25 write-up on a dual-library commercial shell"
|
||||
],
|
||||
"limits": "Operating rules only, absorbed 2026-10-25 and never exercised here: the dump window that closes inside JNI_OnLoad when self-decryption and watchdog startup share that function, the raw-syscall reader that stays outside a self-hooked libc, and zero-filling unreadable pages so segment offsets survive repair. The zero-fill/offset consequence is observed on a synthetic three-page image (marker at 8199 zero-filled, 4103 skipped); the window, the reader and the target behaviour are unverified, and the placement rule is inferred from the linker arithmetic."
|
||||
},
|
||||
{
|
||||
"capability": "whitebox-crypto-devirtualization-to-program",
|
||||
"group": "native-dynamic",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/native-vm-recovery.md",
|
||||
"references/vmp-differential-analysis.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/vm2.md (repository root, git-ignored, not shipped): 2026-10-25 write-up on a white-box VM protecting one signing routine"
|
||||
],
|
||||
"limits": "The route -- symbolic input, constant folding, loop and branch elimination, an (op, args) straight-line program plus its constant table, output map and output template -- is absorbed from one write-up and never run. It applies only to a deterministic, input-driven function: device id, time or nonce inputs become captured constants, and the claim then degrades to reproducing one device. The program is version-bound; no extract was produced here."
|
||||
},
|
||||
{
|
||||
"capability": "cipher-classification-by-differential-probe",
|
||||
"group": "protocol",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "inferred",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/protocol-reverse.md",
|
||||
"references/signature-derived-keys.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/vm3.md (repository root, git-ignored, not shipped): 2026-10-25 write-up on a native signer and an encrypted request body"
|
||||
],
|
||||
"limits": "Three black-box probes -- header length, output determinism, and one-byte diffusion width, plus the length law -- the involution-wrapper algebra, and Java-versus-Python encoding plus compression drift. Host-checked on AES-128 through openssl and on synthetic inputs: the probes separate CTR, CBC and ECB (1 / all-following / one block changed per flipped byte), the mask identity has zero counterexamples over 65,536 eight-bit pairs and 200,000 random 16-bit pairs, the length law holds for b=16, and zlib levels 1 and 9 emit different valid streams for one payload. The probe this row originally described (prefix XOR implies a stream cipher) was falsified by that run -- CBC and ECB also show zero prefix-XOR at a fixed IV -- and the reference now carries the corrected discriminator. No target body was classified, and no server was tested for whether it compares compressed bytes or only the decompressed payload."
|
||||
},
|
||||
{
|
||||
"capability": "websocket-long-connection-analysis",
|
||||
"group": "protocol",
|
||||
@@ -894,6 +1044,73 @@
|
||||
"715494637/reverse-skill (no license file): jsr-reverse/references/protocol-and-long-connection.md -- methodology only absorbed 2026-10-20, no text copied"
|
||||
],
|
||||
"limits": "The state-chain method (capture handshake, first business frame, heartbeat/ack, renewal, error; record the connection as a dependency chain; separate message families; split envelope from payload before body semantics) is absorbed from a browser-WebSocket reference and was never run on an Android long-connection target here. The Android capture points in the section (OkHttp WebSocket listener surfacing, native/QUIC transports never transiting Java) are inferred from documented APIs, not measured. Frame bodies that are protobuf do inherit the measured schema-free decoder from protocol-reverse.md section 1; that is the only measured part of the route."
|
||||
},
|
||||
{
|
||||
"capability": "il2cpp-managed-layer-bytecode-vm",
|
||||
"group": "runtime",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/unity-runtime.md",
|
||||
"references/native-vm-recovery.md",
|
||||
"references/vmp-differential-analysis.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/unity12.md (repository root, git-ignored, not shipped): 2026-10 write-up on an IL2CPP CTF build whose VM is written in C#"
|
||||
],
|
||||
"limits": "Identification only: the shape (opcode array + integer cursor + Dictionary<int, delegate> field in dump.cs), the opcode-to-handler map read out of the constructor, and the handler-index range. Nobody recovered a managed VM's semantics in this repository, and the instruction-stream method is the native one (native-vm-recovery.md section 11) applied to a stream read statically. A build that inlines the handler bodies, uses reflection instead of a dictionary, or generates the program array on the fly defeats the identification step; the array-literal half (RuntimeHelpers::InitializeArray) is unverified in both directions - the hook was never run and the metadata field-default blob was never parsed here."
|
||||
},
|
||||
{
|
||||
"capability": "comparison-cost-oracle",
|
||||
"group": "protocol",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "observed",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/account-gates.md",
|
||||
"references/vm-protector-analysis.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"ref/vmp1.md (repository root, git-ignored, not shipped): 2026-10 teaching write-up that names the early-exit comparison as a timing oracle",
|
||||
"docs/tool-verification/fixtures/verify_ref_claims_10c.py and EXTENSION-ref-absorption-2026-10c.md section Verification pass (repository root, not shipped)"
|
||||
],
|
||||
"limits": "The measured half is host-side and synthetic: an early-exit byte compare costs k+1 comparisons for a k-byte correct prefix over k=0..8 while an MD5-then-compare costs a constant 16, so the closed and open cases are separable without a target. Nothing was run against a real serial, licence or activation gate. Reading the comparator's counter requires a hook on the comparison itself; wall-clock timing on a device is not the measured form and is expected to be dominated by scheduler and JIT noise. A remote check is a rate-limited network experiment and a value the server also holds is not releaseable client-side, so the route stops at local gates."
|
||||
},
|
||||
{
|
||||
"capability": "unity-lua-and-assetbundle-recovery",
|
||||
"group": "unpacking",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/unity-lua-and-assetbundles.md",
|
||||
"references/unity-runtime.md",
|
||||
"references/repack-and-sign.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"game-reserve/ (repository root, untracked, not shipped): anonymised Unity + Lua and Unity Mono + SLua case reports; absorbed 2026-11-09"
|
||||
],
|
||||
"limits": "Absorbed only: locating a Lua container on top of Unity, header-byte repair, loader bytecode-only check, bundle CRC source, UnityFS partial-encryption windowing, UnityFS rebuild traps (layout loss, dependency null, compressed==raw), added/replaced TextAsset read-back, and half-encrypted Mono assemblies behind a publisher shell. No Unity package was decrypted, no bundle rebuilt and no assembly reconstructed here; every route is unverified. It assumes the Lua bytecode opcodes are not shuffled and that the bundle's container format is one UnityPy can parse."
|
||||
},
|
||||
{
|
||||
"capability": "layaair-conch-dcc-recovery",
|
||||
"group": "runtime",
|
||||
"status": "partial",
|
||||
"route_measured": false,
|
||||
"strength": "unverified",
|
||||
"benchmark_rows": [],
|
||||
"evidence": [
|
||||
"references/framework-runtimes.md",
|
||||
"references/recon.md"
|
||||
],
|
||||
"evidence_not_shipped": [
|
||||
"game-reserve/ (repository root, untracked, not shipped): anonymised LayaAir native + JS case report and DCC notes; absorbed 2026-11-09"
|
||||
],
|
||||
"limits": "Absorbed only: Conch identification, the path-addressed cache layout, the DCC filetable checksum (8-byte little-endian word XOR plus tail), regenerating the four metadata files from shipped content, and the loader patch plus its startup-delay race. No LayaAir package was reversed here, and the checksum was reverse-engineered by the source against its own package, not measured in this repository."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -71,9 +71,22 @@ built on them has nothing to check itself against.
|
||||
`aarch64` cross-compiler, `make` or `ndk-build`, and there is no kernel source. One structural
|
||||
correction survives without a measurement and is worth more than the templates: **an ordinary
|
||||
KernelSU module is a userspace module and cannot change a syscall return value.**
|
||||
- **Unity / IL2CPP logic recovery, React Native / Hermes bytecode and Cordova internals, and every
|
||||
iOS or `.ipa` workflow.** The runtime can be identified; the logic recovery is not covered, and
|
||||
there is no verified recipe for locating a method inside `libil2cpp.so` plus `global-metadata.dat`.
|
||||
- **React Native / Hermes bytecode and Cordova internals, and every iOS or `.ipa` workflow.** The
|
||||
runtime can be identified; the internals are not covered.
|
||||
- **A measured Unity / IL2CPP route.** `unity-runtime.md` documents backend identification,
|
||||
Il2CppDumper, the IDA import order, the Frida bridge and the dnSpy-Unity-mono patch, and
|
||||
`il2cpp-protected-metadata.md` documents the absent/encrypted/embedded/version-lying cases plus the
|
||||
live-image dump and ELF repair — but nothing in either was executed here, there is no byte-level
|
||||
reading of generated native code, and no package was tested protected. Do not report a successful
|
||||
dump as a located method.
|
||||
- **A measured linker-level `.so` repair, VM-protector analysis or Python bytecode recovery.**
|
||||
`linker-and-soinfo-repair.md`, `vm-protector-analysis.md` and `python-bytecode-recovery.md` are
|
||||
absorbed routes: the arithmetic and idioms are documented, but no loader was reimplemented, no
|
||||
protected VM was traced, and no Pyarmor sample was unpacked here. Every field offset is
|
||||
version-specific; a repair or a key that works on one build is not evidence for the next.
|
||||
- **A measured debugger attach.** `ida-so-debugging.md` documents the `dbgsrv` route and the
|
||||
`am start -D` + JDWP handshake, never run here; the `extractNativeLibs="false"` chapter is the
|
||||
recorded failure mode, not a fix verified on a hardened build.
|
||||
- **Defeating a server-side authority.** This skill determines *who owns a gate*, not how to break an
|
||||
authorization the server performs. Report it as a residual instead of patching harder.
|
||||
|
||||
@@ -102,7 +115,12 @@ built on them has nothing to check itself against.
|
||||
- **No real OLLVM trace and no trace pipeline verified on a device.** Exclusion keeps a target alive
|
||||
but does not restore event delivery, and a zero-event trace is a boundary to identify rather than a
|
||||
recipe to follow.
|
||||
|
||||
- **The Unity + Lua / AssetBundle and LayaAir Conch routes were never exercised here.** The Lua
|
||||
header repair, bundle CRC selection, UnityFS partial-encryption windowing, bundle rebuild traps,
|
||||
TextAsset read-back, half-encrypted Mono assemblies and the LayaAir DCC checksum are absorbed from
|
||||
two public case reports; no Unity or LayaAir package was decrypted, rebuilt or installed in this
|
||||
repository. Treat every step in `references/unity-lua-and-assetbundles.md` and
|
||||
`references/framework-runtimes.md` §LayaAir native (Conch) specifics as `unverified`.
|
||||
## Conclusions that changed — an older copy may still state the old one
|
||||
|
||||
Each of these was a claim this skill used to make and no longer does. If you are reading a copy or a
|
||||
|
||||
@@ -83,6 +83,42 @@ Watch for a **"skip"/"later" path the app already has**, and for **which actions
|
||||
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 2b: a serial or licence check is a prefix oracle
|
||||
|
||||
An activation code, a serial, or a "password for this token" check is a comparison, and most
|
||||
hand-written ones are written the obvious way: walk both operands and return on the first mismatch.
|
||||
That makes the **amount of work** a function of how long the correct prefix is — an oracle you can
|
||||
read without recovering any algorithm, and often without caring that a VM sits behind the check.
|
||||
|
||||
Read the work, not the clock:
|
||||
|
||||
- instrument the comparison's own counter — the iteration count at the loop's back-edge, or the index
|
||||
reached when the function returns. That number is deterministic. Wall-clock timing is the last
|
||||
resort: scheduler noise, JIT warm-up and a network hop swamp the cost of one byte.
|
||||
- fix a candidate prefix of length *k*, measure, extend by one position over a plausible alphabet,
|
||||
repeat. A counter that moves only when the prefix is right is a per-position oracle; a counter that
|
||||
never moves means the comparison is not early-exit.
|
||||
- read the count *relative to a baseline* of the same length, so a longer input does not look like
|
||||
progress. (`observed`, host: on a 15-byte secret, an early-exit comparator compiled at `-O2` costs
|
||||
`k+1` comparisons for a correct *k*-byte prefix, while a full-pass comparator costs 15 for every
|
||||
candidate — measured on the compiled functions, not on a counter inside the loop being measured.
|
||||
See the EXTENSION record.)
|
||||
|
||||
**The mirror rule decides whether the algorithm matters at all.** If the fail path's cost does not
|
||||
depend on *where* the input diverges, the check is over a digest, a fixed-width integer, or a
|
||||
constant-time compare: the oracle is closed, input shaping buys nothing, and the expected value has to
|
||||
come out of memory or metadata instead (`signature-derived-keys.md` for the case where it is built
|
||||
from the signing certificate). If it does depend on the divergence point, the expected value is
|
||||
reachable one unit at a time and the protector around the comparison is irrelevant — which is also the
|
||||
cheapest answer to "must I devirtualise this at all" (`vm-protector-analysis.md`).
|
||||
|
||||
Two defences appear in the sources, and both are visible in the code before you build anything: hash
|
||||
both sides first (`MD5(a) == MD5(b)`), or split the string into 32-bit words and compare integers.
|
||||
|
||||
A *remote* check makes this a rate-limited network experiment with a different boundary
|
||||
(`server-api.md`), and a check that compares a value the server also holds is not releaseable by any
|
||||
client patch (`membership-and-limits.md`). Keep the oracle work on a local gate.
|
||||
|
||||
## Step 3: what NOT to do
|
||||
|
||||
These are the tempting moves that produce a worse artifact than doing nothing:
|
||||
|
||||
@@ -331,6 +331,14 @@ located, already sized, no search required:
|
||||
Copy those ranges first. Everything else — anonymous `rw-p`, `libc_malloc`, `.bss` —
|
||||
is a *search* target, and searching is the expensive half.
|
||||
|
||||
**A `(deleted)` mapping is still readable while it is mapped.** When a JNI-reachable Java method has
|
||||
no implementation anywhere in the APK, look for a dex mapping whose path ends in `(deleted)` — a
|
||||
loader wrote the file, mapped or loaded it, then unlinked it. Copy that range before the process
|
||||
exits; `/proc/<pid>/mem` does not care that the name is gone. On one sample this recovered the only
|
||||
copy of a dynamically loaded dex and the Java method that had been invisible to jadx. Treat the
|
||||
range's `r--p` permission and a plausible `dex\n035` header as the control that it is code, not a
|
||||
cache.
|
||||
|
||||
### Address arithmetic is where this route silently breaks
|
||||
|
||||
Three device-shell traps cost real time on the first run, and each one produces a
|
||||
|
||||
@@ -159,6 +159,51 @@ payload and jumping to a zero entry. Treat "`Invalid ELF magic` appears on my bu
|
||||
original" as **proof the loader is validating the build**, which is exactly what makes the
|
||||
string-redirect route worth trying.
|
||||
|
||||
When the loader itself becomes the object of study — you need to load, dump or repair its payload
|
||||
rather than neutralise its check — `linker-and-soinfo-repair.md` owns the pipeline arithmetic and
|
||||
the `soinfo` hand-off; this file owns recognising that the loader is present and deciding whether
|
||||
to keep it.
|
||||
|
||||
## Staged loaders that decrypt a DEX from assets
|
||||
|
||||
A second family does not keep the payload in the APK's dex at all. Recognise it by the *shape*, not
|
||||
by a product name:
|
||||
|
||||
1. A Java `Application`/`attachBaseContext` loads a small stage-1 `.so`.
|
||||
2. That library's `JNI_OnLoad` calls `RegisterNatives` for two or three methods and returns.
|
||||
3. `attachBaseContext` then calls one of them with `dataDir`, `nativeLibraryDir` and the
|
||||
`AssetManager` — the arguments are the tell that the native side is about to write a file and
|
||||
load code from it.
|
||||
4. The native method opens an asset whose name looks random, derives a key, decrypts an AES payload
|
||||
into Dalvik bytecode, and returns a direct `ByteBuffer`.
|
||||
5. Java passes that buffer to a `DexClassLoader`/`loadDex` path. The stage-1 `.so` may then launch a
|
||||
stage-2 `.so` from the decrypted code.
|
||||
|
||||
The stage-2 payload often lives in `assets` as an extensionless `.sec` file. One sample selected it
|
||||
by CPU family — including mapping **ARM64 to an `x64`-named payload** — then:
|
||||
|
||||
- hex-decoded a constant string into an AES-256 key and a per-block IV;
|
||||
- decrypted 16-byte blocks with AES, then XORed each with the IV;
|
||||
- read an **8-byte tail** from the `.sec` file as an offset, copied `[offset, EOF)` as the real
|
||||
payload, and XORed that region with the file's own prefix;
|
||||
- decrypted the exported symbol name with the same construction before `dlsym`, and `unlink`ed the
|
||||
temporary file after `dlopen`.
|
||||
|
||||
**What generalises:** the asset name, key, IV and tail layout are per-build and must be read from
|
||||
the loader, not carried across. What does carry is the diagnostic chain — *asset with a random name +
|
||||
`AssetManager` passed into a registered native method + a returned direct buffer + `DexClassLoader`*
|
||||
— and the fact that the second stage picks its payload by ABI, so an x86 host may never see the
|
||||
ARM64 branch.
|
||||
|
||||
**Preconditions to record before spending time:** whether the loader writes to `dataDir` or
|
||||
`nativeLibraryDir`, whether the payload is deleted after load, and which ABI the running process
|
||||
reports. A dump taken after the `unlink` can only come from memory; a dump taken before it can come
|
||||
from the file, which is cheaper and gives an exact length.
|
||||
|
||||
**Claim strength.** One family, one sample, absorbed from a public write-up; keys and offsets are
|
||||
deliberately not reproduced. Treat the sequence as a recognition template and recover the constants
|
||||
from the binary in front of you.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -114,7 +114,10 @@ its own strength note at the top.
|
||||
- **Instruction-level tracing and de-obfuscation** — the OLLVM shapes, a Stalker trace, the
|
||||
trace-to-CFG route, and the measured boundaries in `native-dbi-and-deobfuscation.md`.
|
||||
- **Protocol reversing beyond REST** — protobuf without a schema, gRPC frame capture, the QUIC/HTTP3
|
||||
limit, native-side certificate pinning (`protocol-reverse.md`).
|
||||
limit, native-side certificate pinning, and — for an opaque body — classifying the primitive by
|
||||
differential probes (header length, determinism, diffusion width, the length law) before implementing
|
||||
it
|
||||
(`protocol-reverse.md`).
|
||||
- **What to do when userspace hooking provably cannot reach the check** — raw `svc` syscalls,
|
||||
`init_array`-early detection, and the kernel-route map with its version gate
|
||||
(`kernel-and-environment-hardening.md`).
|
||||
@@ -136,8 +139,22 @@ its own strength note at the top.
|
||||
(`scripts/vm_handler_slice.py`).
|
||||
- **Native VM recovery procedure** — the full method (dispatcher-layer separation, register
|
||||
anchoring with triple verification, nested segment stacks, STORE-backward slicing, clean-re-VM
|
||||
validation) absorbed from two public write-ups; every step `inferred`, none run here
|
||||
(`native-vm-recovery.md`).
|
||||
validation) plus a devirtualization end state that emits a runnable straight-line program with its
|
||||
constant table, output map and template; absorbed from public write-ups, every step `inferred` and
|
||||
none run here (`native-vm-recovery.md`).
|
||||
- **A VM written in the managed layer** — IL2CPP builds whose interpreter is C#: the `dump.cs` shape
|
||||
(opcode array + cursor + `Dictionary<int, delegate>`), the opcode→handler map read out of the
|
||||
constructor, and array literals materialised by `RuntimeHelpers::InitializeArray` rather than stored
|
||||
in `.rodata`; identified only, no managed VM was recovered here (`unity-runtime.md`,
|
||||
`native-vm-recovery.md`).
|
||||
- **Comparison gates as prefix oracles** — instrument the comparator's own counter, grow the prefix one
|
||||
position at a time, and decide from the fail-path cost whether the oracle is open (early exit) or
|
||||
closed (digest / fixed-width / constant-time). The cost separation is host-measured on synthetic
|
||||
compares; no real gate was attacked, and a remote check is a different, rate-limited experiment
|
||||
(`account-gates.md`).
|
||||
- **Pyarmor builds that wrap the whole file** — three nonce scopes (outer container, per code object,
|
||||
per string) sharing one master key, and why a live dump is structurally incomplete; the
|
||||
counter-mode half is host-measured, the layering itself is absorbed (`python-bytecode-recovery.md`).
|
||||
- **JS VMP (jsvmp) recovery** — reading logic protected as a private JS opcode stream: recognition
|
||||
signals, the call-it-first route (AST restore + environment fill), stack- and register-machine
|
||||
reading procedures, AST instruction extraction with register/immediate typing, the four
|
||||
@@ -166,12 +183,54 @@ its own strength note at the top.
|
||||
for browser targets and never run on an Android long-connection app here — `unverified`
|
||||
end to end, with Android capture points `inferred` from documented APIs
|
||||
(`protocol-reverse.md` §6).
|
||||
- **Unity logic recovery (Mono and readable IL2CPP)** — telling the backends apart by what they
|
||||
ship, dumping `libil2cpp.so` + `global-metadata.dat` with Il2CppDumper, the metadata magic that
|
||||
decides whether the dump is even possible, the four-step IDA import order, a run-time class/method
|
||||
lookup over frida-il2cpp-bridge, and the dnSpy-Unity-mono patch that makes a retail Mono player
|
||||
accept a debugger. Absorbed from public write-ups; no package was dumped here and no patched
|
||||
runtime was built, so every step is `unverified` (`unity-runtime.md`).
|
||||
- **Protected IL2CPP metadata** — when the pair is absent, 0 bytes, encrypted, embedded or version-
|
||||
inconsistent: anchoring on the consumer's output pointer, the version-independent header-sizing
|
||||
rule, the repeating-key XOR / custom bytecode-VM / XXTEA container shapes, the second-mapping
|
||||
live dump, and the ELF repair that names symbols again. Absorbed from public write-ups and never
|
||||
executed here (`il2cpp-protected-metadata.md`).
|
||||
- **Linker-level SO unpacking and `soinfo` repair** — the `dlopen` pipeline as a loader
|
||||
specification, `load_bias` and segment arithmetic including `seg_page_offset`, `DT_*` parsing,
|
||||
relocation targets and the defining-library-versus-caller bias, the minimal `soinfo` repair set,
|
||||
anti-dump header XOR detected by ELF invariants, the dump window at `LoadSegments`, the narrower
|
||||
window that closes inside `JNI_OnLoad` when self-decryption and watchdog startup share that
|
||||
function, a raw-syscall reader outside a self-hooked libc, and zero-filled unreadable pages.
|
||||
Source-reading synthesis plus two write-ups; no loader was reimplemented here
|
||||
(`linker-and-soinfo-repair.md`).
|
||||
- **VM protector analysis** — envelope triage, VM_DATA/VM_CONTEXT/vEIP/vStack anatomy, data-anchored
|
||||
breakpoints, forged-return recognition, trace-then-search-by-constant, virtual eflags as writable
|
||||
data, NAND lowering and branchless select. Absorbed from x86 VMProtect samples; never executed
|
||||
against an Android target here (`vm-protector-analysis.md`).
|
||||
- **Python bytecode / Pyarmor recovery** — the MD5 key schedule, AES-CTR nonce construction, the
|
||||
12-byte nonce-XOR VM, version-gated `pyc` parsing and pre-3.8 flag remap, the extra-section TLV,
|
||||
per-code-object and per-string decryption. Absorbed from one public write-up; no sample was
|
||||
unpacked here (`python-bytecode-recovery.md`).
|
||||
- **Attaching IDA's remote debug server to a `.so`** — ABI-matched `dbgsrv`, the root server, the
|
||||
wait-for-debugger start plus the JDWP handshake that releases the process, and the
|
||||
`extractNativeLibs="false"` failure where the library is mapped from `base.apk` and no breakpoint
|
||||
can bind. Absorbed from two walkthroughs; never run here, and neither source targeted a hardened
|
||||
app (`ida-so-debugging.md`).
|
||||
- **Kernel-side event injection** — invisible watchpoints and register rewrites from a driver, as
|
||||
generated templates with their gates; nothing kernel-side was ever compiled or loaded here
|
||||
(`kernel-event-injection.md`, `scripts/kernel_instrument_scaffold.py`).
|
||||
- **Working from the phone itself** — MT Manager, its APK MCP surface, LSPosed Manager, on-device
|
||||
data inspection (`on-device-tooling.md`, `scripts/mt_mcp_probe.py`).
|
||||
|
||||
- **Unity + Lua and AssetBundle recovery** — finding a Lua container on top of Unity, repairing the
|
||||
Lua 5.1 header byte, checking the loader's bytecode-only flag, reading the CRC manifest the game
|
||||
actually reads, bounding a partial-encryption window, rebuilding a UnityFS bundle without losing
|
||||
its layout or dependency edges, verifying added/replaced TextAsset read-back, and reading
|
||||
half-encrypted Mono assemblies behind a publisher shell. Absorbed from two anonymised case reports;
|
||||
no package was decrypted or bundle rebuilt here, so every step is `unverified`
|
||||
(`unity-lua-and-assetbundles.md`).
|
||||
- **LayaAir native (Conch) DCC recovery** — Conch identification, the path-addressed cache, the
|
||||
filetable checksum, regenerating metadata from shipped content, and the loader patch with its
|
||||
startup-delay race. Absorbed from one case report; no LayaAir package was reversed here
|
||||
(`framework-runtimes.md` §LayaAir native (Conch) specifics).
|
||||
## Dependencies this skill does not ship — name them before the workflow starts
|
||||
|
||||
- **JS AST rewriting needs node + babel** (`@babel/parser`/`traverse`/`generator`) — the detector
|
||||
@@ -189,10 +248,12 @@ its own strength note at the top.
|
||||
|
||||
## 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`.
|
||||
- **A *verified* Unity / IL2CPP route.** `unity-runtime.md` and
|
||||
`il2cpp-protected-metadata.md` carry documented routes — backend identification, Il2CppDumper, the
|
||||
IDA import order, the Frida bridge, consumer-side metadata recovery and ELF repair — but nothing in
|
||||
either was run in this record, and neither is the IL2CPP equivalent of `dart-aot.md`: there is no
|
||||
byte-level reading of generated native code here, no opcode map, and no measurement on a stripped
|
||||
or protected package. Do not present a dump as proof that a method was located.
|
||||
- **React Native / Hermes bytecode** and Cordova/hybrid internals, beyond runtime identification and
|
||||
the generic "find the string, then find what references it" approach. One carve-out: if the JS
|
||||
layer's problem is **VMP-protected JavaScript** (a jsvmp opcode literal plus interpreter), that is
|
||||
|
||||
@@ -26,6 +26,7 @@ the evidence record condensed in `references/evidence-summary.md` §Where the fu
|
||||
| Flutter / Dart AOT | analysing and patching `libapp.so` **given a snapshot dump** | `dart-aot.md` |
|
||||
| Runtime and server side | Frida analysis, API probing, feature-scoped TLS failures, update/forced-upgrade neutralisation | `dynamic-frida.md`, `server-api.md`, `tls-and-cert.md`, `updates-and-forced-upgrade.md` |
|
||||
| Verification discipline | the claim ladder, control builds, capture-and-look, bounded waits | `verification.md`, `long-task-discipline.md` |
|
||||
| A comparison gate as an oracle | instrument the comparator's own counter (not the clock), grow the correct prefix one position at a time, and read the fail-path cost to decide whether the oracle is open or the check is over a digest — host-measured on synthetic compares, no real gate attacked | `account-gates.md` |
|
||||
|
||||
## Also covered, by documented routes — mostly *inferred* rather than measured
|
||||
|
||||
@@ -52,9 +53,20 @@ route was not measured on this repository's evidence**. Treat them as leads with
|
||||
| JS AST pre-deobfuscation | family detection + per-family pass order + safe-rewrite rules; detector shipped and fixture-tested, rewriting needs node+babel (not shipped) — `js-ast-deobfuscation.md`, `js_obf_detect.py` |
|
||||
| Kotlin original-name recovery | obfuscated→original class map from `@DebugMetadata`/`@Metadata` in any jadx export; parsing fixture-tested, recovery rates upstream-claimed — `kotlin-name-recovery.md`, `kotlin_name_recovery.py` |
|
||||
| Long-connection (WebSocket) analysis | state chains, message families, envelope/payload split — absorbed methodology, never run on an Android target here — `protocol-reverse.md` |
|
||||
| Unity (Mono and IL2CPP) | backend identification, Il2CppDumper over `libil2cpp.so` + `global-metadata.dat`, the IDA import order, a run-time lookup over frida-il2cpp-bridge, the dnSpy-Unity-mono patch, and a VM that lives in the managed layer (opcode array + cursor + `Dictionary<int, delegate>` in `dump.cs`, handler indices from the constructor, array literals via `InitializeArray`) — absorbed, nothing run here — `unity-runtime.md` |
|
||||
| Protected IL2CPP metadata | when the pair is not readable: consumer-side dump, header sizing without trusting the version, XOR/VM/XXTEA containers, the live-image dump and ELF repair, and the ELF fingerprint of a rebuilt `libil2cpp` (`JNI_OnLoad` / own `DT_INIT` / `SHT_LOUSER`) — absorbed, nothing run here — `il2cpp-protected-metadata.md` |
|
||||
| Linker-level SO unpacking and repair | the `dlopen` pipeline as a loader spec, load_bias/segment arithmetic, `DT_*` and relocation rules, `soinfo` repair, anti-dump header XOR — source-reading synthesis, no loader reimplemented — `linker-and-soinfo-repair.md` |
|
||||
| VM protector analysis | virtual eflags, NAND lowering, branchless select, data-anchored breakpoints and trace search by constant — absorbed from x86 VMProtect samples, never run on Android here — `vm-protector-analysis.md` |
|
||||
| Python bytecode / Pyarmor | key schedule, AES-CTR nonce rules, the 12-byte VM, version-gated `pyc` parsing, the extra-section TLV, and the outer container layer with its three nonce scopes — absorbed, no sample unpacked here; the counter-mode nonce behaviour is host-measured — `python-bytecode-recovery.md` |
|
||||
| Attaching a real debugger to a `.so` | IDA `dbgsrv` with the ABI match, wait-for-debugger plus the JDWP handshake, and the `extractNativeLibs="false"` failure where no breakpoint binds — `ida-so-debugging.md` |
|
||||
| Kernel-side event injection | watchpoints and register rewrites from a driver, as gated templates — `kernel-event-injection.md` |
|
||||
| Working from the phone itself | MT Manager edit/repack/sign and its APK MCP, LSPosed Manager, Termux — `on-device-tooling.md` |
|
||||
| Unity + Lua scripts and AssetBundle rebuilds | find/decrypt the Lua container, repair a Lua 5.1 header, locate the live CRC manifest, bound a partial-encryption window, rebuild a UnityFS bundle without losing layout/dependencies, verify TextAsset read-back, and recover half-encrypted Mono assemblies behind a publisher shell — absorbed from two case reports; nothing was run here — `unity-lua-and-assetbundles.md` |
|
||||
| LayaAir native (Conch) DCC recovery | Conch identification, path-addressed cache, DCC filetable checksum and metadata regeneration, and the loader patch with its startup-delay race — absorbed; no LayaAir package was reversed here — `framework-runtimes.md` §LayaAir native (Conch) specifics |
|
||||
| Publishing without publishing the target | the leak scanner, the do-not-anonymize list, and the graded precedent library — `desensitization-and-leak-scans.md`, `scripts/scan_leaks.py`, `precedents/` |
|
||||
| Native dump window and syscall reader | dump at `android_dlopen_ext` entry when self-decryption and watchdog startup share `JNI_OnLoad`; read via raw syscalls; zero-fill unreadable pages so offsets survive repair — absorbed, nothing run here — `linker-and-soinfo-repair.md` |
|
||||
| White-box crypto devirtualization | fold a deterministic VM transform into a straight-line `(op, args)` program plus constant table, output map and template, pinned to one build — absorbed, no extract produced — `native-vm-recovery.md` |
|
||||
| Cipher classification by differential probe | header length, determinism, one-byte diffusion width and the length law separate CTR/CBC/ECB; involution wrappers cancel; encoding/compression drift is the last mile — probes host-checked on AES-128, no target classified — `protocol-reverse.md` |
|
||||
|
||||
## Dependencies this skill does not ship
|
||||
|
||||
@@ -76,9 +88,11 @@ dependency yourself.
|
||||
|
||||
## Not covered — say so rather than improvise
|
||||
|
||||
Unity / IL2CPP logic recovery · React Native, Hermes bytecode and Cordova internals · iOS of any kind ·
|
||||
React Native, Hermes bytecode and Cordova internals · iOS of any kind ·
|
||||
defeating a server-side authority · an off-the-shelf unpacker · an anti-detection arms race · building
|
||||
and shipping a kernel module · a Stalker trace guaranteed on every device.
|
||||
and shipping a kernel module · a Stalker trace guaranteed on every device · **a measured** Unity /
|
||||
IL2CPP route (the documented ones are `unity-runtime.md` and `il2cpp-protected-metadata.md`, and neither
|
||||
carries a measurement).
|
||||
|
||||
Each has a reason and, where one exists, an evidence boundary — in `references/coverage-and-limits.md`.
|
||||
**Silence in that record is not support**, and a route that is only "documented" is not a route that
|
||||
|
||||
@@ -257,6 +257,29 @@ shipped library. A crash frame in JIT output cannot be mapped to a file offset.
|
||||
API where the framework compiles reflection at runtime, and treat "the frame has no file" as a fact
|
||||
about compilation, not as a hidden module.
|
||||
|
||||
### Filter signals by module before believing them
|
||||
|
||||
A process under instrumentation produces signals that are not the target's. ART takes an implicit
|
||||
`SIGSEGV` for null and bounds checks inside `boot*.oat`, `*.odex` and anonymous JIT pages, and resumes
|
||||
the thread in its own handler. A deliberate crash, a protector's kill and the runtime's own fault can
|
||||
all reach your observer looking identical: "signal 11". (`unverified`: documented ART behaviour plus the
|
||||
source's observation — no trace of it was taken in this record.)
|
||||
|
||||
The tuple that discriminates is **(signal, faulting address, faulting module)**, not the signal number.
|
||||
Count a signal only when the address resolves inside the library you are studying; log the rest and
|
||||
let them through untouched.
|
||||
|
||||
Two consequences:
|
||||
|
||||
- **Do not install a handler that swallows what the runtime expects to handle.** ART's implicit faults
|
||||
are how its null checks work; swallowing them turns a healthy process into a mysterious hang. A
|
||||
handler that intercepts signals has to forward anything whose faulting module is not the target.
|
||||
(`inferred`.)
|
||||
- **A `boot*.oat` or `odex` frame in a crash record is the runtime's, not the shell's.** Chasing it
|
||||
produces "the VM is corrupting memory" when the truth is that the VM's own fault handling ran.
|
||||
(`inferred`: a consequence of the attribution rule, not a case measured here.)
|
||||
|
||||
|
||||
### Stage 6: the precise stop, and the static alternative to it
|
||||
|
||||
**Input signal:** a named module + offset from Stage 2, Stage 3 or Stage 5. **Action:** neutralise
|
||||
@@ -279,6 +302,16 @@ hand showed 21 byte-scan "svc sites" that were all **data**, with no call-number
|
||||
them: a byte scan for `svc` matches inside data, so read the neighbours before believing a count.
|
||||
That distinction — structural absence vs. observed absence — is what Stage 6 is for.
|
||||
|
||||
### Timing-delayed checks: hook the delay, not the branch
|
||||
|
||||
A check that appears only after you hook a particular library, and appears **seconds later**, may be
|
||||
measuring elapsed time rather than reacting immediately. The primitive is usually `sleep` or
|
||||
`nanosleep`: hook it, rewrite `args[0]` to a large value, and take a backtrace from the hook. If the
|
||||
delayed popup disappears and the backtrace names one module plus a handful of offsets, those callers
|
||||
are the next static target. This is lower-risk than patching the checker because it changes the
|
||||
measurement, not the decision — and it gives you the module to read. (`unverified`: absorbed from one
|
||||
write-up; not run here.)
|
||||
|
||||
### The routing chain, on one page
|
||||
|
||||
```
|
||||
|
||||
@@ -180,6 +180,32 @@ Patch spec format for `patch_smali.py`:
|
||||
]
|
||||
```
|
||||
|
||||
### Deleting calls instead of rewriting the method
|
||||
|
||||
For a large lifecycle method (`onCreate`, an Application initialiser, a main-screen controller), do
|
||||
not hand-write the whole body in smali. The source's native case tried that and produced two failure
|
||||
classes: `VerifyError` from a `invoke-static/range` whose argument registers were placed at the
|
||||
wrong end of the range, and a missing repository initialiser that surfaced later as
|
||||
`lateinit property ... has not been initialized`.
|
||||
|
||||
The safer shape:
|
||||
|
||||
1. **Keep the original method body.** Remove `.line` directives only for the purpose of matching.
|
||||
2. **Delete the specific calls** (network, analytics, push, billing, account) with multi-line anchors,
|
||||
and assert each anchor matches exactly once.
|
||||
3. **Delete the instructions that existed only to prepare that call** — the `move-object` and
|
||||
`check-cast` pairs that feed its arguments. Leaving them is harmless only if their registers stay
|
||||
live; removing the call and leaving a half-built argument list is how verification fails.
|
||||
4. **Put new logic in a Java class** compiled with `javac` + `d8` into an extra `classesN.dex`;
|
||||
the smali edit becomes one `invoke-static` line. The new class is testable on the host and does not
|
||||
disturb register allocation in the original method.
|
||||
5. **Find the real input point, not every consumer.** In the source's case the dead profile supplied
|
||||
"current character" and "language"; changing those two getters to read local settings made the
|
||||
whole default-model and greeting chain work without touching the model loader.
|
||||
|
||||
Verify with `dex_classdiff`, install, cold-start, and exercise the exact entry that used the deleted
|
||||
call. A build that verifies can still have removed an initialiser that only one screen needs.
|
||||
|
||||
## Finding the call site
|
||||
|
||||
Reverse-lookup from a smali tree or a set of disassembled dex:
|
||||
|
||||
@@ -223,6 +223,46 @@ Interceptor.attach(f, {
|
||||
});
|
||||
```
|
||||
|
||||
### Native registration, load order and late mapping
|
||||
|
||||
Five mechanics that a plain `Interceptor.attach` misses. They are absorbed from a public Frida
|
||||
cookbook and not measured here; the failure each one prevents is.
|
||||
|
||||
**A `RegisterNatives` table is walked once.** Enumerate `libart.so` symbols, keep names containing
|
||||
`JNI` but **not** `CheckJNI` (the debug wrapper duplicates the export), attach the `RegisterNatives`
|
||||
you find, and read `args[2]` as an array of `JNINativeMethod`: name pointer at `+0`, signature
|
||||
pointer at `+ptr_size`, native entry at `+2*ptr_size`. Because registration happens before
|
||||
`dlopen` returns, attach-to-running-process sees nothing; spawn with `-f`.
|
||||
|
||||
**A module may not be mapped when the script loads.** Gate the real hook on module load: attach both
|
||||
`dlopen` and `android_dlopen_ext` (the latter for newer Android), match the path in `onEnter`, and
|
||||
install the target hook in `onLeave`. A `Module.findBaseAddress` that returns `null` at injection
|
||||
time is an ordering problem, not a missing library.
|
||||
|
||||
**Read registers at the instruction *after* the one that sets them.** Attaching at `0x...1C` to read
|
||||
a register written by the instruction at `0x...18` sees the old value on some compilers. Attach to
|
||||
the next instruction and read `this.context.xN`. For Thumb, pass `base.add(off).add(1)` to the
|
||||
disassembler, or it decodes in ARM mode and every mnemonic is nonsense.
|
||||
|
||||
**JNI argument shapes are readable without a decompiler.** A pointer argument wants `hexdump`; a
|
||||
small positive integer is often a length; `&x` is an output buffer; a pointer-to-pointer needs one
|
||||
more `readPointer()` before the dump. For a `jstring`, use
|
||||
`ptr(Java.vm.tryGetEnv().getStringUtfChars(args[n])).readCString()`, and the same on `retval`.
|
||||
If the routine is a C++ member, active invocation needs the right convention:
|
||||
`new NativeFunction(addr, 'int', ['pointer','int'], 'thiscall')`.
|
||||
|
||||
**Patch the init function, not the exit it calls.** When a library's `DT_INIT` is the check, hooking
|
||||
`kill`/`exit` is often too late or never reached. Enumerate the linker's symbols for
|
||||
`__dl__ZL13call_functionPKcPFviPPcS2_ES0_`; on enter, `args[0]` is the tag (`DT_INIT`), `args[1]`
|
||||
the function, `args[2]` the library path. Match the path and patch the function's first bytes to two
|
||||
Thumb NOPs (`00 bf 00 bf`) **while `call_function` is running**, before the loader calls it. Patching
|
||||
after `dlopen` returns is by definition after the check has run.
|
||||
|
||||
**OLLVM does not flatten the call graph.** When the decompiler output is unreadable, prioritize calls
|
||||
that sit outside `if`/`while` bodies, infer the algorithm family from constants used on
|
||||
non-conditional paths, and hook the candidate rather than reading the graph. A hook that prints the
|
||||
input/output shapes is cheaper evidence than a deobfuscated listing.
|
||||
|
||||
### Network / domain observation (cheap and very informative)
|
||||
```javascript
|
||||
const Inet = Java.use('java.net.InetAddress');
|
||||
@@ -495,6 +535,7 @@ runtime-grade information, and they are often enough to finish the job:
|
||||
| **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 |
|
||||
| **A real debugger** — IDA's `dbgsrv` on the device, `am start -D`, and the JDWP handshake that releases the process | single-step, register and stack reads at an exact instruction, and one-shot breakpoints without writing a hook | needs a debuggable build, leaves `TracerPid` non-zero, and its software breakpoints are visible in mapped pages — `ida-so-debugging.md` |
|
||||
| **`LD_PRELOAD`** — the classic libc-interposition route | function-level interception with no on-device agent | effectively closed on Android: zygote-forked apps do not inherit your environment, restricted processes drop it, and linker namespaces limit which `.so` paths load at all (namespaces: Android 7.0+, fully in force from 8.0/Treble — older targets are less constrained); the debuggable-build `wrap.sh` escape hatch is the one place it still works. *(inferred — absorbed from milksu.org notes, retrieved 2026-10-19)* |
|
||||
|
||||
The last one is worth remembering because it is the cheapest and it is easy to
|
||||
|
||||
@@ -123,6 +123,16 @@ wrong conclusion is the one that gets written down and trusted later.
|
||||
|
||||
Emulators are the right place to iterate and the wrong place to conclude.
|
||||
|
||||
- **Architecture is not interchangeable.** A VirtualBox-derived AVD is x86_64; an app that ships only
|
||||
ARM64 libraries may install and then crash at load. Windows Subsystem for Android can run an ARM64
|
||||
*app* through its ARM translation layer, but it cannot run an ARM64 `frida-server`; pointing an
|
||||
x86_64 server at the same process commonly yields no process in the list and no hooks — which looks
|
||||
like an anti-debug finding and is a host/guest mismatch. Dynamic work on an ARM64-only target
|
||||
therefore needs a rooted physical ARM device or an Apple-silicon host. For an AVD, a `rootAVD`-style
|
||||
ramdisk patch plus `-writable-system -selinux disabled` is the documented route; verify with
|
||||
`su -c id` rather than trusting the boot flag. (Absorbed from a public walkthrough, not measured
|
||||
here.)
|
||||
|
||||
- **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.
|
||||
|
||||
@@ -58,6 +58,8 @@ next** — and points at the one section that says "the full record is elsewhere
|
||||
| Hardware memory watchpoints (ptrace) | The encoders and refusals are host-tested and the emitted helper compiles as a static aarch64 ELF; **no watchpoint was ever armed on a device**, and the route leaves `TracerPid` visible by design | partial | unverified | `references/hardware-watchpoints.md`, `scripts/hw_watch.py` |
|
||||
| Differential trace reduction | First divergence, divergent regions and per-side unique blocks measured on synthetic flattened-dispatcher fixtures, in both Stalker and wrapped-log grammars; no real-target producer (Stalker pair or cs_etm decode) has fed it yet | partial | observed | `references/ete-diff-tracing.md`, `scripts/trace_diff.py` |
|
||||
| ETE hardware tracing | Gates and capture wrapper host-measured to the no-device boundary; no coresight capture or decode ever ran here, and `--control` exists to say so on a real device in one command | blocked | unverified | `references/ete-diff-tracing.md`, `scripts/ete_capture.py` |
|
||||
| A VM written in the managed layer (IL2CPP C#) | Identified, not recovered: opcode array + cursor + `Dictionary<int, delegate>` in `dump.cs`, handler indices read out of the constructor, array literals taken from `InitializeArray` rather than `.rodata` | partial | unverified | `references/unity-runtime.md`, `references/native-vm-recovery.md` |
|
||||
| Comparison gate as a prefix oracle | Host half measured: an early-exit compare costs k+1 comparisons for a k-byte correct prefix (k=0..8) while an MD5-then-compare is constant; no serial or licence gate was attacked | partial | observed | `references/account-gates.md` |
|
||||
| SPE/BRBE sampling and crash forensics | The address→symbol loop is host-verified on a real cross-compiled `.so`; SPE/BRBE mechanisms are documented-and-gated, never captured here | partial | unverified | `references/hardware-sampling-and-crash.md`, `scripts/trace_addr2sym.py` |
|
||||
| Interpreter-trace de-virtualization | Dispatcher slicing, signature clustering and the opcode trajectory measured on synthetic interpreter traces; the calibration facts come from a public IR-VM's source, and no hardened binary was traced | partial | observed | `references/ete-diff-tracing.md` §5, `scripts/vm_handler_slice.py` |
|
||||
| Native VM recovery procedure | The full method is absorbed from two public write-ups (dispatcher-layer separation, register anchoring with triple verification, nested segment stacks, STORE-backward slicing, clean-re-VM validation); no step was executed by this repository | partial | inferred | `references/native-vm-recovery.md` |
|
||||
@@ -73,8 +75,19 @@ next** — and points at the one section that says "the full record is elsewhere
|
||||
| Update and forced-upgrade neutralisation | Documented, no measurement; the failure shape is a build that installs, runs and fails every signed request | partial | inferred | `references/updates-and-forced-upgrade.md`, `references/signature-derived-keys.md` |
|
||||
| Signature-derived keys | Documented only: neither the offline candidate path nor the live read has a public-target measurement here | partial | unverified | `references/signature-derived-keys.md`, `scripts/sig_probe.py` |
|
||||
| Publishing sanitisation and leak scanning | Every rule fired on a planted corpus with zero false positives on the do-not-anonymize list, and the scan found 26 strong hits in its own evidence file | ok | observed | `references/desensitization-and-leak-scans.md`, `scripts/scan_leaks.py` |
|
||||
| Unity / IL2CPP, React Native / Hermes, iOS | Outside this skill: the runtime can be identified, the logic recovery is not covered | blocked | unverified | `references/framework-runtimes.md`, `references/coverage-and-limits.md` |
|
||||
| Unity / IL2CPP logic recovery | Documented route only: backend identification, Il2CppDumper over `libil2cpp.so` + `global-metadata.dat`, the IDA import order, the Frida bridge, and the dnSpy-Unity-mono patch. No Unity package was dumped here and no patched Mono runtime was built | partial | unverified | `references/unity-runtime.md`, `references/framework-runtimes.md` |
|
||||
| IL2CPP protected metadata recovery | Absorbed route only: consumer-side dump, version-independent header sizing, the repeating-key XOR / bytecode-VM / XXTEA container shapes, the live-image dump and the ELF repair that makes it usable. No Unity metadata was decrypted or dumped here | partial | unverified | `references/il2cpp-protected-metadata.md`, `references/unity-runtime.md` |
|
||||
| Linker-level SO unpacking and `soinfo` repair | Absorbed route only: the `dlopen` pipeline as a loader spec, load_bias and segment arithmetic, `DT_*` and relocation rules, the minimal `soinfo` repair set, anti-dump header XOR, and the dump points. No loader was reimplemented here | partial | unverified | `references/linker-and-soinfo-repair.md`, `references/code-virtualization-and-custom-linkers.md` |
|
||||
| VM protector analysis (virtual eflags, NAND lowering) | Absorbed from three public VMProtect write-ups: envelope triage, VM anatomy, data-anchored breakpoints, trace-then-search-by-constant, virtual-eflags patching, branchless select and NAND lowering. No VM-protected binary was traced here | partial | unverified | `references/vm-protector-analysis.md`, `references/native-vm-recovery.md` |
|
||||
| Python bytecode / Pyarmor recovery | Absorbed from one public write-up: the key schedule, AES-CTR nonce rules, the 12-byte VM, version-gated `pyc` parsing, the extra-section TLV, and per-object/per-string decryption. No sample was unpacked here | partial | unverified | `references/python-bytecode-recovery.md` |
|
||||
| Attaching IDA's debug server to a `.so` | Documented route only: ABI-matched `dbgsrv`, root server, wait-for-debugger plus the JDWP handshake that releases the process, and the `extractNativeLibs="false"` failure where no breakpoint binds. Never run here; neither source targeted a hardened app | partial | unverified | `references/ida-so-debugging.md` |
|
||||
| React Native / Hermes, iOS | Outside this skill: the runtime can be identified, the logic recovery is not covered | blocked | unverified | `references/framework-runtimes.md`, `references/coverage-and-limits.md` |
|
||||
| Defeating a server-side authority | Out of scope by design; report it as a residual rather than patching harder | blocked | unverified | `references/server-api.md`, `references/handoff-boundaries.md` |
|
||||
| Native dump window and syscall reader | Absorbed operating rules: dump at `android_dlopen_ext` entry because the window closes inside `JNI_OnLoad`, a raw-syscall reader outside a self-hooked libc, and zero-filled holes so repair keeps offsets. Zero-fill offset arithmetic host-checked on a synthetic image; the window itself never exercised here | partial | unverified | `references/linker-and-soinfo-repair.md` §6.2 |
|
||||
| White-box crypto devirtualization to a program | Absorbed route: symbolic input, constant folding, a straight-line `(op, args)` program plus its constant table, output map and template; version-bound, deterministic functions only. No extract was produced here | partial | unverified | `references/native-vm-recovery.md` §11 |
|
||||
| Cipher classification by differential probe | Method: header length, determinism, one-byte diffusion width and the length law separate CTR, CBC and ECB (the earlier prefix-XOR-only claim was falsified and is corrected); involution wrappers cancel; Java/Python encoding and compression drift decide the last mile. Probes and algebra host-checked on AES-128 and synthetic inputs; no target body classified | partial | inferred | `references/protocol-reverse.md` §7 |
|
||||
| Unity + Lua scripts and AssetBundle rebuilds | Absorbed: Locating a Lua container on top of Unity, the Lua 5.1 header-byte tamper, loader bytecode-only check, the CRC manifest the game actually reads, UnityFS partial-encryption windows, rebuild traps (layout loss, dependency null, compressed == raw), TextAsset read-back, and half-encrypted Mono assemblies behind a publisher shell. No package was decrypted or bundle rebuilt here | partial | unverified | `references/unity-lua-and-assetbundles.md` |
|
||||
| LayaAir native (Conch) DCC recovery | Absorbed: Conch identification, the path-addressed cache, the DCC filetable checksum, regenerating metadata from shipped content, the loader patch, and the startup-delay race. No LayaAir package was reversed here | partial | unverified | `references/framework-runtimes.md` §LayaAir native (Conch) specifics |
|
||||
|
||||
## Where the full record lives — repository root, not shipped
|
||||
|
||||
|
||||
@@ -14,9 +14,11 @@ Signals in the APK:
|
||||
|---|---|
|
||||
| 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` |
|
||||
| Unity | `libunity.so`, `libil2cpp.so`, `assets/bin/Data/`, `globalgamemanagers` → `unity-runtime.md` for Mono versus IL2CPP |
|
||||
| Cordova / Ionic | `assets/www/`, `cordova.js` |
|
||||
| Xamarin / .NET | `libmonodroid.so`, `assemblies/` in the APK |
|
||||
| Python (Chaquopy / Kivy / BeeWare) | `libpython3.*.so`, `assets/` with `.pyc`/`.pyz`, `pyarmor`/`__pyarmor__` bootstrap → `python-bytecode-recovery.md` |
|
||||
| Python compiled away (Nuitka / Cython / `pyd`) | `libpython3.*.so` **or** a bare CPython dependency, no `.pyc`/`.pyz` anywhere, and `PyInit_*` exports in a target `.so` → the bytecode route has no input; the bodies are native (`native-and-so.md`) |
|
||||
|
||||
A `classes.dex` that is small relative to the total payload is another strong hint that the real code
|
||||
lives elsewhere.
|
||||
@@ -74,6 +76,66 @@ building a decompiler for exactly that version, the object-pool model and how to
|
||||
and boolean conventions, the three assembly signatures that identify most business logic, the locating
|
||||
workflow, and how to patch this layer safely.
|
||||
|
||||
## Unity specifics
|
||||
|
||||
- **Two backends, and they are not the same problem.** A Mono build ships readable CIL
|
||||
(`assets/bin/Data/Managed/Assembly-CSharp.dll`); an IL2CPP build ships
|
||||
`lib/<abi>/libil2cpp.so` **plus** `assets/bin/Data/Managed/Metadata/global-metadata.dat`, and the
|
||||
metadata is what carries the names. `references/unity-runtime.md` covers identifying which one you
|
||||
have, dumping the pair with Il2CppDumper, importing the result into IDA in the order that works, and
|
||||
the Frida bridge for a run-time lookup.
|
||||
- **A Unity UI is drawn by the engine, so Java hooks are glue.** The Android layer is SDKs, permissions
|
||||
and the launch Activity; the gate you are looking at is a C# method. Patching the dex to remove it is
|
||||
the layer error this file opens with.
|
||||
- **`Debugger.IsAttached` is a real anti-debug here.** A retail Mono runtime refuses a debugger
|
||||
connection at the VM level, which reads as "the game is protected" — `unity-runtime.md` §Debugging
|
||||
Mono at run time owns that path, and `ida-so-debugging.md` owns the native attach underneath it.
|
||||
- **The metadata can be encrypted while the `.so` is not, or the reverse.** Check each file's magic
|
||||
before concluding the dump failed; the two failures have different routes.
|
||||
|
||||
## LayaAir native (Conch) specifics
|
||||
|
||||
LayaAir's native shell is a recognisable shape: `lib/<abi>/liblayaair.so` plus `libv8*.so`, a
|
||||
`assets/scripts/` directory (`index.js`, `apploader.js`, `config.js`), an `assets/config.ini`,
|
||||
and a cache tree `assets/cache/https.__<host>_<path>/`. If those are present, the game logic is
|
||||
JavaScript and the engine is Conch, not a WebView.
|
||||
|
||||
- **Cache file names are content-addressed by path, not by content:** each relative path (leading `/`)
|
||||
is named `'%08x' % crc32(path)`. The same directory holds `allfiles.txt`, `filetable.txt`,
|
||||
`filetable1.txt`, `filetable.bin` and `assetsid.txt`.
|
||||
- **The game's logic is usually one plaintext compressed file:** `js/bundle.js`. Before reversing it,
|
||||
fetch `js/bundle.js.map` from the same CDN path if it exists — in the source's project it contained
|
||||
470 TypeScript source files, which is the source, not a reconstruction.
|
||||
- **DCC checksums are recomputed by the engine, not trusted from the table.** `filetable.txt` is a
|
||||
`ffeeffee 1` header, the assets id split over two lines, then one `fileid chksum` line per file.
|
||||
The checksum is XOR over 8-byte blocks of little-endian `uint32` words, with the remaining 0–7
|
||||
bytes XORed individually. The source matched 8,940 of 8,943 files. The engine recomputes it from the
|
||||
file's content; a mismatch makes it re-download, so offline it fails with
|
||||
`JsAppCache::loadCachedURL Error, no cache data` or `Load start url error`.
|
||||
- **Do not copy the CDN's file table.** The source found its values inconsistent with the file contents
|
||||
(same content, different checksum). Recompute every checksum from the bytes you are shipping and
|
||||
regenerate all four metadata files, then `bundle.js` can be edited freely.
|
||||
- **The loader is plain JS and lives outside the cache** (`index.js` under `assets/scripts/`). It calls
|
||||
`updateDcc()`; offline that fails and, if a cached id exists, the app exits with
|
||||
`onLayaInitError`. Patch the loader to skip the update but **re-create the side effect it had**:
|
||||
`cache.setResourceID('appurl', urlpath)`. Then keep a delay of roughly three seconds before
|
||||
starting: in the source, the network update had been hiding a startup race, and an instant start
|
||||
crashed in `JCScriptRuntime::dispatchLayaGLBuffer` on the GL thread (x86 and arm), with or without
|
||||
any offline JS module. Prove it with a control build that contains only the loader patch.
|
||||
- **`loadLib()` is asynchronous.** A hook installed before `loadLib('js/bundle.js')` returns sees no
|
||||
`Laya` object; poll until the engine exists, then install the hook.
|
||||
- **A local module is loaded by `require("offline_server")`**, which Conch resolves from
|
||||
`assets/scripts/`, the same way the game's own modules load.
|
||||
|
||||
**Failure shape to remember:** one uncaught exception in a Laya render callback freezes the game,
|
||||
because the main loop is `requestAnimationFrame(loop)` and an exception stops the next frame. The
|
||||
symptom is a frozen or black screen while the debug channel still answers; the check is
|
||||
`Laya.timer.currFrame` not increasing. Wrapping `Laya.stage._loop` in try/catch is a diagnostic
|
||||
guard, not a fix for the underlying null asset. Mocked XHR responses can also poison a pooled
|
||||
`HttpRequest` instance — clear the own properties you defined in `open()` or every later request
|
||||
on that instance fails instantly. These are engine-side behaviours from the source's case, not
|
||||
measured here.
|
||||
|
||||
## Locating logic without symbols
|
||||
|
||||
- **Strings first.** User-visible text (dialog bodies, feature labels) is the cheapest anchor in any
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
# Attaching a real debugger: IDA's remote server, and the handshake that releases the app
|
||||
|
||||
Load this when Frida is the wrong instrument — you need to single-step, read registers at a fault, or
|
||||
set a breakpoint inside a `.so` and inspect the stack — and the target is debuggable or you can make
|
||||
it so. `dynamic-frida.md` owns hooking; `hardware-watchpoints.md` owns observation with no debugger
|
||||
attached at all; this file owns the debug-server route and the two preconditions that decide whether
|
||||
it works.
|
||||
|
||||
**Claim strength.** Absorbed from three public walkthroughs (2024-07, plus a MuMu-emulator note and
|
||||
a 2026 Unity session), all against CTF apps that were already debuggable, and none reproduced here.
|
||||
The debugger-side signal policy in §8 is one source's account, `unverified`. Commands on which the
|
||||
sources agree are stated plainly; the single-source details are marked *unverified*; anything this file adds
|
||||
as judgement is marked *inferred*.
|
||||
|
||||
## 1. Two manifest facts decide everything
|
||||
|
||||
- **`android:debuggable="true"`** — without it the app cannot be started in wait-for-debugger mode and
|
||||
`run-as` does not exist. A retail build needs a repack (`repack-and-sign.md`) or a
|
||||
`ro.debuggable` override on a rooted ROM (`magisk resetprop ro.debuggable 1`, then `stop; start`).
|
||||
The override is **global and persistent** — every app on the device becomes debuggable — so it is a
|
||||
fallback for your own analysis device, never part of a deliverable.
|
||||
- **`android:extractNativeLibs="true"`** — this one is not about permissions. It decides whether the
|
||||
`.so` exists as a file on disk, which is what a debugger needs; §5 below is the failure it causes.
|
||||
|
||||
Read them from `apktool d` → `AndroidManifest.xml`, or `aapt dump xmltree app.apk AndroidManifest.xml`.
|
||||
On a split package check the base member, not the last file you opened (`split-apk.md`).
|
||||
|
||||
## 2. Match the server to the ABI that is actually loaded
|
||||
|
||||
IDA ships one debug server per ABI under `dbgsrv/`. The library's directory decides which: a target in
|
||||
`lib/arm64-v8a/` wants the arm64 server, one in `lib/x86_64/` wants the x86-64 server. A mismatch is
|
||||
reported **when the server starts** ("expected X but Y"), not when you attach — so read the server's
|
||||
first line instead of interpreting a silent attach later.
|
||||
|
||||
```bash
|
||||
adb push <ida>/dbgsrv/android_x64_server /data/local/tmp/android_x64_server
|
||||
adb shell
|
||||
su
|
||||
chmod 755 /data/local/tmp/android_x64_server
|
||||
```
|
||||
|
||||
The write-up uses `777`; `755` is sufficient when the file is owned by the shell user and the server runs
|
||||
as root (*inferred*). Two mechanical traps it records: `\` and `/` are not interchangeable in the push
|
||||
path, and the file keeps the name you gave it on the destination side — the later
|
||||
`./<name>` must match that, not the source filename. `/data/local/tmp` is the only location an
|
||||
unprivileged `adb push` can write and a root shell can execute without SELinux complaints on most
|
||||
builds.
|
||||
|
||||
## 3. Run it as root, forward the port, and leave it running
|
||||
|
||||
```bash
|
||||
adb forward tcp:23946 tcp:23946 # IDA's default debug-server port
|
||||
/data/local/tmp/android_x64_server # in the root shell from §2
|
||||
```
|
||||
|
||||
Start the server **as uid 0**. A server running as the shell user can only see its own processes, so
|
||||
the target is simply absent from IDA's attach list — the recorded symptom is "the list is empty or has
|
||||
one entry that is not the app". Keep that terminal open: killing it detaches every session.
|
||||
|
||||
## 4. Start paused, then release the app
|
||||
|
||||
```bash
|
||||
adb shell am start -D -n <pkg>/.MainActivity
|
||||
```
|
||||
|
||||
`-D` starts the process **suspended, waiting for a debugger**. Attaching from IDA alone does not
|
||||
resolve that wait, because what the process is waiting for is the *JDWP* handshake, not the remote
|
||||
debug server. That is why the app appears frozen and why breakpoints "never fire": no code is
|
||||
executing yet. Forward a second port and connect the JDWP client:
|
||||
|
||||
```bash
|
||||
adb shell ps | grep <pkg> # or: adb jdwp / frida-ps -U
|
||||
adb forward tcp:8700 jdwp:<pid>
|
||||
jdb -connect com.sun.jdi.SocketAttach:hostname=127.0.0.1,port=8700
|
||||
```
|
||||
|
||||
Use a high port (the write-ups recommend 5000–10000) so it does not collide with 23946, and use the
|
||||
pid of the **app** process, not of the debug server. IDA → Debugger → Attach to process now, with the
|
||||
remote host set to `127.0.0.1` and port `23946`. Suspending on process entry, on thread start/exit and
|
||||
on library load/unload is worth enabling before the first run: without it, an early breakpoint in a
|
||||
library constructor is already behind you when the process stops.
|
||||
|
||||
## 5. "The breakpoint will not bind": the `.so` was never extracted
|
||||
|
||||
**Symptom.** The process runs, IDA lists and attaches to it, the module list has no `libtarget.so`, and
|
||||
every breakpoint set in it is refused or never hits. Nothing in logcat. The library is plainly loaded —
|
||||
the feature it implements works.
|
||||
|
||||
**Root cause.** `android:extractNativeLibs="false"` means installation leaves the library inside
|
||||
`base.apk` and the loader maps it from there. There is no
|
||||
`/data/app/<pkg>-<hash>/lib/<abi>/libtarget.so` for the debugger to name, so breakpoint resolution has
|
||||
nothing to bind to. `pm path <pkg>` names the APK's directory; `ls` beside it finds no `lib/` at all.
|
||||
The mapped region is backed by the APK, which is the same shape as the "an `r--s` view of `base.apk`
|
||||
looks like a dex" case in `advanced-unpacking.md` — the file on disk is not the thing in memory.
|
||||
|
||||
**Two fixes.**
|
||||
|
||||
1. Repack with `android:extractNativeLibs="true"`. The install then lays the libraries out under
|
||||
`lib/<abi>/`, and every debugger names them normally. It changes the signing certificate, so a
|
||||
signature check turns this into the `signature-derived-keys.md` problem.
|
||||
2. Keep the original package and give the loader the on-disk copy it prefers. `pm path <pkg>` to find
|
||||
the install directory, then push the matching `.so` into
|
||||
`/data/app/<pkg>-<hash>/lib/<abi>/` as root (create the directory if absent). The recorded result is
|
||||
that the app then loads the file instead of the in-APK copy. Whether a *hardened* build still
|
||||
prefers it, and whether its own integrity check notices the extra file, is *unverified* — verify
|
||||
both before building a plan on it.
|
||||
|
||||
**What not to do.** Pointing IDA at the `.so` extracted from the APK and calling that "the module" is
|
||||
the trap that wastes the session: the addresses in that file are the ones the process never mapped, so
|
||||
a breakpoint that *does* set lands on a copy of the code rather than the code.
|
||||
|
||||
## 6. Prove the channel before blaming the target
|
||||
|
||||
Set one breakpoint in a library that certainly executes early — `libc`'s `open`, the ART loader — and
|
||||
resume. If it hits, the channel is good and a non-hitting breakpoint in the target is about the target
|
||||
(never loaded, different copy, inlined, or anti-debug). If it does not hit, the fault is in setup:
|
||||
server uid, ABI mismatch, or a JDWP wait that was never released. This is the same control-run
|
||||
discipline as `long-task-discipline.md` §single-variable discipline, applied to the debugger itself.
|
||||
|
||||
## 7. What this route cannot hide
|
||||
|
||||
- `TracerPid` in `/proc/self/status` is non-zero for as long as you are attached, so any check that
|
||||
reads it sees you (`detection-and-anti-analysis.md`).
|
||||
- The server binary is a file with a known name in `/data/local/tmp`, and a process whose parent is a
|
||||
root shell is visible in `ps`.
|
||||
- Software breakpoints are written into executable pages; a checksum over a mapped library catches them
|
||||
(`byte-level-patching.md`). For observation with no writes, use `hardware-watchpoints.md`.
|
||||
- `am start -D` is visible to the platform and puts the process in a debuggable state that the app can
|
||||
query, so "the app behaves differently only while I debug it" is a real observation, not a mistake.
|
||||
|
||||
## 8. Stops that are the debugger's, not the target's
|
||||
|
||||
Most "the target crashed" observations in a debug session are properties of the debugger's own
|
||||
settings. Three that cost a whole session:
|
||||
|
||||
- **A platform signal is not target logic.** A Unity-backed app under IDA repeatedly stops on
|
||||
`SIGPWR`/`SIGXCPU`-class signals it never handles, because the platform raises them and the app
|
||||
ignores them. With the default *suspend on this signal* the pause **is** the crash: the process is
|
||||
stopped somewhere it cannot make progress, the watchdog or runtime aborts, and the abort takes IDA
|
||||
down with it. Set those signals to *pass to application* (report on log or silent). After that the
|
||||
same signal costs a log line instead of a session, and the only thing that changed was your
|
||||
debugger.
|
||||
- **One database per activity.** Attaching and detaching from the database you used for static
|
||||
analysis tends to hang on exit or leave it unusable — and the annotations are the expensive part.
|
||||
Copy the database (or keep a separate debug-only one) and leave the static one read-only.
|
||||
- **Interacting with a paused process is input injection.** Clicking around the app while it is
|
||||
stopped delivers real input into the frozen process and reproduces the same hang/crash class.
|
||||
Resume, then interact; do not "help" a suspended app.
|
||||
|
||||
Nothing here is about anti-debug: if the process dies while it is *stopped*, suspect the debugger's
|
||||
signal policy before suspecting the target.
|
||||
|
||||
## 9. Boundary
|
||||
|
||||
All three sources are emulator or AVD walkthroughs on CTF apps with `debuggable` already set; none
|
||||
exercised a hardened target, and this record did not run the route at all. `unverified`: the exact
|
||||
`dbgsrv` filenames per IDA release, the `chmod` mode, the debugger menu labels across 7.x and 8.x, and
|
||||
whether an on-disk `.so` outranks the in-APK copy on a hardened build. What would make the route
|
||||
`observed`: one breakpoint hit and one register read at a known function, on a package whose only
|
||||
modification is the manifest.
|
||||
@@ -0,0 +1,322 @@
|
||||
# IL2CPP when the metadata is not a readable file
|
||||
|
||||
Load this when a Unity package is IL2CPP but the usual pair is not usable: `global-metadata.dat` is
|
||||
0 bytes, absent, has the wrong magic, carries a custom container, or Il2CppDumper rejects the
|
||||
`libil2cpp.so` it came with. This file owns getting *a* parseable metadata image and *a* dumpable
|
||||
`.so`; `unity-runtime.md` owns backend identification, the normal dump, the IDA import order and
|
||||
the runtime bridge. Load that first if the pair is plainly readable.
|
||||
|
||||
**Claim strength.** Absorbed from eight public write-ups (2024-2026) and not reproduced here: no
|
||||
Unity package was decrypted, dumped or re-imported in this record. Every offset, magic value and
|
||||
tool behaviour below is `unverified` until you reproduce it on your sample; the *ordering rules*
|
||||
(which anchor to read, which layer to attack, what a failure means) are `inferred` from those
|
||||
sources. Nothing here is a measurement. Where a number identifies one sample rather than a format,
|
||||
the text says "one sample" and you must not carry it to another build.
|
||||
|
||||
## 1. Triage: four shapes that all look like "encrypted metadata"
|
||||
|
||||
Before choosing a route, decide which shape you have. They need different work, and retrying the
|
||||
same dumper is the wrong response to three of the four.
|
||||
|
||||
| Observation | Shape | First move |
|
||||
|---|---|---|
|
||||
| File is 0 bytes, or absent, while the game clearly runs | metadata is supplied from memory, a PE resource, or an appended blob | find the consumer, read its output pointer (§2) |
|
||||
| File exists, `xxd -l 4` is not `af 1b b1 fa` | encrypted or wrapped container | identify the cipher shape (§3) |
|
||||
| Magic is right, but the dumper reports a version and then produces garbage fields | version field lies, or the layout is spliced | treat the version as a claim, validate the struct (§5) |
|
||||
| `libil2cpp.so` is present, but every registration search returns 0 | protected/repacked `.so`, or the wrong module is mapped | dump the live image (§4) |
|
||||
|
||||
Two cheap checks come before any reverse engineering:
|
||||
|
||||
```bash
|
||||
xxd -l 16 assets/bin/Data/Managed/Metadata/global-metadata.dat # 0xFAB11BAF
|
||||
xxd -l 16 lib/arm64-v8a/libil2cpp.so # 7f 45 4c 46
|
||||
```
|
||||
|
||||
A correct magic proves the first 4 bytes only. A file can pass that check and still carry an
|
||||
encrypted string blob, a wrong header size field, or a custom program table (§3, §5). Conversely,
|
||||
a zeroed magic does not prove the file is encrypted: one shipping build wipes magic and version and
|
||||
embeds the metadata in the `.so` with the rest of the header intact.
|
||||
|
||||
**A 0-byte metadata file is a positive finding, not a missing file.** It means the build does not
|
||||
use the file at all, so a static decryptor has nothing to decrypt. Look for the loader's output.
|
||||
|
||||
### 1.1 A rebuilt `libil2cpp` announces itself in the ELF tables
|
||||
|
||||
One build's own triage script flags three things before it parses anything: a `JNI_OnLoad` export, a
|
||||
`DT_INIT`/`init_array` of the library's own, and an `SHT_LOUSER` section. None of the three is
|
||||
something the engine's build path needs, so any of them is a candidate added step — read them as
|
||||
heuristics, where a false positive costs one `readelf`:
|
||||
|
||||
```bash
|
||||
readelf -sW libil2cpp.so | grep -i jnionload
|
||||
readelf -dW libil2cpp.so | grep -Ei 'INIT|FINI'
|
||||
readelf -SW libil2cpp.so | grep -w LOUSER # a section type, not a name
|
||||
```
|
||||
|
||||
`JNI_OnLoad` means the library wants a JVM-side entry point, which is a JNI-sinking or loader shape
|
||||
rather than something the engine itself calls through. An own `DT_INIT`/`init_array` is the earliest
|
||||
place arbitrary code can run. `SHT_LOUSER` is a section the
|
||||
linker reserves for the application — a convenient place to park a payload, and a common marker in
|
||||
this family. Read these tables **before** hunting ciphertext: the injected entry is where metadata and
|
||||
code are decrypted, and it is also what a dumper's "this file may be protected" refusal is reacting to.
|
||||
Then continue at §2 and anchor on the consumer rather than the file.
|
||||
|
||||
## 2. Anchor on the consumer, not the path
|
||||
|
||||
The reliable address is the pointer *after* decryption and de-obfuscation. Two anchors exist, and
|
||||
they are not interchangeable:
|
||||
|
||||
- `il2cpp::vm::MetadataLoader::LoadMetadataFile` — the function that returns the metadata base.
|
||||
Its return value (or the global it stores into) is the plaintext image.
|
||||
- `il2cpp::GlobalMetadata::Initialize` — a second entry point some builds use for a custom
|
||||
decrypt-and-validate step. One write-up wasted a diffing pass inside `LoadMetadataFile` before
|
||||
finding the cipher in `GlobalMetadata::Initialize`.
|
||||
- `il2cpp::utils::MemoryMappedFile::Map` — the file-mapping layer. A `jmp` from here into a
|
||||
non-standard section is a signal that the mapping was replaced by a custom loader.
|
||||
|
||||
Procedure:
|
||||
|
||||
1. Find the metadata path string (`global-metadata.dat`) and its xrefs. The consumer is usually
|
||||
one or two calls away.
|
||||
2. Diff the function against the matching upstream `libil2cpp` source tag. A short added loop over
|
||||
the mapped buffer is the decryption, stated in the open.
|
||||
3. Hook the *return* of the loader, or read the global it writes after the call. Do not hook the
|
||||
`open`/`mmap` path: that is the ciphertext.
|
||||
4. Dump `[base, base + size)` using the size rule in §2.1 rather than a guessed length.
|
||||
|
||||
### 2.1 Sizing a header whose fields you do not trust
|
||||
|
||||
The metadata header is an array of 64 `int32` values. For a version whose tail counts are unknown,
|
||||
walk backwards from `0x10C` in steps of 8:
|
||||
|
||||
```text
|
||||
i = 0x10C
|
||||
count = read_i32(base + i)
|
||||
offset = read_i32(base + i - 4)
|
||||
if count != 0: size = offset + count; stop
|
||||
i -= 8
|
||||
```
|
||||
|
||||
This works when magic and version are zeroed, and it survives a version mismatch because it uses
|
||||
only offset/count pairs that are still laid out in the same order. (`observed`, host: on a synthetic
|
||||
header whose magic and version are zeroed and whose tail counts are zero, the walk returns the true
|
||||
length `0x1140` while a fixed mid-header pair returns `0x1098`; see
|
||||
`docs/tool-verification/fixtures/verify_ref_claims_10c.py`.) Bound the loop (for example
|
||||
`i > 0`), wrap reads in the platform's fault handler on Windows, and treat a non-monotone result as
|
||||
"this is not the header you think it is", not as a size.
|
||||
|
||||
### 2.2 Metadata outside the filesystem
|
||||
|
||||
Three placements recur:
|
||||
|
||||
- **PE resource, located by a hashed logical name.** One loader hashes the requested name with two
|
||||
accumulators (an FNV-1a-style `hash *= 0x1000193; hash ^= byte` and a roll
|
||||
`hash = hash*0x83 + byte`), combines them into a 64-bit key, and compares against constants that
|
||||
map to a resource id. It then calls `FindResourceA(hModule, id, "CFG")`, `SizeofResource`,
|
||||
`LoadResource`, `LockResource`. The hash table is small and reimplementable offline with
|
||||
`pefile`; once the resource is extracted, the container cipher decides the next step.
|
||||
- **Appended or embedded in `libil2cpp.so`.** No separate file, and no section name that announces
|
||||
itself. Find the offset from the loader's pointer arithmetic, then cut the blob from the mapped
|
||||
image rather than from the file if the loader applies a relocation-relative offset.
|
||||
- **A non-standard section reached by a `jmp`.** The entry stub replaces the mapping function; the
|
||||
payload lives in a section whose name is product-specific. Treat it as a custom container, not as
|
||||
ELF data, and use the loader's own parse order.
|
||||
|
||||
## 3. Container and cipher shapes worth trying first
|
||||
|
||||
Do not begin by assuming AES. Public Unity protections in this set are dominated by cheap,
|
||||
self-describing transforms, and each has a diagnostic that distinguishes it from "real crypto".
|
||||
|
||||
### 3.1 Whole-file repeating-key XOR
|
||||
|
||||
The most common shape: after the mapping call, a loop does
|
||||
|
||||
```c
|
||||
for (i = 0; i < mapped_size; i++)
|
||||
mapped[i] ^= key[i & 0x7F]; // 128-byte table, index masked
|
||||
```
|
||||
|
||||
Look for `^=` on the mapped buffer in the loader diff. The key is often a fixed byte table in
|
||||
`.rodata`, not a derived secret. Extraction is mechanical: copy the table, apply it to the file,
|
||||
check for `0xFAB11BAF`. If the file grows by a few bytes between versions, do not assume the same
|
||||
key or the same offset; re-diff.
|
||||
|
||||
### 3.2 Custom magic plus a bytecode VM
|
||||
|
||||
One family wraps the header in a container with its own magic (`0x1357FEDA` in one sample) and a
|
||||
program table, then runs a 255-case `switch` over the body. Each case computes an index into the
|
||||
destination and applies one of: XOR with an immediate, add, subtract, byte swap, or rotate by a
|
||||
key byte masked with 7. The layout in that sample was: magic at 0, length at 4, header at 8,
|
||||
program at `0x108` (64 bytes), data at `0x148`, and the plaintext began 8 bytes into the
|
||||
decrypted region.
|
||||
|
||||
The generalisable part is not the opcode set; it is that **the VM is a dispatcher over a
|
||||
self-describing container**. Dump the program table, name each case by its effect, and replay the
|
||||
program in Python. Do not single-step the VM instruction by instruction in a debugger; the table
|
||||
is the specification.
|
||||
|
||||
**Read the call site before replaying, because the schedule decides what a unit test is.** One build
|
||||
runs the interpreter once per fixed-size block — `apply(program, 0x40, table, out + i, min(0x40,
|
||||
remaining))` in a loop — with the same constant table re-passed on every call and no state carried
|
||||
between them. That makes one block a complete test: decrypt block 0, check the result against the
|
||||
plaintext you already know it must contain (a magic, or the first string), and only then run the rest.
|
||||
If the call site instead updates a context between iterations, the blocks are chained: no per-block
|
||||
shortcut exists, replay must start at 0, and a mismatch at block 7 is a key/program error you cannot
|
||||
localise by looking at block 7. The truncated tail is also worth reading explicitly, because a tail
|
||||
handled as a full block shifts everything after the last boundary.
|
||||
|
||||
### 3.3 XXTEA with a length word
|
||||
|
||||
A resource-container sample used XXTEA: `delta = 0x9E3779B9`, `rounds = 6 + 52/n`, decrypt from
|
||||
the tail, key a short ASCII string zero-padded to 16 bytes. The plaintext length was stored in the
|
||||
**last 32-bit word** and accepted only when it fell in `[total-7, total-4]`. Check that range before
|
||||
trusting a decrypted buffer; a wrong key usually fails it.
|
||||
|
||||
### 3.4 Length-derived string ciphers
|
||||
|
||||
String literals are often encrypted separately from the header (and may be the only encrypted
|
||||
region). Two shapes recur:
|
||||
|
||||
- A single-byte key derived from the literal length, for example `key = length ^ 0x2E` applied to
|
||||
every byte. Long literals may use a vectorised bulk path and short ones a scalar path; both must
|
||||
produce the same byte-wise result.
|
||||
- A key derived from counters that are recoverable from the method body, such as
|
||||
`ilLength * exceptionClauseCount * localVarCount` duplicated into a 64-bit value and rendered as
|
||||
a decimal string. This appeared in a HybridCLR Interpreter build.
|
||||
|
||||
Try length-derived key material before attacking the cipher. It is cheap, and it explains why a
|
||||
generic XOR brute force finds nothing.
|
||||
|
||||
## 4. A live image is the fallback, and it is usually cheaper
|
||||
|
||||
When the metadata and the `.so` are both protected per version, reimplementing the loader is more
|
||||
work than dumping the process. The constraint is that the dump must be *the image the process
|
||||
mapped*, not the file on disk.
|
||||
|
||||
1. Read `/proc/<pid>/maps` and take the **second** mapping of `libil2cpp.so`. The first is the
|
||||
file-backed, still-encrypted view; the second is the anonymous/decrypted image. Dumping the
|
||||
first produces a file that looks plausible and fails every registration search.
|
||||
2. Record the mapping base. Dump the whole mapping to a file.
|
||||
3. Run Il2CppDumper on the dump **with the base address** when auto-detection fails. On one sample
|
||||
the base `0x7ad74c3000` produced `CodeRegistration 0x7ad85254d0` and
|
||||
`MetadataRegistration 0x7ad856ff38`; those offsets are sample-specific.
|
||||
4. If the metadata was decrypted in place at load, dump metadata from the same process as well:
|
||||
comparing the APK file with the memory image is how the in-place transform is proved.
|
||||
|
||||
The dump loses section headers and dynamic symbols. A disassembler will open it and show no
|
||||
symbols; that is an ELF-metadata problem, not a bad dump.
|
||||
|
||||
### 4.1 Repairing the dumped ELF
|
||||
|
||||
Set, for every program header:
|
||||
|
||||
```text
|
||||
p_offset = p_vaddr
|
||||
p_filesz = p_memsz
|
||||
```
|
||||
|
||||
The end of the last `PT_LOAD` is the original section-header offset. In one sample the eleventh
|
||||
program header ended at `0x13BC000 + 63352 = 0x13CB778`, and that value belonged in `e_shoff`;
|
||||
that arithmetic is the reusable part, not the address.
|
||||
|
||||
Then:
|
||||
|
||||
- `e_shstrndx` names a section whose `sh_addr` is 0 because it is not file-resident. Find the
|
||||
neighbouring section with the same `sh_offset` and a valid `sh_addr`; copy that address over the
|
||||
broken field.
|
||||
- Set every section's `sh_offset = sh_addr`.
|
||||
- Copy the section-header bytes into the file if they were not dumped, then re-analyse.
|
||||
- Rebase the database to the dump's load address **before** importing headers or scripts.
|
||||
|
||||
After repair, import the IL2CPP tables in the order `unity-runtime.md` §4 gives. Running the
|
||||
struct script twice (once with `script.json` + `il2cpp.h`, once with `stringliteral.json`) is the
|
||||
order that names both functions and literals.
|
||||
|
||||
## 5. When the version field lies
|
||||
|
||||
A header can say version 31 while its tail is a long run of zeros and it lacks the fields that
|
||||
version introduced. In one build, three separate failures traced to one integer:
|
||||
|
||||
- The dumper auto-located `CodeRegistration` at a wrong address; setting it manually was required.
|
||||
- Metadata claimed 31, but the struct was a 29 layout; patching the version constant to 29 made the
|
||||
dumper proceed.
|
||||
- A `methodDef` parse failed because one field was read at `+0x20` where the build used `+0x24`.
|
||||
Lowering the version constant in the dumper source fixed the stride.
|
||||
- A large `libil2cpp.so` can make `genericMethodPointersCount` look like a 29.1 layout even when the
|
||||
version was already forced to 29; force the constant in the dumper rather than accepting the
|
||||
heuristic's label. Size is not a version.
|
||||
|
||||
**The version integer is a claim; the struct layout is evidence.** Validate a candidate layout by
|
||||
plausibility: string offsets inside the file, counts that fit the remaining bytes, section tables
|
||||
that are monotone, and a first string that is a real identifier (`mscorlib` is a useful landmark).
|
||||
Do not "upgrade" a dump because the version says so.
|
||||
|
||||
A related trap: after a successful dump, only one region may be wrong. If the string blob's first
|
||||
entry is garbage while the rest of the header is coherent, the blob is decrypted in place at load
|
||||
(§4); do not discard the whole metadata image.
|
||||
|
||||
## 6. String literals: index space, encoding, re-import
|
||||
|
||||
When only literals are encrypted, the header arithmetic is stable:
|
||||
|
||||
- entry size is `8` bytes: `<int32 length, int32 dataIndex>`;
|
||||
- entry `i` is at `stringLiteralOffset + i*8`;
|
||||
- the bytes are at `stringLiteralDataOffset + dataIndex`, `length` bytes;
|
||||
- the count is `stringLiteralSize / 8`.
|
||||
|
||||
The recovered value is UTF-8 in the metadata, but the runtime `Il2CppString` is UTF-16LE. When
|
||||
hooking `il2cpp::vm::String::NewLen`, convert UTF-16LE to UTF-8 **before** writing back, or the
|
||||
re-imported metadata is silently corrupt and the dumper still accepts it.
|
||||
|
||||
Dump `index,hex` to CSV, decrypt offline, patch the metadata file, then re-run Il2CppDumper. This
|
||||
keeps the proof in one place: the tool either parses the patched file or it does not.
|
||||
|
||||
**When the literal cipher lives inside the protected VM, do not reverse it — drive the runtime.**
|
||||
`String::NewLen(ptr, len)` *is* the decryption oracle, and it takes exactly the two fields the literal
|
||||
table stores. Enumerate `i` from 0 to `count-1` yourself, read `(dataOffset + dataIndex, length)`, call
|
||||
the runtime entry for each, and collect the returned UTF-16 buffers. Three properties make this better
|
||||
than either hooking natural calls or reimplementing the cipher: it is exhaustive rather than a sample
|
||||
of what the app happened to load, it is a completeness proof for the table (every index either
|
||||
decrypts or visibly fails), and it keeps you out of the VM. The cost is that the process must be
|
||||
alive and past metadata init, so it is the wrong route when the question is what a dead sample
|
||||
contains.
|
||||
|
||||
## 7. Adjacent artifacts that fail the same way
|
||||
|
||||
These are not metadata, but they are the next files the same build protects, and the diagnostic
|
||||
shape is shared.
|
||||
|
||||
- **AssetBundle header patched by the engine.** One build reports a fabricated Unity version
|
||||
(suffix `p1`) and XORs the first 32-bit field of each block and each directory node's size with
|
||||
`0x1024`. The fix is in the reader (AssetStudio), not in the bundle: apply the same XOR before
|
||||
parsing.
|
||||
- **Repeating-key XOR over bundles.** With one plaintext sibling, XOR the two headers to recover
|
||||
the 16-byte key. Only the first few tens of KB need decrypting for the tooling to accept the
|
||||
file; the body can stay encrypted until an asset is actually needed.
|
||||
- **Byte-inversion AssetBundle wrapper.** A custom `Stream` skips 4 bytes and inverts the next 5,
|
||||
then a second wrapper inverts bytes 0..4 of every 8-byte block, applied only to the 128-byte
|
||||
header. Script it as a header transform; do not invert the whole file.
|
||||
- **CRC32-named paths and blend shapes.** Names in animation data are CRC32 of the full path,
|
||||
displayed as bare integers. Recover the prefix from uncompiled sources or the middleware's SDK,
|
||||
then build the name→CRC map. A hash is not encryption, but without the prefix it is not a name.
|
||||
|
||||
## 8. Order of attack
|
||||
|
||||
1. Decide the shape (§1).
|
||||
2. If the metadata is file-resident and cheaply wrapped, decrypt statically (§3) and validate the
|
||||
magic and the first string.
|
||||
3. If the loader is per-version or the file is absent, dump the consumer's output and the second
|
||||
`.so` mapping (§2, §4).
|
||||
4. Repair the ELF only if a disassembler must consume the dump (§4.1).
|
||||
5. Validate the metadata version against the struct before trusting any field (§5).
|
||||
6. Recover literals last, and re-import them into the tool that must parse the result (§6).
|
||||
|
||||
## 9. Boundary
|
||||
|
||||
Every procedure here stops at a dependency you must supply: a device that can run the game, a
|
||||
dumper version that matches the metadata layout, or the loader's own container format. None was
|
||||
exercised in this record. The steps that would make a row `observed`: decrypt one file and show
|
||||
the magic and first string, dump one live image and show a named function in the disassembler, and
|
||||
re-import one literal table and show the dumper accepting it. Until then, treat the offsets as
|
||||
examples, not as constants, and do not present a repaired dump as a working target without running
|
||||
the feature it belongs to.
|
||||
@@ -0,0 +1,256 @@
|
||||
# Loading, dumping and repairing a protected `.so` at the linker level
|
||||
|
||||
Load this when a custom loader or packer sits between the APK and a usable native image: an
|
||||
unpacked `.so` will not `dlopen`, a dump validates as ELF but crashes on load, a repaired
|
||||
`soinfo` points at garbage, or you need to know *where* in the load pipeline it is safe to take a
|
||||
dump. `native-and-so.md` owns patching and which library is actually loaded;
|
||||
`code-virtualization-and-custom-linkers.md` owns recognising the loader and the keep-it/drop-it
|
||||
deadlock; `advanced-unpacking.md` owns the dump routes above this layer. This file is the linker
|
||||
contract those files assume.
|
||||
|
||||
**Claim strength.** The load/link pipeline and field layouts are absorbed from two public
|
||||
source-reading write-ups (Android 5.0 and 8.x `bionic/linker`) and one Frida cookbook; no loader
|
||||
was reimplemented and no dump was produced here. Source citations are `unverified` against your
|
||||
tree until you open the matching AOSP tag. The *arithmetic* (bias, page offset, relocation target)
|
||||
is `inferred` from that source and should be checked with one control load before it is trusted.
|
||||
The `soinfo` offsets quoted below are explicitly version-specific and are examples, not constants. The dump-window and reader rules in §6.2–6.3 were added 2026-10 from a write-up
|
||||
on a dual-library commercial shell; they are `unverified` operating rules, not measurements.
|
||||
|
||||
## 1. The pipeline, as a specification for a loader
|
||||
|
||||
A loader must reproduce what `bionic` does without assuming a filesystem-backed file. The chain,
|
||||
with the units that matter:
|
||||
|
||||
```text
|
||||
dlopen
|
||||
-> do_dlopen
|
||||
-> find_library
|
||||
-> find_library_internal
|
||||
-> find_loaded_library_by_soname (already loaded? return its soinfo)
|
||||
-> load_library
|
||||
-> ElfReader::Read ReadElfHeader / VerifyElfHeader
|
||||
ReadProgramHeaders / ReadSectionHeaders
|
||||
ReadDynamicSection
|
||||
-> ElfReader::Load ReserveAddressSpace / LoadSegments / FindPhdr
|
||||
-> soinfo_alloc link into the global soinfo list
|
||||
-> soinfo_link_image prelink + relocate
|
||||
-> CallConstructors dependencies first, then own init/init_array
|
||||
```
|
||||
|
||||
A custom loader that mirrors these eight calls is functionally a linker. That is why "the shell
|
||||
decrypts a `.so` and calls `dlopen` on the plaintext" is the easy case, and "the shell never
|
||||
writes a valid file" is the case that needs the field-level repair below.
|
||||
|
||||
`VerifyElfHeader` rejects: wrong magic, class mismatch, endianness, `e_type`, version != 1,
|
||||
machine mismatch. A packer that corrupts `e_ident` cannot rely on system loading at all, so it
|
||||
must carry its own loader. That is a useful diagnostic: if the file's header is deliberately
|
||||
invalid, look for a loader before trying to repair the file for `dlopen`.
|
||||
|
||||
`load_library` reads `DT_RUNPATH` and `DT_SONAME` from the dynamic array *before* `prelink_image`
|
||||
overwrites them from `PT_LOAD` data. A reimplementation that skips this loses the `soname` used by
|
||||
`find_loaded_library_by_soname`, and a second `dlopen` of the same library then loads a duplicate.
|
||||
|
||||
## 2. Address arithmetic that every repair depends on
|
||||
|
||||
### 2.1 Load size and bias
|
||||
|
||||
```text
|
||||
min_vaddr = min(p_vaddr for PT_LOAD)
|
||||
max_vaddr = max(p_vaddr + p_memsz for PT_LOAD)
|
||||
load_size = page_align_up(max_vaddr) - page_align_down(min_vaddr)
|
||||
load_bias = load_start - page_align_down(min_vaddr)
|
||||
```
|
||||
|
||||
For an ordinary shared object `min_vaddr == 0`, so `load_bias == load_start`. For a protected
|
||||
image with a non-zero first segment, the difference is exactly the bias. **Every** `vaddr` to
|
||||
runtime conversion adds `load_bias`, never the mapping base, and a repair that writes `base` where
|
||||
`bias` is required produces addresses off by the first segment's page.
|
||||
|
||||
### 2.2 Mapping one segment
|
||||
|
||||
```text
|
||||
seg_start = page_align_down(p_vaddr + load_bias)
|
||||
seg_end = page_align_up(p_vaddr + load_bias + p_memsz)
|
||||
file_page_start = page_align_down(p_offset)
|
||||
file_length = page_align_up(p_offset + p_filesz) - file_page_start
|
||||
mmap(seg_start, file_length, prot, flags, fd, file_page_start)
|
||||
```
|
||||
|
||||
For a memory-sourced payload the sequence is: reserve anonymous memory, then `memcpy` into
|
||||
`seg_start + seg_page_offset`, where `seg_page_offset = p_offset & (page_size - 1)`. Omitting
|
||||
`seg_page_offset` is the classic silent corruption: the segment is page-aligned on the file side
|
||||
but its first bytes belong at a non-zero offset inside the destination page.
|
||||
|
||||
## 3. Parse `DT_*` first; treat `soinfo` as volatile
|
||||
|
||||
The dynamic section is the stable ABI. `prelink_image` is a `switch(d_tag)` terminated by
|
||||
`DT_NULL`:
|
||||
|
||||
| Tag | Meaning | Address form |
|
||||
|---|---|---|
|
||||
| `DT_HASH` | SysV hash table: `nbucket`, `nchain`, `bucket[]`, `chain[]` | `load_bias + d_ptr` |
|
||||
| `DT_GNU_HASH` | GNU hash: `nbucket`, `symndx`, `maskwords`, `shift2`, bloom, buckets, chain | `load_bias + d_ptr` |
|
||||
| `DT_STRTAB` / `DT_STRSZ` | string table and size | pointer uses bias, size is a value |
|
||||
| `DT_SYMTAB` / `DT_SYMENT` | symbol table; `DT_SYMENT` must equal `sizeof(ElfW(Sym))` | pointer uses bias |
|
||||
|
||||
Both hash formats must be handled: a repaired `soinfo` that carries only the one the shell happens
|
||||
to use will fail `dlsym` for symbols that exist. `DT_GNU_HASH` validates that `maskwords` is a
|
||||
power of two and stores `maskwords - 1`. The symbol count is not stored in the GNU format; it is
|
||||
derived from the highest chain index, which is why "the symbol table looks one entry short" is a
|
||||
parse bug, not a stripped export.
|
||||
|
||||
## 4. Relocation rules and the two biases
|
||||
|
||||
| Type | Value written | Note |
|
||||
|---|---|---|
|
||||
| `R_*_RELATIVE` | `load_bias + addend` | no symbol |
|
||||
| `R_*_GLOB_DAT` | `sym_addr + addend` | data import |
|
||||
| `R_*_JUMP_SLOT` | `sym_addr + addend` | `bionic` processes it like a normal reloc; lazy binding is not a separate path |
|
||||
| `R_*_IRELATIVE` | `ifunc_resolver(load_bias + addend)` | may need temporary exec permission when the page is read-only |
|
||||
|
||||
Two addresses are in play and mixing them is the most common silent bug:
|
||||
|
||||
- the **definition**: `sym_addr = symtab[sym].st_value + defining_soinfo->load_bias`;
|
||||
- the **slot**: `write_addr = r_offset + caller_soinfo->load_bias`.
|
||||
|
||||
A symbol resolved from a dependency uses the *dependency's* bias. A relocation in the caller uses
|
||||
the *caller's* bias. They are equal only when both libraries loaded at the same base.
|
||||
|
||||
### 4.1 Packed relocations
|
||||
|
||||
If the table pointed to by `DT_ANDROID_REL`/`DT_ANDROID_RELA` begins with `"APS2"`, the body is
|
||||
SLEB128-packed and must be read with the packed-relocation iterator starting after the 4-byte magic. A loader that assumes
|
||||
plain `ElfW(Rel)` arrays produces a GOT full of garbage that still "looks like" relocated data.
|
||||
This is an easy accidental symptom after hand-writing a loader; check the tag's first four bytes
|
||||
before interpreting the table.
|
||||
|
||||
## 5. Repairing `soinfo` after an in-memory load
|
||||
|
||||
A loader that maps and relocates the payload still has to hand the result to the runtime. The
|
||||
minimal field set one write-up reports as sufficient:
|
||||
|
||||
```text
|
||||
base, size, load_bias
|
||||
sym_tab, str_tab
|
||||
nbucket, nchain, bucket, chain
|
||||
ARM_exidx, ARM_exidx_count
|
||||
```
|
||||
|
||||
The acquisition method is `dlopen(self, RTLD_NOW)` for the loader's own `soinfo`, then overwrite
|
||||
the fields with the protected image's values. Two cautions:
|
||||
|
||||
- **Offsets are version-specific.** One 64-bit example walked the global `solist` with `next` at
|
||||
`+40`, `name` at `+408`, `base` at `+16`, `size` at `+24`, `load_bias` at `+256`. Those
|
||||
numbers hold for one cited build. Resolve `solist` by symbol
|
||||
(`__dl__ZL6solist`) and take the layout from the matching AOSP tag, or use the `dlopen` handle
|
||||
instead of walking the list.
|
||||
- **A repair is not a load.** Overwriting `soinfo` makes symbols resolvable through the linker;
|
||||
it does not run constructors, apply `DT_NEEDED` dependencies, or register the image with the
|
||||
runtime's own bookkeeping. If the feature calls into the library before constructors would have
|
||||
run, it fails in a way that looks like a bad relocation.
|
||||
|
||||
## 6. Where it is safe to take a dump
|
||||
|
||||
The dump is valid only in the window where segments are mapped but relocation is not complete, or
|
||||
after relocation if you also record the bias. Four practical hook points:
|
||||
|
||||
1. **`mprotect`** — flag calls granting `PROT_EXEC` on a large range. The "allocate then make it
|
||||
executable" pattern is a stager. The same call is used offensively: skip the exec grant when a
|
||||
debugger is present, which is a reason a hook may see the allocation and not the execution.
|
||||
2. **`mmap`** — large file-backed mappings are likely the payload; anonymous large mappings are
|
||||
likely the decrypted image. Record `(addr, len, prot)`.
|
||||
3. **`ElfReader::LoadSegments` / the loader's segment-copy loop** — after the copy, before link
|
||||
fixups. This is the cleanest point because the image is complete and the loader's own state is
|
||||
still available.
|
||||
4. **The `soinfo` list** — enumerate every loaded object and record `base`, `size`, `load_bias`.
|
||||
This gives the dump bounds without knowing the packer, and it is version-portable if you resolve
|
||||
the list head by symbol.
|
||||
|
||||
Record the bias with the dump. A dump without its bias is only usable if you can recover the first
|
||||
segment's `p_vaddr` from the program headers and prove the alignment.
|
||||
|
||||
### 6.1 Anti-dump by header corruption
|
||||
|
||||
A shell may XOR selected `PT_LOAD` fields after loading (`p_vaddr`, `p_memsz`, `p_filesz`,
|
||||
`p_offset` with one constant) and restore them at use time. The dump then fails ELF validation
|
||||
even though the code is intact. Detect it with invariants rather than by guessing the constant:
|
||||
|
||||
- `p_vaddr` is page-aligned for a loadable segment;
|
||||
- `p_filesz <= p_memsz`;
|
||||
- `p_offset` is monotone across program headers and page-aligned in the usual way;
|
||||
- the first `PT_LOAD` covers the ELF header for a normal executable.
|
||||
|
||||
Test a candidate constant by applying it to all four fields and re-checking those invariants. A
|
||||
uniform XOR survives every check that looks at one field alone.
|
||||
|
||||
Deleting the header instead of XORing it is a weaker defence but a nastier symptom: the file is
|
||||
*cleanly* rejected, so the analyst blames the dump site. If the dump site is right and the header
|
||||
is missing, the correct conclusion is "the shell removed it", not "the dump was early".
|
||||
|
||||
### 6.2 The window can close inside `JNI_OnLoad`
|
||||
|
||||
The dump points above are ordered by *how much of the image exists*. A protector that modifies itself
|
||||
adds a second axis: *how long the process lives*. A shell that decrypts its own code in
|
||||
`JNI_OnLoad` (SMC) and starts watchdog threads from the same function leaves exactly one interval in
|
||||
which both hold — segments mapped, SMC not yet run. Dumping after `dlopen` returns is late twice
|
||||
over: the self-decryption has completed, and the watchdog is already armed by the time any
|
||||
post-return hook runs.
|
||||
|
||||
So: hook `android_dlopen_ext`, and dump in `onEnter` when the target path matches. Treat "the image
|
||||
is not relocated yet" as expected, and record the bias and relocation tables in the same pass
|
||||
(§2, §4). An unrelocated dump plus its bias is recoverable; an unrelocated dump without one is not.
|
||||
|
||||
A dump taken *inside* `JNI_OnLoad` is the worst of both: the code is complete, so the dump looks
|
||||
right, and the watchdog is up, so the process dies during the read. **If the target dies while you
|
||||
dump and only then, this is the shape — not a broken tool.**
|
||||
|
||||
**Claim strength.** The window itself — SMC completing *and* watchdogs starting inside the same
|
||||
`JNI_OnLoad` — is `unverified`: one write-up reports it and this record did not reproduce it. The
|
||||
placement rule (dump in `onEnter`, keep the bias) is `inferred` from the arithmetic in §2 and §4. The
|
||||
symptom is the source's report, also `unverified`.
|
||||
|
||||
### 6.3 Read with syscalls, and pad the holes
|
||||
|
||||
Two properties of the reader decide whether the dump is usable.
|
||||
|
||||
- **The reader must not travel through the library the protector hooks.** A shell that inline-hooks
|
||||
libc's `open`/`read`/`write` sees your dump as one more caller and can refuse or terminate. A
|
||||
raw-syscall reader (`svc #0` from a small stub, or a kernel-side reader) sits outside that
|
||||
surface. This is `advanced-unpacking.md` §"Layered descent" applied to your own tooling: the layer
|
||||
you read from is also the layer the target can watch. (`unverified` for the protector-hook claim;
|
||||
the layer rule it extends is `measured` there.)
|
||||
- **An unreadable page is a hole to fill, not a range to skip.** Skipping shifts every later byte
|
||||
and produces a file that repairs into a plausible ELF with missing logic. Zero-filling preserves
|
||||
offsets and sizes, so segment placement still works; record which ranges were unreadable so the
|
||||
repair can be audited. A dump is evidence, and "these ranges were unreadable" belongs in it.
|
||||
(`observed`, host: in a synthetic three-page image with one unreadable page, a marker meant for
|
||||
offset 8199 lands at 8199 when the page is zero-filled and at 4103 when it is skipped — see the
|
||||
EXTENSION record.)
|
||||
|
||||
Then repair the image with a tool that rebuilds what the loader would have written (program headers,
|
||||
dynamic table, section headers). The repair consumes a file whose *offsets* are right; that is what
|
||||
the zero-fill protects. (`inferred`: the offset/size argument above, not a repair run here.)
|
||||
|
||||
|
||||
## 7. Timing: constructors and one-shot registrations
|
||||
|
||||
`dlopen` does not return until `CallConstructors` has run the dependencies' constructors, then the
|
||||
library's `init`, then its `init_array`. Two consequences:
|
||||
|
||||
- A breakpoint on `do_dlopen` or `CallConstructors` catches unpacking before user code runs.
|
||||
- A hook installed after the library is already loaded misses every one-shot registration. A
|
||||
`RegisterNatives` table is walked once; spawn the process under instrumentation or gate on
|
||||
`dlopen`/`android_dlopen_ext`, and run the real hook in `onLeave` when the module is mapped.
|
||||
|
||||
The `dlopen` symbol name differs by Android version; hook both `dlopen` and
|
||||
`android_dlopen_ext`. A module that is mapped but not yet resolvable returns no base address, and
|
||||
that is a timing failure, not a missing module.
|
||||
|
||||
## 8. Boundary
|
||||
|
||||
This file describes the contract, not a working unpacker. Nothing here was compiled against a
|
||||
device's `linker` or used to load a real protected library. The steps that would make a row
|
||||
`observed`: load a trivial `.so` from memory with the arithmetic above, show one symbol resolved
|
||||
through the repaired `soinfo`, and dump one protected image at `LoadSegments` and open it in a
|
||||
disassembler with symbols. Until then, treat every offset as a lead and verify the bias with a
|
||||
control library that loads normally.
|
||||
@@ -159,6 +159,69 @@ terminate path is the end of the check; nothing downstream re-reads "did I die".
|
||||
rather than assuming: after a successful suppression the app must reach its **normal UI and stay
|
||||
there**, not loop through half-initialised states.
|
||||
|
||||
## Which site — and in what order
|
||||
|
||||
Patch sites are not interchangeable. Fixing the wrong one costs a day; fixing them in the wrong order
|
||||
costs the same day twice, because you cannot tell which change mattered. Sort the candidates first.
|
||||
|
||||
### One predicate may be deciding for all of them
|
||||
|
||||
Group the branches you found by the function whose return value they test. When every detector funnels
|
||||
into one `is_clean()`-shaped call, rewriting that return is the whole bypass: the kill sites are never
|
||||
reached, and the branches you did not enumerate are covered too.
|
||||
|
||||
Two conditions, both required:
|
||||
|
||||
- the function is a **decision** (returns a verdict), not the **action** (performs the kill). Patching
|
||||
an action changes the response; patching a decision changes the belief. The second is what makes a
|
||||
bypass stable.
|
||||
- you have checked its other callers. A predicate that also gates a feature will disable that feature
|
||||
once it always returns clean. Enumerate the callers before you touch it — the xref list in the
|
||||
disassembler, or the same caller enumeration `scripts/find_refs.py` does for dex methods.
|
||||
|
||||
(`unverified` that a given target funnels every detector through one predicate — that is the
|
||||
source's finding. The decision-versus-action rule is `inferred` from it.)
|
||||
|
||||
### Grade the sites by what being wrong costs
|
||||
|
||||
| Tier | What it is | How to patch it | Why this order |
|
||||
|---|---|---|---|
|
||||
| **Tier 0** | terminate primitives: `exit_group`/`tgkill`/`kill` call sites, the shellcode executor, the unified kill point | replace with a no-op or a returning stub | until they stop, every other result is unobservable — the process dies first |
|
||||
| **Tier 1** | decision functions: the shared predicate, each scanner (`/proc` walk, `TracerPid` read, module checksum) | return the benign value *for that caller's branch* | they are the belief; a clean verdict also skips the report path |
|
||||
| **Tier 2** | auxiliary gates: adb/debug flags, telemetry, feature switches | only if observed to gate the thing you care about | unbounded work; most are inert in your environment |
|
||||
|
||||
The benign value is not always 0. Read the caller's branch: a "found something" scanner returns
|
||||
non-zero, a "list of hits" scanner returns NULL, a "should continue" predicate returns 1. Returning
|
||||
0 everywhere is a guess that happens to work half the time — and the failing half reads as a broken
|
||||
patch instead of a wrong constant.
|
||||
|
||||
(`inferred`: the order follows from observability — a death at tier 0 hides every other result —
|
||||
and the benign-value rule from the caller's branch. The tier vocabulary is the source's,
|
||||
`unverified`; no graded set was run here.)
|
||||
|
||||
### Count the watchdogs before declaring the set closed
|
||||
|
||||
One kill site is rarely the only thread. The threads are distinguishable by what they *read*, not by
|
||||
their names:
|
||||
|
||||
- a `/proc/self/task`, `/proc/self/fd` or `/proc/self/maps` walk — looking for your instrumentation;
|
||||
- `TracerPid`, the parent pid, or a task in state `T` — looking for a debugger or a suspended process;
|
||||
- a checksum over a loaded module — looking for a modified page.
|
||||
|
||||
Patch one and the app still dies, at a different delay, which reads as "the patch did not work" rather
|
||||
than "there were three". After the tier 0/1 set, the process must survive longer than the **longest**
|
||||
timer you have observed, not the first one.
|
||||
|
||||
(`unverified` for the probe inventory — source-reported for one shell; `inferred` for "identify a
|
||||
thread by what it reads", which follows from the probe classes themselves.)
|
||||
|
||||
### One tier per run
|
||||
|
||||
Patch tier 0, run, record; then tier 1; then tier 2 only if needed. A build with all tiers changed at once cannot
|
||||
tell you which one mattered, and the next failure is unattributable. This is the single-variable rule
|
||||
of `pitfalls.md` P21 applied to a patch set. (`inferred`.)
|
||||
|
||||
|
||||
## ELF hardening you will meet in these targets
|
||||
|
||||
Hardening libraries are not normal ELF files. Assume the following until measured otherwise.
|
||||
|
||||
@@ -5,15 +5,19 @@ xvmp-class IR virtualizer, or any private-bytecode loop — and the question is
|
||||
the handler soup to the guest program. This file owns the recovery procedure; the **capture**
|
||||
half lives in `references/ete-diff-tracing.md`, the **slicing** tool in
|
||||
`scripts/vm_handler_slice.py`, and the OLLVM-only case in
|
||||
`references/native-dbi-and-deobfuscation.md`.
|
||||
`references/native-dbi-and-deobfuscation.md`. If the interpreter is itself written in a managed
|
||||
language — a C# class holding an opcode array plus a cursor under IL2CPP, or a JS dispatch loop — this
|
||||
is the wrong file: `unity-runtime.md` §when the managed layer is itself the interpreter, and
|
||||
`jsvmp-recovery.md`, own those shapes.
|
||||
|
||||
**Claim strength.** Every method step here is absorbed from two public reverse-engineering
|
||||
write-ups (Kanxue, 2026-08/09, titles and authors anonymized in this record; one is a full
|
||||
arm64 custom-VM recovery, the other a VMP interpreter recovery with trace-driven IR lifting).
|
||||
The write-ups are `observed` by their authors; this repository has **never run any of these
|
||||
steps on a real VM target** — everything below is `inferred` from those write-ups, cross-read
|
||||
against the open xvmp source facts in `references/ete-diff-tracing.md` §5. The pipeline's
|
||||
host-tested pieces (trace parsing, slicing, diffing) carry their own labels where named.
|
||||
steps on a real VM target**, so the mechanics below are `unverified` here — reported, not
|
||||
reproduced — and the ordering judgements built on them are `inferred`, cross-read against the
|
||||
open xvmp source facts in `references/ete-diff-tracing.md` §5. The pipeline's host-tested pieces
|
||||
(trace parsing, slicing, diffing) carry their own labels where named.
|
||||
|
||||
## 1. Deciding it is a VM at all
|
||||
|
||||
@@ -21,6 +25,9 @@ None of the signals below proves a VM alone — a big switch, a state machine, a
|
||||
table and an event dispatcher all look similar. The judgement is **several appearing together**:
|
||||
|
||||
1. one large native function, called often, taking a chunk of external data;
|
||||
|
||||
If the missing piece is not the dispatcher but *what a handler computes* — no `cmp`/`sub`, a flags
|
||||
slot written to the virtual context, `and/or/not` runs — `vm-protector-analysis.md` owns that idiom.
|
||||
2. a loop that reads a cursor from one buffer, dispatches on the value read, and writes the
|
||||
cursor back — the `while(running){ opcode=code[pc]; execute(opcode); pc=next_pc; }` shape;
|
||||
3. a **virtual register file**: many paths access `base + index*8` (or *4, *2) where *index*
|
||||
@@ -49,6 +56,22 @@ proves nothing about which layer it is. Judge by behaviour, not shape:
|
||||
Mislabelling the CFF table as `VM_HANDLER_TABLE` poisons everything downstream: every
|
||||
opcode→handler pair after it is wrong. The write-up's first correction was exactly this.
|
||||
|
||||
### 2.1 Encoded handler tables
|
||||
|
||||
A table entry does not have to be a pointer. One ARM64 sample stored 64-bit values that only become
|
||||
targets after adding a constant (`table[i] + 0x740078FC`, yielding offsets such as `0x3BA04`).
|
||||
Resolve both arms arithmetically before deciding which one is semantically required, then patch the
|
||||
conditional, not the table. When a callee is patched, undefine and rebuild the caller, or the
|
||||
decompiler keeps the stale target and the next reading is wrong.
|
||||
|
||||
### 2.2 A dispatcher invariant worth exploiting
|
||||
|
||||
When the obfuscator routes every transfer through one register (`r9` in one sample, `rdx` in
|
||||
another) and the landing instruction is a benign `nop`, enumerate real blocks by filtering the trace
|
||||
for "indirect jump through that register whose target begins with `nop`". That skips symbolic
|
||||
simplification of the MBA expressions entirely. The register is sample-specific; the invariant is the
|
||||
benign landing instruction.
|
||||
|
||||
## 3. Do not fully deflatten first — chase the VM data flow
|
||||
|
||||
Full native-CFG recovery of a flattened interpreter is expensive and unnecessary. What the VM
|
||||
@@ -152,7 +175,50 @@ pre-IP and post-IP are both recorded (`0x2 -> 0x3`), the 200k-line IR sequence *
|
||||
execution trace: +1 is fallthrough, jumps are branches, back-edges are loops — the guest CFG
|
||||
falls out. That is the end state this file walks toward: the guest program as data.
|
||||
|
||||
## 11. Where this repository's tools plug in
|
||||
## 11. The other end state: a program you can run
|
||||
|
||||
Sections 1–10 aim at a guest program you can **read**. When the interpreter implements one
|
||||
deterministic function — a request signer, a decoder, a checksum — the cheaper deliverable is a
|
||||
program you can **run**, and the handler semantics never need to be understood. (`unverified`: one
|
||||
write-up reports the route; this record did not run it.)
|
||||
|
||||
1. **Fix the boundary.** One native entry that takes a buffer in and produces a buffer out.
|
||||
Everything inside is the VM; everything outside is protocol.
|
||||
2. **Symbolic input, concrete everything else.** Seed the input bytes as symbols and run the VM (live,
|
||||
or over the recorded trace). Constant-fold every node whose value does not depend on them; delete
|
||||
loops and branches whose condition folds. What cannot fold is the part you must reproduce.
|
||||
3. **What remains is straight-line.** An SSA list of `(op, args)`, where `args` are constants or the
|
||||
indices of earlier nodes, and `op` is the ALU subset the real semantics needed — read input byte,
|
||||
load from the constant table, add/sub, and/or/xor, shift, truncate, sign-extend. No loop, no
|
||||
dispatcher, no handler table.
|
||||
4. **Capture four artifacts together, from one trace.** They are only valid as a set:
|
||||
- the program;
|
||||
- the constant table and its base (program offsets are relative to it);
|
||||
- the **output map** — which node byte lands at which output offset;
|
||||
- the **output template** — the fixed characters the transform does not compute.
|
||||
|
||||
The map and the template are what people skip. Without them the transform is right and the string
|
||||
is wrong, which looks like an off-by-one in the algorithm and is not.
|
||||
5. **Implement it in tens of lines.** A loop over `(op, args)` with a value array. No emulator, no JNI,
|
||||
no device — a function you can call at unit-test speed.
|
||||
|
||||
**Version binding.** The program is a property of one build. Store the library's fingerprint (size and
|
||||
build id) beside it and re-extract on upgrade: the tables and the map move even when the algorithm
|
||||
does not. Say which build a program came from; an extract with no fingerprint is not reproducible.
|
||||
(`inferred` for the fingerprint discipline; `unverified` for the source's report that the tables move
|
||||
on update.)
|
||||
|
||||
**Validation is per node, not per output.** Compare node values at several checkpoints against a
|
||||
device run. A node that is right in value but wrong in width (32-bit truncation where the VM kept 64)
|
||||
passes the final comparison on some inputs and fails on others — §9's failure seen from the other
|
||||
side. (`inferred` from §9.)
|
||||
|
||||
**Boundary.** This route needs a deterministic, input-driven computation. If the VM folds in a device
|
||||
id, a timestamp or a nonce, those become constants from one trace, and the honest claim is
|
||||
"reproduces one device's answers", not "implements the algorithm". For a signer that is often exactly
|
||||
enough, but the report has to say which claim it is making.
|
||||
|
||||
## 12. Where this repository's tools plug in
|
||||
|
||||
| Step | Tool |
|
||||
|---|---|
|
||||
@@ -174,4 +240,5 @@ falls out. That is the end state this file walks toward: the guest program as da
|
||||
- [ ] segments stacked if entry can nest (§7); slicer's nested-loop diagnostic honoured
|
||||
- [ ] operand slicing seeded on all STOREs; byte provenance (not value) decides folding
|
||||
- [ ] clean re-VM runs real bytecode against trace ground truth before any IR is trusted
|
||||
- [ ] labels: write-up methods `inferred`, shipped tools `observed` (host), no VM target run here
|
||||
- [ ] labels: write-up mechanisms `unverified`, ordering judgements `inferred`, shipped tools `observed` (host), no VM target run here
|
||||
- [ ] if the deliverable is a callable signer/decoder: §11's four artifacts captured as a set, program pinned to a build fingerprint
|
||||
@@ -88,6 +88,11 @@ rounds) re-deriving what a cleaner experiment would have shown in one run.
|
||||
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.
|
||||
- **A build with Google PairIP is usually the one to leave alone.** Look for `com.pairip` classes and
|
||||
a `LicenseClient` before committing: it combines Play licensing with partial code virtualization and
|
||||
terminates a re-signed process. If the app ships several variants, an older or regional build without
|
||||
PairIP is a better target than an unwinnable one — that is target selection, not defeat. The source's
|
||||
native case chose the older regional split build and accepted fewer cosmetics.
|
||||
|
||||
## Native libraries as a place to live
|
||||
|
||||
|
||||
@@ -1437,3 +1437,162 @@ is recorded. Two traps recur: regex metacharacters that are legal characters in
|
||||
descriptors, `[` in array types, `.` in package names), and representation mismatches that hide
|
||||
behind a matching line count. The encoding cousins of this failure are in `framework-runtimes.md`
|
||||
and the line-ending trap in `patch-audit.md`.
|
||||
|
||||
## P48. Every breakpoint in the target `.so` refuses to bind, and the app is running fine
|
||||
|
||||
**Symptom**
|
||||
A debugger attaches to the process, the process keeps running normally, the feature implemented by
|
||||
the library works — and the library is not in the module list. Breakpoints set in it are refused, or
|
||||
are accepted and never hit. There is no error, no log line, and no crash, so the first hypothesis is
|
||||
an anti-debug check, then "the library is packed", and the session is spent on both.
|
||||
|
||||
**Root cause**
|
||||
`android:extractNativeLibs="false"` — the default for modern packages — leaves the `.so` inside
|
||||
`base.apk`, and the loader maps it from there. There is no
|
||||
`/data/app/<pkg>-<hash>/lib/<abi>/libtarget.so` on disk, and a debugger binds breakpoints to a
|
||||
module *file*. The library is present in memory and absent from the filesystem, which is a
|
||||
contradiction only if you assume those are the same thing. `pm path <pkg>` names the APK's directory,
|
||||
and `ls` beside it finds no `lib/` at all; the mapped region is backed by the APK, the same shape as an
|
||||
`r--s` mapping of `base.apk` that looks like a dex (`advanced-unpacking.md`).
|
||||
|
||||
**Why it is hard to see**
|
||||
Everything that would normally discriminate a setup fault from a target fault reports success.
|
||||
Attach works, the process is alive, PID and ABI match, the server logged nothing. The one fact that
|
||||
explains it — the missing file — is a *negative* the tool never prints: a debugger lists the modules
|
||||
it can see, not the modules it cannot. And the target's own behaviour is the strongest false signal
|
||||
available: the feature works, so the library is obviously loaded, so the debugger must be blocked.
|
||||
|
||||
**The rule**
|
||||
**When a breakpoint will not bind and the module list is short, look for the file before you look for
|
||||
a check.** `adb shell pm path <pkg>` and `ls` the sibling `lib/<abi>/`; if it is absent, this is
|
||||
`extractNativeLibs`, not anti-debug. Fix it by repacking with the flag at `true` (and then handle the
|
||||
signature consequences — `signature-derived-keys.md`), or by giving the loader an on-disk copy in
|
||||
`lib/<abi>/` on a rooted device and verifying that the app loads it. Never point the debugger at the
|
||||
`.so` extracted from the APK and call it the module: those addresses belong to a copy the process
|
||||
never mapped, so a breakpoint that does land is worse than one that does not. The full attach sequence
|
||||
is in `ida-so-debugging.md`.
|
||||
|
||||
## P49. A reimplemented signer is byte-wrong, and the defect is in the extraction
|
||||
|
||||
**Symptom**
|
||||
A reproduced signer emits a signature of the right shape and length and the server rejects it. Every
|
||||
intermediate value looks sane; the difference is at the tail. The working hypothesis becomes "there is
|
||||
a final MAC", then "a truncated hash", then "a per-version tweak", and each one gets its own day.
|
||||
|
||||
**Root cause**
|
||||
The input to the pipeline is not byte-identical to the device's. The dump read two bytes past the real
|
||||
buffer, or a length field in the container lies, or the buffer was copied at an unaligned offset. One
|
||||
wrong byte early makes every later stage wrong, and the result still has the right shape.
|
||||
|
||||
**Why it is hard to see**
|
||||
A wrong algorithm and a wrong input produce the same class of output: plausible, wrong, deterministic.
|
||||
Byte-level total failure fits every hypothesis, so there is unlimited room for confirmation bias. And
|
||||
the defect lives in memory, where you cannot diff it the way you diff two files.
|
||||
|
||||
**The rule**
|
||||
**Prove each stage's input is byte-identical — length, alignment, encoding — before touching the
|
||||
algorithm.** Compare stage inputs against the device, not final outputs; a stage-input diff localises
|
||||
in minutes what an output diff cannot localise at all. P42 is the decoder-desync cousin; this one is
|
||||
an extraction length. (`inferred` — a reasoning rule from how one byte propagates; no target case was
|
||||
measured for this record.)
|
||||
|
||||
## P50. A "custom cipher" is a wrapper that cancels
|
||||
|
||||
**Symptom**
|
||||
Reimplementing an odd transform produces output that is either double-transformed or exactly what the
|
||||
standard primitive would have produced — the transform appears to do nothing, which reads as a missing
|
||||
step rather than an extra one.
|
||||
|
||||
**Root cause**
|
||||
An involution applied symmetrically. `(x & ~m) | (~x & m)` is `x ^ m` for a mask whose bits partition
|
||||
the word; called on both the encrypt and the decrypt path, it cancels. A fixed keyless permutation is
|
||||
the other member of the family: an encoding dressed as encryption.
|
||||
|
||||
**Why it is hard to see**
|
||||
The function name and the bit arithmetic read as custom crypto, and the wrapper sits between you and
|
||||
the primitive, so reading either alone misleads. A no-op transform is not something you expect to find
|
||||
*inside* a protected algorithm, so it gets modelled as key mixing and carried through every later
|
||||
step.
|
||||
|
||||
**The rule**
|
||||
**Compose it with itself before reimplementing it** (`f(f(x)) == x`), and check whether the caller
|
||||
invokes it on both paths. If it cancels, drop it and recover the standard primitive underneath; keep
|
||||
the wrapper in the report, because it is the reason the algorithm looked unfamiliar. The method, with
|
||||
the differential probes that identify the primitive underneath, is `protocol-reverse.md` §7; the
|
||||
mask identity itself is host-checked there (`observed`: zero counterexamples over 65,536 eight-bit
|
||||
pairs and 200,000 random 16-bit pairs).
|
||||
|
||||
## P51. The low-API branch you need was removed by R8
|
||||
|
||||
**Symptom**
|
||||
A build with `minSdkVersion 29` is changed to 28 and installed on Android 9. It starts, then dies on
|
||||
`No virtual method rebase()`, `registerActivityLifecycleCallbacks`, or `WindowInsets$Builder`; or it
|
||||
runs but lifecycle events never arrive, so coroutines inside `lifecycleScope` never execute.
|
||||
|
||||
**Root cause**
|
||||
R8 evaluated `if (SDK_INT >= 29)` as true for the declared `minSdk` and deleted the else branch. The
|
||||
`$ApiNNImpl` fallbacks below 29, the old `WindowInsetsCompat` implementation, and the pre-29 path in
|
||||
`ReportFragment.dispatch` (which became an empty function) are no longer in the dex.
|
||||
|
||||
**Why it is hard to see**
|
||||
The APK installs and starts; only the path that needs the deleted branch fails. The stack names a
|
||||
framework or AndroidX class, so the first hypothesis is an SDK/framework mismatch, not "our own build
|
||||
deleted this code". The empty lifecycle method is silent: nothing throws, the observable is "the app
|
||||
does nothing".
|
||||
|
||||
**The rule**
|
||||
**Lowering `minSdk` is a code change, not a manifest edit.** Audit every `$ApiNNImpl` with N at or
|
||||
above the original minSdk, the lifecycle dispatch, and `WindowInsetsCompat`; add a version guard that
|
||||
returns the default on old devices and restore the old implementation. Test on the oldest API you
|
||||
claim to support. Prefer a newer emulator over lowering the floor; if you must lower it, treat every
|
||||
`SDK_INT` comparison as a branch you may have to re-create.
|
||||
|
||||
## P52. A decompiled Lua file does not match its filename
|
||||
|
||||
**Symptom**
|
||||
A batch decompile produces valid Lua, but many files in different directories contain the same
|
||||
unrelated script (the source found 112). The running game is fine, so the "source" is the only thing
|
||||
that is wrong. A later variant: a script you replaced is not the script the build patched; constants
|
||||
from the hot update disappear, and a runtime stack contains a function name that does not exist
|
||||
anywhere in the decompiled source.
|
||||
|
||||
**Root cause**
|
||||
The bundle writer cloned a template `TextAsset` and wrote new bytes with `save_typetree`; the
|
||||
library's `read()` kept parsing the template object's original bytes. The same cache applies after a
|
||||
hot-update merge: `set_raw`/replacement writes the new script, but `read()` still returns the packaged
|
||||
old one, so a read-modify-write patch operates on the old file and silently overwrites the new one.
|
||||
|
||||
**Why it is hard to see**
|
||||
Every file is syntactically valid Lua. Nothing in the pipeline reports an error; the only signal is
|
||||
semantic — a function that should exist does not, or two entries share identical content. If the
|
||||
analysis copy is wrong, the patch is written against a file the device never runs.
|
||||
|
||||
**The rule**
|
||||
**Compare the entry name with the chunk name before analysing a batch.** Lua 5.1 bytecode stores
|
||||
`@UI/...` immediately after the header; zero mismatches is the gate for trusting the export. In your
|
||||
own bundle writer, keep a sidecar map of every written payload and make reads return it first, then
|
||||
compare the bytes read back with the hot-update source. The quick runtime signal is a stack frame
|
||||
naming a function absent from the "source" — that means you are reading the old script.
|
||||
|
||||
## P53. A retained AssetBundle returns null after stripping unused bundles
|
||||
|
||||
**Symptom**
|
||||
You remove bundles that the package does not seem to use. The build installs and starts, but a bundle
|
||||
you kept now loads as null or its assets are missing. There is no CRC error and the removed files are
|
||||
not mentioned in the log.
|
||||
|
||||
**Root cause**
|
||||
`AssetBundleManifest` still lists the removed bundle as a dependency of a retained one. Unity resolves
|
||||
the dependency graph before loading; a missing edge makes the parent unavailable even though its own
|
||||
bytes are intact.
|
||||
|
||||
**Why it is hard to see**
|
||||
The failure is attributed to the bundle that is still present, or to the patch you just made. The
|
||||
removed bundle is absent from the evidence by definition, and "the file exists" looks like proof that a
|
||||
bundle should load.
|
||||
|
||||
**The rule**
|
||||
**When you remove an AssetBundle, rebuild the dependency list in the manifest in the same step.**
|
||||
Never treat file presence as loadability. Load each retained bundle in a control build and check for
|
||||
null before signing; keep the removed-bundle list in the build record so a later change can rebuild
|
||||
the graph.
|
||||
@@ -138,6 +138,21 @@ The measured record for this tool -- every command, both input forms, the round
|
||||
framing mistake it does *not* protect you from -- is in
|
||||
`references/evidence-summary.md` §The capability matrix.
|
||||
|
||||
### 1.1 If the body is self-describing, skip the schema hunt
|
||||
|
||||
Not every binary body is protobuf. **MessagePack** is self-describing: the first byte is a type and
|
||||
length tag, and maps/arrays carry their own shape, so a decoder needs no `.proto` and no generated
|
||||
code. Plausible leading tags are fixmap `0x80`-`0x8f`, fixarray `0x90`-`0x9f`, positive fixint
|
||||
`0x00`-`0x7f`, `str8 0xd9` and `map16 0xde`; the confirmation is a full decode with no leftover
|
||||
bytes. Re-encode with the same library (`packb`/`unpackb`) and re-encrypt with the app's own
|
||||
routine.
|
||||
|
||||
**Prefer mutating the outbound request over the inbound response.** A response edit can make the UI
|
||||
render an unlocked state while the server still authorizes the live entry, so the change is visible
|
||||
and ineffective; a request edit changes what the server is asked to do. When both directions are
|
||||
available, test both once and record which one the server re-derives. (`unverified`: absorbed from
|
||||
one write-up; no MessagePack target was captured here.)
|
||||
|
||||
## 2. Recovering the schema from the APK
|
||||
|
||||
### What generated protobuf code looks like
|
||||
@@ -354,7 +369,83 @@ frame's dependency set, and the envelope decodes stably across several samples.
|
||||
is still "which state did this frame consume", no amount of body decoding helps — go capture the
|
||||
missing family first.
|
||||
|
||||
## 7. Failure modes
|
||||
## 7. Encrypted bodies — classify the primitive before you implement it
|
||||
|
||||
**Load this when** the body is opaque: a long base64/hex field in the query, a binary request body, a
|
||||
fixed prefix on every response — and the transform lives in a native library or a helper class.
|
||||
|
||||
Three black-box experiments on captured pairs, before any static work. The probes themselves were
|
||||
host-checked here on AES-128 through `openssl` (commands and output in the verification record,
|
||||
`docs/tool-verification/EXTENSION-ref-absorption-2026-10b.md`, under "Verification pass"). What they prove
|
||||
about *your* target is one step further, and stays `inferred` until you vary the key and the
|
||||
request.
|
||||
|
||||
1. **Header length.** Encrypt two payloads under the same key and decode both. A constant first N
|
||||
bytes ⇒ a deterministic header: fixed plaintext, or derived from the key/IV. A prefix that changes
|
||||
when the key changes ⇒ keyed. A prefix that changes per request ⇒ a per-message nonce.
|
||||
(`observed` on synthetic inputs.)
|
||||
2. **Determinism, then diffusion width.** Encrypt `P` and `P || X`, and XOR the ciphertexts. Zeros
|
||||
over the common prefix ⇒ the construction is deterministic under a fixed key and IV — **and that
|
||||
is all it proves.** Measured: CTR, CBC and ECB all give zero prefix-XOR at a fixed IV, so this
|
||||
experiment cannot separate a stream cipher from a block mode. (An earlier draft of this file said
|
||||
it could; one run falsified it.) Repeat with a different IV: a CTR-style mode diverges, and so does
|
||||
any mode that carries a per-message nonce.
|
||||
|
||||
The separation comes from a one-byte plaintext flip, counted over the ciphertext: **1 changed
|
||||
byte** ⇒ a keystream independent of the plaintext (measured: CTR, 1 of 32); **every block from
|
||||
that point on** ⇒ a chained mode (measured: CBC, 32 of 32); **exactly one block** ⇒ ECB (measured:
|
||||
16 of 32, later blocks untouched). (`observed`, host.)
|
||||
3. **Length law.** `len(c) = len(p)` ⇒ no padding — which fits CTR and a `nopad` block mode equally,
|
||||
so it never decides alone. `len(c) = b * ceil((len(p)+1)/b)` ⇒ a padded block mode (PKCS#7;
|
||||
checked for b = 16, p = 0…32). A compressed prefix with a constant length relation ⇒
|
||||
compress-then-encrypt, and the plaintext you are looking for is the compressor's output.
|
||||
(`observed`, host.)
|
||||
|
||||
The classification decides what you implement: a keystream cipher needs its keystream and nothing
|
||||
else; a chained mode needs the mode and the IV; ECB needs neither to explain its structure. Skipping
|
||||
this step is how a standard construction gets reimplemented as something exotic.
|
||||
|
||||
### A custom-looking transform may be a wrapper that cancels
|
||||
|
||||
Wrapper arithmetic is cheaper to check than to rewrite. Two shapes cover most of what looks strange:
|
||||
|
||||
- **Involution applied symmetrically.** A transform with `f(f(x)) == x` that is called on the way in
|
||||
*and* on the way out contributes nothing. The common disguise is a mask pair:
|
||||
`(x & ~m) | (~x & m)` is exactly `x ^ m`. Exhaustively checked here over all 8-bit `(x, m)` pairs
|
||||
and 200,000 random 16-bit pairs: zero counterexamples, and the composition is an involution. If
|
||||
both encrypt and decrypt call it, drop it and recover the standard primitive underneath.
|
||||
(`observed`, host — the algebra; whether a target's wrapper is that shape is `inferred`.)
|
||||
- **A fixed permutation.** The same 256-byte table applied to every input with no key dependence is
|
||||
an encoding, not encryption. Index it out and compare against known S-boxes. (`inferred`.)
|
||||
|
||||
Test the composition before reimplementing: apply the function twice, and check whether the caller
|
||||
uses it twice. If it cancels, the algorithm is standard and the reason it looked unfamiliar is now
|
||||
written down.
|
||||
|
||||
### The last mile is encoding, not crypto
|
||||
|
||||
Two non-cryptographic differences fail signatures that are otherwise correct. Both are invisible in
|
||||
the algorithm and both are cheap to eliminate:
|
||||
|
||||
- **The client's encoder may be Java's.** `URLEncoder` writes a space as `+`, leaves `*`, `-`, `_`,
|
||||
`.` alone, and percent-encodes `~` as `%7E` with uppercase hex over UTF-8. Python's does the
|
||||
opposite on two of those: measured on this host, `quote` gives `a%20b~%2A-_.` (space `%20`, `*`
|
||||
encoded, `~` kept) and `quote_plus` gives `a+b~%2A-_.` (space `+`, `*` still encoded). Reimplement
|
||||
what the client does and check it against one captured parameter, not against documentation.
|
||||
(Python side `observed`; the Java side is `unverified` here — no JDK on the analysis host — and is
|
||||
quoted from the JDK API contract, so confirm it on one captured value.)
|
||||
- **Compressed bytes are implementation-defined.** Measured: `zlib.compress(data, 1)` and `(data, 9)`
|
||||
produce different byte streams (49 vs 48 bytes) for the same payload, and both decompress to it.
|
||||
Whether the difference breaks a signature is a property of the **server**: if it decompresses and
|
||||
checks a CRC or the plaintext, byte equality is not required; if it compares the stored blob, it
|
||||
is. One mutation tells you which. (The general claim is `observed`; the specific liblz4-vs-python-
|
||||
lz4 divergence is `unverified` — no lz4 binding here.)
|
||||
|
||||
**Boundary.** None of the three experiments needs the `.so`; that is the point. When the keystream is
|
||||
derived per message from a device secret, the native route comes back and §5's attribution applies.
|
||||
(`inferred`.)
|
||||
|
||||
## 8. Failure modes
|
||||
|
||||
**A decode that looks valid but is not.** protobuf is self-synchronising enough that random bytes
|
||||
often decode into a plausible-looking field list. Guard against it by (a) decoding several samples of
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
# Python bytecode behind a packer: Pyarmor and the `.pyc` route
|
||||
|
||||
Load this when the logic you need is not Java, Kotlin, Dart or native, but Python: the APK embeds a
|
||||
Python runtime (Chaquopy, Kivy, BeeWare), ships a `.pyc`/`.pyz`, or the companion desktop tool
|
||||
that produces the data you are analysing is a PyInstaller/Pyarmor build. This file covers static
|
||||
recovery of Pyarmor-protected bytecode; `emulation-and-rpc.md` owns calling the recovered routine
|
||||
instead of reading it, and `framework-runtimes.md` owns deciding whether the runtime is Python at
|
||||
all.
|
||||
|
||||
**Claim strength.** Absorbed from one detailed public write-up on a Pyarmor build and a modified
|
||||
`pycdc` (2026). The field layouts, flags and opcode numbers are `unverified` here; no Pyarmor
|
||||
sample was unpacked in this record. The general rules (static-first, self-describing TLV,
|
||||
mirror-the-host-codegen) are `inferred` from that source. Version numbers matter: every branch
|
||||
below is gated on the `pycdc`/Python version, and applying a newer layout to an older file fails
|
||||
silently rather than loudly. The three-scope nonce layering (§2.2) and the counter-mode correction
|
||||
in §5 were added in the 2026-10 audit pass; the counter behaviour is `observed` on the host, the
|
||||
layering itself is `unverified`.
|
||||
|
||||
## 1. Recognition
|
||||
|
||||
| Signal | Meaning |
|
||||
|---|---|
|
||||
| `pyarmor-vax-\d{6}` string | Pyarmor build tag; `000000` is the free build, other values are a customer id |
|
||||
| A `.pyc` whose code object starts with a private opcode or a high-entropy body | encrypted code object |
|
||||
| `pyarmor` runtime module, `__pyarmor__` import, or a bootstrap that loads a shared object | protected distribution |
|
||||
| `m_flags & 0x20000000` on a code object | Pyarmor's `CO_PYARMOR_OBFUSCATED` marker |
|
||||
| A string blob where the first byte has a small tag and the rest is random | per-string encryption |
|
||||
|
||||
The packer is not a general-purpose VM. It is a key schedule plus AES-CTR plus a small bytecode
|
||||
VM that derives one XOR key. That makes the static route the cheap one: you do not need to run the
|
||||
program to recover its code.
|
||||
|
||||
## 2. Key schedule
|
||||
|
||||
One observed build derives the master key with MD5 over four concatenated inputs:
|
||||
|
||||
1. the ASCII build tag `pyarmor-vax-{6 digits}`;
|
||||
2. `RSA_KEY1`: the blob at file offset 0, length `0x10E`;
|
||||
3. `RSA_KEY2`: the blob at `0x110 + 0x20 = 0x130`, length taken from the 4-byte field at
|
||||
header offset `+4`;
|
||||
4. a 16-byte value XORed with `0xF1` first.
|
||||
|
||||
`RSA_KEY2`'s first 12 bytes are the `AST_nonce` used later. The resulting 16-byte digest is the
|
||||
AES-128 key; the nonce plus the code metadata select the CTR offset. The exact blob offsets belong
|
||||
to the observed version; read them from the bootstrap, do not assume them for another build.
|
||||
|
||||
### 2.1 The 12-byte nonce-XOR key
|
||||
|
||||
When a header field `xor_key_procedure_length` is non-zero, the packer runs a tiny VM over a
|
||||
12-byte output. The VM is worth knowing because its bugs become your key:
|
||||
|
||||
```text
|
||||
registers[8], only indices 0..5 and 7 are valid (one build remapped 15 -> 7)
|
||||
cursor starts at in + 16
|
||||
opcode 1: terminate
|
||||
opcode 2,3,4,6,7: += -= *= ^= = (destination is cur[1] >> 4)
|
||||
opcode 5: /=, then overwrites registers[0] with the quotient — the x86_64 lowering
|
||||
keeps rax as both the dividend and the result
|
||||
opcode 8: load, cursor += 2
|
||||
opcode 9: store registers[cur[1] & 7] as 4 bytes at out+0
|
||||
opcode 0xA: address setup/store, cursor += 6
|
||||
opcode 0xB: store 4 bytes at out + cur[2], cursor += 3
|
||||
unknown opcode: zero the 12-byte output and abort
|
||||
```
|
||||
|
||||
The `idiv` side effect is the general lesson: when reimplementing a packer's VM, mirror the *host
|
||||
code generation*, including register clobbers the author did not intend. A clean abstract
|
||||
interpreter will produce a different key and every downstream field will decrypt to noise.
|
||||
|
||||
Width is part of the same contract: the VM is a transcription of machine instructions, so each
|
||||
operation must be evaluated at the host register width — a multiply keeps only the low 32 bits,
|
||||
division is signed and truncates toward zero, and results wrap. Evaluating the same program with
|
||||
Python's unbounded integers diverges after a few instructions and produces a key that is wrong in a
|
||||
way that looks like a wrong nonce downstream, not like an arithmetic error.
|
||||
|
||||
### 2.2 The shipped blob is wrapped once more
|
||||
|
||||
The `.pyc` is the *inner* artefact. At least one build ships
|
||||
`AES-CTR(master key, AST_nonce, pyc-with-encrypted-parts)`: the file on disk is not a pyc, its first
|
||||
four bytes are not the marshal magic, and a parser pointed at it reports a corrupt header rather than
|
||||
an encrypted file. Three scopes share one master key and are separated only by which nonce is used:
|
||||
|
||||
| Scope | Nonce | Plaintext it yields |
|
||||
|---|---|---|
|
||||
| outer container, whole file | `AST_nonce` from `RSA_KEY2`, `nonce[15] = 2` | the pyc: header, string blob, code section |
|
||||
| each code object | 12 bytes sliced out of that object's own `m_code` (§5) | that object's bytecode |
|
||||
| each string | `pyarmor_mix_str_aes_nonce` | that one literal |
|
||||
|
||||
The order is not a preference. Applying a code object's nonce to the on-disk bytes decrypts layer 1's
|
||||
ciphertext with layer 2's stream and yields high-entropy bytes that look like a private opcode set, so
|
||||
the failure is "this packer uses a custom ISA", which is the wrong conclusion. Peel the outer layer
|
||||
first, then check for the pyc header, then parse (§3).
|
||||
|
||||
A live dump does not replace this pass either: the packer decrypts each code object when it is first
|
||||
imported, so a process dump holds the objects that ran and leaves everything else as ciphertext. A
|
||||
function missing from a dump means "not reached yet", not "not present" — force the modules to import
|
||||
before calling a dump complete, and keep the static pass as the only complete route.
|
||||
|
||||
## 3. Parsing the code object
|
||||
|
||||
**Once the outer layer is off (§2.2)**, the file is a normal `.pyc` with extra fields, so the parser
|
||||
must be version-aware.
|
||||
Fields that change and the versions that introduced them:
|
||||
|
||||
| Field | Width / condition |
|
||||
|---|---|
|
||||
| `m_argCount` | 16-bit for 1.3-2.2, 32-bit from 2.3 |
|
||||
| `m_posOnlyArgCount` | present from 3.8 |
|
||||
| `m_numLocals` | present below 3.11 |
|
||||
| `m_localKinds` | present from 3.11 |
|
||||
| `m_qualName` | present from 3.11 |
|
||||
| `m_exceptTable` | present from 3.11 |
|
||||
|
||||
For files older than 3.8, the flags field is remapped before use:
|
||||
|
||||
```text
|
||||
m_flags = (m_flags & 0x1FFF)
|
||||
| ((m_flags & 0xFFFE000) << 4)
|
||||
| (m_flags & 0x20000000)
|
||||
```
|
||||
|
||||
Warn if `m_flags & 0xD0000000` is set: those bits are not part of the layout this parser knows.
|
||||
Getting the remap wrong moves every subsequent field by four bytes and the failure looks like a
|
||||
corrupt string table, not a version error.
|
||||
|
||||
## 4. The extra section: a self-describing TLV
|
||||
|
||||
After the code object's usual fields:
|
||||
|
||||
```text
|
||||
1 byte extra_length
|
||||
256 bytes extra_data
|
||||
```
|
||||
|
||||
Decode it as a small TLV, not as fixed offsets:
|
||||
|
||||
```text
|
||||
if extra_data[0] & 0xF0: reject (unknown feature bits)
|
||||
fn_count = extra_data[0] & 3
|
||||
descriptor_count = (extra_data[0] >> 2) & 3
|
||||
ptr = extra_data + 4
|
||||
for each item:
|
||||
item_len = (*ptr >> 6) + 2 ; low 6 bits are flags
|
||||
...
|
||||
```
|
||||
|
||||
Skip `fn_count` items, then walk `descriptor_count` items. For a descriptor item, ignore the low
|
||||
6 bits of each byte and big-endian accumulate the remaining bits into a `consts_index`. That index
|
||||
selects a string in the code object's constants; the string is the `descriptor`, and a descriptor
|
||||
shorter than 20 bytes is invalid. The layout is self-describing precisely so the packer can change
|
||||
the counts without changing the parser; hard-coding `fn_count = 1` breaks on the next build.
|
||||
|
||||
## 5. Decrypting one code object
|
||||
|
||||
The descriptor's first 8 bytes are not data: at run time they hold `&PyCodeObject`, and the
|
||||
unpacker replaces them with the literal string `"<COAddr>"`. The rest is a struct at
|
||||
`descriptor.data() + 8`:
|
||||
|
||||
```text
|
||||
flags = *(u32*)struct
|
||||
copy_prologue = flags & 0x8
|
||||
xor_aes_nonce = flags & 0x4
|
||||
short_code = flags & 0x2
|
||||
decrypt_begin = ...
|
||||
decrypt_length = ...
|
||||
short_nonce_index= ...
|
||||
```
|
||||
|
||||
Then:
|
||||
|
||||
1. Choose the nonce source index:
|
||||
`short_code ? short_nonce_index : short_nonce_index + decrypt_begin + decrypt_length`.
|
||||
2. Copy 12 bytes from `m_code + nonce_index` into a zeroed 16-byte nonce, then set
|
||||
`nonce[15] = 2`.
|
||||
3. If `xor_aes_nonce`, XOR those 12 bytes with the 12-byte VM key from §2.1.
|
||||
4. AES-128-CTR decrypt `code[decrypt_begin .. decrypt_begin + decrypt_length]`.
|
||||
5. If `copy_prologue`, copy `decrypt_begin_index` bytes from `code + decrypt_length` to `code + 0`,
|
||||
then fill `code[decrypt_length .. decrypt_length + decrypt_begin_index]` with `0x09` (NOP).
|
||||
6. Replace the descriptor's first 8 bytes with the `"<COAddr>"` placeholder so a later re-run does
|
||||
not treat runtime data as a key.
|
||||
|
||||
The nonce construction is the part that is easy to get wrong, and the usual description of *how* it
|
||||
fails is wrong: `nonce[15] = 2` is not a flag that only affects later blocks. In counter mode every
|
||||
block's keystream is `E(nonce || counter)`, so changing byte 15 changes the counter start and corrupts
|
||||
**block 0 onward** — there is no "first block decrypts plausibly" state to catch you. (`observed`,
|
||||
host: two 16-byte counter blocks differing only in byte 15 differ in 16 of 16 keystream bytes, so
|
||||
the ciphertext differs from block 0 — see the EXTENSION record and
|
||||
`docs/tool-verification/fixtures/verify_ref_claims_10c.py`.) What an *unset* tail does is worse in a different way: the leftover bytes
|
||||
are whatever the buffer held, so the keystream is not reproducible at all and the same input decrypts
|
||||
differently on two runs. Zero the buffer, set the byte, and check the first eight bytes of the result
|
||||
against a known code-object prologue instead of trusting a plausible-looking body.
|
||||
|
||||
## 6. Decrypting strings
|
||||
|
||||
Strings are separate from code and use a tag byte:
|
||||
|
||||
```text
|
||||
v[0] & 0x80 == 0 -> not encrypted (skip)
|
||||
v[0] & 0x7F == 0 -> empty/plain (skip)
|
||||
(v[0] & 0x7F) > 4 -> not an encrypted string (skip)
|
||||
otherwise:
|
||||
drop byte 0
|
||||
nonce = 12 bytes of pyarmor_mix_str_aes_nonce, nonce[15] = 2
|
||||
AES-CTR with the same master key
|
||||
```
|
||||
|
||||
The tag is a type code, not a length. Treating the low 7 bits as a length is the usual way a
|
||||
reimplementation decrypts some strings and corrupts the rest.
|
||||
|
||||
## 7. What to do with the result
|
||||
|
||||
- A recovered `.pyc` can be decompiled by a version-matched decompiler, but the bodies are only
|
||||
useful if the decompiler understands the Python version's opcodes. Pin both.
|
||||
- If the decompiler fails on one code object, keep the decrypted bytes and read the disassembly
|
||||
(`dis`) rather than re-attacking the packer. The packer is solved once; the decompiler is a
|
||||
separate problem.
|
||||
- If the goal is *calling* the routine rather than reading it, load the recovered module in the
|
||||
matching Python and call the entry point, or use the emulation/RPC route. Do not rebuild the
|
||||
cipher from a partial read when the decrypted function is in front of you.
|
||||
|
||||
## 8. Failure modes
|
||||
|
||||
| Symptom | Likely cause |
|
||||
|---|---|
|
||||
| Descriptor shorter than 20 bytes | wrong `consts_index` (bit accumulation ignored the low-6-bit skip) |
|
||||
| Header fields shift by 4 after `m_flags` | wrong version remap (pre-3.8) |
|
||||
| First block decrypts, rest is noise | nonce tail not zeroed + `nonce[15]` not set, or CTR offset wrong |
|
||||
| VM key differs from the packer's | host-codegen clobber (`idiv`) not modelled |
|
||||
| Some strings decrypt, others do not | tag byte treated as length, or the `> 4` guard missing |
|
||||
| Code object decrypts but prologue is garbage | `copy_prologue` flag ignored, or NOP fill used the wrong length |
|
||||
|
||||
## 9. Boundary
|
||||
|
||||
This route is static and offline, which is its advantage: no device, no runtime, no root. It also
|
||||
means every claim about a field is a claim about one Pyarmor version. Nothing here was run against
|
||||
a real sample in this record. The steps that would make a row `observed`: parse one `.pyc`, show
|
||||
the extra section counts matching the file, decrypt one code object, and execute the recovered
|
||||
module to the same output as the original. Until then, treat the offsets as a template and keep the
|
||||
original bytes so a wrong branch can be retried without re-extracting the sample.
|
||||
|
||||
For a packaged Android app, the Python payload may sit in `assets/` or be extracted on first run.
|
||||
Locate it the same way as any other runtime: find the loader (the Python runtime's initialization
|
||||
call), then the payload path it builds. `recon.md` owns that search; this file begins once a
|
||||
protected `.pyc` is in hand.
|
||||
@@ -54,6 +54,51 @@ 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`.
|
||||
|
||||
## 1c. Resource completeness and the encryption map
|
||||
|
||||
Two questions are cheap on day one and expensive after a week of patching: **how much of the game is
|
||||
in this APK**, and **what exactly is encrypted**. Answer both before choosing a route.
|
||||
|
||||
**Completeness.** A 1.2 GB package can be a quarter of the game. Find the game's own catalogue
|
||||
(`manifest.*`, `AssetDatabase.manifest`, a version file, a native manifest) and diff it against the
|
||||
files actually present, summed by directory. Then diff the content tables (costumes, characters,
|
||||
levels) against entries that have a model or texture. In the source's micro-client case, the manifest
|
||||
listed 42,700 bundles / 4.62 GB while the APK held 12,120 / 1.05 GB, and about 91% of the clothing
|
||||
models were absent. The rest was downloaded on first launch and died with the server.
|
||||
|
||||
A player's app backup is often the only complete source; treat it as untrusted: identify the container
|
||||
(headers, compression, encryption), verify every file against the backup's own manifest and MD5, and
|
||||
confirm the APK inside is the **same build** — the source found a backup APK with the same version
|
||||
name and versionCode but 1,518 differing files. Merge the hot-update layer (scripts, manifests, updated
|
||||
bundles) into the package and make it survive the client's first-launch cleanup, or the files are
|
||||
deleted before they are read. If the missing resources were never in any player's copy, stop and say so
|
||||
rather than patching around a game that cannot be complete.
|
||||
|
||||
**Encryption map.** Do not answer "is anything else encrypted?" from memory. Spend half an hour:
|
||||
|
||||
1. **Classify every entry** — installed files plus the hot-update directory: size, first 16 bytes,
|
||||
magic type, and entropy over the first 64 KB. The goal is zero "unknown" entries.
|
||||
2. **High entropy is not encryption.** Compressed bundles, audio and textures all sit above 7.5.
|
||||
Test whether the standard loader opens the file (a resource bundle that UnityPy loads is not
|
||||
encrypted), whether a public header is present and plausible (e.g. `FSB5`), and whether a sample
|
||||
decodes to a real image or sound.
|
||||
3. **Judge text resources one by one** — readable text, a public binary format (skeleton, sound bank,
|
||||
protobuf), or high entropy and a length that is a multiple of the block size (a cipher candidate).
|
||||
4. **A fixed prefix is not encryption.** Several zero bytes at the start of every bundle are a common
|
||||
anti-unpacker trick; count them in the original, skip them on read, preserve them on write.
|
||||
5. **Check config tables by field**, not by vibe: decode with the protocol description, then scan for
|
||||
field numbers the description does not contain. Zero unknown fields, and a re-serialization of the
|
||||
same byte length, are two independent confirmations.
|
||||
6. **Find the second copy.** Packages often contain an old config database while the phone's
|
||||
hot-updated copy is newer. Compare row counts per table and build from the newer one.
|
||||
7. **List runtime crypto points separately** — script load, login token, resource check, payment,
|
||||
network packet — and record for each whether the offline route needs it.
|
||||
8. **Separate "cannot decrypt" from "not in hand".** A server database or an unreadable private
|
||||
directory is missing data, not an encryption problem; mixing the two produces a false "cracked".
|
||||
|
||||
The map is a deliverable: it lets a later reader see which conclusions were measured, which were
|
||||
inferred, and which files nobody could open.
|
||||
|
||||
## 2. Is it packed?
|
||||
|
||||
Read `AndroidManifest.xml` → `application android:name`.
|
||||
@@ -129,6 +174,8 @@ Heuristic: the business dex mixes the app's package prefix (hundreds of hits) wi
|
||||
| `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/` |
|
||||
| `libunity.so` + a `luascript` bundle or thousands of Lua `TextAsset` entries | **Unity + Lua** (xLua / tolua / SLua) — the logic is in a bundle, not the assembly — `unity-lua-and-assetbundles.md` |
|
||||
| `liblayaair.so` + `libv8*.so` + `assets/scripts/*.js` | **LayaAir native (Conch)** — JavaScript logic and a DCC cache — `framework-runtimes.md` §LayaAir native (Conch) specifics |
|
||||
| `libreactnativejni.so` + `assets/index.android.bundle` | **React Native** — JS bundle under `assets/` |
|
||||
| `libhermes.so` | **Hermes bytecode** |
|
||||
| Almost everything in `.so` | **Native** — different toolchain entirely |
|
||||
|
||||
@@ -206,6 +206,33 @@ Always pass the explicit range (Route B above) and read the scheme list from tha
|
||||
|
||||
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.
|
||||
|
||||
### Renaming the package so two builds coexist
|
||||
|
||||
Same package name plus a different signature is an install refusal, and uninstalling the official app
|
||||
destroys its data. To install alongside it, rename the package in three places — a manifest-only edit
|
||||
produces an APK that installs and then fails to find its own resources:
|
||||
|
||||
1. **Binary `AndroidManifest.xml`.** Rebuild the UTF-16 string pool and replace the package name and
|
||||
**every string that carries its prefix** (permissions, provider authorities, the file provider, the
|
||||
push `C2D_MESSAGE` permission, and similar). Enumerate the suffixes from a table rather than
|
||||
guessing; update the chunk sizes and the file size; assert that no occurrence of the old name
|
||||
remains. Do not rename Java class names.
|
||||
2. **The `resources.arsc` package block.** Its name is a fixed 128-UTF-16-character field. Miss it
|
||||
and the build installs but resource resolution fails at start — the same symptom as a missing
|
||||
resource, far from the cause.
|
||||
3. **The launcher label**, in the arsc UTF-8 string pool. This can be replaced in place only when the
|
||||
new label is not longer than the old one.
|
||||
|
||||
Then grep Java/smali for quoted package-name literals and change build scripts to read the name from
|
||||
one variable instead of hardcoding it. The app's data directory becomes
|
||||
`Android/data/<new-package>/`, so old saves are not carried over — say so in the install notes.
|
||||
|
||||
Verify with `aapt dump badging` (package and label), then install both builds on one device: the new
|
||||
one must reach its main screen and read/write a save while the official one remains installed. The
|
||||
source's LayaAir/Conch case also had to change the arsc package name (Android 9+ compares it when
|
||||
resolving resources); hardcoded private-directory paths used a build-time placeholder, and the local
|
||||
licence value derived from `ANDROID_ID` did not change with the package name, while saves did.
|
||||
|
||||
### Vendor install interception (OEM shells)
|
||||
|
||||
Some ROMs route `adb install` through their own "security centre", which can return
|
||||
|
||||
@@ -83,8 +83,17 @@ reference file is not named here, or when a script is not named here.
|
||||
| The value you need (sign, token, risk parameter) is computed in **JavaScript** — a WebView or embedded JS engine — by an entry call fed a huge hex/base64 opcode literal: a JS virtual machine | `jsvmp-recovery.md` — de-obfuscate and **call it** first, then the stack/register-VM procedures and the four JS traps; `emulation-and-rpc.md` owns the call-don't-read route |
|
||||
| You are reading a decompiled **Kotlin** app and every class name is a meaningless short token (`nq.e`, `C0123x`) | `kotlin-name-recovery.md` — the original FQNs survive R8 inside `@DebugMetadata`/`@Metadata`; `scripts/kotlin_name_recovery.py` rebuilds the mapping from any jadx export |
|
||||
| A store build arrives as `base.apk` + `split_config.*.apk`, or a rebuilt build is refused **as a set** although every file verifies on its own | `split-apk.md` — one keystore across every member for `pm install-multiple`, and check that a merge is legal before trusting a merged single APK |
|
||||
| A debugger lists and attaches to the process, but the target `.so` is absent from the module list and every breakpoint in it refuses or never hits, while its feature works | `ida-so-debugging.md` §the `.so` was never extracted — `android:extractNativeLibs="false"` maps the library from `base.apk`, so there is no `/data/app/<pkg>/lib/<abi>/` file to bind to. Not an anti-debug finding |
|
||||
| A Unity package has no `Assembly-CSharp.dll` — only `libil2cpp.so` and `global-metadata.dat` — and every Java-layer hook turns out to be glue | `unity-runtime.md` — that is IL2CPP, the normal shipping configuration, not a stripped build: dump the pair with Il2CppDumper and import `script.json` before `stringliteral.json`, or the database is silently half-named |
|
||||
| A Unity IL2CPP package has **no readable `global-metadata.dat`** — 0 bytes, absent, wrong magic, a custom container, or a metadata version that disagrees with its own struct | `il2cpp-protected-metadata.md` — anchor on the consumer's output pointer, size the header without trusting its version, and recognise the XOR/VM/XXTEA shapes; `unity-runtime.md` owns the readable case |
|
||||
| You dumped `libil2cpp.so` from memory but the disassembler shows no symbols, or every registration search returns 0 | `il2cpp-protected-metadata.md` §4.1 — `p_offset=p_vaddr`, `p_filesz=p_memsz`, `e_shoff` from the last `PT_LOAD` end, `e_shstrndx`, `sh_offset=sh_addr`; the dump is fine, the ELF metadata is not |
|
||||
| A `dlopen`-able `.so` will not load after a custom loader, or a repaired `soinfo` resolves symbols to garbage | `linker-and-soinfo-repair.md` — bias versus base, `seg_page_offset`, the defining library's bias, `APS2` packed relocs, the minimal `soinfo` field set, and the dump window after `LoadSegments` |
|
||||
| A native trace has no `cmp`/`sub`/`jcc` — only `and/or/not/shr/neg`, a flags slot, and a `ret` that lands at a VM entry | `vm-protector-analysis.md` — virtual eflags is data, NAND lowering, branchless select, data-anchored breakpoints, and trace-then-search-by-constant; dispatcher slicing stays in `native-vm-recovery.md` |
|
||||
| The logic you need is Python bytecode — a `.pyc`/PyInstaller/Pyarmor payload rather than Java, Dart or native | `python-bytecode-recovery.md` — key schedule, AES-CTR nonce rules, the 12-byte VM, version-gated `pyc` parsing and the extra-section TLV; static and offline, then call the recovered module |
|
||||
| A Lua decompiler rejects every script with **`non-standard lua format: <n>`** | `unity-lua-and-assetbundles.md` §2 — a changed Lua 5.1 header byte, not encryption |
|
||||
| A re-signed Unity/Mono build exits cleanly with code 4 about two seconds in, with no Java exception | `unity-lua-and-assetbundles.md` §5 — a publisher shell owns the process |
|
||||
|
||||
_56 row(s) below the header._
|
||||
_70 row(s) below the header._
|
||||
|
||||
## Reference index (no longer inline in `SKILL.md`)
|
||||
|
||||
@@ -147,8 +156,15 @@ _56 row(s) below the header._
|
||||
| `references/kernel-and-environment-hardening.md` | Userspace hooking provably cannot reach the check — raw `svc` syscalls, `init_array`-early detection: what each layer can still do, the kernel-route map with its version gate, and when escalating is wrong |
|
||||
| `references/on-device-tooling.md` | Working **from the phone itself**: MT Manager edit/repack/sign and its built-in APK MCP, LSPosed Manager, Termux+frida, and on-device data inspection |
|
||||
| `references/split-apk.md` | The target is a **split APK / App Bundle set** (`base.apk` + `split_config.*.apk`), or `pm path <PKG>` returned several files: reading a set, merge versus unified re-signing, and the install refusal each mistake produces |
|
||||
| `references/unity-runtime.md` | The package is **Unity**: telling Mono from IL2CPP, dumping `libil2cpp.so` + `global-metadata.dat` with Il2CppDumper and importing it into IDA in the order that works, a run-time lookup over frida-il2cpp-bridge, the dnSpy-Unity-mono patch for a Mono player, and the audit probes when the deliverable is a report |
|
||||
| `references/unity-lua-and-assetbundles.md` | A Unity game keeps its logic in **Lua** (xLua/tolua/SLua), or the edit is in an AssetBundle: finding and decrypting the scripts, the Lua 5.1 header tamper, bundle CRC in the manifest the game actually reads, partial-encryption windows, UnityFS rebuild traps (layout loss, stripped dependencies, compressed==raw), added/replaced TextAsset read-back, and half-encrypted Mono assemblies behind a publisher shell |
|
||||
| `references/il2cpp-protected-metadata.md` | A Unity IL2CPP pair is **not readable**: `global-metadata.dat` is absent, 0 bytes, encrypted, embedded, or its version lies. Consumer-side dump, version-independent header sizing, the XOR/VM/XXTEA container shapes, the live-image dump, and the ELF repair that makes a dump usable |
|
||||
| `references/python-bytecode-recovery.md` | The logic is **Python bytecode** behind Pyarmor or PyInstaller: key derivation, AES-CTR nonce rules, the 12-byte VM, a version-gated `pyc` parser, the extra-section TLV, and per-code-object / per-string decryption |
|
||||
| `references/linker-and-soinfo-repair.md` | A protected `.so` must be loaded or dumped **by hand**: the `dlopen` pipeline as a loader spec, load_bias and segment arithmetic, `DT_*` parsing, relocation rules and the two biases, the minimal `soinfo` repair set, anti-dump header XOR, and where a dump is valid |
|
||||
| `references/vm-protector-analysis.md` | A native function is a VM protector with **virtual eflags**: no `cmp`/`sub`/`jcc`, only `and/or/not/shr/neg` and a flags slot. Envelope triage, VM anatomy, data-anchored breakpoints, trace-then-search-by-constant, NAND lowering, and branchless select. Handler slicing stays in `native-vm-recovery.md` |
|
||||
| `references/ida-so-debugging.md` | You need to **single-step or breakpoint a `.so`** rather than hook it: IDA's `dbgsrv` server with the ABI match, the wait-for-debugger start plus the JDWP handshake that actually releases the app, and the `extractNativeLibs="false"` failure where no breakpoint can bind |
|
||||
|
||||
_46 row(s) below the header._
|
||||
_62 row(s) below the header._
|
||||
|
||||
## Script index (no longer inline in `SKILL.md`)
|
||||
|
||||
@@ -220,4 +236,4 @@ _46 row(s) below the header._
|
||||
| `scripts/svc_scan.py` | Name the syscall behind an inline `svc` and the segment it sits in — which decides whether a libc-level hook can observe the call at all. `--context` shows neighbours, because a byte scan also matches data |
|
||||
| `scripts/anti_detect_probe.js` | Observer-only probe (patches nothing): path/loader/thread/kill hooks with **caller module + offset**, an environment self-report (`TracerPid`, frida-named mappings), and live streaming so a sub-second target still yields evidence |
|
||||
|
||||
_56 row(s) below the header._
|
||||
_64 row(s) below the header._
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
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.
|
||||
|
||||
**Test the outbound direction first.** Rewriting a response can make the client render a state the
|
||||
server never granted; rewriting a request changes what the server is asked to do. When you have both
|
||||
proxies available, mutate the request once and the response once, and keep the one whose effect
|
||||
survives a reload. A response-only success is a UI fact, not an authority fact.
|
||||
|
||||
## Harvest the API surface from the client
|
||||
|
||||
```bash
|
||||
|
||||
@@ -141,6 +141,39 @@ it also fails, the problem is environmental (`references/tls-and-cert.md`,
|
||||
- **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`.
|
||||
|
||||
## Variant: the value is an input to the digest, not the key
|
||||
|
||||
A different failure with the same source. A signer is reconstructed from static analysis and produces
|
||||
a signature the server refuses, while every ingredient visible in the request looks right. The formula
|
||||
turns out to be `sig = prefix + H(input || salt || key)`, and `salt` never appears in the request — it
|
||||
is generated at init from the certificate and cached in a global. (The certificate origin is
|
||||
`unverified` here; it is the same mechanism as the key case above, which is documented and likewise
|
||||
unmeasured.)
|
||||
|
||||
**Why it defeats black-box search: the search space is missing an argument.** Trying MD5/HMAC/SHA
|
||||
combinations over the visible parameters cannot find a value that is concatenated inside the digest and
|
||||
never transmitted. The symptom is *uniform* failure, not near-misses — that is the tell, and it is
|
||||
also why this is misread as "the algorithm is not fully recovered". (`observed`, host, synthetic: a
|
||||
36-combination search over three algorithms and four field orders returns zero hits against a digest
|
||||
with a hidden 16-byte salt, and returns the target the moment the salt is included — see the
|
||||
EXTENSION record.)
|
||||
|
||||
How to get it:
|
||||
|
||||
- **Find the buffer.** It is written once (during `JNI_OnLoad` or the first signature call), it is a
|
||||
fixed-size array, and no exported function returns it. A memory read after init is enough.
|
||||
- **Or hook the digest update** and dump its argument on one request; the salt is the constant run
|
||||
inside an otherwise changing buffer.
|
||||
- **Verify with three captured triples** that vary one field each. A formula that matches all three is
|
||||
the formula; one that matches one is a coincidence. (`inferred`.)
|
||||
|
||||
Consequence for the deliverable: the salt is per build and per certificate. A local signer carries the
|
||||
captured constant plus a build fingerprint (the same discipline as an extracted VM program,
|
||||
`native-vm-recovery.md` §11), and the report says which build it came from. On update the value
|
||||
changes and the signer must be re-derived — do not present the constant as an algorithm.
|
||||
(`inferred` from the certificate binding, not measured.)
|
||||
|
||||
|
||||
## Cost of getting this wrong
|
||||
|
||||
Without this step the task stalls in the worst possible way: the artifact is correct, the
|
||||
|
||||
@@ -221,6 +221,28 @@ the attribute chunks around it, which is what `apktool` is for — and note that
|
||||
`apktool b` rebuild rewrites the whole archive
|
||||
(`references/repack-and-sign.md` §Repacking an unpacked (de-shelled) app).
|
||||
|
||||
### A narrow manual merge through apktool (when bundletool is unavailable)
|
||||
|
||||
The rule above is the safe one: do not fold resource tables by hand. There is one exception narrow
|
||||
enough to name — a set whose resource splits are **additive** (density or language variants that do not
|
||||
redefine an existing name with a different id). The source's native case did this and installed the
|
||||
result as a single APK:
|
||||
|
||||
1. Install the base as an apktool framework: `apktool if base.apk -p <dir> -t <tag>`.
|
||||
2. Decode each split with the same `-p/-t` so its resources keep their **original ids** instead of
|
||||
being renumbered by the decoder.
|
||||
3. Copy the split's `res/` files into the base and add their ids to the base's `public.xml`. Skip a
|
||||
name that already exists with the same id; replace `APKTOOL_DUMMY_0x...` names by looking the real
|
||||
name up in the base's id table.
|
||||
4. Copy `lib/<abi>/` into the base. In the manifest, remove `requiredSplitTypes`, `splitTypes`,
|
||||
`vending.splits` and `stamp.*`, and set `extractNativeLibs="true"`.
|
||||
5. Verify every resource reference resolves and the app renders the split-only content. If two members
|
||||
define the same resource name with different ids, **stop** — that is the folding problem the first
|
||||
rule warns about, and bundletool is the route.
|
||||
|
||||
This is a per-set workaround, not a resource merger. Say in the delivery which splits were folded and
|
||||
which resource families they carried.
|
||||
|
||||
## 6. Install refusals, and what each one means
|
||||
|
||||
| Message | What it actually says | Attribution |
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
# Unity + Lua, AssetBundles, and half-encrypted Mono assemblies
|
||||
|
||||
Load this when a Unity APK keeps its game logic in Lua (xLua / tolua / SLua), when the thing you need to
|
||||
edit is an AssetBundle rather than an assembly, or when a rebuilt Unity package fails in a way that
|
||||
looks like the patch: a decompiler rejects every script, a bundle loads as null, a repacked bundle
|
||||
crashes only on device, or a re-signed Mono build exits cleanly a second or two after the splash. It
|
||||
is the script-and-asset half of Unity; `unity-runtime.md` owns Mono/IL2CPP identification and the
|
||||
managed-code route, and `il2cpp-protected-metadata.md` owns protected IL2CPP metadata.
|
||||
|
||||
**Claim strength.** Absorbed from a public game-preservation skill's anonymised case reports: one
|
||||
Unity + Lua target (1,443 encrypted TextAssets, a Lua bundle, CRC in an AssetBundle manifest) and one
|
||||
Unity Mono + SLua target (8,420 Lua 5.1 TextAssets, a publisher shell that decrypts the first 4 KB of
|
||||
each assembly, a 1.2 GB micro-client). The source reports these as work performed on real devices;
|
||||
**this repository has run none of it** — no Unity package was decrypted, no bundle rebuilt, and no
|
||||
Mono assembly reconstructed here. Every mechanism below is therefore `unverified`, and the counts
|
||||
and offsets are the source's, not this repository's measurements. What generalises is the failure
|
||||
shape, not the constants.
|
||||
|
||||
## 1. Recognise the shape before choosing a tool
|
||||
|
||||
| What is in the package | Where the logic is | Route |
|
||||
|---|---|---|
|
||||
| `libunity.so` + `libmono*.so` + `assets/bin/Data/Managed/Assembly-CSharp.dll` | C# IL | `unity-runtime.md` §Mono |
|
||||
| `libunity.so` + `libil2cpp.so` + `global-metadata.dat` | native + metadata | `unity-runtime.md` §IL2CPP |
|
||||
| `libunity.so` + a `luascript` bundle or thousands of Lua `TextAsset` entries | Lua source or Lua 5.1 bytecode | this file §2 |
|
||||
| `assets/AssetBundles/<platform>/` with per-bundle `.manifest` files | assets, prefabs, textures, sometimes scripts | this file §3–§4 |
|
||||
| `Application` is a vendor shell class + `libtprt.so` / `__tpinfo.tsa` | shell decrypts managed assemblies at run time | this file §5 |
|
||||
|
||||
The first question is not "how do I decrypt Lua" but **which layer owns the behaviour**. A Lua game
|
||||
can have almost no interesting C#: the C# boots the engine, loads a bundle and calls into Lua. In that
|
||||
shape, editing IL is the wrong layer even when the IL is readable.
|
||||
|
||||
## 2. Getting Lua out of a Unity package
|
||||
|
||||
### 2.1 Find the container and the key
|
||||
|
||||
Scripts usually live in one of three places: a dedicated bundle such as `luascript`, individual
|
||||
`TextAsset` entries inside many bundles, or a loose file list such as `all_lua_files.lua` (which is
|
||||
often the one plaintext index that names the rest). Locate the loader first: a C# method with names
|
||||
like `LuaScriptKey`, `ScriptKey`, `Key()` or `LuaRuntimeConfig` is where the key is chosen.
|
||||
|
||||
The source's case A: 1,443 `TextAsset` entries, DES-CBC, and **`key == IV ==` an 8-byte constant**
|
||||
taken from `LuaRuntimeConfig.LuaScriptKey()`. Do not assume every script is encrypted: in that case
|
||||
`all_lua_files.lua` was plaintext. Decrypt a sample, then prove the output is a script (it parses,
|
||||
and its first line is plausible Lua) before batch-processing 1,443 files.
|
||||
|
||||
Patterns worth recognising without reversing the decryptor:
|
||||
|
||||
- **Header-only tamper.** A Lua 5.1 chunk starts with signature `1B 4C 75 61` and version `51`;
|
||||
the next byte (offset 5) is the format byte, normally `00`. A build that changes it to `01` makes
|
||||
`unluac` say *"non-standard lua format: 1"* while the rest of the file is untouched. Compare the
|
||||
first 12 bytes with the standard header before concluding "encrypted".
|
||||
- **A single-byte XOR tail** with a strongly encrypted head (see §5 for the assembly version). The
|
||||
tell is the plaintext zero: deep in the file, the same byte repeats in long runs. One byte of XOR
|
||||
turns every plaintext zero into that byte.
|
||||
- **A "decrypt" that is only a wrapper.** Before implementing a cipher, check whether the transform
|
||||
cancels (a repeating XOR with a fixed key, or a stream cipher applied twice). `protocol-reverse.md`
|
||||
§7 has the differential probe for classifying a primitive; use it when the shape is not obvious.
|
||||
|
||||
### 2.2 Repair the header, then decide what the loader accepts
|
||||
|
||||
For the byte-5 tamper, copy the standard 5.1 header over the first 12 bytes, then decompile one file.
|
||||
If the opcodes were not shuffled, the output is clean source; if the decompiler produces nonsense,
|
||||
the build may also have shuffled opcodes, which is a different problem.
|
||||
|
||||
The other half is the loader: the C# call that loads a chunk often takes a mode/`bytecodeOnly` flag.
|
||||
If the bundle path loads with `bytecodeOnly == false`, your patch can be **plaintext Lua** — no need
|
||||
to find a matching 32-bit `luac`. If it is true, recompile the module to the exact Lua version and
|
||||
ABI, or patch the loader to accept source. Read the call site, do not guess from the file extension.
|
||||
|
||||
Batch decompilation is CPU-bound per file (a JVM start per script in the source's toolchain); run it
|
||||
in parallel and keep the output indexed by entry name, because the next step is a lookup, not a read.
|
||||
|
||||
### 2.3 Verify content against entry names
|
||||
|
||||
Lua 5.1 bytecode stores its source name immediately after the header (for example
|
||||
`@UI/reputationshop/shop.lua`). After a batch decompile, compare **the entry name with the chunk
|
||||
name** before analysing anything. In the source's case, 112 files decompiled to the same unrelated
|
||||
file because their bundle writer had cloned a template object and `read()` kept returning the
|
||||
template's bytes. The game itself was fine; only the analysis copy was wrong.
|
||||
|
||||
The same warning applies to a hot-update merge: if your bundle wrapper replaces `main.lua` but
|
||||
`read()` still returns the packaged original, the build patches the **old** script, and the
|
||||
hot-update version's constants silently disappear. Keep a sidecar map of every byte you write
|
||||
(replacements and additions) and make your reader return it first; then compare the bytes read back
|
||||
with the hot-update file before trusting a patch.
|
||||
|
||||
## 3. AssetBundle integrity: the CRC is not where you guess
|
||||
|
||||
Unity verifies a bundle's CRC when it loads it. The value can live in:
|
||||
|
||||
- `<bundle>.manifest` next to the bundle, and
|
||||
- `assets/AssetBundles/<platform>/AssetDatabase.manifest` (the catalogue).
|
||||
|
||||
Guessing which one is live costs a full round. **Run the unmodified build once and read the log** —
|
||||
Unity prints both values:
|
||||
|
||||
```text
|
||||
E/Unity: CRC Mismatch. Provided d906612, calculated ab764880 from data.
|
||||
Will not load AssetBundle 'luascript'
|
||||
```
|
||||
|
||||
Change the manifest the game actually reads (the catalogue in the source's case, not the same-named
|
||||
bundle manifest) to `0` (skip) or to the computed value. Then verify the bundle loads, not only that
|
||||
the error disappeared.
|
||||
|
||||
**An 8-byte zero prefix is not corruption.** In the source's case A, 2,354 of 2,355 bundles began with
|
||||
eight `0x00` bytes in the original package; the only exception was the catalogue. All of them loaded.
|
||||
An earlier pass "repaired" 13 of them and carried the damage into the next baseline. Count the prefix
|
||||
across the original package before treating it as a fault; skip it on read and preserve it on write.
|
||||
|
||||
### 3.1 A bundle whose first block will not decompress
|
||||
|
||||
The shape is: a valid `UnityFS` header, the first compressed block fails to decompress, later blocks
|
||||
are fine. That is a **partial-encryption window**, not a corrupt download. To bound it:
|
||||
|
||||
1. Parse the UnityFS header and block table yourself; decompress each block independently and record
|
||||
which blocks fail.
|
||||
2. Entropy-scan the failing block's compressed stream. A sharp drop in entropy marks the end of the
|
||||
encrypted window.
|
||||
3. Run the block's compressor (often LZ4) directly over the ciphertext; the byte offset where it
|
||||
crashes is the start of the window.
|
||||
4. Compare the start/end across several bundles. The source found 1,691 bundles with the same
|
||||
`[56:4096]` window, which proves a build-wide scheme rather than per-file damage.
|
||||
5. XOR two ciphertexts from different bundles: if the transform is a fixed stream cipher, the
|
||||
plaintext-derived difference is stable. That tells you the shape, not the key.
|
||||
|
||||
Only after this do you know what you are missing: the key or the algorithm. Do not rebuild the
|
||||
bundles before the window is pinned.
|
||||
|
||||
## 4. Rebuilding a bundle without changing it
|
||||
|
||||
A bundle is a serialized container, not a zip. Two independent traps:
|
||||
|
||||
**The rewriter changes the header/layout.** UnityPy's `save_typetree` can produce a much smaller
|
||||
serialized file than the original (the source saw 6,700 → 3,552 bytes) because it drops the original
|
||||
header layout and alignment padding. Compare the object metadata and header of old and new files; if
|
||||
they differ, pad/restore the original layout before writing the bundle back. For a texture, render the
|
||||
new text with the game's own font and encode it back to the original format (ETC2 in that case); do
|
||||
not assume a PNG round-trip is equivalent.
|
||||
|
||||
**A stripped resource is still in the dependency graph.** If you remove an AssetBundle but leave the
|
||||
`AssetBundleManifest` listing it as a dependency of a retained bundle, Unity returns **null** for the
|
||||
retained bundle. Remove the dependency edges when you remove the assets, not only the files.
|
||||
|
||||
**The compressed-size edge case.** A rebuilt bundle can crash where a block's compressed size equals
|
||||
its raw size — the loader takes a branch that assumes compression. Do not debug this inside a full
|
||||
build. Replace one hand-made bundle into an existing signed APK, re-align and re-sign, install and
|
||||
cold-start; each experiment is about a minute. Write a minimal UnityFS reader that lets you change one
|
||||
block size, one compression flag or one field at a time, and keep a control bundle that differs in
|
||||
nothing. That is how the source found the exact equality that broke the load.
|
||||
|
||||
### 4.1 Adding or replacing a TextAsset
|
||||
|
||||
When a Lua script is added to an existing bundle, the writer has to create a new serialized object and
|
||||
update the container index. Two checks make this safe:
|
||||
|
||||
- **Keep the bytes you wrote.** Do not rely on a library's `read()` after `set_raw`/`save_typetree`;
|
||||
some versions return the template object or the original bytes. Store the written payload in a
|
||||
sidecar map and serve it on read.
|
||||
- **Verify entry name and chunk name agree**, for every added and every replaced script. Then verify
|
||||
the bytes read back equal the source file you intended (especially after merging a hot-update
|
||||
layer). A build that patches the old script is indistinguishable from a patch that did nothing.
|
||||
|
||||
## 5. Mono assemblies: half-encryption, a rebuilt PE header, and the publisher shell
|
||||
|
||||
This is a different shape from a packed dex. The assembly file is present and looks like a PE, but its
|
||||
first `0x1000` bytes are strongly encrypted and the rest is XORed with one byte. The tell is the same
|
||||
as §2: deep in the file, one value repeats in long runs, because plaintext zeros became that value.
|
||||
Autocorrelation does not show a period; the repeated value does.
|
||||
|
||||
To read it without reversing the runtime's decryptor:
|
||||
|
||||
1. XOR the tail with the single byte.
|
||||
2. Rebuild the PE header from structural landmarks rather than guessing offsets: the
|
||||
`_CorDllMain`/`mscoree.dll` import, the `FF 25 00 20 40 00` entry trampoline, the `.reloc`
|
||||
block that points at it, `VS_VERSION_INFO` in `.rsrc`, and the `BSJB` metadata root.
|
||||
3. Watch for an extra `.sdata` section (static-field initial values): it appears as a hole between
|
||||
`.text` and `.rsrc` and as a file offset `0x400` instead of `0x200` for `.text`. Missing it
|
||||
makes ILSpy report *"Field data (rva=...) could not be found in any section"*.
|
||||
4. Accept the boundary: methods whose bodies lived in the first 4 KB are lost (the source counted 87
|
||||
small constructors and 123 getters across two assemblies). Static analysis of the rest still works.
|
||||
|
||||
**The publisher shell changes the plan.** If `AndroidManifest`'s `application` is a vendor class
|
||||
(for example a `TPShellApplication`) and `lib/` contains its runtime, the shell checks the APK
|
||||
(signature/CRC/package) and kills the process about two seconds after launch. The symptom is
|
||||
`Process ... exited cleanly (4)` with **no Java exception** and no tombstone. Do not read that as a
|
||||
normal crash. The same shell often decrypts the assembly heads, so removing it also removes the thing
|
||||
that made the assemblies readable.
|
||||
|
||||
The source's route: switch the shell off through its own dex string constants (same-length value
|
||||
change, then recompute the dex header's SHA-1 and adler32), and recover the plaintext assemblies from
|
||||
the **original game's process memory** — root, read `/proc/<pid>/maps`, stream anonymous regions,
|
||||
locate the known XORed body, and restore the DOS header the shell zeroed. That route is specific to
|
||||
that shell; the general rule is: identify the shell's own kill signal and its own string gate before
|
||||
patching, and do not ship a rebuild while the shell still owns the process. Shell identification and
|
||||
the keep/drop decision are in `packers.md` and `code-virtualization-and-custom-linkers.md`;
|
||||
`advanced-unpacking.md` owns the memory-dump boundary.
|
||||
|
||||
## 6. Verification
|
||||
|
||||
A Unity asset patch is done when:
|
||||
|
||||
- the bundle **loads** (the CRC error is gone, and no null bundle appears in the log);
|
||||
- the script's **entry name, chunk name and decompiled content** agree;
|
||||
- a replaced script's bytes read back byte-identical to the source you wrote;
|
||||
- an added entry exists in the container index and is returned by the loader;
|
||||
- the on-device screen shows the change, after a cold start, on the same build you installed;
|
||||
- a control build with **no** patch shows the old behaviour on the same device.
|
||||
|
||||
A hash of the APK is not evidence that the bundle inside it changed — check the bundle entry, not the
|
||||
APK size. Signing and alignment stay in `repack-and-sign.md`.
|
||||
|
||||
## 7. Boundary
|
||||
|
||||
- **IL2CPP metadata and native code** — `unity-runtime.md` and `il2cpp-protected-metadata.md`.
|
||||
- **A packer or a self-terminating native check** — `packers.md`,
|
||||
`code-virtualization-and-custom-linkers.md`, `native-tamper-and-suicide.md`.
|
||||
- **Crypto classification** — `protocol-reverse.md` §7; do not implement a cipher from a guess.
|
||||
- **The game's network layer** — `protocol-reverse.md` and `server-api.md`.
|
||||
- **Splitting, signing and package rename** — `split-apk.md` and `repack-and-sign.md`.
|
||||
@@ -0,0 +1,277 @@
|
||||
# Unity: Mono and IL2CPP, and where the logic actually lives
|
||||
|
||||
Load this when the package is Unity — `libunity.so` under `lib/<abi>/`, `assets/bin/Data/` — and the
|
||||
question is where the game logic is, how to read it, or how to attach a debugger to it.
|
||||
`framework-runtimes.md` owns *is this even a runtime* and the layer trap; this file owns the two
|
||||
backends and the tools that turn each one back into readable code. Patching that layer is
|
||||
`native-and-so.md`; the Android shell around it is `recon.md`.
|
||||
|
||||
**Claim strength.** Absorbed from three public write-ups (2026-02 and 2026-06, plus a
|
||||
dnSpy-Unity-mono build note), not measured here: no Unity package was dumped and no patched Mono
|
||||
runtime was built in this record. Tool names, paths and the two magic numbers are `unverified`
|
||||
until you reproduce them; the statements about *which layer owns what* are `inferred` from the same
|
||||
sources. Steps this file adds as judgement rather than quotation are marked inline.
|
||||
|
||||
## 1. Two backends, decided by two files
|
||||
|
||||
| What the package ships | Backend | Where the logic is |
|
||||
|---|---|---|
|
||||
| `assets/bin/Data/Managed/*.dll` — `Assembly-CSharp.dll` first | **Mono** | CIL in the managed assemblies, JIT-compiled by the Mono VM at run time |
|
||||
| `lib/<abi>/libil2cpp.so` **and** `assets/bin/Data/Managed/Metadata/global-metadata.dat` | **IL2CPP** | C# compiled to C++ then to native code in the `.so`; names, types and literals survive in the metadata |
|
||||
|
||||
`libunity.so` is the engine and is present either way. A Mono build still ships native engine code,
|
||||
so "there is a big `.so`" proves nothing. On a desktop build the same split appears as
|
||||
`*_Data/Managed/Assembly-CSharp.dll` versus `GameAssembly.dll` + `*_Data/il2cpp_data/Metadata/global-metadata.dat`.
|
||||
|
||||
```bash
|
||||
unzip -l app.apk | grep -Ei 'Assembly-CSharp|libil2cpp|libunity|global-metadata'
|
||||
```
|
||||
|
||||
Two mis-readings to kill early:
|
||||
|
||||
- **"No `Assembly-CSharp.dll`, so the code is stripped or encrypted."** No — that is IL2CPP, the
|
||||
normal shipping configuration. The logic is in `libil2cpp.so`; nothing is missing.
|
||||
- **"The metadata is not at that path, so this build has no metadata."** Older and split packages move
|
||||
it; look for `global-metadata.dat` anywhere under `assets/` before concluding anything, and if the
|
||||
package is split, check every member (`split-apk.md`).
|
||||
|
||||
## 2. Mono: the logic is IL, and IL is readable
|
||||
|
||||
`Assembly-CSharp.dll` is the developer's own code. `UnityEngine*.dll`, `mscorlib`, `netstandard` and
|
||||
the `System.*` family are the framework — worth opening once to learn an API's shape, never the
|
||||
target of a search. dnSpyEx or ILSpy opens the assembly and decompiles it to C#; search for the
|
||||
user-visible string first, then `Analyze` on the method that references it for callers and callees.
|
||||
|
||||
The only real obstacles at this layer are name obfuscation (locate by string, field shape and
|
||||
call graph instead) and an `Assembly-CSharp.dll` that will not parse at all (then it is encrypted,
|
||||
which is a packer problem — `packers.md`).
|
||||
|
||||
## 3. Debugging Mono at run time: the stock runtime will not accept the connection
|
||||
|
||||
dnSpy's *Unity (connect)* expects to drive the Mono debugger agent through
|
||||
`--debugger-agent=transport=dt_socket,...` handed to `mono_jit_parse_options`, and it expects
|
||||
`Debugger.IsAttached` to be truthful. A retail Unity build ships a Mono runtime that carries neither
|
||||
the dnSpy hook nor a launcher that passes those options, and `defer=y` versus `suspend=n` differs by
|
||||
Unity version — so the connection is either never accepted or the player sits suspended at startup.
|
||||
The published route is to build the Unity-flavoured Mono with the dnSpy-Unity-mono changes and swap
|
||||
`MonoBleedingEdge/EmbedRuntime/mono-2.0-bdwgc.dll` (back the original up first, then start the game
|
||||
and use *File → Debug → Unity (connect)*).
|
||||
|
||||
The patch is small and each hunk has a purpose worth knowing, because the same hooks are what a
|
||||
hardened game would detect:
|
||||
|
||||
| Change | Effect |
|
||||
|---|---|
|
||||
| `ves_icall_System_Diagnostics_Debugger_IsAttached_internal` returns 0 while `dnSpy_hideDebugger` is set | the game's own `Debugger.IsAttached` anti-debug reads "not attached" **while you are attached** — the flag defaults to 1, i.e. hiding is the default |
|
||||
| `dnSpy_debugger_init()` called from `mini_init`, reading `DNSPY_UNITY_DBG` / `DNSPY_UNITY_DBG2`, else a built-in `--debugger-agent=transport=dt_socket,server=y,address=127.0.0.1:55555,defer=y` | the agent is configured before the VM starts, with no launcher cooperation |
|
||||
| `dnSpy_debugger_agent_parse_options` accepts a `no-hide-debugger` argument | the opt-out from the lie above, for the case where you *want* the game to see you |
|
||||
| `mono_debug_init` returns instead of `g_assert(!mono_debug_initialized)` | a second initialisation no longer aborts; the agent and the engine both call it |
|
||||
| `insert_breakpoint` prefers a sequence point without `MONO_SEQ_POINT_FLAG_NONEMPTY_STACK` | a breakpoint at an IL offset lands somewhere legal instead of being deferred or rejected |
|
||||
| bdwgc built with `GC_DISABLE_INCREMENTAL` | the incremental collector no longer moves objects under the debugger's feet |
|
||||
| a dummy `mono_profiler_install` after `debugger_agent_init` | the agent's profiler events are not overwritten by the engine's installer |
|
||||
|
||||
Build `libmono-dynamic` Release/x64 from `msvc/mono.sln`. The write-up's own trap: linking fails
|
||||
until the new `dnSpy.c` is compiled by hand first, because the project file has not picked it up yet.
|
||||
|
||||
Two boundaries. A prebuilt `mono-2.0-bdwgc.dll` for one Unity version circulates with that write-up —
|
||||
that is a third-party binary, so audit it before use (`third-party-builds.md`). And on Android the
|
||||
equivalent artifact is `lib/<abi>/libmono.so` (*inferred* — the source is desktop-only); replacing it
|
||||
changes the APK, so it is a repack with all of a repack's obligations (`repack-and-sign.md`,
|
||||
`signature-derived-keys.md`).
|
||||
|
||||
## 4. IL2CPP: native code plus a metadata table
|
||||
|
||||
`libil2cpp.so` is the whole of the C# code, ahead-of-time compiled, with no IL and no names. The
|
||||
names, namespaces, field and method signatures, type relationships and string literals live in
|
||||
`global-metadata.dat`. The pair is the unit of work: the `.so` is unreadable without the metadata, and
|
||||
the metadata alone gives you a class list with no addresses.
|
||||
|
||||
Both files also tell you whether they are plain, in one line each — and getting this wrong is the most
|
||||
expensive mis-diagnosis at this layer, because "no symbols" and "encrypted symbols" look identical in
|
||||
a decompiler:
|
||||
|
||||
```bash
|
||||
xxd -l 16 lib/arm64-v8a/libil2cpp.so # 7f 45 4c 46 (ELF)
|
||||
xxd -l 16 assets/bin/Data/Managed/Metadata/global-metadata.dat # af 1b b1 fa (0xFAB11BAF)
|
||||
```
|
||||
|
||||
### Il2CppDumper, and the order of the IDA import
|
||||
|
||||
```bash
|
||||
Il2CppDumper libil2cpp.so global-metadata.dat out/
|
||||
```
|
||||
|
||||
On a desktop build pass `GameAssembly.dll` in place of `libil2cpp.so`. The outputs that matter:
|
||||
|
||||
| Output | Use |
|
||||
|---|---|
|
||||
| `DummyDll/` (and `dump.cs`) | the recovered class / method / field *outline* — open in ILSpy or dnSpy to navigate; bodies are absent by construction |
|
||||
| `il2cpp.h` | structs for the decompiler, so IL2CPP objects stop looking like `void*` |
|
||||
| `script.json` | method → address, the table that names functions in IDA or Ghidra |
|
||||
| `stringliteral.json` | literal → address, the table that names string data |
|
||||
| `ida_py3.py` / `ida_with_struct_py3.py` (or `ghidra.py`) | the importers |
|
||||
|
||||
The import order is not cosmetic: each script decorates what the previous one produced, so running
|
||||
them out of order **succeeds** and leaves a half-named database. In IDA, File → Script file, in this
|
||||
order:
|
||||
|
||||
1. `ida_py3.py`
|
||||
2. `script.json`
|
||||
3. `stringliteral.json`
|
||||
4. `ida_with_struct_py3.py`, answering `script.json` then `il2cpp.h`
|
||||
|
||||
Then analyse from a named function, not from the string blob. Cpp2IL is the alternative front end
|
||||
(`Cpp2IL --help`, then `--game-path <dir> --output-to <dir>`); when two dumpers disagree about the
|
||||
same binary, the disagreement is a claim about your toolchain until a reproducible run settles it —
|
||||
the same rule as `pitfalls.md` P47.
|
||||
|
||||
### When the metadata does not parse
|
||||
|
||||
- **Encrypted metadata** (`xxd` shows the wrong magic): dump at run time with Zygisk-Il2CppDumper, or
|
||||
recover the loader's decryption (`packers.md`). A static dumper will never succeed here, and retrying
|
||||
with another one is the wrong move.
|
||||
When the file is absent, 0 bytes, embedded, or wrapped in a custom container, `il2cpp-protected-metadata.md`
|
||||
owns the consumer-side dump, the header sizing rule and the container shapes; this file resumes once a
|
||||
parseable pair exists.
|
||||
- **Version newer than the dumper**: pin the dumper to the Unity version. A dump from the wrong version
|
||||
produces plausible names with wrong struct offsets, so treat every field offset as suspect until one
|
||||
is confirmed at run time.
|
||||
- **Names still missing after a successful dump**: check you are looking at the module the process
|
||||
actually loads — a split or stubbed `libil2cpp.so` inside the APK is not necessarily the one mapped
|
||||
(`native-and-so.md`).
|
||||
|
||||
### When the managed layer is itself the interpreter
|
||||
|
||||
IL2CPP is ahead-of-time compiled, which makes it tempting to read `libil2cpp.so` as the only code that
|
||||
matters. A `.so` that looks like a thin wrapper over `Dictionary` and delegate calls is often sitting
|
||||
on top of an interpreter written in C# — and a VM written in C# is recoverable from `dump.cs` without
|
||||
ever reading an opcode handler in assembly. The shape in `dump.cs`:
|
||||
|
||||
```text
|
||||
class <obf> {
|
||||
int[] aa1; // the guest program, built from a literal
|
||||
int aa5; // the cursor, i.e. the PC / vEIP
|
||||
Dictionary<int, Action> aa8; // opcode -> handler
|
||||
}
|
||||
```
|
||||
|
||||
A `while` loop that reads `array[cursor]` and calls `dict[op]` is the dispatcher; the array initialised
|
||||
from a literal and the dictionary filled in the constructor are the program and the handler table. The
|
||||
handler *indices* are assigned in the constructor by walking an enum or a `static_fields` block (one
|
||||
sample enumerated 1..22 and used those values as dictionary keys), so the opcode→handler map is a
|
||||
property of the constructor, not something to discover by tracing. Read the constructor first, rename
|
||||
the fields positionally to `a1..aN`, delete the null and length guards, and the dispatch loop becomes
|
||||
plain control flow. If the program array is built at run time, hook the constructor and take its
|
||||
argument instead of tracing the loop.
|
||||
|
||||
The recovery method does not change once you have the instruction stream — `vmp-differential-analysis.md`
|
||||
for the opcode map and `native-vm-recovery.md` §11 for the artefact set. What changes is the cost: a
|
||||
managed VM is read statically, in a decompiler that still has names.
|
||||
|
||||
### Array literals are not in `.rodata`
|
||||
|
||||
A static array literal — a crypto key, an S-box, a constant table — has **no inline initialiser in
|
||||
`libil2cpp.so`**. IL2CPP stores the field's default value in the metadata and materialises it at class
|
||||
init by calling `RuntimeHelpers::InitializeArray` (the managed-side name; the implementation copies
|
||||
from the field-default blob). Consequences for both reading and searching:
|
||||
|
||||
- `grep`-ing the `.so`, or `strings`-`ing` it, cannot find the table, and its absence is not evidence
|
||||
that the table is derived at run time.
|
||||
- Hook `InitializeArray` (or break on it) and the argument is the table; the same bytes are also
|
||||
readable from the metadata field-default blob without a device.
|
||||
- The table is per-field, so one hook gives you every literal the class initialisation touches, which
|
||||
is usually the whole key schedule of a hand-rolled cipher.
|
||||
|
||||
This is the cheapest way to answer "where does this constant come from" in a Unity target, and it is
|
||||
cheaper than reconstructing the cipher. `unverified`: the API name is stable across Unity versions, the
|
||||
argument shape is not.
|
||||
|
||||
## 5. Driving IL2CPP at run time: frida-il2cpp-bridge
|
||||
|
||||
When the dump is encrypted or the question is behavioural, the bridge resolves classes by name at run
|
||||
time through the exported il2cpp API. Trace a class:
|
||||
|
||||
```ts
|
||||
import "frida-il2cpp-bridge";
|
||||
Il2Cpp.perform(() => {
|
||||
const image = Il2Cpp.domain.assembly("Assembly-CSharp").image;
|
||||
const cls = image.class("Assets.Scripts.AndroidKit");
|
||||
Il2Cpp.trace(true).classes(cls).and().attach();
|
||||
});
|
||||
```
|
||||
|
||||
or one method, with `Il2Cpp.trace(true).methods(cls.method("SetShield")).and().attach()`. Run it with
|
||||
`frida -U -f <pkg> -l frida.js`, and `Il2Cpp.dump()` writes a metadata dump from the live process —
|
||||
the usual answer to an encrypted `global-metadata.dat`. Il2CppHookScripts (`il2cpp-hooker`) is a
|
||||
scripted alternative with the same dependency.
|
||||
|
||||
**Ask the live object graph before rebuilding crypto.** When the question is a decrypted value
|
||||
rather than a class's shape, the cheapest route is often to let the app construct it:
|
||||
|
||||
```ts
|
||||
Il2Cpp.perform(() => {
|
||||
const api = Il2Cpp.domain.assembly("Assembly-CSharp").image.class("Game.APIManager");
|
||||
Il2Cpp.gc.choose(api).forEach(instance => {
|
||||
const cipher = instance.method<Il2Cpp.Object>("get_Crypt").invoke();
|
||||
console.log(cipher.method<Il2Cpp.Object>("get_Key").invoke().toString());
|
||||
console.log(cipher.method<Il2Cpp.Object>("get_IV").invoke().toString());
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
`Il2Cpp.gc.choose` enumerates live instances without knowing the allocation site; getters and
|
||||
fields then return the object the app actually uses. This is `inferred` from a public write-up and
|
||||
not exercised here: the method names and class names are target-specific, and a build that hides
|
||||
the il2cpp exports breaks the bridge exactly as in the paragraph above.
|
||||
|
||||
`Il2Cpp.dump("name", "/data/data/<pkg>/files")` takes an explicit name and an app-writable
|
||||
directory; with no arguments it uses defaults that may not be writable on a hardened build. A dump
|
||||
written before the metadata is decrypted is the encrypted file again — check the magic before
|
||||
importing it.
|
||||
|
||||
**Hook the framework primitive, not the app's wrapper.** Obfuscation renames the app's classes; it
|
||||
does not rename `System.Security.Cryptography.*`, `javax.crypto.Cipher` or `java.security.*`. So when
|
||||
the question is "what key does this use", trace the primitive instead of the wrapper the app built:
|
||||
|
||||
```ts
|
||||
Il2Cpp.trace(true).classes(Il2Cpp.domain.assembly("System.Security.Cryptography")
|
||||
.image.class("System.Security.Cryptography.AesCryptoServiceProvider")).and().attach();
|
||||
```
|
||||
|
||||
One such trace reports every key/IV pair the process constructs, no matter which wrapper or
|
||||
obfuscated call chain produced it, and it removes the need to reconstruct the derivation. On the Java
|
||||
side the equivalent pair is a hook on `Cipher.getInstance` plus `SecretKeySpec` / `IvParameterSpec`.
|
||||
The trade is provenance: the primitive tells you the value, not which call site asked for it — use the
|
||||
app's own class (above) when you need the call site, and the primitive when the derivation is hostile
|
||||
and you only need the material. `unverified` here: neither trace was run in this record.
|
||||
|
||||
|
||||
The dependency is the boundary: a build that hides or strips the il2cpp exports breaks the bridge, and
|
||||
the failure presents as *class not found* — indistinguishable from a wrong class name. Confirm the
|
||||
exports exist before believing a negative lookup.
|
||||
|
||||
## 6. When the deliverable is an audit rather than a patch
|
||||
|
||||
The same artifacts answer "what does this package leak", which is often the actual request. One probe
|
||||
per question:
|
||||
|
||||
| Question | Probe |
|
||||
|---|---|
|
||||
| Is this a development build? | `android:debuggable` in the manifest; `Development Build` / script-debugging strings; the `Unity` logcat tag |
|
||||
| Do test endpoints or secrets ship in the code? | `strings -a libil2cpp.so \| rg -i 'secret\|token\|password\|gm\|cheat\|test-api'`, the same over `global-metadata.dat`, and `rg` over `dump.cs` / `DummyDll` |
|
||||
| Are unshipped assets in the package? | AssetStudio or AssetRipper over `assets/bin/Data`: `TextAsset` configs, `Texture2D`, `AudioClip`, `AssetBundle` names |
|
||||
| Does the Android shell leak? | jadx for hardcoded SDK keys, permissions, exported components; `apktool d` for the manifest |
|
||||
| Is the client authoritative for currency, drops or purchases? | proxy and replay (`protocol-reverse.md`): a client-supplied value the server never recomputes is the finding, and no client-side change fixes it (`server-api.md`) |
|
||||
|
||||
Report one finding per row with the probe, the file and the offset or line, and a boundary sentence
|
||||
saying which versions it was observed on. "The package contains X" and "the server trusts X" are
|
||||
different findings with different owners.
|
||||
|
||||
## 7. Boundary
|
||||
|
||||
Nothing here was exercised in this record. The steps that would make it `observed`: dump a known
|
||||
Unity package with Il2CppDumper, re-import into IDA in the order above, and set a breakpoint that
|
||||
hits at a named method; separately, build the Mono patch and hit a breakpoint in dnSpy. Until then,
|
||||
treat the tool output as a map that still needs one verified landmark. For a target that fights the
|
||||
debugger, `detection-and-anti-analysis.md` owns the triage — and `ida-so-debugging.md` owns the
|
||||
attach mechanics for the underlying `.so`.
|
||||
@@ -0,0 +1,241 @@
|
||||
# Reading a VM protector: envelope, virtual eflags, and trace search
|
||||
|
||||
Load this when a native function turns out to be an interpreter but the usual "find the dispatcher"
|
||||
advice does not fit: `cmp`, `sub` and conditional jumps are missing, the trace is dominated by
|
||||
`and/or/not/shr/neg`, a flags value is written into a stack slot, or a `ret` lands back at a VM
|
||||
entry instead of the next instruction. `native-vm-recovery.md` owns the Android-side dispatcher
|
||||
slicing and register anchoring; `vmp-differential-analysis.md` owns the Dex-level opcode
|
||||
differential; `native-dbi-and-deobfuscation.md` owns the trace mechanics. This file owns the
|
||||
*protector idiom* that sits on top of all three.
|
||||
|
||||
**Claim strength.** Absorbed from three public write-ups on x86 VMProtect-style targets and one
|
||||
practical crack (2024-2026). The envelopes, instruction sequences and trace counts are quoted from
|
||||
those samples and are `unverified` here; the general rules (anchor on data, trace then search by
|
||||
constant, patch the flag value rather than the branch) are `inferred` from the same sources. No
|
||||
VM-protected binary was traced in this record. Addresses and probabilities below are one sample's,
|
||||
not constants.
|
||||
|
||||
## 1. Envelope triage
|
||||
|
||||
A VM protector is recognisable before any handler is read:
|
||||
|
||||
| Signal | What to look for |
|
||||
|---|---|
|
||||
| A new section | `vmp`/`VMP0`-named, often hundreds of KB on a small binary; the section's raw size is a large fraction of the image |
|
||||
| Entry stub | first instruction is a `jmp`, followed by `push <imm>; call <target>`; the prologue does not match the compiler's idiom (no `push ebp; mov ebp, esp`) |
|
||||
| Saved physical state | a block of `push` instructions with no matching `pop` before the transfer |
|
||||
| Dispatcher shape | `mov reg, [index*4 + table]`, or handler-to-handler `jmp reg` / `push reg; ret` |
|
||||
| Data pointer | a register loaded from the stack and then adjusted by an addend; this is the VM bytecode pointer, not a normal local |
|
||||
|
||||
Procedure: open the section in the debugger, set a **memory access breakpoint** on it, run, and
|
||||
catch the first `push imm; call`. Delete the section breakpoint once you are inside; it fires on
|
||||
every handler and will drown the session. The same entry is reachable from a hardware breakpoint on
|
||||
the section's first page when software breakpoints are detected.
|
||||
|
||||
## 2. VM anatomy, in the order the fields appear
|
||||
|
||||
The names are conventional; the layout is what matters.
|
||||
|
||||
- **VM_DATA**: the encrypted bytecode. A pointer is staged through the stack, then adjusted by an
|
||||
addend to the real base. Handler dispatch reads the next opcode from it.
|
||||
- **VM_CONTEXT**: virtual registers. One sample carved `0xC0` bytes with `sub esp, 0xC0`; slots
|
||||
are addressed as `[esp + virtual_reg_offset]`, with values staged through a scratch register.
|
||||
`0xC0 / 4 = 48` virtual registers is a useful sanity check.
|
||||
- **vEIP**: the virtual instruction pointer. In one family it is `ESI`; in another it is a field in
|
||||
VM_CONTEXT. It points into VM_DATA or at the next handler, depending on the threading style.
|
||||
- **vStack**: `EBP` marks its top; slots are `[ebp + off]`. The VM checks stack fullness by
|
||||
comparing top against bottom, which is the one place a normal stack discipline survives.
|
||||
- **Physical saves**: below the virtual context, so that leaving the VM can restore the host state.
|
||||
|
||||
Two dispatch styles appear in the same product line:
|
||||
|
||||
- **Central dispatcher**: a jump table indexed by opcode, with every handler returning to the
|
||||
dispatcher. Easy to find, easy to instrument.
|
||||
- **Direct threading** (later versions): each handler ends with `jmp next` or
|
||||
`push next; ret`, so there is no single dispatcher. The stable signal is not a table but the
|
||||
repeated epilogue that loads vEIP and transfers.
|
||||
|
||||
Do not key a detector on a fixed register. One write-up saw `r9` in one sample and `rdx` in
|
||||
another for the same role; the invariant is "one register carries the next handler and the landing
|
||||
instruction is benign", not the register's name.
|
||||
|
||||
## 3. Anchor on data, not on code
|
||||
|
||||
Virtualisation destroys the call graph you would normally walk. The method that survives is
|
||||
data-anchored:
|
||||
|
||||
1. Run the target with a distinctive input: a long repeated string, a unique serial, a value you
|
||||
can recognise in any buffer.
|
||||
2. Let the expected failure path execute (a wrong-license dialog, an error string).
|
||||
3. Find the failure string or your input in memory and set an **access breakpoint** on it.
|
||||
4. At the break, unwind the stack's return addresses. Keep frames that belong to the target; drop
|
||||
loader, CRT and system frames.
|
||||
5. Set breakpoints on those frames, re-run with a second distinctive input, and step until one frame
|
||||
shows your bytes. That frame is the comparison or the caller that owns it.
|
||||
6. Replace the code-section breakpoint with a **read breakpoint on your input address** as soon as
|
||||
you have it. The VM section breakpoint fires constantly; the data breakpoint fires once per use.
|
||||
|
||||
The same technique finds the string decryptor: break on the buffer, then walk to the code that
|
||||
writes it.
|
||||
|
||||
### 3.1 A forged return is a landmark, not a bug
|
||||
|
||||
If stepping out of a callee lands at a VM entry instead of the instruction after the call, the
|
||||
return address was forged deliberately. That site is protected logic. Do **not** NOP the region:
|
||||
one write-up crashed immediately because the VM state expected the forged transfer. The correct
|
||||
next move is to keep the transfer intact and change the value the protected branch consumes (§5),
|
||||
or to trace forward from the real entry.
|
||||
|
||||
## 4. Trace, then search by constant
|
||||
|
||||
A full trace is cheap to produce and impossible to read. The useful unit is a *constant* that the
|
||||
emulated semantics must materialise. In one crack:
|
||||
|
||||
- the trace was 259,607 instructions and took hours;
|
||||
- searching for `0x40` (the ZF bit) produced about 100 hits;
|
||||
- filtering to `and` instructions and correlating operand values left three sites, whose
|
||||
execution counts were 1, 1 and 30;
|
||||
- the discriminating context was `eax = 0x40`, `ecx = eflags`, and a preceding
|
||||
`not eax; not ecx` pair;
|
||||
- forcing `eax = 0x40` at those three sites removed the registration check.
|
||||
|
||||
The reusable recipe:
|
||||
|
||||
1. Trace with a tool that stores disassembly, not only addresses and registers. A trace you cannot
|
||||
search is a log, not evidence.
|
||||
2. Search for the semantic constant (`0x40` for ZF, `0x815` for the arithmetic flag mask,
|
||||
`0x80000000` for sign, a known comparison value).
|
||||
3. Filter by instruction shape: the constant is usually an operand of `and`, not of `cmp`.
|
||||
4. Correlate operand roles, not just values. `and eax, ecx` with `eax = 0x40` is a flag test;
|
||||
`and eax, ecx` with `eax = 0xFFFF...` is a mask.
|
||||
5. Check execution counts. The handler that runs once per operation is not the one that runs once
|
||||
per check.
|
||||
6. Patch the *value written back* to the virtual flags slot, not the instruction that computes it,
|
||||
when the same handler serves many operations.
|
||||
|
||||
### 4.1 Trace one call, not the process
|
||||
|
||||
A whole-process trace of a VM is unreadable and slow. Anchor it to a call site:
|
||||
|
||||
- resolve the call target from the instruction, including `rel32` manually when the tracer needs an
|
||||
absolute address (`e8`/`e9`, `rel = read_s32(addr+1)`, `target = addr+5+rel`); follow short
|
||||
`jmp` thunks (a handful of hops) rather than stopping at the first one;
|
||||
- start at the callee entry and stop at the call's return address, so the trace contains exactly the
|
||||
operation you care about;
|
||||
- keep per-thread state and log `module:VA!RVA insn | reg=before->after`; a trace without register
|
||||
deltas cannot answer "what did this handler compute";
|
||||
- **suppress hot loops.** Count back-edges (a jump whose target is lower than the current address);
|
||||
after a small number of iterations `unfollow` the thread and garbage-collect, then install a
|
||||
one-shot interceptor at the loop's fall-through to resume. Without this, a VM's dispatch loop
|
||||
produces thousands of identical segments and buries the one iteration that differs.
|
||||
|
||||
This recipe is `unverified` here (one public write-up); the hot-loop suppression is the part that
|
||||
decides whether the trace is usable at all.
|
||||
|
||||
## 5. Virtual eflags is data; patch the data
|
||||
|
||||
On a real CPU only a few instructions write flags directly. In a VM, eflags is a stack slot, so the
|
||||
protector can synthesise any value it wants. A recurring synthesis is:
|
||||
|
||||
```text
|
||||
eflags = (eflags1 & 0x815) + (eflags2 & ~0x815)
|
||||
```
|
||||
|
||||
The two halves carry the arithmetic flags and the control flags; the sum combines them. The ZF
|
||||
test is then `zf = eflags & 0x40`. A debugger breakpoint on the test sees the branch only after the
|
||||
value is already wrong, which is why patching the branch is fragile: the same handler computes many
|
||||
conditions. Patch the value stored into the virtual flags slot (force `0x40`) and every consumer of
|
||||
that slot agrees.
|
||||
|
||||
This is also why a search for `cmp`/`sub` fails. Subtraction is lowered as
|
||||
`a - b = ~(~a + b)`, and comparison is a flag synthesis, so the instruction mix contains no
|
||||
`sub` at all. Recognise the identity before concluding the function is not a comparison.
|
||||
|
||||
## 6. The lowering idioms that make a VM look like crypto
|
||||
|
||||
### 6.1 The universal gate, and the naming trap
|
||||
|
||||
The sequence that dominates these traces is `not a; not b; and`, i.e. `~a & ~b`. That is **NOR**,
|
||||
not NAND (`~(a & b)`), even though the write-ups call it NAND. Use the identities as emitted:
|
||||
|
||||
```text
|
||||
f(a,b) = ~a & ~b ; the actual primitive (NOR)
|
||||
Not(a) = f(a,a)
|
||||
Or(a,b) = f(f(a,b), f(a,b))
|
||||
And(a,b) = f(f(a,a), f(b,b))
|
||||
Xor(a,b) = f(f(a, f(a,b)), f(b, f(a,b)))
|
||||
```
|
||||
|
||||
Defining `f` as NAND and keeping the same right-hand sides swaps AND and OR — a mistake that
|
||||
produces a plausible but wrong truth table. A protector that lowers everything through this gate
|
||||
produces long runs of `not; not; and`, which reads as noise. Arithmetic is built the same way:
|
||||
|
||||
```text
|
||||
add(a,b) = loop: sum = a ^ b; carry = (a & b) << 1; until carry == 0
|
||||
neg(a) = add(~a, 1)
|
||||
sub(a,b) = add(a, neg(b))
|
||||
mul(a,b) = shift-add on b & 1
|
||||
div(a,b) = restoring division over 32 bits
|
||||
```
|
||||
|
||||
The value of knowing this is diagnostic: a trace with no `sub` but thousands of `not/and` is not
|
||||
"encrypted", it is lowered. Stop looking for the missing instruction.
|
||||
|
||||
### 6.2 Branchless select
|
||||
|
||||
A conditional move/select is lowered to:
|
||||
|
||||
```text
|
||||
sub a,b; pushfd; pop x; and x,0x40; shr x,6 ; ZF -> bit 0
|
||||
mov y,1; sub y,x ; complement
|
||||
neg x; neg y ; 0 -> 0, 1 -> 0xFFFFFFFF
|
||||
and x,f1; and y,f2; or x,y; call x ; select one function pointer
|
||||
```
|
||||
|
||||
Exactly one mask is all ones, so the AND/OR pair selects a target without a jump.
|
||||
|
||||
The same construction appears as a branchless `max`/`min`:
|
||||
|
||||
```text
|
||||
flip(n) = n ^ 1
|
||||
sign(n) = flip((n >> 31) & 1)
|
||||
c = a - b; sa = sign(a); sb = sign(b); sc = sign(c)
|
||||
dif = sa ^ sb; same = flip(dif)
|
||||
returnA = dif*sa + same*sc
|
||||
returnB = flip(returnA)
|
||||
result = a*returnA + b*returnB
|
||||
```
|
||||
|
||||
There is no branch to patch. Change the operands or the value the final select consumes, and verify
|
||||
with both orderings of the input — a max built this way is easy to mistake for a checksum. The tell is a
|
||||
register that holds `0x40` and a `shr` by 6; the control flow graph shows neither a `je` nor a
|
||||
`jne`. If you patch the `sub` that feeds the flag, you change the selected function; if you patch
|
||||
the final `call`, you change only one branch of the select.
|
||||
|
||||
### 6.3 Why this matters for an APK
|
||||
|
||||
The same idioms appear in native Android protectors, especially where a bytecode VM emulates
|
||||
comparisons for a license or signature check. The envelope differs (ELF section, JNI entry), but
|
||||
the trace signature is identical: no `cmp`, a flags slot, and NAND-shaped arithmetic. Use
|
||||
`native-vm-recovery.md` for the handler-slicing procedure once you have decided it is a VM; use
|
||||
this file to decide what the handler is *computing*.
|
||||
|
||||
## 7. Static checks around the dynamic route
|
||||
|
||||
- **Rebase before trusting offsets.** Compute the section-relative offset
|
||||
(`runtime_addr - image_base`) and apply it in both debugger and disassembler. One sample needed
|
||||
`0x3E6000 - 0x381000 = 0x65000` and a rebase to `0x380000` to land on the function.
|
||||
- **Xrefs can be empty and still be correct.** In the same sample, 24 "callers" from IDA never hit
|
||||
at run time because the site was reached by `jmp` or `call reg`. An empty xref list is not
|
||||
evidence that the function is unused; it is evidence that the call is indirect.
|
||||
- **Address stability is not guaranteed.** Some debuggers reopen a sample at a different base each
|
||||
run. Trust execution order and relative structure; re-derive absolute addresses per session.
|
||||
|
||||
## 8. Boundary
|
||||
|
||||
This is a reading method, not a devirtualiser. It tells you which value the protected branch
|
||||
consumes and how to change it at run time; it does not reconstruct the original instruction stream.
|
||||
Nothing here was run against an Android target in this record. The steps that would make a row
|
||||
`observed`: trace one protected comparison, find the flags slot, force the value, and show the
|
||||
failure path disappear with the VM still intact. Until then, treat instruction counts and offsets
|
||||
as illustrative and keep a control run of the unmodified target.
|
||||
@@ -112,3 +112,25 @@ def test_an_index_row_past_the_hard_limit_fails_rather_than_warns(budget):
|
||||
assert levels(budget.INDEX_ROW_HARD + 10) == {"fail"}, (
|
||||
"a row past INDEX_ROW_HARD (%d chars) must fail the gate, not warn about it"
|
||||
% budget.INDEX_ROW_HARD)
|
||||
|
||||
def test_the_corpus_count_ignores_a_bytecode_cache(budget, tmp_path, monkeypatch):
|
||||
"""A measurement that changes when a reader runs the suite measures the reader.
|
||||
|
||||
The corpus note once counted scripts/__pycache__/*.pyc, so the same commit reported 27 scripts
|
||||
on a machine that had run pytest and 16 on a clean checkout. The routing gate said 16 the whole
|
||||
time; the disagreement between two gates about one tree is what surfaced it.
|
||||
"""
|
||||
refs = tmp_path / "references"
|
||||
refs.mkdir()
|
||||
(refs / "one.md").write_text("# one\n", encoding="utf-8")
|
||||
scripts = tmp_path / "scripts"
|
||||
scripts.mkdir()
|
||||
(scripts / "one.py").write_text("print(1)\n", encoding="utf-8")
|
||||
cache = scripts / "__pycache__"
|
||||
cache.mkdir()
|
||||
(cache / "one.cpython-314.pyc").write_bytes(b"\x00" * 10)
|
||||
|
||||
monkeypatch.setattr(budget, "REFS", str(refs))
|
||||
monkeypatch.setattr(budget, "SKILL_DIR", str(tmp_path))
|
||||
notes = budget.check_corpus()
|
||||
assert notes[0].startswith("corpus: 1 references + 1 scripts = 2 files"), notes[0]
|
||||
@@ -0,0 +1,93 @@
|
||||
"""The 2026-10-27 host fixture must be able to fail.
|
||||
|
||||
`docs/tool-verification/fixtures/verify_ref_claims_10c.py` is the only thing standing behind three
|
||||
`observed` labels, so its checks are as load-bearing as a gate. The first draft failed the rule this
|
||||
repository applies to gates: the comparison check counted iterations inside the Python loop it was
|
||||
measuring, so `n == k + 1` restated its own source and could never fail for a real reason. It now
|
||||
compiles the two comparators and measures the compiler's output.
|
||||
|
||||
Each test here injects the wrong claim and requires the check to reject it, plus one test that the
|
||||
process exit code follows the verdict. `observed` on a host with neither `openssl` nor a C compiler
|
||||
is a skip, not a pass.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import shutil
|
||||
|
||||
import pytest
|
||||
|
||||
from conftest import REPO_ROOT
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
FIXTURE = REPO_ROOT / "docs" / "tool-verification" / "fixtures" / "verify_ref_claims_10c.py"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def claims():
|
||||
spec = importlib.util.spec_from_file_location("verify_ref_claims_10c", str(FIXTURE))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _need_openssl():
|
||||
if not shutil.which("openssl"):
|
||||
pytest.skip("no openssl on this host: the CTR check degrades to SKIP")
|
||||
|
||||
|
||||
def _need_cc():
|
||||
if not (shutil.which("gcc") or shutil.which("cc") or shutil.which("clang")):
|
||||
pytest.skip("no C compiler on this host: the comparison check degrades to SKIP")
|
||||
|
||||
|
||||
def test_checks_pass_on_the_claim(claims):
|
||||
_need_openssl()
|
||||
_need_cc()
|
||||
assert claims.ctr_nonce_tail() is True
|
||||
assert claims.comparison_oracle() is True
|
||||
assert claims.header_walk() is True
|
||||
|
||||
|
||||
def test_ctr_check_rejects_an_unchanged_nonce(claims):
|
||||
_need_openssl()
|
||||
base = bytes(range(12)) + b"\x00\x00\x00"
|
||||
same = base + b"\x02"
|
||||
assert claims.ctr_nonce_tail(nonce_a=same, nonce_b=same) is False
|
||||
|
||||
|
||||
def test_comparison_check_rejects_a_full_pass_mislabelled_early(claims):
|
||||
_need_cc()
|
||||
assert claims.comparison_oracle(early_source=claims.C_FULL) is False
|
||||
|
||||
|
||||
def test_comparison_check_rejects_an_early_exit_mislabelled_constant(claims):
|
||||
_need_cc()
|
||||
assert claims.comparison_oracle(full_source=claims.C_EARLY) is False
|
||||
|
||||
|
||||
def test_header_check_rejects_an_off_grid_start(claims):
|
||||
assert claims.header_walk(start=0x110) is False
|
||||
|
||||
|
||||
def test_header_check_rejects_ground_truth_that_disagrees(claims):
|
||||
# the tail-most pair no longer sits at the largest offset, so "declared" and the forward scan
|
||||
# cannot both be the file length
|
||||
pairs = [(0x1100, 0x08), (0x1300, 0x10), (0x10A0, 0x10)]
|
||||
assert claims.header_walk(pairs=pairs) is False
|
||||
|
||||
|
||||
def test_main_exit_code_follows_the_verdict(claims, monkeypatch):
|
||||
# a check that returns False without printing must still fail the run
|
||||
monkeypatch.setattr(claims, "ctr_nonce_tail", lambda: False)
|
||||
monkeypatch.setattr(claims, "comparison_oracle", lambda: True)
|
||||
monkeypatch.setattr(claims, "header_walk", lambda: True)
|
||||
assert claims.main() == 1
|
||||
|
||||
|
||||
def test_main_treats_a_skip_as_not_a_failure(claims, monkeypatch):
|
||||
monkeypatch.setattr(claims, "ctr_nonce_tail", lambda: None)
|
||||
monkeypatch.setattr(claims, "comparison_oracle", lambda: True)
|
||||
monkeypatch.setattr(claims, "header_walk", lambda: True)
|
||||
assert claims.main() == 0
|
||||
Reference in new issue
Block a user