19 Commits
Author SHA1 Message Date
bfloat16 f862633512 chore: bump version to 1.3.0 2026-09-07 22:59:25 +08:00
bfloat16 ed2731f8e0 fix(windows): restore managed companion DLLs 2026-09-07 21:43:54 +08:00
bfloat16 53ef36c837 build: require Rust 1.98.1 2026-09-07 21:43:15 +08:00
bfloat16 6250ca4e98 refactor: align platform crate boundaries 2026-09-07 19:29:54 +08:00
bfloat16 aa1bcaa2eb fix(android): support compact ELF dynamic table layouts 2026-09-07 16:31:38 +08:00
bfloat16 2d92360d87 fix(elf): validate section names from ELF string table 2026-09-07 13:23:16 +08:00
bfloat16 4d73406ab1 fix(metadata): support Android v29 method layouts 2026-09-07 00:43:34 +08:00
bfloat16 776d246065 fix(scan): stream Android package targets 2026-09-06 22:25:41 +08:00
bfloat16 d436a200ba refactor: consolidate platform engines into senbei-engine 2026-09-06 19:31:19 +08:00
Momoko-Ayase cbfacbc31f Upgrade dependencies to latest stable
zip 0.6.6 -> 8.6.0 (the 0.6 line is unmaintained), aes 0.8 -> 0.9
(BlockCipherDecrypt trait replaces BlockDecrypt), sha2 0.10 -> 0.11
(Array no longer formats as hex; local hex_digest helpers). Outputs are
byte-identical across the upgrade: full golden corpus and Android corpus
sidecars all pass.
2026-09-02 03:19:06 +08:00
Momoko-Ayase d3dd1a8ff8 Merge Android (AArch64) shared-library restoration, bump to 1.2.0
Adds the Android protection-scheme pipeline: hollowed ELF64/AArch64
libraries are restored statically (stage-1/stage-2 module extraction,
container decode, dynamic-linker table rebuild), with app-package
(.apk/.apks/.xapk) container handling, cross-source content dedup, and
il2cpp metadata support for the Android variants (seeded RID permutation;
embedded XOR-wrapped blob extraction).

The single senbei CLI now routes single .so files, packages, and folders
by content; outputs follow the existing .unpack-infix naming under
<root>/unpack or --out. PE behavior is unchanged (35/35 goldens).
2026-09-02 03:09:21 +08:00
bfloat16 35076848b6 chore: ignore local test corpus 2026-08-16 03:49:11 +08:00
bfloat16 18886272e5 docs: note embedded metadata compatibility 2026-08-16 03:43:12 +08:00
bfloat16 b534de872d refactor: move library implementations into modules 2026-08-16 03:38:42 +08:00
bfloat16 a9aaf95e01 docs: add Android compatibility matrix 2026-08-16 03:31:25 +08:00
bfloat16 7f827d6400 feat: add folder-based Android unpack workflow 2026-08-16 02:38:07 +08:00
bfloat16 131ced6db5 feat: add static stage extraction and metadata detection 2026-08-16 01:47:25 +08:00
bfloat16 b1d3699df3 feat: add static Android il2cpp restoration 2026-08-16 00:34:08 +08:00
bfloat16 9433b4dcca Initial commit 2026-08-15 22:20:03 +08:00
76 changed files with 9741 additions and 1549 deletions
+20 -62
View File
@@ -1,82 +1,40 @@
# AGENTS.md # AGENTS.md
Guidance for AI coding agents (and human contributors) working in this repo. Guidance for contributors working in this repository.
## Project ## Project
Senbei is a static unpacker for Crackproof-protected PE files: a Cargo Senbei is a static unpacker for protected PE files and Android AArch64 shared libraries. The workspace contains `senbei-cli`, `senbei-crypto`, `senbei-elf`, `senbei-engine`, `senbei-io`, `senbei-metadata`, and `senbei-pe`; `senbei-wasm` is a separate crate for the browser frontend.
workspace with a pure, panic-free, no-I/O unpacker core (`senbei-pe/`, built
on `senbei-crypto/`), an il2cpp metadata de-obfuscator (`senbei-metadata/`), Read `docs/design.md` before changing architecture or pipeline boundaries.
filesystem/CLI orchestration (`senbei-io/`), the `senbei` binary
(`senbei-cli/`), WebAssembly bindings (`senbei-wasm/`, outside the workspace;
builds into `web/pkg/`), and the static browser frontend assets (`web/`).
Read `docs/design.md` first.
## Commands ## Commands
```cmd ```cmd
cargo build --release :: CLI (default member: senbei-cli) cargo build --release
cargo test --release --workspace :: full suite (golden corpus: samples/, git-ignored) cargo test --release --workspace
cargo clippy --workspace --all-targets -- -D warnings cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --all cargo fmt --all
cd senbei-wasm && wasm-pack build --target web --release --out-dir ../web/pkg :: browser build cd senbei-wasm && wasm-pack build --target web --release --out-dir ../web/pkg
``` ```
The `samples/` corpus is user-managed and absent on CI; without it the The optional `samples/` corpus is user-managed and ignored by Git. The Android corpus is under `samples/android/` when present. Do not delete sample directories as part of routine cleanup.
samples test is a no-op pass. `SENBEI_REQUIRE_SAMPLES=1` makes an absent
corpus fail (use this on a private CI that *does* have the corpus). Do not
delete `samples/` with `rm -rf` — it may be a junction; use git
worktree-aware cleanup.
## Hard rules ## Crate Boundaries
- **The unpacker core stays pure**: no file I/O, no `unsafe`, no panics across `senbei-pe` and `senbei-elf` contain format parsing, address mapping, and ELF dynamic-table helpers only. `senbei-engine/src/windows/` contains the PE unpacking pipeline; `senbei-engine/src/android/` contains Android extraction and ELF restoration. `senbei-crypto/src/windows/` and `senbei-crypto/src/android/` contain platform-specific primitives; seeded Android metadata code is under `senbei-metadata/src/android/`, while the structural metadata transform is shared at the metadata crate root. Shared source stays directly under `src/`.
the public boundary, no platform-specific code. It must keep compiling to
`wasm32-unknown-unknown` (`cargo check --target wasm32-unknown-unknown`).
- **`catch_unwind` does not work on wasm** (the prebuilt std can't unwind; a
caught panic becomes a fatal `unreachable` trap). Native code may rely on
`catch_unpack`, but any routing decision must also work without a catchable
panic: spliced companion inputs route straight to the EXE pipeline, and the
web app isolates every unpack in a disposable Web Worker, retrying trapped
DLLs with `job::unpack_bytes_force_exe`. Never make correctness on wasm
depend on catching a panic.
- **Byte-identical output is the contract.** Any pipeline change must re-run
the full golden corpus; a byte mismatch on any golden is a regression.
- **Trial-and-validate, never trust a heuristic.** A silently wrong offset
produces a silently broken binary — worse than an error. Every layout
candidate must be validated (checksum / structural oracle) with fall-through
to the next candidate.
- **Determinism under parallelism.** Block fan-out must stay byte-identical
regardless of thread count (`SENBEI_THREADS=1` is the sequential reference).
- **Folder scanning: deny-list, never allow-list.** Targets are recognised by
content, not extension, and can carry arbitrary names — there is no closed
set of target extensions an allow-list could enumerate. Only known
bulk-asset formats are excluded.
- **No binaries in the repo** — not as fixtures, not in commits. The only
corpus is the local git-ignored `samples/`. (Issue attachments of
protected inputs are fine when the user is authorized to share them, but
never commit them.)
## Public-repo hygiene (important) The format crates and PE engine remain free of filesystem I/O. Native Android extraction and restoration may memory-map inputs and write temporary workspaces. The browser binding must continue to compile for `wasm32-unknown-unknown`.
This is a public research repository. In code comments, docs, tests, and ## Hard Rules
commit messages:
- **Never name specific games, publishers, or product codenames.** Refer to - Outputs must be byte-identical to the available golden corpus.
build families generically ("older EXE-64 builds", "the marker-less - Layout heuristics must trial and validate every candidate before accepting it.
layout", "external-companion builds"). Keep offsets/numbers — drop names. - Deterministic parallel and sequential paths must produce identical bytes.
- **Never name specific protected filenames** from real distributions. Test - Folder scanning must not open bulk assets. Windows candidates are `.exe`, `.dll`, and `global-metadata.dat`; Android candidates are `.so` and `global-metadata.dat`. Matching `.exe._` and `.dll._` files are auxiliary payloads and are not counted as skipped targets.
fixtures use generic names (`app.exe`, `managed.dll`, `daemon.exe`). - APK, APKS, and XAPK processing must inspect manifests first and extract only `.so` and `global-metadata.dat` entries.
Exceptions (platform-standard technology names, allowed): `il2cpp`, - Do not commit protected or restored binaries. Use generic fixture names and do not add product-specific names or external tool references to public code, docs, tests, or commit messages.
`Unity`, `global-metadata.dat`, the Crackproof magic `KONN`.
- **Never reference other tools, projects, implementations, or paths outside
this repo.** Describe behavior and layout directly; do not mention prior
art, porting, or where any algorithm came from.
## Conventions ## Documentation
- Comments explain *why* (layout rationale, observed variants, failure modes), Use one line for each normal Markdown paragraph. Keep code blocks, table rows, and list items structurally separate. Update `docs/usage.md` when CLI behavior changes.
not *what*.
- Rust 2024 edition; clippy-clean at `-D warnings`; rustfmt default style.
- CLI behavior (flags, exit codes, output naming) is documented in
`docs/usage.md` — update the doc when changing behavior.
Generated
+345 -7
View File
@@ -2,6 +2,17 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "aes"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"
dependencies = [
"cipher",
"cpubits",
"cpufeatures",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.104" version = "1.0.104"
@@ -14,6 +25,15 @@ version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.20.3" version = "3.20.3"
@@ -26,6 +46,16 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"crypto-common",
"inout",
]
[[package]] [[package]]
name = "console" name = "console"
version = "0.16.4" version = "0.16.4"
@@ -38,12 +68,68 @@ dependencies = [
"windows-sys", "windows-sys",
] ]
[[package]]
name = "const-oid"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550"
dependencies = [
"cfg-if",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
]
[[package]] [[package]]
name = "encode_unicode" name = "encode_unicode"
version = "1.0.0" version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]] [[package]]
name = "errno" name = "errno"
version = "0.3.14" version = "0.3.14"
@@ -60,6 +146,15 @@ version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "flate2"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"zlib-rs",
]
[[package]] [[package]]
name = "futures-core" name = "futures-core"
version = "0.3.34" version = "0.3.34"
@@ -95,6 +190,42 @@ dependencies = [
"r-efi", "r-efi",
] ]
[[package]]
name = "goblin"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17582616a7718cca54cec18e534a76c7c4aec11a8b9a85695712f262fd15a4c8"
dependencies = [
"log",
"plain",
"scroll",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "hybrid-array"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
dependencies = [
"typenum",
]
[[package]]
name = "indexmap"
version = "2.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]] [[package]]
name = "indicatif" name = "indicatif"
version = "0.18.6" version = "0.18.6"
@@ -108,6 +239,21 @@ dependencies = [
"web-time", "web-time",
] ]
[[package]]
name = "inout"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
dependencies = [
"hybrid-array",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.104" version = "0.3.104"
@@ -131,6 +277,27 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "log"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "memmap2"
version = "0.9.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@@ -149,6 +316,12 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "plain"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]] [[package]]
name = "portable-atomic" name = "portable-atomic"
version = "1.15.0" version = "1.15.0"
@@ -208,48 +381,163 @@ dependencies = [
] ]
[[package]] [[package]]
name = "senbei-cli" name = "scroll"
version = "1.1.0" version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1257cd4248b4132760d6524d6dda4e053bc648c9070b960929bf50cfb1e7add"
dependencies = [ dependencies = [
"scroll_derive",
]
[[package]]
name = "scroll_derive"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1a36a382ed65dbcc0ab47fd5e9a94112417ccd34560a392ef3b7b0f0ec39148"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.4",
]
[[package]]
name = "senbei-cli"
version = "1.3.0"
dependencies = [
"senbei-engine",
"senbei-io", "senbei-io",
"senbei-metadata", "senbei-metadata",
"sha2",
"tempfile", "tempfile",
] ]
[[package]] [[package]]
name = "senbei-crypto" name = "senbei-crypto"
version = "1.1.0" version = "1.3.0"
dependencies = [ dependencies = [
"aes",
"thiserror",
]
[[package]]
name = "senbei-elf"
version = "1.3.0"
dependencies = [
"goblin",
"thiserror",
]
[[package]]
name = "senbei-engine"
version = "1.3.0"
dependencies = [
"memmap2",
"senbei-crypto",
"senbei-elf",
"senbei-pe",
"serde",
"serde_json",
"sha2",
"tempfile",
"thiserror", "thiserror",
] ]
[[package]] [[package]]
name = "senbei-io" name = "senbei-io"
version = "1.1.0" version = "1.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"indicatif", "indicatif",
"libc", "libc",
"memmap2",
"owo-colors", "owo-colors",
"senbei-crypto",
"senbei-elf",
"senbei-engine",
"senbei-metadata", "senbei-metadata",
"senbei-pe", "senbei-pe",
"sha2",
"tempfile", "tempfile",
"walkdir", "walkdir",
"windows", "windows",
"zip",
] ]
[[package]] [[package]]
name = "senbei-metadata" name = "senbei-metadata"
version = "1.1.0" version = "1.3.0"
dependencies = [
"serde",
"thiserror",
]
[[package]] [[package]]
name = "senbei-pe" name = "senbei-pe"
version = "1.1.0" version = "1.3.0"
dependencies = [ dependencies = [
"senbei-crypto",
"thiserror", "thiserror",
] ]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.4",
]
[[package]]
name = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sha2"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.12" version = "0.4.12"
@@ -311,6 +599,18 @@ dependencies = [
"syn 3.0.4", "syn 3.0.4",
] ]
[[package]]
name = "typed-path"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.24" version = "1.0.24"
@@ -521,3 +821,41 @@ checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [ dependencies = [
"windows-link", "windows-link",
] ]
[[package]]
name = "zip"
version = "8.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
dependencies = [
"crc32fast",
"flate2",
"indexmap",
"memchr",
"typed-path",
"zopfli",
]
[[package]]
name = "zlib-rs"
version = "0.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
+22 -1
View File
@@ -2,6 +2,8 @@
members = [ members = [
"senbei-cli", "senbei-cli",
"senbei-crypto", "senbei-crypto",
"senbei-elf",
"senbei-engine",
"senbei-io", "senbei-io",
"senbei-metadata", "senbei-metadata",
"senbei-pe", "senbei-pe",
@@ -13,15 +15,22 @@ exclude = ["senbei-wasm"]
resolver = "2" resolver = "2"
[workspace.package] [workspace.package]
version = "1.1.0" version = "1.3.0"
edition = "2024" edition = "2024"
rust-version = "1.98.1"
license = "AGPL-3.0-only" license = "AGPL-3.0-only"
[workspace.dependencies] [workspace.dependencies]
aes = "0.9"
anyhow = "1" anyhow = "1"
goblin = "0.10"
indicatif = "0.18" indicatif = "0.18"
libc = "0.2" libc = "0.2"
memmap2 = "0.9"
owo-colors = "4" owo-colors = "4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.11"
tempfile = "3" tempfile = "3"
thiserror = "2" thiserror = "2"
walkdir = "2" walkdir = "2"
@@ -30,11 +39,23 @@ windows = { version = "0.62", features = [
"Win32_System_Console", "Win32_System_Console",
"Win32_System_SystemInformation", "Win32_System_SystemInformation",
] } ] }
zip = { version = "8", default-features = false, features = ["deflate"] }
senbei-crypto = { path = "senbei-crypto" } senbei-crypto = { path = "senbei-crypto" }
senbei-elf = { path = "senbei-elf" }
senbei-engine = { path = "senbei-engine" }
senbei-io = { path = "senbei-io" } senbei-io = { path = "senbei-io" }
senbei-metadata = { path = "senbei-metadata" } senbei-metadata = { path = "senbei-metadata" }
senbei-pe = { path = "senbei-pe" } senbei-pe = { path = "senbei-pe" }
[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
[workspace.lints.clippy]
correctness = { level = "deny", priority = -1 }
suspicious = { level = "warn", priority = -1 }
complexity = { level = "warn", priority = -1 }
perf = { level = "warn", priority = -1 }
[profile.release] [profile.release]
opt-level = 3 opt-level = 3
lto = true lto = true
+34 -55
View File
@@ -1,77 +1,56 @@
# Senbei # Senbei
A static unpacker for Crackproof-protected 64-bit and 32-bit PE files. Point it A static unpacker for Crackproof-protected 64-bit and 32-bit PE files and protected Android AArch64 shared libraries. Point it at a file, an app package, or a folder and it writes decrypted copies without launching the protected program.
at a file or a folder and it writes decrypted copies — no launch of the
protected program, no kernel driver, no code runs out of the protected binary.
> _"Crackproof"? It's senbei (煎餅 — rice cracker). Cracks itself._ Senbei reads protected input bytes and replays the unpacking algorithm statically. The command-line tool adds filesystem scanning, progress reporting, and logs; `senbei-wasm` provides the browser binding.
Senbei reads a protected `.exe` or `.dll`, replays the unpacking algorithm ## Crates
entirely in memory, and writes the recovered image to a new file. The core is a
pure, panic-free library with no file I/O; the CLI wraps it with scanning, a
progress bar, and a run log. A browser version (WebAssembly, fully client-side)
lives in [`web/`](web/).
## Legal notice and intended use The workspace contains eight crates: `senbei-cli`, `senbei-crypto`, `senbei-io`, `senbei-metadata`, `senbei-pe`, `senbei-elf`, `senbei-engine`, and `senbei-wasm`.
**Read this before using Senbei.** `senbei-pe` and `senbei-elf` contain validated format parsing, address mapping, and ELF dynamic-table helpers. Protection-specific code is in `senbei-engine/src/windows/` and `senbei-engine/src/android/`. Platform-specific crypto is grouped under `senbei-crypto/src/windows/` and `senbei-crypto/src/android/`; metadata code shared by both platforms stays at the `senbei-metadata` root, with seeded Android code under `src/android/`.
- Senbei is a research and interoperability tool. It exists to enable lawful ## Supported Inputs
reverse engineering, security research, preservation, and interoperability
with software you already legitimately possess.
- **Only process binaries you own or are explicitly authorized to analyze.**
Depending on your jurisdiction and license agreements, circumventing
technological protection measures may be restricted (for example under
DMCA §1201 in the United States, which contains exemptions for security
research and interoperability). It is your responsibility to ensure your use
is lawful.
- Senbei does not bypass any access control for you: it performs a purely
static transformation of a file already on your disk. It derives everything
it needs from the input file itself, contains no vendor code or secrets, and
distributes no keys, cracks, or copyrighted content.
- Senbei does not enable online play, license fraud, or cheating, and must not
be used to redistribute decrypted binaries. Do not upload outputs anywhere.
- The authors provide this software "as is", without warranty of any kind, and
accept no liability for misuse. See [LICENSE](LICENSE) (AGPL-3.0).
- "Crackproof" is a trademark of its respective owner; this project is not
affiliated with or endorsed by the protection vendor or any software
publisher. Names are used for identification only.
## What it handles - Protected Windows `.exe` and `.dll` files, including external `<name>.exe._` and `<name>.dll._` payloads.
- `global-metadata.dat` files with supported method-token layouts.
- Protected Android `.so` files and Android `.apk`, `.apks`, and `.xapk` packages.
| Kind | Description | Windows scanning probes only `.exe`, `.dll`, and `global-metadata.dat`; companion payloads are consumed through their matching stub and are not counted as skipped files. Android scanning probes only `.so` and `global-metadata.dat`. Android packages are inspected from their ZIP manifests and only matching `.so` and metadata entries are extracted.
| --- | --- |
| `NativeExe` | Crackproof-protected native executable (PE32+ and PE32). |
| `ManagedExe` | Protected .NET executable (has a CLR data directory). |
| `NativeDll` | Protected native (unmanaged) DLL. |
| `ManagedDll` | Protected .NET assembly (has a CLR data directory). |
| `._` companion | Stub + external encrypted payload layout, spliced automatically. |
| `global-metadata.dat` | il2cpp metadata with obfuscated method tokens, de-obfuscated in place. |
Detection is content-based (header key-table at offset 4096, magic `KONN`), ## Quick Start
not extension-based. Anything unrecognized is left untouched.
## Quick start
```cmd ```cmd
cargo build --release cargo build --release
senbei protected.exe senbei protected.exe
:: -> unpack\protected.unpack.exe senbei game.apk
senbei "C:\Games\MyGame" senbei "C:\Games\MyGame"
:: -> C:\Games\MyGame\unpack\... (recursive, skips non-targets)
``` ```
Every output is sanity-checked statically; structurally broken results are Outputs are written below an `unpack` directory unless `--out` is supplied. Every restored PE or ELF image passes a structural validation step before it is reported as successful.
flagged as suspect rather than silently trusted.
## Documentation ## Tests
- [Usage reference](docs/usage.md) — CLI flags, exit codes, integrity check ```cmd
- [Design](docs/design.md) — architecture, routing, and error model cargo test --release --workspace
- [Development](docs/development.md) — building, testing, environment variables cargo clippy --workspace --all-targets -- -D warnings
- [Web version](web/README.md) — run Senbei in a browser cargo fmt --all -- --check
```
The local `test/` corpus can be passed to the CLI for real sample verification. The tracked `samples/` corpus is optional and remains user-managed.
## Web Build
```cmd
cd senbei-wasm
wasm-pack build --target web --release --out-dir ../web/pkg
```
The generated package is written to the ignored `web/pkg/` directory and can be served with any static HTTP server.
## Legal Notice
Use Senbei only for software you own or are authorized to analyze. The project is intended for lawful reverse engineering, security research, preservation, and interoperability.
## License ## License
+35 -135
View File
@@ -1,159 +1,59 @@
# Design # Design
Senbei is a fully static unpacker: it replays the unpacking algorithm on the Senbei is a fully static unpacker. It reads protected bytes, replays the protection algorithm, validates the result, and writes a recovered image without launching or attaching to the protected program.
file bytes in memory and writes the recovered PE image. No code from the
protected binary is ever executed, no process is launched or attached to, and
no driver or proxy DLL is involved.
## Crate layout ## Crate Layout
Senbei is a Cargo workspace split into a pure core and thin shells around it: The workspace is organized into eight crates. `senbei-cli` is the command-line entry point, `senbei-io` owns filesystem orchestration, `senbei-wasm` provides browser bindings, `senbei-pe` and `senbei-elf` provide basic format parsing, `senbei-crypto` provides shared primitives, `senbei-metadata` restores metadata, and `senbei-engine` owns protection-specific pipelines.
- **`senbei-pe/`** — the core. Pure functions over byte slices: no file I/O, Single-platform source stays directly under `src/`. Multi-platform crates keep platform code below `src/windows/` and `src/android/`, with shared code directly below `src/`.
no environment access (beyond a few debugging overrides, see
[development.md](development.md)), panic-free at the public boundary (all
internal panics are trapped and converted to `UnpackError::Corrupt`). This
is what the WebAssembly build embeds.
- **`senbei-crypto/`** — cryptographic, checksum, compression, and bytecode
primitives the core is built from. Same purity rules as `senbei-pe`.
- **`senbei-metadata/`** — il2cpp `global-metadata.dat` method-token
de-obfuscation (format version 31; other versions are left untouched).
- **`senbei-io/`** — filesystem and orchestration: recursive folder scanning,
per-run log file, progress bar, Explorer-friendly exit pause, and the
single-file/folder orchestration in `job.rs` (incl. the wasm-safe in-memory
byte API used by the web frontend).
- **`senbei-cli/`** — the `senbei` binary: argument parsing + dispatch. The
integration test suite (incl. the golden corpus test) lives in
`senbei-cli/tests/`.
``` ```text
senbei-cli/ senbei-cli/src/main.rs
└── src/main.rs argument parsing + dispatch
senbei-io/src/
├── job.rs single-file + folder orchestration, out-naming,
│ companion splice, stub overlay/TLS restore,
│ pipeline routing (incl. the wasm-safe byte API)
├── scan.rs recursive Crackproof + metadata discovery
├── logfile.rs per-run timestamped log
├── ui.rs progress bar + status lines
└── pause.rs Explorer-friendly exit pause
senbei-metadata/src/
└── metadata.rs il2cpp global-metadata.dat de-obfuscation
senbei-crypto/src/ senbei-crypto/src/
├── primitives.rs decrypt_data* steps, key derivation senbei-crypto/src/android/
├── bytecode.rs bytecode VM senbei-crypto/src/windows/
├── tables.rs constant tables senbei-elf/src/
└── crc32.rs checksum senbei-engine/src/windows/
senbei-pe/src/engine/ pure, panic-free, no-I/O core senbei-engine/src/android/
├── mod.rs detection + unpack_auto dispatch senbei-io/src/
├── error.rs structured error taxonomy senbei-io/src/android/
├── integrity.rs static post-unpack sanity check senbei-io/src/windows/
├── parallel.rs deterministic block-parallel fan-out senbei-metadata/src/
├── layout/ layout discovery + validation senbei-metadata/src/windows/
│ ├── dd8.rs .text dd8 key-formula + shift selection senbei-metadata/src/android/
│ ├── discovery.rs layout candidate discovery (trial-and-validate) senbei-pe/src/
│ └── image.rs PE image reconstruction helpers senbei-wasm/src/
├── exe/
│ ├── pipeline.rs EXE pipeline (PE32+ and PE32 orchestration)
│ └── pipeline/pe32.rs PE32-specific EXE restore
└── dll/
└── pipeline.rs native + managed DLL pipeline
``` ```
## Detection and routing `senbei-pe` and `senbei-elf` own validated format models, address mapping, and ELF dynamic hash helpers. They do not depend on the unpacking engines, filesystem code, or platform protection logic.
Detection is content-based (`unpacker::detect`), never extension-based: the ## Windows Engine
key table is derived from the file header and checked against the format
magic, then the PE characteristics classify the input as EXE or DLL and the
CLR data directory splits each into native vs managed (`NativeExe` /
`ManagedExe` / `NativeDll` / `ManagedDll`).
`unpack_auto` then dispatches: `senbei-engine/src/windows/` contains PE detection, layout discovery, EXE and DLL restoration, deterministic block parallelism, and structural integrity checks. Candidate layouts are trial-decrypted and validated before an output is accepted.
- `NativeExe` / `ManagedExe` → the EXE pipeline (handles both PE32+ and External companion inputs are reconstructed as `stub[..4096]` followed by the matching `._` payload. The stub's export, TLS, and declared CLR regions are overlaid after unpacking because those regions are not present in the encrypted companion. Managed restoration follows the COR20 directory and referenced metadata, resources, and vtable fixups through each file's RVA mapping, preserving the decrypted method bodies.
PE32). Managed EXEs take the same path: their import-string table is null
(imports are the CLR bootstrap stub), the entry point comes from the
protected header (the config block stores 0 for managed images), and the
COR20 header, BSJB metadata stream, and CLR resources are restored verbatim
from the protected file, mirroring the managed-DLL restore.
- `NativeDll` / `ManagedDll` → the DLL pipeline first; on failure, the EXE
pipeline as a fallback. Two DLL layouts exist in the wild: an older layout
the DLL pipeline parses, and a newer one that protects DLLs with the
EXE-style shell layout instead. The DLL-first order keeps old-layout outputs
byte-identical (the EXE pipeline also "succeeds" on old-layout DLLs but
produces different bytes); the fallback handles the new layout (including
the managed-DLL .NET metadata restore).
One routing shortcut bypasses `unpack_auto`: inputs spliced from an external ## Android Engine
companion (`job.rs`, both the CLI and the wasm byte API) go **straight to the
EXE pipeline**. The companion layout is definitionally the EXE-style shell,
so the DLL probe can never be right for it — and the probe's rejection of
EXE-shell DLLs relies on a caught panic, which is a fatal trap on targets
without unwinding (WebAssembly). Output bytes are identical to the
probe-then-fallback route.
## External-companion inputs `senbei-engine/src/android/extract/` decrypts the stage-1 header and stage-2 record streams and writes a temporary module workspace. `senbei-engine/src/android/restore/` applies decoded image and fixup containers to the hollowed ELF and rebuilds dynamic-linker tables. Both phases validate bounds and table placement before writing output.
Some builds split a protected module into an on-disk loader stub plus an Windows protection primitives are in `senbei-crypto/src/windows/`, while Android protection primitives are in `senbei-crypto/src/android/`. Android seeded metadata restoration is in `senbei-metadata/src/android/`; the structural MethodDef transform is shared at the metadata crate root because both platform paths use it.
encrypted `._` companion. When a `<name>._` sibling matches the stub's header
region, `job.rs` splices the two before unpacking and afterwards overlays the
export table and TLS directory from the stub — pieces the encrypted companion
does not carry. All overlay steps are best-effort no-ops when their inputs
can't be mapped, so a malformed stub can never corrupt an otherwise-good
unpack.
## Pipelines Android ELF dynamic tables are located from the input section table and its actual file ranges. When the original gap is too small, restoration adds a validated read-only `PT_LOAD` after the existing load image and updates the dynamic tags; it never overwrites an adjacent section or emits a partial image.
Both pipelines are **heuristic with trial-and-validate**: where a layout ## Scanning and Packages
leaves ambiguity (e.g. which block is the real file decryptor, or a page-XOR
shift), the pipeline tries candidates and validates the result structurally
(an entry-stub oracle, checksum stamps, cluster stamps) instead of trusting
the first match. A validation failure falls through to the next candidate
rather than producing silently wrong output.
Several protected stages are themselves little bytecode programs. The core Folder scanning uses platform target names to avoid opening bulk assets: Windows candidates are `.exe`, `.dll`, and `global-metadata.dat`; Android candidates are `.so` and `global-metadata.dat`. The shared walker is in `senbei-io/src/scan.rs`; platform name filters and PE companion byte adaptation are in `senbei-io/src/windows/`, and Android package adaptation is in `senbei-io/src/android/`. A Windows `.exe._` or `.dll._` companion is auxiliary input for its sibling stub and is excluded from the skipped count.
includes a small VM (`bytecode.rs`) that generates and interprets those
programs rather than hardcoding each variant's constants.
## Integrity check APK, APKS, and XAPK files are containers. Senbei reads their ZIP manifests first, follows nested APK entries when necessary, and extracts only `.so` and exact `global-metadata.dat` entries. Extraction streams directly to temporary files, so compressed and decompressed copies are not held in memory together.
Every produced image passes through `integrity::check` — a static, execution- ## Validation
free sanity check that only flags defects impossible in a correctly unpacked
image (malformed headers, unmapped/non-executable/all-zero/all-int3 entry
point, a native DLL with no base-relocation directory, any import descriptor
whose DLL name is still ciphertext, a managed image whose COR20 header or BSJB
metadata did not survive). See [usage.md](usage.md#integrity-check).
A clean report is not a proof of correctness; a non-clean report is a reliable
"broken" signal.
## Parallelism Every heuristic layout uses trial-and-validate. A candidate that fails structural checks, checksums, or table bounds is rejected and the next candidate is tried. A failed restore is reported as an error rather than emitting a silently damaged binary.
Section decrypt/decompress blocks write disjoint output spans and read only The PE integrity check verifies headers, section ranges, entry-point mapping, import names, relocation requirements, and managed metadata signatures. Android restoration validates ELF ranges, decoded container sizes, fixup bounds, and rebuilt dynamic tables.
immutable input plus snapshotted key tables, so `parallel.rs` fans them out
across worker threads with **byte-identical** output regardless of thread
count. There is no `unsafe`: the buffer is carved with safe `split_at_mut`
chains so the borrow checker proves spans never alias. Overlapping spans (only
possible on corrupt input) degrade to the sequential whole-buffer pass,
preserving the deterministic last-writer-wins behavior of the serial
pipeline. `SENBEI_THREADS=1` forces the sequential path; on targets without
threads (WebAssembly) the sequential path is used automatically.
## Error model ## WebAssembly
The public API never panics: every pipeline runs under a `catch_unwind` The browser binding depends on `senbei-engine` through the I/O byte API. Native filesystem and Android package orchestration remain outside the browser workflow. Each browser unpack runs in a disposable worker because WebAssembly cannot recover from a caught panic in the same way as native code.
wrapper (`catch_unpack`) that converts a trapped panic to
`UnpackError::Corrupt`, with the default panic hook transiently suppressed.
Size requests are bounds-checked against a 1 GiB `MAX_IMAGE_SIZE` before
allocation so a crafted header cannot abort the process with a huge
allocation. In folder mode each file is isolated: one file's failure is logged
and counted, never fatal to the run.
**WebAssembly caveat:** the prebuilt wasm std cannot unwind, so a caught
panic becomes a fatal `unreachable` trap there. The DLL-routing probe relies
on this mechanism to reject EXE-shell-layout DLLs, so the web build routes
around it instead of through it: spliced companion inputs skip the probe
entirely (see "Detection and routing"), and the web app isolates every unpack
in a disposable Web Worker — a trapped DLL is retried once in a fresh worker
with the forced-EXE pipeline (`job::unpack_bytes_force_exe`), reproducing the
probe-then-fallback outcome without a catchable panic. A trap on any other
input is reported as a clean error rather than freezing the page.
+34 -95
View File
@@ -2,121 +2,60 @@
## Building ## Building
Requires a Rust toolchain (MSVC backend is the default on Windows; Rust 1.98.1 is required and pinned in `rust-toolchain.toml`. Build the CLI with `cargo build --release`; the binary is written to `target/release/senbei.exe` on Windows.
`rustup-init.exe` from <https://rustup.rs> installs it). The pinned toolchain
and targets are in `rust-toolchain.toml`.
```cmd The workspace crates are portable where their APIs are pure. The browser binding is outside the workspace and is checked with `cargo check --manifest-path senbei-wasm/Cargo.toml` or built with `wasm-pack`.
cargo build --release
```
Output: `target\release\senbei.exe`. The binary is self-contained — no driver,
no proxy DLL, no external assets.
The library and CLI also build for Linux/macOS (`cfg`-gated platform code
only) and for `wasm32-unknown-unknown` (see the [web version](../web/README.md)).
## Testing ## Testing
```cmd ```cmd
cargo test --release cargo test --release --workspace
cargo clippy --workspace --all-targets -- -D warnings
cargo fmt --all -- --check
``` ```
The suite covers CLI behavior, detection, the folder driver, the run log, and The tracked test suite is safe without protected samples. The optional local `samples/` corpus is user-managed and the ignored `test/` folder can be used for real Windows and Android runs.
byte-exact golden tests over `samples/` — a user-managed corpus (git-ignored,
see `samples/README.md`) of real Crackproof inputs plus `<base>.golden.<ext>`
reference outputs. Every input goes through `job::unpack_bytes` — the same
routing the CLI uses, so an `<input>._` companion in the corpus is spliced and
the stub export/TLS overlays run — and is gated on **two** checks: the static
integrity check (catches runtime-broken outputs even when a stale golden would
still byte-match) and, when a golden exists, a bit-for-bit comparison. il2cpp
`*.dat` inputs are routed through `metadata::deobfuscate` instead. An empty or
absent corpus is a no-op pass; set `SENBEI_REQUIRE_SAMPLES` to make it fail
instead (useful on a private CI that has the corpus — public CI never does,
since binaries are not committed).
> **Note:** goldens encode expected *bytes*, not runtime behavior. A golden For an Android package, use one command at a time because a protected `.so` can be hundreds of megabytes. APK, APKS, and XAPK tests read the ZIP manifest first and extract only `.so` and `global-metadata.dat` entries.
> produced before a pipeline fix may byte-match while still being wrong — the
> integrity check is the second gate for exactly this reason. Re-verify
> goldens against real runs when touching the affected pipeline stages.
>
> **The corpus only protects what it contains.** Wire the test to the routing
> the CLI actually takes (it is), and keep a sample for every layout family —
> marker-based, marker-less, external-companion, PE32, PE32+, native, managed,
> metadata. An unrepresented family has no regression gate at all, which is
> how a "re-run the golden corpus" rule can pass while silently covering
> nothing.
## Debugging levers (environment variables) ## Environment Variables
- `DD8_SHIFT` override the `decrypt_data8` page-XOR shift (`99` skips dd8 - `DD8_SHIFT` overrides the PE page-XOR shift; `99` skips that stage.
entirely). - `SEL_DIAG` prints PE layout-selector diagnostics.
- `SEL_DIAG` — print the dd8 selector's scores: the per-shift `0xCC` counts and - `SENBEI_THREADS` caps deterministic block fan-out; `1` forces the sequential reference path.
the plaintext baseline they are compared against (PE32+), and the per-formula - `SENBEI_SCAN_ALL` enables probing selected target names below the size floor; it never enables arbitrary filenames.
counts, baseline and net gain (PE32). - `SENBEI_ANDROID_SAMPLES` overrides the Android sample corpus location.
- `SENBEI_THREADS` — cap the block-parallel fan-out (`1` forces the fully
sequential path).
- `SENBEI_SCAN_ALL` — same as `--scan-all` (probe every file in a folder).
## Conventions ## Conventions
- The `senbei-pe/` core (and its `senbei-crypto/` base) is pure: no file I/O, Format crates stay free of filesystem I/O and protection-specific logic. Windows engine code lives below `senbei-engine/src/windows/`, Android engine code below `senbei-engine/src/android/`, and shared code stays directly under each crate's `src/`.
no panics across the public boundary, no `unsafe`. Keep it that way — it is
what the WebAssembly build embeds.
- Layout heuristics must **trial-and-validate**: never pick a candidate offset
on shape alone and trust it; validate by decryption/checksum and fall
through to the next candidate on failure. A silent wrong offset produces a
silently broken output, which is worse than an error.
- Output must remain byte-identical against the golden corpus for every
supported layout. When fixing one build family, re-run the full golden
corpus to prove no other family regressed.
- Folder scanning uses a size floor plus an extension **deny**-list, never an
allow-list: targets are recognised by content, not extension, and can carry
arbitrary names, so only known bulk-asset extensions are excluded. The
pre-filter exists because folder-scan cost is per-file I/O latency, not the
walk — probe fewer files, don't parallelize the probe loop.
- `cargo fmt` and `cargo clippy` must stay clean (CI enforces both).
## Repository layout Layout heuristics must trial and validate every candidate. A failed validation is an error or a fall-through, never a silently accepted offset.
``` Outputs must remain byte-identical against the available golden corpus. Run the full workspace tests after changing a pipeline or a metadata layout.
senbei/
├── Cargo.toml workspace root (members: the senbei-* crates) Folder scanning uses explicit target names to avoid opening bulk assets. External `.exe._` and `.dll._` files are auxiliary data for their sibling stubs and are not independent scan targets.
├── rust-toolchain.toml pinned toolchain + targets
├── senbei-cli/ senbei binary (default member) ## Repository Layout
│ └── tests/ CLI, detection, golden, and folder tests
├── senbei-pe/ pure unpacker core (see docs/design.md) ```text
├── senbei-crypto/ crypto/compression primitives senbei-cli/ command-line binary and integration tests
├── senbei-metadata/ il2cpp metadata de-obfuscation senbei-crypto/ Windows and Android crypto primitives
├── senbei-io/ filesystem, scanning, CLI orchestration senbei-elf/ ELF parsing, mapping, and dynamic-table helpers
├── senbei-wasm/ WebAssembly bindings crate (own Cargo.lock, senbei-engine/ Windows and Android unpacking engines
│ outside the workspace; builds into web/pkg/) senbei-io/ filesystem, package, scanning, and platform adapters
├── samples/ local-only test corpus (git-ignored) senbei-metadata/ shared, Windows, and Android metadata restoration
├── web/ static browser frontend assets (+ built pkg/) senbei-pe/ PE parsing, data directories, and RVA mapping
├── docs/ usage, design, and development documentation senbei-wasm/ browser bindings and its own lockfile
└── .github/ CI workflows and issue templates web/ static browser frontend
samples/ optional local corpus
``` ```
## Web build ## Web Build
See [web/README.md](../web/README.md). In short:
```cmd ```cmd
cd senbei-wasm cd senbei-wasm
wasm-pack build --target web --release --out-dir ../web/pkg wasm-pack build --target web --release --out-dir ../web/pkg
``` ```
then serve `web/` statically and open `index.html`. Everything runs Serve `web/` with a static HTTP server after the build. The browser never uploads input files.
client-side; no file leaves the browser.
## Contributing
Issues and pull requests are welcome. A few ground rules:
- **Never commit binaries** (protected or decrypted) to the repository —
the only corpus is the local git-ignored `samples/`. Attaching a protected
input file to an issue is welcome if it helps diagnose the problem; only
attach files you are authorized to share.
- Run `cargo test --release`, `cargo clippy`, and `cargo fmt` before
submitting.
- Keep the unpacker core free of I/O, `unsafe`, and platform-specific code.
+26 -95
View File
@@ -1,126 +1,57 @@
# Usage # Usage
``` ```text
senbei <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--scan-all] senbei <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--scan-all] [--no-log] [--no-pause] [-V|--version] [-h|--help]
[--no-log] [--no-pause] [-V|--version] [-h|--help]
``` ```
Real runs print `Senbei <version>` once at start. Use `-V` / `--version` to ## Single File
print the version and exit.
## Single file The output is written below `<parent>/unpack/` with `.unpack` inserted before the extension. `--out DIR` changes both the output and log directory.
The decrypted image is written under `<parent>/unpack/` with `.unpack` inserted
before the extension. A `senbei-<timestamp>.log` is written in the same
directory. With `--out DIR`, both the output and the log go into `DIR` instead:
```cmd ```cmd
senbei app.exe senbei app.exe
:: -> unpack\app.unpack.exe
:: -> unpack\senbei-YYYYMMDD-HHMMSS.log
senbei app.exe --out C:\out senbei app.exe --out C:\out
:: -> C:\out\app.unpack.exe
:: -> C:\out\senbei-YYYYMMDD-HHMMSS.log
``` ```
Pointing senbei directly at an il2cpp `global-metadata.dat` rewrites its For `global-metadata.dat`, Senbei writes `global-metadata.unpack.dat` only when method tokens change. Unsupported metadata versions remain untouched and are reported as skipped.
obfuscated method tokens back to the contiguous per-module range il2cpp
expects; the output is `global-metadata.unpack.dat`, written only when tokens
actually changed. Only metadata format version 31 is rewritten; other versions
are reported and left untouched.
## Folder mode ## Android Targets
Senbei walks the directory recursively, skips any subdirectory literally named Protected `.so` files are restored from their encrypted payload sections and written as `libil2cpp.unpack.so` or the corresponding input name. APK, APKS, and XAPK files are treated as containers: their manifests are read first, nested APKs are followed when necessary, and only `.so` and exact `global-metadata.dat` entries are extracted.
`unpack`, and unpacks every file it recognises as Crackproof-protected (by
content, not extension — renamed files and `.bak` backups are still found).
Results land under `<root>/unpack/` (or `--out DIR`), mirroring the input
tree's relative paths. The run log is written **in that same out directory**:
```cmd If a restored library contains embedded metadata, the unwrapped blob is written beside it as `global-metadata.unpack.dat`. Identical loose and package entries are restored once, preferring the loose file.
senbei "C:\Games\MyGame"
:: -> C:\Games\MyGame\unpack\...
:: -> C:\Games\MyGame\unpack\senbei-YYYYMMDD-HHMMSS.log
```
Folder mode also picks up `global-metadata.dat` files and external-companion ## Folder Mode
`._` payloads: a module whose `<name>._` sibling matches its header region is
spliced with the companion automatically (no flag needed) and unpacked as one
image, with the output named for the stub.
Each file is processed in isolation: an error or panic on one file is caught, Folder mode walks recursively, skips directories named `unpack`, and mirrors recognized outputs below `<root>/unpack/` or `--out DIR`. Windows candidates are `.exe`, `.dll`, and `global-metadata.dat`; Android candidates are `.so` and `global-metadata.dat`. A matching `.exe._` or `.dll._` payload is consumed by its stub and is excluded from the skipped count.
counted, and logged, and the run continues. Folder mode finishes with a summary
line, then duration:
``` Managed DLL companions retain CLR metadata and related runtime tables in the original DLL. Both the DLL and its matching `._` file must be available; Senbei restores the declared CLR regions from the DLL while retaining method bodies decrypted from the companion. Invalid or missing referenced regions are reported as errors.
12 unpacked · 3 skipped · 0 errors · 1 suspect · 2 metadata
done in 1234 ms
```
## Integrity check The summary has the form `12 unpacked · 3 skipped · 0 errors · 1 suspect · 2 metadata`; the package count is appended when packages were opened. Each file is isolated so one failed target does not stop the folder run.
A successful unpack is not always a runnable one: a layout heuristic can pick ## Integrity Check
the wrong offset and leave the entry-point stub or import strings encrypted, so
the pipeline reports success but the OS loader faults at runtime (typically
`0xC0000005`, STATUS_ACCESS_VIOLATION). To catch this, senbei runs a static
sanity check over every output it produces — inspecting the bytes alone, with
no reference image and no execution.
It flags only defects that cannot occur in a correctly unpacked image: PE outputs are checked for valid headers, section ranges, entry-point mapping, readable import names, relocation requirements, and managed metadata signatures. Android outputs are validated during ELF restoration, including decoded container sizes, fixup bounds, and rebuilt dynamic tables.
- malformed DOS/PE headers, bad optional-header magic, implausible section A clean report is not a proof of correctness, but a non-clean report is a reliable broken-output signal. Suspect PE files are still written and counted separately.
count, zero `SizeOfImage`, or section raw-data ranges that run past EOF;
- an entry point that doesn't map into a section, isn't in an executable
section, or whose stub is all zeros or all `0xCC` int3 padding (the classic
left-encrypted symptom);
- a native (unmanaged) DLL with no base-relocation directory — it cannot
survive being mapped at a non-preferred base;
- **any** import descriptor whose DLL name doesn't resolve or isn't readable
ASCII (imports left encrypted) — the whole table is walked, not just the
first entry;
- for a managed assembly, a COR20 header whose `cb` isn't `0x48` or a
MetaData stream missing its `BSJB` signature (the CLR would reject the
image outright).
The entry-point and import checks are skipped for managed assemblies, whose
native EP and import stub are legitimately not what the native loader expects.
The check is deliberately conservative: a clean report is **not** a proof of
correctness, but a non-clean report is a reliable "this is broken" signal. A
suspect file is still written (the bytes are the best available) and flagged —
single-file mode prints a warning to stderr, folder mode prints a yellow `!`
line, adds a `SUSPECT` entry to the run log, and counts it in the summary's
`suspect` total (which is additive to `unpacked`).
## Flags ## Flags
| Flag | Behavior | | Flag | Behavior |
| --- | --- | | --- | --- |
| `--out DIR` | Write outputs (and the log, unless `--no-log`) under `DIR`. | | `--out DIR` | Write outputs and logs below `DIR`. |
| `-v`, `--verbose` | Print detailed `[N/9]` per-stage unpack progress (and the destination path) for each file. In folder mode this replaces the progress bar. | | `-v`, `--verbose` | Print per-stage progress. |
| `-q`, `--quiet` | Once: hide progress bar and per-file lines; keep banner, summary, and duration. Twice (`-q -q`): suppress all stdio (exit code only). | | `-q`, `--quiet` | Hide progress and per-file lines; repeat to suppress all standard output. |
| `--no-log` | Do not write `senbei-*.log`. Console output is unchanged by this flag alone. | | `--no-log` | Do not write a run log. |
| `--scan-all` | Probe every file in a folder, including ones the scan pre-filter skips (under 4128 bytes, or a bulk-asset extension like `.ab`/`.xml`/`.acb`). Much slower on large game trees; finds the same targets in practice. | | `--scan-all` | Probe every selected target-name candidate, including files below the size floor. |
| `--no-pause` | Skip the "Press Enter to exit" prompt (for scripted runs). | | `--no-pause` | Disable the Explorer-friendly Windows exit prompt. |
| `-V`, `--version` | Print `Senbei <version>` and exit. | | `-V`, `--version` | Print the version and exit. |
| `-h`, `--help` | Show usage. | | `-h`, `--help` | Show usage. |
On Windows, when launched from Explorer (the process owns its console) senbei ## Exit Codes
pauses for Enter before exiting so the window doesn't vanish. `--no-pause`
disables this; it has no effect when stdout is piped or run from another
process.
## Exit codes
| Code | Meaning | | Code | Meaning |
| --- | --- | | --- | --- |
| `0` | Success (single file unpacked, or folder run with no errors). | | `0` | The requested restore completed without errors. |
| `1` | At least one file failed, a scan probe was unreadable, or a single-file unpack errored. | | `1` | A target failed, a scan probe was unreadable, or a single-file restore errored. |
| `2` | Usage error: no path given, unknown option, missing `--out` value, or multiple input paths (help printed). | | `2` | The command line was invalid. |
A folder run also fails with `1` when parts of the tree could not be scanned
(unreadable directory entries or files that failed the content probe) — those
are potential missed targets, not clean skips. An il2cpp metadata blob whose
format version senbei does not handle is *not* an error: it is reported, left
untouched, and counted as skipped.
+1 -1
View File
@@ -1,3 +1,3 @@
[toolchain] [toolchain]
channel = "stable" channel = "1.98.1"
targets = ["x86_64-pc-windows-msvc", "wasm32-unknown-unknown"] targets = ["x86_64-pc-windows-msvc", "wasm32-unknown-unknown"]
+15 -76
View File
@@ -1,84 +1,23 @@
# senbei/samples # Samples
Drop-in corpus for the `samples` integration test (`tests/samples.rs`). This ignored directory is the optional local corpus used by the samples integration test. Protected binaries and restored outputs must never be committed.
This folder is **git-ignored** (only this `README.md` is tracked), so it holds Place protected `.exe` and `.dll` files, exact `global-metadata.dat` files, and matching `.exe._` or `.dll._` companion payloads here. A golden output may sit beside an input as `<base>.golden.<ext>`.
whatever Crackproof binaries happen to be on your machine. Nothing here is
committed.
## What to put here ```text
Place protected inputs directly in this folder:
- `*.exe` — Crackproof-protected executables (PE32 or PE32+)
- `*.dll` — Crackproof-protected DLLs (native or managed)
- `*.dat` — il2cpp `global-metadata.dat` blobs (method-token de-obfuscation)
For an **external-companion** module, copy the `<name>._` payload in as well,
keeping the exact `._` suffix on the full file name. The test splices it the
same way the CLI does; without it the loader stub alone is meaningless and the
splice / export-overlay / TLS-restore code is never exercised.
Optionally, place a **golden** next to each input — the known-good unpacked
output, named `<base>.golden.<ext>`:
```
samples/ samples/
app.exe <- input app.exe
app.golden.exe <- golden (optional) app.golden.exe
managed.dll <- input managed.dll
managed.golden.dll <- golden (optional) stub.dll
stub.dll <- input (external-companion layout) stub.dll._
stub.dll._ <- its encrypted payload (NOT an input itself) stub.golden.dll
stub.golden.dll <- golden global-metadata.dat
global-metadata.dat <- input global-metadata.golden.dat
global-metadata.golden.dat<- golden
mystery.exe <- input, no golden
``` ```
The type (EXE vs native/managed DLL vs metadata) is auto-detected from the file Run `cargo test --release --test samples -- --nocapture`. A missing golden prints a warning; a mismatched golden or failed restore fails the test. An empty corpus is a no-op pass.
contents, not the extension, so you don't need to classify anything by hand.
Since the corpus is the only regression gate on byte-identical output, keep it ## Android Corpus
broad: each build family, each layout (marker-based and marker-less), and at
least one external-companion pair. A family with no sample here is a family no
test protects.
## How the test treats each input `samples/android/` may contain one extracted app tree per subdirectory. Protected libraries are restored through the real pipeline and can carry SHA-256 sidecars named `<base>.golden.so.sha256` and `<base>.golden.metadata.sha256`. An empty `<base>.restore-fails` marker documents a known restore gap.
Run with:
```
cargo test --release --test samples
```
For every input file, the test runs the same routing the CLI uses
(`job::unpack_bytes`, so companions splice and the stub overlays run) — or
`metadata::deobfuscate` for an il2cpp blob — and then:
| Situation | Result |
| ------------------------------------------- | ------------------------------- |
| Golden present, bytes **identical** | **pass** |
| Golden present, bytes **differ** | **fail** (test fails) |
| **No golden** found | **warning** (needs manual check)|
| Unpack errored / file unreadable | **fail** |
Warnings are printed but do not fail the test — they flag outputs you should
eyeball or promote to a golden once verified. Failures fail the test. An empty
or absent folder is a no-op pass.
To see the per-file warning/pass/fail summary, run with output shown:
```
cargo test --release --test samples -- --nocapture
```
## Naming rules
- An **input** is any `*.exe` / `*.dll` / `*.dat` whose name does **not**
contain the `.golden.` segment.
- A **golden** is `<base>.golden.<ext>` sitting next to its input. Files with
`.golden.` in the name are never treated as inputs.
- A **companion** is `<input file name>._` (e.g. `stub.dll._` for `stub.dll`).
Its extension is `_`, so it is never picked up as an input of its own; it is
read only when its base module is processed.
+2
View File
@@ -13,8 +13,10 @@ path = "src/main.rs"
[dependencies] [dependencies]
senbei-io.workspace = true senbei-io.workspace = true
senbei-engine.workspace = true
[dev-dependencies] [dev-dependencies]
senbei-io.workspace = true senbei-io.workspace = true
senbei-metadata.workspace = true senbei-metadata.workspace = true
sha2.workspace = true
tempfile.workspace = true tempfile.workspace = true
+9 -11
View File
@@ -74,14 +74,7 @@ fn main() -> std::process::ExitCode {
match result { match result {
Ok(summary) => { Ok(summary) => {
if quiet < 2 { if quiet < 2 {
println!( println!("{}", summary.line());
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
summary.unpacked,
summary.skipped,
summary.errors,
summary.suspect,
summary.metadata
);
println!("done in {} ms", summary.duration_ms); println!("done in {} ms", summary.duration_ms);
} }
if summary.errors > 0 { 1 } else { 0 } if summary.errors > 0 { 1 } else { 0 }
@@ -105,8 +98,13 @@ fn print_help() {
"senbei <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--scan-all] [--no-log] [--no-pause] [-V|--version] [-h|--help]" "senbei <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--scan-all] [--no-log] [--no-pause] [-V|--version] [-h|--help]"
); );
println!( println!(
" --scan-all probe every file in a folder, including ones the scan\n\ " input a Crackproof PE (.exe/.dll), an il2cpp global-metadata.dat,\n\
\x20 pre-filter skips (under 4128 bytes, extensionless,\n\ \x20 a protected Android AArch64 library (.so), an Android app\n\
\x20 or a bulk-asset extension). Much slower on large trees." \x20 package (.apk/.apks/.xapk), or a folder containing any of\n\
\x20 these"
);
println!(
" --scan-all probe selected .exe/.dll/.so/metadata names below the\n\
\x20 size floor; other filenames remain excluded."
); );
} }
+231
View File
@@ -0,0 +1,231 @@
//! Corpus test over the user-managed Android samples.
//!
//! Each immediate subdirectory of `samples/android/` that contains a `lib/`
//! tree is one app-package sample (an extracted APK layout). For every
//! protected AArch64 `.so` found by content probe, the test runs the real
//! restore pipeline and checks the result:
//!
//! - `<name>.golden.so.sha256` next to the input pins the restored bytes
//! (byte-identity through the digest; absent sidecar -> WARNING).
//! - `<name>.restore-fails` (empty marker) documents an input whose restore
//! is known to fail; the test then *requires* failure, so a future fix
//! surfaces as a test failure too. Without the marker a failed restore is
//! a test failure.
//! - A restored library carrying an unwrappable embedded metadata blob must
//! produce one, pinned by `<name>.golden.metadata.sha256`.
//!
//! The folder-mode driver is then run over each app dir to exercise the
//! scan/restore/write path end to end; its error count must equal the number
//! of marked known-failures.
//!
//! The corpus is git-ignored and absent on CI (no binaries in the repo);
//! `SENBEI_REQUIRE_SAMPLES=1` turns an absent corpus into a failure, and
//! `SENBEI_ANDROID_SAMPLES` overrides the corpus location.
mod common;
use std::path::{Path, PathBuf};
use senbei_io::{android, job};
fn corpus_dir() -> PathBuf {
if let Some(dir) = std::env::var_os("SENBEI_ANDROID_SAMPLES") {
return PathBuf::from(dir);
}
common::samples_dir().join("android")
}
/// Immediate subdirectories of `root` that hold an app tree (a `lib/`
/// folder) — research notes, dumps, and other non-app material in the corpus
/// never match.
fn app_dirs(root: &Path) -> Vec<PathBuf> {
let mut dirs: Vec<PathBuf> = std::fs::read_dir(root)
.unwrap_or_else(|e| panic!("read {}: {e}", root.display()))
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| path.is_dir() && path.join("lib").is_dir())
.collect();
dirs.sort();
dirs
}
/// Every regular `.so` below `dir`, skipping previous output trees.
fn collect_so_files(dir: &Path, out: &mut Vec<PathBuf>) {
let mut entries: Vec<_> = std::fs::read_dir(dir)
.unwrap_or_else(|e| panic!("read {}: {e}", dir.display()))
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.collect();
entries.sort();
for path in entries {
if path.is_dir() {
if path
.file_name()
.is_some_and(|name| !name.eq_ignore_ascii_case("unpack"))
{
collect_so_files(&path, out);
}
} else if path
.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| ext.eq_ignore_ascii_case("so"))
{
out.push(path);
}
}
}
fn sha256_hex(data: &[u8]) -> String {
use sha2::Digest;
let mut digest = sha2::Sha256::new();
digest.update(data);
let mut out = String::with_capacity(64);
for byte in digest.finalize() {
out.push_str(&format!("{byte:02x}"));
}
out
}
/// `<stem>.golden.so.sha256` next to `input`.
fn golden_sidecar(input: &Path, artifact: &str) -> PathBuf {
let file = input.file_name().unwrap().to_string_lossy();
let stem = file.strip_suffix(".so").unwrap_or(&file);
input.with_file_name(format!("{stem}.golden.{artifact}.sha256"))
}
fn read_sidecar(path: &Path) -> Option<String> {
std::fs::read_to_string(path)
.ok()
.map(|text| text.trim().to_ascii_lowercase())
}
#[test]
fn android_samples_restore_against_goldens() {
let root = corpus_dir();
// Same opt-in gate as the PE corpus test: an absent corpus is a no-op
// pass unless CI explicitly requires it.
let require = std::env::var_os("SENBEI_REQUIRE_SAMPLES").is_some();
if !root.is_dir() {
assert!(
!require,
"android samples: {} does not exist — corpus required (CI)",
root.display()
);
eprintln!(
"android samples: {} does not exist, nothing to test",
root.display()
);
return;
}
let apps = app_dirs(&root);
if apps.is_empty() {
assert!(
!require,
"android samples: no app trees under {} — corpus required (CI)",
root.display()
);
eprintln!("android samples: no app trees under {}", root.display());
return;
}
let mut passed = 0usize;
let mut warnings: Vec<String> = Vec::new();
let mut failures: Vec<String> = Vec::new();
for app in &apps {
let mut so_files = Vec::new();
collect_so_files(app, &mut so_files);
let protected: Vec<PathBuf> = so_files
.into_iter()
.filter(|path| android::is_protected_so_file(path))
.collect();
let mut known_failures = 0usize;
for input in &protected {
let name = input.file_name().unwrap().to_string_lossy().to_string();
let known_fails = input.with_file_name(format!(
"{}.restore-fails",
name.strip_suffix(".so").unwrap_or(&name)
));
let temp = tempfile::tempdir().expect("tempdir");
let dest = temp.path().join("restored.so");
match android::restore_so_file(input, &dest, false) {
Ok(embedded) => {
if known_fails.is_file() {
failures.push(format!(
"{name}: restore succeeded but a restore-fails marker exists \
(delete the marker the gap is fixed)"
));
continue;
}
let bytes = std::fs::read(&dest).expect("read restored output");
match read_sidecar(&golden_sidecar(input, "so")) {
Some(expected) if expected == sha256_hex(&bytes) => passed += 1,
Some(expected) => failures.push(format!(
"{name}: restored bytes differ from golden\n expected sha256 {expected}\n actual sha256 {}",
sha256_hex(&bytes)
)),
None => warnings.push(format!(
"{name}: no golden sidecar — restored sha256 {}",
sha256_hex(&bytes)
)),
}
if let Some(blob) = embedded {
match read_sidecar(&golden_sidecar(input, "metadata")) {
Some(expected) if expected == sha256_hex(&blob) => {}
Some(expected) => failures.push(format!(
"{name}: embedded metadata differs from golden\n expected sha256 {expected}\n actual sha256 {}",
sha256_hex(&blob)
)),
None => warnings.push(format!(
"{name}: no embedded-metadata sidecar — sha256 {}",
sha256_hex(&blob)
)),
}
}
}
Err(error) => {
if known_fails.is_file() {
known_failures += 1;
} else {
failures.push(format!("{name}: restore failed: {error:#}"));
}
}
}
}
// Folder-mode smoke run: the scan must route every protected library,
// and only the marked known-failures may error.
let out_temp = tempfile::tempdir().expect("tempdir");
match job::run_folder_opts(app, Some(out_temp.path()), 2, false, true, false) {
Ok(summary) => {
if summary.errors != known_failures {
failures.push(format!(
"{}: folder run errors {} != known-failure markers {known_failures}",
app.display(),
summary.errors
));
}
if summary.unpacked < protected.len().saturating_sub(known_failures) {
failures.push(format!(
"{}: folder run restored {} libraries, per-file pass found {} ({} known-failing)",
app.display(),
summary.unpacked,
protected.len(),
known_failures
));
}
}
Err(error) => failures.push(format!("{}: folder run failed: {error:#}", app.display())),
}
}
for warning in &warnings {
eprintln!("WARNING: {warning}");
}
eprintln!(
"android samples: {} app tree(s) — {passed} pass, {} warning(s), {} failure(s)",
apps.len(),
warnings.len(),
failures.len()
);
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
+1
View File
@@ -6,4 +6,5 @@ license.workspace = true
description = "Cryptographic and compression primitives for Senbei" description = "Cryptographic and compression primitives for Senbei"
[dependencies] [dependencies]
aes.workspace = true
thiserror.workspace = true thiserror.workspace = true
+8
View File
@@ -0,0 +1,8 @@
//! Android container cryptography and decoding primitives.
mod protector;
pub use protector::{
ContainerHeader, EncodedSegment, Error, HuffmanLzDecoder, Module9bConfig, ProtectedDescriptor,
decode_container, gf32_mul_fixed, transform_segment,
};
+712
View File
@@ -0,0 +1,712 @@
//! Cryptographic and compression primitives used by the Android protector.
use aes::Aes256;
use aes::cipher::{BlockCipherDecrypt, KeyInit};
const RECORD_SIZE: usize = 0x5c;
/// Errors raised while parsing or decoding protector containers.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{0}")]
Invalid(String),
}
type Result<T> = std::result::Result<T, Error>;
fn invalid<T>(message: impl Into<String>) -> Result<T> {
Err(Error::Invalid(message.into()))
}
fn range(data: &[u8], offset: usize, size: usize) -> Result<&[u8]> {
let end = offset
.checked_add(size)
.ok_or_else(|| Error::Invalid("byte range overflow".to_owned()))?;
data.get(offset..end).ok_or_else(|| {
Error::Invalid(format!(
"byte range 0x{offset:x}..0x{end:x} is out of bounds"
))
})
}
fn read_u16(data: &[u8], offset: usize) -> Result<u16> {
let bytes: [u8; 2] = range(data, offset, 2)?
.try_into()
.map_err(|_| Error::Invalid("invalid u16 range".to_owned()))?;
Ok(u16::from_le_bytes(bytes))
}
fn read_u32(data: &[u8], offset: usize) -> Result<u32> {
let bytes: [u8; 4] = range(data, offset, 4)?
.try_into()
.map_err(|_| Error::Invalid("invalid u32 range".to_owned()))?;
Ok(u32::from_le_bytes(bytes))
}
fn align_up(value: usize, alignment: usize) -> Result<usize> {
let mask = alignment
.checked_sub(1)
.ok_or_else(|| Error::Invalid("zero alignment".to_owned()))?;
value
.checked_add(mask)
.map(|v| v & !mask)
.ok_or_else(|| Error::Invalid("alignment overflow".to_owned()))
}
/// Multiply by the fixed element used by the native GF(2^32) transform.
#[must_use]
pub fn gf32_mul_fixed(mut value: u32) -> u32 {
let mut multiplier = 0x9451_1dd2_u32;
let mut result = 0_u32;
while multiplier != 0 {
if multiplier & 1 != 0 {
result ^= value;
}
let carry = value >> 31;
value = value.wrapping_shl(1);
if carry != 0 {
value ^= 0x5793_57eb;
}
multiplier >>= 1;
}
result
}
fn mix_columns(block: [u8; 16]) -> [u8; 16] {
const fn xtime(value: u8) -> u8 {
(value << 1) ^ if value & 0x80 != 0 { 0x1b } else { 0 }
}
let mut output = [0_u8; 16];
for offset in (0..16).step_by(4) {
let [a, b, c, d] = block[offset..offset + 4] else {
unreachable!("fixed four-byte AES column")
};
output[offset] = xtime(a) ^ (xtime(b) ^ b) ^ c ^ d;
output[offset + 1] = a ^ xtime(b) ^ (xtime(c) ^ c) ^ d;
output[offset + 2] = a ^ b ^ xtime(c) ^ (xtime(d) ^ d);
output[offset + 3] = (xtime(a) ^ a) ^ b ^ c ^ xtime(d);
}
output
}
/// Static configuration recovered from module `0x9B`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Module9bConfig {
pub header_seed: u32,
pub container_seed: u32,
pub aes_key: [u8; 32],
pub skip_aes: bool,
pub schedule_offset: usize,
}
impl Module9bConfig {
/// Parse the unique AES-256 decryption schedule and adjacent configuration.
pub fn parse(image: &[u8]) -> Result<Self> {
Self::parse_inner(image, true)
}
/// Parse the decoder configuration embedded in the raw Stage 2 image.
///
/// The embedded decoder ends before the interpreter-only `skip_aes`
/// field, so that flag is definitionally false for this layout.
pub fn parse_embedded(image: &[u8]) -> Result<Self> {
Self::parse_inner(image, false)
}
fn parse_inner(image: &[u8], has_skip_aes: bool) -> Result<Self> {
const MARKER: [u8; 4] = [0x00, 0x01, 0x0e, 0x00];
let mut matches = image
.windows(MARKER.len())
.enumerate()
.filter_map(|(offset, bytes)| (bytes == MARKER).then_some(offset));
let schedule_offset = matches
.next()
.ok_or_else(|| Error::Invalid("cannot locate the 0x9B AES-256 schedule".to_owned()))?;
if schedule_offset < 8 || matches.next().is_some() {
return invalid("cannot uniquely locate the 0x9B AES-256 schedule");
}
let header_seed = read_u32(image, schedule_offset - 8)?;
let schedule_size = read_u32(image, schedule_offset - 4)?;
if !matches!(schedule_size, 0 | 0xf4) {
return invalid(format!(
"unexpected 0x9B AES schedule size 0x{schedule_size:x}"
));
}
let bits = read_u16(image, schedule_offset)?;
let rounds = read_u16(image, schedule_offset + 2)?;
if (bits, rounds) != (0x100, 14) {
return invalid(format!(
"unexpected AES schedule header 0x{bits:x}/{rounds}"
));
}
let schedule = range(image, schedule_offset + 4, 15 * 16)?;
let mut round_keys = [[0_u8; 16]; 15];
for (round, output) in round_keys.iter_mut().enumerate() {
let source = &schedule[round * 16..round * 16 + 16];
for word in 0..4 {
let start = word * 4;
for byte in 0..4 {
output[start + byte] = source[start + 3 - byte];
}
}
}
let mut aes_key = [0_u8; 32];
aes_key[..16].copy_from_slice(&round_keys[14]);
aes_key[16..].copy_from_slice(&mix_columns(round_keys[13]));
let container_seed_offset = schedule_offset
.checked_add(0x100)
.ok_or_else(|| Error::Invalid("container seed offset overflow".to_owned()))?;
let skip_aes = if has_skip_aes {
let skip_aes_offset = schedule_offset
.checked_add(0x240)
.ok_or_else(|| Error::Invalid("skip-AES offset overflow".to_owned()))?;
*image.get(skip_aes_offset).ok_or_else(|| {
Error::Invalid("module static configuration exceeds its image".to_owned())
})? != 0
} else {
false
};
Ok(Self {
header_seed,
container_seed: if has_skip_aes {
read_u32(image, container_seed_offset)?
} else {
header_seed
},
aes_key,
skip_aes,
schedule_offset,
})
}
}
/// Decrypted header at the start of direct-data object `0x9D`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ProtectedDescriptor {
pub command_id: u32,
pub flags: u32,
pub outer_offset: u32,
pub outer_expected_size: u32,
pub auxiliary_offset: u32,
pub auxiliary_expected_size: u32,
}
impl ProtectedDescriptor {
/// Decrypt the `0x5c`-byte descriptor with the module header seed.
pub fn decrypt(data: &[u8], seed: u32) -> Result<Self> {
if data.len() < RECORD_SIZE {
return invalid("0x9D descriptor is truncated");
}
let base0 = seed.wrapping_add(0xd3e8_7144).wrapping_mul(seed);
let base1 = base0.wrapping_add(seed.wrapping_mul(0x0bd9_418d));
let mut words = [0_u32; RECORD_SIZE / 4];
for (index, word) in words.iter_mut().enumerate() {
let cipher = read_u32(data, index * 4)?;
let subtractor = base0.wrapping_shl(if index & 1 != 0 { 4 } else { 0 });
*word = cipher.wrapping_sub(subtractor)
^ base1.wrapping_shr((seed.wrapping_add((index as u32).wrapping_mul(4))) & 7);
}
if words[6..].iter().any(|&word| word != 0) {
return invalid("unexpected nonzero reserved words in the 0x9D descriptor");
}
let descriptor = Self {
command_id: words[0],
flags: words[1],
outer_offset: words[2],
outer_expected_size: words[3],
auxiliary_offset: words[4],
auxiliary_expected_size: words[5],
};
if descriptor.command_id != 0x9d || descriptor.outer_offset as usize != RECORD_SIZE {
return invalid("unexpected decrypted 0x9D descriptor");
}
Ok(descriptor)
}
}
/// One encrypted segment in a decoded `0x9D` container header.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EncodedSegment {
pub offset: u32,
pub size: u32,
}
/// Parsed primary or auxiliary `0x9D` container.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContainerHeader {
pub start: usize,
pub output_size: u32,
pub skip_aes: bool,
pub tree: Vec<u8>,
pub segments: Vec<EncodedSegment>,
}
impl ContainerHeader {
/// Parse and decrypt a container header, Huffman tree, and segment table.
pub fn parse(data: &[u8], start: usize, seed: u32) -> Result<Self> {
range(data, start, 12)?;
let seed_square = seed.wrapping_mul(seed);
let state = seed_square.wrapping_shr(17) ^ seed_square.wrapping_shl(11);
let raw0 = read_u32(data, start)?;
let raw1 = read_u32(data, start + 4)?;
let raw2 = read_u32(data, start + 8)?;
let output_size = 0xa21d_fb3a_u32
.wrapping_shl(state & 7)
.wrapping_add(state.wrapping_mul(0xf87b_337c))
.wrapping_add(gf32_mul_fixed(raw0));
let flag_word = gf32_mul_fixed(raw1)
^ state
.wrapping_add(0xbd19_c63c)
.wrapping_add(0x416e_2af2_u32.wrapping_shr(state & 0x0d));
let segment_count = (flag_word & 0xff) as usize;
let skip_aes = (flag_word >> 8) & 0xff == 1;
let tree_size = 0x643a_3a3b_u32
.wrapping_shl(state & 0x0b)
.wrapping_sub(state ^ 0x3b2b_f538)
.wrapping_add(gf32_mul_fixed(raw2)) as usize;
if segment_count == 0 || tree_size > 0x1b00 {
return invalid(format!(
"invalid container fields: segments={segment_count}, tree=0x{tree_size:x}"
));
}
let tree_start = start
.checked_add(12)
.ok_or_else(|| Error::Invalid("tree offset overflow".to_owned()))?;
let mut tree = range(data, tree_start, tree_size)?.to_vec();
for offset in (0..tree_size & !3).step_by(4) {
let value = read_u32(&tree, offset)?;
tree[offset..offset + 4].copy_from_slice(&gf32_mul_fixed(value).to_le_bytes());
}
let tree_state = state.wrapping_add(0xf1cb_5b81).wrapping_mul(state);
let tree_delta = tree_state.wrapping_sub(0x23b3_2203_u32.wrapping_mul(state));
for (index, byte) in tree.iter_mut().enumerate() {
let shift = u32::try_from(index & 0x1b)
.map_err(|_| Error::Invalid("tree shift conversion failed".to_owned()))?;
let left = gf32_mul_fixed(tree_state.wrapping_shl(shift));
let right = tree_delta.wrapping_shr((index & 0x17) as u32);
let adjustment = left.wrapping_sub(right).wrapping_shr((index & 0x1f) as u32);
*byte = byte.wrapping_add(adjustment as u8);
}
let table_start = start
.checked_add(align_up(12 + tree_size, 4)?)
.ok_or_else(|| Error::Invalid("segment table offset overflow".to_owned()))?;
let table_size = segment_count
.checked_mul(8)
.ok_or_else(|| Error::Invalid("segment table size overflow".to_owned()))?;
let mut table = range(data, table_start, table_size)?.to_vec();
let table_state = state.wrapping_add(0xb31f_451c).wrapping_mul(state);
let table_xor = table_state.wrapping_shl(3);
let table_add = table_state.wrapping_sub(0x822f_e82d_u32.wrapping_mul(state));
for offset in (0..table_size).step_by(4) {
let value = read_u32(&table, offset)?;
let decoded = gf32_mul_fixed(value ^ table_xor)
.wrapping_add(table_add.wrapping_shr(((offset & 7) + 5) as u32));
table[offset..offset + 4].copy_from_slice(&decoded.to_le_bytes());
}
let mut segments = Vec::with_capacity(segment_count);
for index in 0..segment_count {
let offset = read_u32(&table, index * 8)?;
let size = read_u32(&table, index * 8 + 4)?;
let absolute = start
.checked_add(offset as usize)
.and_then(|value| value.checked_add(size as usize));
if size == 0 || absolute.is_none_or(|end| end > data.len()) {
return invalid(format!("container segment {index} lies outside 0x9D"));
}
segments.push(EncodedSegment { offset, size });
}
Ok(Self {
start,
output_size,
skip_aes,
tree,
segments,
})
}
/// End offset of the furthest encrypted segment.
pub fn encoded_end(&self) -> Result<usize> {
self.segments
.iter()
.map(|segment| {
self.start
.checked_add(segment.offset as usize)
.and_then(|value| value.checked_add(segment.size as usize))
.ok_or_else(|| Error::Invalid("encoded segment end overflow".to_owned()))
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.max()
.ok_or_else(|| Error::Invalid("container has no encoded segments".to_owned()))
}
}
/// Decoder for the protector's Huffman/LZ writer streams.
#[derive(Debug, Clone)]
pub struct HuffmanLzDecoder {
tree: Vec<u8>,
lookup_symbols: Vec<u16>,
lookup_bits: Vec<u8>,
}
impl HuffmanLzDecoder {
/// Build the full 16-bit prefix lookup used by the static decoder.
pub fn new(tree: &[u8]) -> Result<Self> {
if tree.len() < 256 * 3 || !tree.len().is_multiple_of(3) {
return invalid(format!("invalid Huffman tree size 0x{:x}", tree.len()));
}
let mut result = Self {
tree: tree.to_vec(),
lookup_symbols: vec![0; 0x1_0000],
lookup_bits: vec![0; 0x1_0000],
};
for word in 0..0x1_0000_u32 {
let (symbol, bits) = result.decode_symbol(word)?;
if bits <= 16 {
result.lookup_symbols[word as usize] = symbol;
result.lookup_bits[word as usize] = bits;
}
}
Ok(result)
}
fn entry(&self, index: usize) -> Result<(u16, bool, u8)> {
let offset = index
.checked_mul(3)
.ok_or_else(|| Error::Invalid("Huffman node offset overflow".to_owned()))?;
let bytes = range(&self.tree, offset, 3)?;
let raw = u16::from(bytes[0]) | (u16::from(bytes[1]) << 8);
Ok((raw & 0x7fff, raw & 0x8000 != 0, bytes[2]))
}
fn decode_symbol(&self, word: u32) -> Result<(u16, u8)> {
let (mut value, leaf, extra) = self.entry((word & 0xff) as usize)?;
if leaf {
if extra == 0 {
return invalid("zero-width Huffman leaf");
}
return Ok((value, extra));
}
let mut bits = extra
.checked_add(1)
.ok_or_else(|| Error::Invalid("Huffman bit count overflow".to_owned()))?;
let mut mask = 1_u32.wrapping_shl(u32::from(extra));
loop {
let branch = usize::from(word & mask != 0);
let (next, is_leaf, _) = self.entry(usize::from(value) + branch)?;
value = next;
if is_leaf {
return Ok((value, bits));
}
mask = mask.wrapping_shl(1);
bits = bits
.checked_add(1)
.ok_or_else(|| Error::Invalid("Huffman bit count overflow".to_owned()))?;
if bits > 31 {
return invalid("Huffman code exceeds the native 32-bit window");
}
}
}
/// Decode one compressed writer payload to its exact expected size.
pub fn decode(&self, source: &[u8], output_size: usize) -> Result<Vec<u8>> {
let mut output = vec![0_u8; output_size];
let mut source_pos = 0_usize;
let mut bit_buffer = 0_u64;
let mut available = 0_u8;
let mut consumed_bits = 0_usize;
let mut output_pos = 0_usize;
let mut prefix = 0_usize;
while output_pos < output_size {
while available < 24 && source_pos < source.len() {
bit_buffer |= u64::from(source[source_pos]) << available;
source_pos += 1;
available += 8;
}
let key = (bit_buffer & 0xffff) as usize;
let mut bits = self.lookup_bits[key];
let symbol = if bits != 0 {
self.lookup_symbols[key]
} else {
let mut value_offset = ((bit_buffer & 0xff) as usize) * 3;
let mut node = range(&self.tree, value_offset, 3)?;
let mut raw = u16::from(node[0]) | (u16::from(node[1]) << 8);
if raw & 0x8000 != 0 {
bits = node[2];
raw & 0x7fff
} else {
let extra = node[2];
bits = extra + 1;
let mut mask = 1_u64 << extra;
loop {
let branch = usize::from(bit_buffer & mask != 0);
let index = usize::from(raw & 0x7fff) + branch;
value_offset = index
.checked_mul(3)
.ok_or_else(|| Error::Invalid("Huffman node overflow".to_owned()))?;
node = range(&self.tree, value_offset, 3)?;
raw = u16::from(node[0]) | (u16::from(node[1]) << 8);
if raw & 0x8000 != 0 {
break raw & 0x7fff;
}
mask <<= 1;
bits += 1;
}
}
};
if bits == 0 || bits > available {
return invalid("compressed stream ends inside a Huffman code");
}
bit_buffer >>= bits;
available -= bits;
consumed_bits = consumed_bits
.checked_add(usize::from(bits))
.ok_or_else(|| Error::Invalid("consumed bit count overflow".to_owned()))?;
let kind = symbol & 0x300;
let value = usize::from(symbol & 0xff);
match kind {
0 => {
output[output_pos] = value as u8;
output_pos += 1;
}
0x100 => {
if prefix > 0xff {
return invalid("compressed prefix exceeds 16 bits");
}
prefix = if prefix == 0 {
value
} else {
value | (prefix << 8)
};
}
0x200 => {
if prefix == 0 {
prefix = 1;
}
let count = value
.checked_mul(prefix)
.ok_or_else(|| Error::Invalid("repeat count overflow".to_owned()))?;
if !matches!(value, 1 | 2 | 4)
|| value > output_pos
|| output_pos
.checked_add(count)
.is_none_or(|end| end > output_size)
{
return invalid("invalid compressed repeated-pattern command");
}
let pattern = output[output_pos - value..output_pos].to_vec();
for chunk in output[output_pos..output_pos + count].chunks_exact_mut(value) {
chunk.copy_from_slice(&pattern);
}
output_pos += count;
prefix = 0;
}
0x300 => {
let length = value;
let distance = prefix.checked_add(length).ok_or_else(|| {
Error::Invalid("back-reference distance overflow".to_owned())
})?;
if distance > output_pos
|| output_pos
.checked_add(length)
.is_none_or(|end| end > output_size)
{
return invalid("invalid compressed back-reference");
}
let source_start = output_pos - distance;
output.copy_within(source_start..source_start + length, output_pos);
output_pos += length;
prefix = 0;
}
_ => unreachable!("masked Huffman symbol kind"),
}
}
if consumed_bits.div_ceil(8) != source.len() {
return invalid(format!(
"compressed input consumption mismatch: used=0x{:x}, size=0x{:x}",
consumed_bits.div_ceil(8),
source.len()
));
}
Ok(output)
}
}
/// Apply the native word transform and optional AES-256-CBC decryption.
pub fn transform_segment(
data: &[u8],
seed: u32,
aes_key: &[u8; 32],
decrypt_aes: bool,
) -> Result<Vec<u8>> {
let mut transformed = data.to_vec();
let mut state = seed;
let mut left = 0xe34e_ac63_u32;
let mut right = 0x07b4_8238_u32;
for (index, chunk) in transformed.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let index32 = u32::try_from(index)
.map_err(|_| Error::Invalid("segment word index exceeds u32".to_owned()))?;
left = state
.wrapping_add(0x72f6_fcbe)
.wrapping_add(left.wrapping_add(0x4f8b_1bca).wrapping_mul(left))
.wrapping_shr(index32.wrapping_mul(index32) & 0x0f);
right = state
.wrapping_sub(0x71b6_a98d)
.wrapping_add(right.wrapping_sub(0x1605_a81c).wrapping_mul(right))
.wrapping_shl(index32 & 7);
state = left ^ right;
let mut value = u32::from_le_bytes(*chunk);
value = value.wrapping_add(0xb43b_9baf_u32.wrapping_mul(index32 & 0x0d));
value ^= 0xaf57_f7fb_u32.wrapping_mul(index32 & 3);
value = value.wrapping_sub(state) ^ state;
chunk.copy_from_slice(&value.to_le_bytes());
}
if decrypt_aes {
let cipher = Aes256::new_from_slice(aes_key)
.map_err(|_| Error::Invalid("invalid AES-256 key length".to_owned()))?;
let mut previous = [0_u8; 16];
for chunk in transformed.as_chunks_mut::<16>().0 {
let ciphertext = *chunk;
cipher.decrypt_block((&mut *chunk).into());
for (byte, prior) in chunk.iter_mut().zip(previous) {
*byte ^= prior;
}
previous = ciphertext;
}
}
Ok(transformed)
}
/// Decode one complete protector container into its flat output buffer.
///
/// This is the static equivalent of the decoder entrypoint embedded in Stage
/// 2 and in each nested interpreter module.
pub fn decode_container(
data: &[u8],
config: &Module9bConfig,
expected_size: usize,
) -> Result<Vec<u8>> {
let header = ContainerHeader::parse(data, 0, config.container_seed)?;
let header_size = usize::try_from(header.output_size)
.map_err(|_| Error::Invalid("container output size exceeds usize".to_owned()))?;
if header_size != expected_size {
return invalid(format!(
"container output size 0x{header_size:x} != expected 0x{expected_size:x}"
));
}
let decoder = HuffmanLzDecoder::new(&header.tree)?;
let decrypt_aes = !(config.skip_aes || header.skip_aes);
let mut output = vec![0_u8; expected_size];
for (segment_index, encoded) in header.segments.iter().enumerate() {
let start = header
.start
.checked_add(encoded.offset as usize)
.ok_or_else(|| Error::Invalid("encoded segment start overflow".to_owned()))?;
let encoded_data = range(data, start, encoded.size as usize)?;
let transformed = transform_segment(
encoded_data,
config.container_seed,
&config.aes_key,
decrypt_aes,
)?;
if transformed.len() < 16 {
return invalid(format!(
"decoded segment {segment_index} is shorter than its header"
));
}
let base_offset = read_u32(&transformed, 0)? as usize;
let writer_count = read_u32(&transformed, 4)? as usize;
let table_offset = read_u32(&transformed, 8)? as usize;
let data_offset = read_u32(&transformed, 12)? as usize;
let table_size = writer_count
.checked_mul(16)
.ok_or_else(|| Error::Invalid("writer table size overflow".to_owned()))?;
let table_end = table_offset
.checked_add(table_size)
.ok_or_else(|| Error::Invalid("writer table end overflow".to_owned()))?;
if table_end > transformed.len() || data_offset > transformed.len() {
return invalid(format!(
"decoded segment {segment_index} has invalid writer offsets"
));
}
let mut data_cursor = data_offset;
for writer_index in 0..writer_count {
let record =
table_offset
.checked_add(writer_index.checked_mul(16).ok_or_else(|| {
Error::Invalid("writer record offset overflow".to_owned())
})?)
.ok_or_else(|| Error::Invalid("writer record offset overflow".to_owned()))?;
let output_offset = read_u32(&transformed, record)? as usize;
let output_size = read_u32(&transformed, record + 4)? as usize;
let encoded_size = read_u32(&transformed, record + 8)? as usize;
let reserved = read_u32(&transformed, record + 12)?;
let encoded_end = data_cursor
.checked_add(encoded_size)
.ok_or_else(|| Error::Invalid("writer data end overflow".to_owned()))?;
if reserved != 0 || encoded_end > transformed.len() {
return invalid(format!(
"segment {segment_index} writer {writer_index} has invalid bounds"
));
}
let source = &transformed[data_cursor..encoded_end];
let decoded = if encoded_size == output_size {
None
} else {
Some(decoder.decode(source, output_size)?)
};
let decoded = decoded.as_deref().unwrap_or(source);
let target = base_offset
.checked_add(output_offset)
.ok_or_else(|| Error::Invalid("writer target offset overflow".to_owned()))?;
let target_end = target
.checked_add(decoded.len())
.ok_or_else(|| Error::Invalid("writer target end overflow".to_owned()))?;
let destination = output.get_mut(target..target_end).ok_or_else(|| {
Error::Invalid(format!(
"segment {segment_index} writer {writer_index} target is out of range"
))
})?;
destination.copy_from_slice(decoded);
data_cursor = encoded_end;
}
}
Ok(output)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn aes_mix_columns_matches_fips_example() {
let input = [
0xdb, 0x13, 0x53, 0x45, 0xf2, 0x0a, 0x22, 0x5c, 0x01, 0x01, 0x01, 0x01, 0xc6, 0xc6,
0xc6, 0xc6,
];
assert_eq!(
mix_columns(input),
[
0x8e, 0x4d, 0xa1, 0xbc, 0x9f, 0xdc, 0x58, 0x9d, 0x01, 0x01, 0x01, 0x01, 0xc6, 0xc6,
0xc6, 0xc6,
]
);
}
#[test]
fn descriptor_rejects_truncated_input() {
assert!(ProtectedDescriptor::decrypt(&[0_u8; 16], 1).is_err());
}
}
+15 -72
View File
@@ -1,77 +1,20 @@
//! Cryptographic, checksum, compression, and bytecode primitives. //! Cryptographic and compression primitives for the supported protection
//! formats.
pub mod bytecode; pub mod android;
pub mod crc32; pub mod windows;
pub mod primitives;
mod tables;
/// Maximum buffer size accepted by allocation-sensitive transforms. // Keep the historical flat paths available to downstream callers while the
pub const MAX_IMAGE_SIZE: u64 = 1 << 30; // implementations themselves live under their platform boundary.
pub use windows::{BufferOperation, DecompressionFailure, Error, MAX_IMAGE_SIZE};
pub use windows::{bytecode, crc32, primitives};
#[derive(Debug, Clone, Copy, PartialEq, Eq)] /// Lowercase hexadecimal representation for digest and diagnostic bytes.
pub enum BufferOperation { #[must_use]
Read, pub fn hex_digest(data: &[u8]) -> String {
CopySource, let mut output = String::with_capacity(data.len() * 2);
CopyDestination, for byte in data {
ZeroFill, output.push_str(&format!("{byte:02x}"));
}
impl std::fmt::Display for BufferOperation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Read => "read",
Self::CopySource => "copy source",
Self::CopyDestination => "copy destination",
Self::ZeroFill => "zero-fill",
})
} }
} output
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
#[error(
"{operation} range out of bounds (offset {offset}, size {size}, buffer length {buffer_len})"
)]
BufferRangeOutOfBounds {
operation: BufferOperation,
offset: usize,
size: usize,
buffer_len: usize,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum DecompressionFailure {
#[error("compressed source size {size} exceeds limit {max}")]
SourceTooLarge { size: u32, max: u64 },
#[error("Huffman code length {bits} is invalid")]
InvalidCodeLength { bits: u8 },
#[error("Huffman tree traversal exceeded 64 levels")]
HuffmanTraversalLimit,
#[error("pending length accumulator overflowed at {pending}")]
PendingLengthOverflow { pending: u32 },
#[error("output step {step} at byte {written} exceeds expected size {expected}")]
OutputOverflow {
written: u32,
step: u32,
expected: u32,
},
#[error("run-fill width {width} reads before output offset 0x{destination:08X}")]
RunFillBeforeOutput { width: u32, destination: u32 },
#[error("run-fill width {width} is unsupported")]
InvalidRunFillWidth { width: u32 },
#[error("back-reference distance {distance} exceeds {written} written bytes")]
InvalidBackReference { distance: u32, written: u32 },
#[error("Huffman symbol consumed no input and produced no output")]
NoProgress,
#[error(
"output size mismatch (wrote {written}/{expected} bytes after consuming {consumed}/{source_size})"
)]
OutputSizeMismatch {
written: u32,
expected: u32,
consumed: u32,
source_size: u32,
},
} }
+77
View File
@@ -0,0 +1,77 @@
//! Windows PE protection primitives.
pub mod bytecode;
pub mod crc32;
pub mod primitives;
mod tables;
/// Maximum buffer size accepted by allocation-sensitive PE transforms.
pub const MAX_IMAGE_SIZE: u64 = 1 << 30;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BufferOperation {
Read,
CopySource,
CopyDestination,
ZeroFill,
}
impl std::fmt::Display for BufferOperation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Read => "read",
Self::CopySource => "copy source",
Self::CopyDestination => "copy destination",
Self::ZeroFill => "zero-fill",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
#[error(
"{operation} range out of bounds (offset {offset}, size {size}, buffer length {buffer_len})"
)]
BufferRangeOutOfBounds {
operation: BufferOperation,
offset: usize,
size: usize,
buffer_len: usize,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum DecompressionFailure {
#[error("compressed source size {size} exceeds limit {max}")]
SourceTooLarge { size: u32, max: u64 },
#[error("Huffman code length {bits} is invalid")]
InvalidCodeLength { bits: u8 },
#[error("Huffman tree traversal exceeded 64 levels")]
HuffmanTraversalLimit,
#[error("pending length accumulator overflowed at {pending}")]
PendingLengthOverflow { pending: u32 },
#[error("output step {step} at byte {written} exceeds expected size {expected}")]
OutputOverflow {
written: u32,
step: u32,
expected: u32,
},
#[error("run-fill width {width} reads before output offset 0x{destination:08X}")]
RunFillBeforeOutput { width: u32, destination: u32 },
#[error("run-fill width {width} is unsupported")]
InvalidRunFillWidth { width: u32 },
#[error("back-reference distance {distance} exceeds {written} written bytes")]
InvalidBackReference { distance: u32, written: u32 },
#[error("Huffman symbol consumed no input and produced no output")]
NoProgress,
#[error(
"output size mismatch (wrote {written}/{expected} bytes after consuming {consumed}/{source_size})"
)]
OutputSizeMismatch {
written: u32,
expected: u32,
consumed: u32,
source_size: u32,
},
}
@@ -4,9 +4,9 @@
//! Each free function is self-contained: it takes the relevant byte buffer(s) //! Each free function is self-contained: it takes the relevant byte buffer(s)
//! and parameters explicitly, with no coupling to the EXE `Unpacker` struct. //! and parameters explicitly, with no coupling to the EXE `Unpacker` struct.
use super::tables::{COLUMMIX1, COLUMMIX2, COLUMMIX3, COLUMMIX4, SBOX};
use crate::bytecode::{Op, OpsLut}; use crate::bytecode::{Op, OpsLut};
use crate::crc32; use crate::crc32;
use crate::tables::{COLUMMIX1, COLUMMIX2, COLUMMIX3, COLUMMIX4, SBOX};
use std::cell::RefCell; use std::cell::RefCell;
thread_local! { thread_local! {
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "senbei-elf"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "ELF format parsing and structural utilities for Senbei"
[dependencies]
goblin.workspace = true
thiserror.workspace = true
[lints]
workspace = true
+107
View File
@@ -0,0 +1,107 @@
use crate::{Error, Result, invalid};
#[must_use]
pub fn elf_hash(name: &[u8]) -> u32 {
let mut value = 0_u32;
for &byte in name {
value = value.wrapping_shl(4).wrapping_add(u32::from(byte));
let high = value & 0xf000_0000;
if high != 0 {
value ^= high >> 24;
value &= !high;
}
}
value
}
#[must_use]
pub fn gnu_hash(name: &[u8]) -> u32 {
name.iter().fold(5381_u32, |value, &byte| {
value.wrapping_mul(33).wrapping_add(u32::from(byte))
})
}
pub fn build_sysv_hash(names: &[Vec<u8>]) -> Result<Vec<u8>> {
if names.len() < 2 {
return invalid("dynamic symbol table is unexpectedly empty");
}
let bucket_count = names.len();
let symbol_count = names.len();
let mut buckets = vec![0_u32; bucket_count];
let mut chains = vec![0_u32; symbol_count];
for (symbol_index, name) in names.iter().enumerate().skip(1) {
let bucket_index = elf_hash(name) as usize % bucket_count;
let symbol_index32 = u32::try_from(symbol_index)
.map_err(|_| Error::Invalid("dynamic symbol index exceeds u32".to_owned()))?;
if buckets[bucket_index] == 0 {
buckets[bucket_index] = symbol_index32;
continue;
}
let mut chain_index = buckets[bucket_index] as usize;
while chains[chain_index] != 0 {
chain_index = chains[chain_index] as usize;
}
chains[chain_index] = symbol_index32;
}
let mut output = Vec::with_capacity((2 + bucket_count + symbol_count) * 4);
output.extend_from_slice(
&u32::try_from(bucket_count)
.map_err(|_| Error::Invalid("SysV bucket count exceeds u32".to_owned()))?
.to_le_bytes(),
);
output.extend_from_slice(
&u32::try_from(symbol_count)
.map_err(|_| Error::Invalid("SysV symbol count exceeds u32".to_owned()))?
.to_le_bytes(),
);
for value in buckets.into_iter().chain(chains) {
output.extend_from_slice(&value.to_le_bytes());
}
Ok(output)
}
pub fn build_gnu_hash(names: &[Vec<u8>]) -> Result<Vec<u8>> {
let hashes = names
.iter()
.skip(1)
.map(|name| gnu_hash(name))
.collect::<Vec<_>>();
if hashes.is_empty() {
return invalid("GNU hash requires at least one dynamic symbol");
}
let bloom_shift = 5_u32;
let mut bloom_word = 0_u64;
for &value in &hashes {
bloom_word |= 1_u64 << (value & 63);
bloom_word |= 1_u64 << ((value >> bloom_shift) & 63);
}
let mut chains = hashes
.into_iter()
.map(|value| value & !1)
.collect::<Vec<_>>();
let last = chains
.last_mut()
.ok_or_else(|| Error::Invalid("GNU hash chain is empty".to_owned()))?;
*last |= 1;
let mut output = Vec::with_capacity(28 + chains.len() * 4);
for value in [1_u32, 1, 1, bloom_shift] {
output.extend_from_slice(&value.to_le_bytes());
}
output.extend_from_slice(&bloom_word.to_le_bytes());
output.extend_from_slice(&1_u32.to_le_bytes());
for value in chains {
output.extend_from_slice(&value.to_le_bytes());
}
Ok(output)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn standard_elf_hash_is_stable() {
assert_eq!(elf_hash(b"printf"), 0x0779_05a6);
assert_eq!(gnu_hash(b"printf"), 0x156b_2bb8);
}
}
+636
View File
@@ -0,0 +1,636 @@
use crate::{Error, Result, invalid};
pub const SHT_NOBITS: u32 = 8;
pub const SHT_STRTAB: u32 = 3;
pub const SHT_LOUSER: u32 = 0x8000_0000;
pub const SHF_ALLOC: u64 = 2;
const PT_LOAD: u32 = 1;
pub const PF_R: u32 = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LoadSegment {
pub offset: u64,
pub virtual_address: u64,
pub file_size: u64,
pub memory_size: u64,
pub flags: u32,
pub alignment: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SectionHeader {
pub name: u32,
pub section_type: u32,
pub flags: u64,
pub address: u64,
pub offset: u64,
pub size: u64,
pub link: u32,
pub info: u32,
pub alignment: u64,
pub entry_size: u64,
}
impl SectionHeader {
pub const SIZE: usize = 0x40;
fn parse(data: &[u8], offset: usize) -> Result<Self> {
Ok(Self {
name: read_u32(data, offset)?,
section_type: read_u32(data, offset + 4)?,
flags: read_u64(data, offset + 8)?,
address: read_u64(data, offset + 0x10)?,
offset: read_u64(data, offset + 0x18)?,
size: read_u64(data, offset + 0x20)?,
link: read_u32(data, offset + 0x28)?,
info: read_u32(data, offset + 0x2c)?,
alignment: read_u64(data, offset + 0x30)?,
entry_size: read_u64(data, offset + 0x38)?,
})
}
pub fn encode(self) -> [u8; Self::SIZE] {
let mut output = [0_u8; Self::SIZE];
output[0..4].copy_from_slice(&self.name.to_le_bytes());
output[4..8].copy_from_slice(&self.section_type.to_le_bytes());
output[8..0x10].copy_from_slice(&self.flags.to_le_bytes());
output[0x10..0x18].copy_from_slice(&self.address.to_le_bytes());
output[0x18..0x20].copy_from_slice(&self.offset.to_le_bytes());
output[0x20..0x28].copy_from_slice(&self.size.to_le_bytes());
output[0x28..0x2c].copy_from_slice(&self.link.to_le_bytes());
output[0x2c..0x30].copy_from_slice(&self.info.to_le_bytes());
output[0x30..0x38].copy_from_slice(&self.alignment.to_le_bytes());
output[0x38..0x40].copy_from_slice(&self.entry_size.to_le_bytes());
output
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ElfLayout {
pub entrypoint: u64,
pub program_header_offset: usize,
pub program_header_size: usize,
pub program_header_count: usize,
pub program_headers: Vec<LoadSegment>,
pub section_headers: Vec<SectionHeader>,
pub section_name_index: usize,
pub private_section_index: usize,
}
impl ElfLayout {
pub fn parse(data: &[u8], require_private: bool) -> Result<Self> {
let ident = slice(data, 0, 6)?;
if ident[..4] != *b"\x7fELF" || ident[4] != 2 || ident[5] != 1 {
return invalid("input is not a little-endian ELF64 file");
}
if read_u16(data, 0x12)? != crate::AARCH64_MACHINE {
return invalid("input is not an AArch64 ELF");
}
let entrypoint = read_u64(data, 0x18)?;
let program_header_offset = usize_from_u64(read_u64(data, 0x20)?, "program header offset")?;
let section_header_offset = usize_from_u64(read_u64(data, 0x28)?, "section header offset")?;
let program_header_size = usize::from(read_u16(data, 0x36)?);
let program_header_count = usize::from(read_u16(data, 0x38)?);
let section_header_size = usize::from(read_u16(data, 0x3a)?);
let section_header_count = usize::from(read_u16(data, 0x3c)?);
let section_name_index = usize::from(read_u16(data, 0x3e)?);
if program_header_size != 0x38 || section_header_size != SectionHeader::SIZE {
return invalid("unexpected ELF program/section header size");
}
let mut program_headers = Vec::new();
for index in 0..program_header_count {
let offset = checked_index(program_header_offset, index, program_header_size)?;
if read_u32(data, offset)? != PT_LOAD {
continue;
}
let segment = LoadSegment {
flags: read_u32(data, offset + 4)?,
offset: read_u64(data, offset + 8)?,
virtual_address: read_u64(data, offset + 0x10)?,
file_size: read_u64(data, offset + 0x20)?,
memory_size: read_u64(data, offset + 0x28)?,
alignment: read_u64(data, offset + 0x30)?,
};
let file_end = segment
.offset
.checked_add(segment.file_size)
.ok_or_else(|| Error::Invalid(format!("PT_LOAD {index} file range overflow")))?;
if file_end > data.len() as u64 {
return invalid(format!("PT_LOAD {index} exceeds input file"));
}
program_headers.push(segment);
}
if program_headers.is_empty() {
return invalid("input ELF contains no PT_LOAD segments");
}
let mut section_headers = Vec::with_capacity(section_header_count);
for index in 0..section_header_count {
let offset = checked_index(section_header_offset, index, section_header_size)?;
section_headers.push(SectionHeader::parse(data, offset)?);
}
if section_name_index >= section_headers.len() {
return invalid("ELF section-name index is out of range");
}
let private = section_headers
.iter()
.enumerate()
.filter_map(|(index, section)| (section.section_type == SHT_LOUSER).then_some(index))
.collect::<Vec<_>>();
let private_section_index = match private.as_slice() {
[index] => *index,
[] if !require_private => usize::MAX,
_ => {
return invalid(format!(
"expected {} SHT_LOUSER section, found {}",
if require_private {
"one"
} else {
"at most one"
},
private.len()
));
}
};
let layout = Self {
entrypoint,
program_header_offset,
program_header_size,
program_header_count,
program_headers,
section_headers,
section_name_index,
private_section_index,
};
// Section roles are resolved from the ELF's own string table. Validate
// it at the format boundary so callers cannot silently continue with
// fabricated or lossy section names.
layout.section_names(data)?;
Ok(layout)
}
pub fn private_section(&self) -> Result<SectionHeader> {
self.section_headers
.get(self.private_section_index)
.copied()
.ok_or_else(|| Error::Invalid("ELF has no private section".to_owned()))
}
pub fn load_end(&self) -> Result<u64> {
self.program_headers
.iter()
.map(|segment| {
segment
.virtual_address
.checked_add(segment.memory_size)
.ok_or_else(|| Error::Invalid("PT_LOAD memory end overflow".to_owned()))
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.max()
.ok_or_else(|| Error::Invalid("ELF has no PT_LOAD memory range".to_owned()))
}
pub fn file_load_end(&self) -> Result<u64> {
self.program_headers
.iter()
.map(|segment| {
segment
.offset
.checked_add(segment.file_size)
.ok_or_else(|| Error::Invalid("PT_LOAD file end overflow".to_owned()))
})
.collect::<Result<Vec<_>>>()?
.into_iter()
.max()
.ok_or_else(|| Error::Invalid("ELF has no PT_LOAD file range".to_owned()))
}
pub fn load_alignment(&self) -> Result<u64> {
let alignment = self
.program_headers
.iter()
.map(|segment| segment.alignment)
.max()
.ok_or_else(|| Error::Invalid("ELF has no PT_LOAD alignment".to_owned()))?;
if alignment == 0 || !alignment.is_power_of_two() {
return invalid(format!("invalid PT_LOAD alignment 0x{alignment:x}"));
}
Ok(alignment)
}
pub fn append_load_segment(&self, output: &mut [u8], segment: LoadSegment) -> Result<Self> {
if self.program_header_size != 0x38 {
return invalid("unexpected ELF program header size");
}
if segment.file_size == 0 {
return invalid("new PT_LOAD has no file contents");
}
if segment.memory_size < segment.file_size {
return invalid("new PT_LOAD memory size is smaller than file size");
}
if segment.alignment == 0 || !segment.alignment.is_power_of_two() {
return invalid(format!(
"invalid new PT_LOAD alignment 0x{:x}",
segment.alignment
));
}
if segment.offset % segment.alignment != segment.virtual_address % segment.alignment {
return invalid("new PT_LOAD offset and address are misaligned");
}
let segment_file_end = segment
.offset
.checked_add(segment.file_size)
.ok_or_else(|| Error::Invalid("new PT_LOAD file range overflow".to_owned()))?;
let segment_memory_end = segment
.virtual_address
.checked_add(segment.memory_size)
.ok_or_else(|| Error::Invalid("new PT_LOAD memory range overflow".to_owned()))?;
if segment_file_end > output.len() as u64 {
return invalid("new PT_LOAD exceeds output mapping");
}
for existing in &self.program_headers {
let existing_file_end = existing
.offset
.checked_add(existing.file_size)
.ok_or_else(|| Error::Invalid("PT_LOAD file range overflow".to_owned()))?;
if segment.offset < existing_file_end && existing.offset < segment_file_end {
return invalid("new PT_LOAD overlaps an existing file range");
}
let existing_memory_end = existing
.virtual_address
.checked_add(existing.memory_size)
.ok_or_else(|| Error::Invalid("PT_LOAD memory range overflow".to_owned()))?;
if segment.virtual_address < existing_memory_end
&& existing.virtual_address < segment_memory_end
{
return invalid("new PT_LOAD overlaps an existing memory range");
}
}
let new_count = self
.program_header_count
.checked_add(1)
.ok_or_else(|| Error::Invalid("program header count overflow".to_owned()))?;
let new_count_u16 = u16::try_from(new_count)
.map_err(|_| Error::Invalid("program header count exceeds u16".to_owned()))?;
let header_offset = checked_index(
self.program_header_offset,
self.program_header_count,
self.program_header_size,
)?;
let header_end = header_offset
.checked_add(self.program_header_size)
.ok_or_else(|| Error::Invalid("new program header range overflow".to_owned()))?;
slice(output, header_offset, self.program_header_size)?;
let first_file_section = self
.section_headers
.iter()
.filter(|section| section.section_type != SHT_NOBITS && section.size != 0)
.map(|section| section.offset)
.min();
if first_file_section.is_some_and(|offset| header_end as u64 > offset) {
return invalid("no space for an additional program header");
}
let mut header = [0_u8; 0x38];
header[0..4].copy_from_slice(&PT_LOAD.to_le_bytes());
header[4..8].copy_from_slice(&segment.flags.to_le_bytes());
header[8..0x10].copy_from_slice(&segment.offset.to_le_bytes());
header[0x10..0x18].copy_from_slice(&segment.virtual_address.to_le_bytes());
header[0x18..0x20].copy_from_slice(&segment.virtual_address.to_le_bytes());
header[0x20..0x28].copy_from_slice(&segment.file_size.to_le_bytes());
header[0x28..0x30].copy_from_slice(&segment.memory_size.to_le_bytes());
header[0x30..0x38].copy_from_slice(&segment.alignment.to_le_bytes());
output
.get_mut(header_offset..header_end)
.ok_or_else(|| Error::Invalid("new program header exceeds output".to_owned()))?
.copy_from_slice(&header);
output
.get_mut(0x38..0x3a)
.ok_or_else(|| Error::Invalid("ELF header is truncated".to_owned()))?
.copy_from_slice(&new_count_u16.to_le_bytes());
let mut updated = self.clone();
updated.program_header_count = new_count;
updated.program_headers.push(segment);
Ok(updated)
}
/// Resolve every section's name from the ELF `shstrtab` section.
///
/// The returned names are source data, not role labels supplied by the
/// caller. Any malformed string-table reference is an input error.
pub fn section_names(&self, data: &[u8]) -> Result<Vec<String>> {
let table = self
.section_headers
.get(self.section_name_index)
.copied()
.ok_or_else(|| Error::Invalid("ELF section-name index is out of range".to_owned()))?;
if table.section_type != SHT_STRTAB {
return invalid(format!(
"ELF section-name table has unexpected type 0x{:x}",
table.section_type
));
}
let strings = slice_u64(data, table.offset, table.size)?;
if strings.is_empty() || strings[0] != 0 {
return invalid("ELF section-name table does not start with NUL");
}
if strings.last().copied() != Some(0) {
return invalid("ELF section-name table is not NUL terminated");
}
self.section_headers
.iter()
.enumerate()
.map(|(index, section)| {
let offset = section.name as usize;
if offset >= strings.len() {
return invalid(format!(
"ELF section {index} name offset 0x{offset:x} exceeds section-name table"
));
}
let end = strings[offset..]
.iter()
.position(|&byte| byte == 0)
.map(|length| offset + length)
.ok_or_else(|| {
Error::Invalid(format!(
"ELF section {index} name at 0x{offset:x} is unterminated"
))
})?;
let name = std::str::from_utf8(&strings[offset..end]).map_err(|error| {
Error::Invalid(format!(
"ELF section {index} name at 0x{offset:x} is not UTF-8: {error}"
))
})?;
if index == 0 && section.name != 0 {
return invalid("ELF null section has a nonzero name offset");
}
Ok(name.to_owned())
})
.collect()
}
pub fn file_offset_to_virtual_address(&self, offset: u64, size: u64) -> Result<u64> {
let end = offset
.checked_add(size)
.ok_or_else(|| Error::Invalid("file range overflow".to_owned()))?;
for segment in &self.program_headers {
let segment_end = segment
.offset
.checked_add(segment.file_size)
.ok_or_else(|| Error::Invalid("PT_LOAD file range overflow".to_owned()))?;
if segment.offset <= offset && end <= segment_end {
return segment
.virtual_address
.checked_add(offset - segment.offset)
.ok_or_else(|| Error::Invalid("virtual address overflow".to_owned()));
}
}
invalid(format!(
"file range 0x{offset:x}..0x{end:x} is not in PT_LOAD"
))
}
}
pub fn slice(data: &[u8], offset: usize, size: usize) -> Result<&[u8]> {
let end = offset
.checked_add(size)
.ok_or_else(|| Error::Invalid("byte range overflow".to_owned()))?;
data.get(offset..end).ok_or_else(|| {
Error::Invalid(format!(
"byte range 0x{offset:x}..0x{end:x} is out of bounds"
))
})
}
pub fn slice_u64(data: &[u8], offset: u64, size: u64) -> Result<&[u8]> {
slice(
data,
usize_from_u64(offset, "file offset")?,
usize_from_u64(size, "file size")?,
)
}
pub fn read_u16(data: &[u8], offset: usize) -> Result<u16> {
let bytes: [u8; 2] = slice(data, offset, 2)?
.try_into()
.map_err(|_| Error::Invalid("invalid u16 range".to_owned()))?;
Ok(u16::from_le_bytes(bytes))
}
pub fn read_u32(data: &[u8], offset: usize) -> Result<u32> {
let bytes: [u8; 4] = slice(data, offset, 4)?
.try_into()
.map_err(|_| Error::Invalid("invalid u32 range".to_owned()))?;
Ok(u32::from_le_bytes(bytes))
}
pub fn read_u64(data: &[u8], offset: usize) -> Result<u64> {
let bytes: [u8; 8] = slice(data, offset, 8)?
.try_into()
.map_err(|_| Error::Invalid("invalid u64 range".to_owned()))?;
Ok(u64::from_le_bytes(bytes))
}
pub fn read_i64(data: &[u8], offset: usize) -> Result<i64> {
let bytes: [u8; 8] = slice(data, offset, 8)?
.try_into()
.map_err(|_| Error::Invalid("invalid i64 range".to_owned()))?;
Ok(i64::from_le_bytes(bytes))
}
pub fn usize_from_u64(value: u64, field: &str) -> Result<usize> {
usize::try_from(value).map_err(|_| Error::Invalid(format!("{field} 0x{value:x} exceeds usize")))
}
pub fn checked_index(base: usize, index: usize, stride: usize) -> Result<usize> {
index
.checked_mul(stride)
.and_then(|value| base.checked_add(value))
.ok_or_else(|| Error::Invalid("table index overflow".to_owned()))
}
pub fn align_up(value: u64, alignment: u64) -> Result<u64> {
if alignment == 0 || !alignment.is_power_of_two() {
return invalid(format!("invalid alignment {alignment}"));
}
value
.checked_add(alignment - 1)
.map(|aligned| aligned & !(alignment - 1))
.ok_or_else(|| Error::Invalid("alignment overflow".to_owned()))
}
#[cfg(test)]
mod tests {
use super::*;
fn layout(name_index: u32) -> ElfLayout {
ElfLayout {
entrypoint: 0,
program_header_offset: 0,
program_header_size: 0x38,
program_header_count: 0,
program_headers: Vec::new(),
section_headers: vec![
SectionHeader {
name: 0,
section_type: 0,
flags: 0,
address: 0,
offset: 0,
size: 0,
link: 0,
info: 0,
alignment: 0,
entry_size: 0,
},
SectionHeader {
name: name_index,
section_type: 1,
flags: 0,
address: 0,
offset: 0,
size: 0,
link: 0,
info: 0,
alignment: 0,
entry_size: 0,
},
SectionHeader {
name: 1,
section_type: SHT_STRTAB,
flags: 0,
address: 0,
offset: 0,
size: 8,
link: 0,
info: 0,
alignment: 1,
entry_size: 0,
},
],
section_name_index: 2,
private_section_index: usize::MAX,
}
}
#[test]
fn section_names_resolve_from_elf_string_table() {
let names = layout(1)
.section_names(b"\0text\0\0\0")
.expect("valid names");
assert_eq!(names, ["", "text", "text"]);
}
#[test]
fn section_names_reject_out_of_range_name_offsets() {
let error = layout(8)
.section_names(b"\0text\0\0\0")
.expect_err("invalid offset");
assert!(error.to_string().contains("exceeds section-name table"));
}
#[test]
fn section_names_reject_invalid_utf8() {
let mut elf_layout = layout(1);
elf_layout.section_headers[1].name = 1;
let error = elf_layout
.section_names(b"\0\xff\0\0\0\0\0\0")
.expect_err("invalid UTF-8");
assert!(error.to_string().contains("is not UTF-8"));
}
#[test]
fn section_names_reject_non_string_table() {
let mut elf_layout = layout(1);
elf_layout.section_headers[2].section_type = 1;
let error = elf_layout
.section_names(b"\0text\0\0\0")
.expect_err("wrong section type");
assert!(error.to_string().contains("unexpected type"));
}
#[test]
fn section_names_reject_unterminated_table() {
let elf_layout = layout(1);
let error = elf_layout
.section_names(b"\0text\0\x01\x01")
.expect_err("unterminated table");
assert!(error.to_string().contains("not NUL terminated"));
}
#[test]
fn append_load_segment_updates_program_headers() {
let elf_layout = ElfLayout {
entrypoint: 0,
program_header_offset: 0,
program_header_size: 0x38,
program_header_count: 0,
program_headers: Vec::new(),
section_headers: Vec::new(),
section_name_index: 0,
private_section_index: usize::MAX,
};
let mut output = vec![0_u8; 0x2000];
let updated = elf_layout
.append_load_segment(
&mut output,
LoadSegment {
offset: 0x1000,
virtual_address: 0x2000,
file_size: 0x20,
memory_size: 0x20,
flags: PF_R,
alignment: 0x1000,
},
)
.expect("append segment");
assert_eq!(updated.program_header_count, 1);
assert_eq!(updated.program_headers[0].virtual_address, 0x2000);
assert_eq!(&output[0..4], &PT_LOAD.to_le_bytes());
assert_eq!(&output[0x38..0x3a], &1_u16.to_le_bytes());
}
#[test]
fn append_load_segment_rejects_program_header_overlap() {
let mut elf_layout = ElfLayout {
entrypoint: 0,
program_header_offset: 0,
program_header_size: 0x38,
program_header_count: 0,
program_headers: Vec::new(),
section_headers: Vec::new(),
section_name_index: 0,
private_section_index: usize::MAX,
};
elf_layout.section_headers.push(SectionHeader {
name: 0,
section_type: 1,
flags: 0,
address: 0,
offset: 0x20,
size: 1,
link: 0,
info: 0,
alignment: 1,
entry_size: 0,
});
let mut output = vec![0_u8; 0x100];
let error = elf_layout
.append_load_segment(
&mut output,
LoadSegment {
offset: 0x80,
virtual_address: 0x1080,
file_size: 0x20,
memory_size: 0x20,
flags: PF_R,
alignment: 0x1000,
},
)
.expect_err("overlapping program header");
assert!(error.to_string().contains("additional program header"));
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Basic ELF format parsing shared by the unpacking engine.
use goblin::elf::{Elf, header::EM_AARCH64, program_header::PT_LOAD};
use thiserror::Error;
pub mod hash;
pub mod layout;
pub use hash::{build_gnu_hash, build_sysv_hash};
pub use layout::{
ElfLayout, LoadSegment, PF_R, SHF_ALLOC, SHT_LOUSER, SHT_NOBITS, SectionHeader, align_up,
checked_index, read_i64, read_u16, read_u32, read_u64, slice, slice_u64, usize_from_u64,
};
/// ELF machine identifier for AArch64.
pub const AARCH64_MACHINE: u16 = EM_AARCH64;
/// Dynamic sections required by the restored AArch64 loader image.
pub const DYNAMIC_SECTION_NAMES: [&str; 8] = [
".dynsym",
".gnu.version",
".gnu.version_r",
".gnu.hash",
".dynstr",
".rela.dyn",
".rela.plt",
".dynamic",
];
/// Dynamic sections needed to identify a protected image before extraction.
pub const PROBE_SECTION_NAMES: [&str; 5] = [
".dynsym",
".dynstr",
".gnu.hash",
".gnu.version",
".gnu.version_r",
];
/// ELF64 dynamic table record sizes.
pub const ELF64_SYMBOL_SIZE: usize = 0x18;
pub const ELF64_RELA_SIZE: usize = 0x18;
/// AArch64 relocation kinds used by the dynamic linker.
pub const R_AARCH64_ABS64: u32 = 0x101;
pub const R_AARCH64_GLOB_DAT: u32 = 0x401;
pub const R_AARCH64_JUMP_SLOT: u32 = 0x402;
pub const R_AARCH64_RELATIVE: u32 = 0x403;
pub const VER_NDX_GLOBAL: u16 = 1;
/// ELF dynamic-table tag identifiers used by restored images.
pub const DT_PLTRELSZ: u64 = 2;
pub const DT_HASH: u64 = 4;
pub const DT_STRTAB: u64 = 5;
pub const DT_SYMTAB: u64 = 6;
pub const DT_RELA: u64 = 7;
pub const DT_RELASZ: u64 = 8;
pub const DT_STRSZ: u64 = 10;
pub const DT_JMPREL: u64 = 23;
pub const DT_GNU_HASH: u64 = 0x6fff_fef5;
pub const DT_VERSYM: u64 = 0x6fff_fff0;
pub const DT_RELACOUNT: u64 = 0x6fff_fff9;
pub const DT_VERNEED: u64 = 0x6fff_fffe;
#[derive(Debug, Error)]
pub enum Error {
#[error("ELF parse failed: {0}")]
Parse(#[from] goblin::error::Error),
#[error("input is not an ELF64 little-endian image")]
NotElf64,
#[error("input is not an AArch64 image")]
NotAarch64,
#[error("invalid ELF layout: {0}")]
Invalid(String),
}
pub type Result<T> = std::result::Result<T, Error>;
/// Parse an ELF64 little-endian image.
pub fn parse(data: &[u8]) -> Result<Elf<'_>> {
let elf = Elf::parse(data)?;
if elf.header.e_ident[4] != 2 || elf.header.e_ident[5] != 1 {
return Err(Error::NotElf64);
}
Ok(elf)
}
/// Return true when `data` starts with a valid AArch64 ELF64 image.
pub fn is_aarch64(data: &[u8]) -> bool {
parse(data)
.map(|elf| elf.header.e_machine == EM_AARCH64)
.unwrap_or(false)
}
/// Return whether a short prefix identifies an ELF64 little-endian AArch64
/// image. This is intentionally a prefix-only check for filesystem scanners;
/// callers that need structural guarantees must use [`parse`].
#[must_use]
pub fn is_aarch64_prefix(data: &[u8]) -> bool {
data.get(0..6) == Some(b"\x7fELF\x02\x01")
&& data
.get(18..20)
.is_some_and(|bytes| u16::from_le_bytes([bytes[0], bytes[1]]) == EM_AARCH64)
}
/// Return the maximum file end among PT_LOAD segments.
pub fn load_file_end(data: &[u8]) -> Result<u64> {
let elf = parse(data)?;
Ok(elf
.program_headers
.iter()
.filter(|ph| ph.p_type == PT_LOAD)
.map(|ph| ph.p_offset.saturating_add(ph.p_filesz))
.max()
.unwrap_or(0))
}
pub(crate) fn invalid<T>(message: impl Into<String>) -> Result<T> {
Err(Error::Invalid(message.into()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rejects_non_elf() {
assert!(matches!(parse(b"not elf"), Err(Error::Parse(_))));
}
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "senbei-engine"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Platform unpacking engines for Senbei"
[dependencies]
memmap2.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
tempfile.workspace = true
thiserror.workspace = true
senbei-crypto.workspace = true
senbei-elf.workspace = true
senbei-pe.workspace = true
[lints]
workspace = true
+32
View File
@@ -0,0 +1,32 @@
//! Shared Android engine filesystem and digest helpers.
use std::io::Write;
use std::path::{Path, PathBuf};
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;
pub(crate) fn absolute(path: &Path) -> std::io::Result<PathBuf> {
if path.is_absolute() {
Ok(path.to_path_buf())
} else {
std::env::current_dir().map(|current| current.join(path))
}
}
pub(crate) fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
let parent = path.parent().unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)?;
let mut temporary = NamedTempFile::new_in(parent)?;
temporary.write_all(data)?;
temporary.as_file().sync_all()?;
temporary.persist(path).map_err(|error| error.error)?;
Ok(())
}
#[must_use]
pub(crate) fn sha256(data: &[u8]) -> String {
let mut digest = Sha256::new();
digest.update(data);
senbei_crypto::hex_digest(&digest.finalize())
}
@@ -0,0 +1,63 @@
use std::path::{Path, PathBuf};
/// Stage 1 or Stage 2 extraction failure.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{action} `{path}`: {source}")]
Io {
action: &'static str,
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("parse ELF `{path}`: {source}")]
Elf {
path: PathBuf,
#[source]
source: senbei_elf::Error,
},
#[error("serialize extraction index: {0}")]
Json(#[from] serde_json::Error),
#[error("embedded Stage 2 decoder configuration: {0}")]
EmbeddedConfig(#[source] senbei_crypto::android::Error),
#[error(
"depth {depth} stream 0x{stream_id:02X} interpreter 0x{interpreter_id:02X} configuration: {source}"
)]
InterpreterConfig {
depth: usize,
stream_id: u32,
interpreter_id: u32,
#[source]
source: senbei_crypto::android::Error,
},
#[error(
"depth {depth} stream 0x{stream_id:02X} record {record_index} command 0x{command_id:02X} {part}: {source}"
)]
RecordDecode {
depth: usize,
stream_id: u32,
record_index: usize,
command_id: u32,
part: &'static str,
#[source]
source: senbei_crypto::android::Error,
},
#[error("{0}")]
Invalid(String),
}
impl Error {
pub(crate) fn io(action: &'static str, path: &Path, source: std::io::Error) -> Self {
Self::Io {
action,
path: path.to_path_buf(),
source,
}
}
}
pub(crate) type Result<T> = std::result::Result<T, Error>;
pub(crate) fn invalid<T>(message: impl Into<String>) -> Result<T> {
Err(Error::Invalid(message.into()))
}
+12
View File
@@ -0,0 +1,12 @@
mod error;
mod pipeline;
mod probe;
mod report;
mod stage1;
mod stream;
pub use error::Error;
pub use pipeline::{ExtractOptions, extract_stage2};
pub use probe::is_protected_libil2cpp;
pub use report::ExtractionReport;
pub use stage1::{DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE};
@@ -0,0 +1,508 @@
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs::File;
use std::path::{Path, PathBuf};
use memmap2::MmapOptions;
use senbei_crypto::android::{Module9bConfig, decode_container};
use serde_json::to_vec_pretty;
use super::super::common;
use super::error::{Error, Result, invalid};
use super::report::{
ArtifactReport, DecoderReport, ExtractionReport, ModuleRegistryEntry, RecordReport,
Stage1Report, StreamParent, StreamReport,
};
use super::stage1::{
DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE, SHT_LOUSER, Stage1Result, inspect,
};
use super::stream::{DIRECT_FLAG, Record, parse_record_stream};
/// Inputs and output locations for one complete static Stage 2 extraction.
#[derive(Debug, Clone)]
pub struct ExtractOptions {
pub input: PathBuf,
pub output_dir: PathBuf,
pub stage2_output: Option<PathBuf>,
pub outer_size: usize,
pub cipher_constant: u32,
}
impl ExtractOptions {
#[must_use]
pub fn with_defaults(input: PathBuf, output_dir: PathBuf) -> Self {
Self {
input,
output_dir,
stage2_output: None,
outer_size: DEFAULT_OUTER_SIZE,
cipher_constant: DEFAULT_CIPHER_CONSTANT,
}
}
}
#[derive(Debug)]
struct LoadedModule {
image: Vec<u8>,
metadata: Option<Vec<u8>>,
image_path: String,
metadata_path: Option<String>,
sha256: String,
depth: usize,
record_index: usize,
command_id: u32,
init_offset: u32,
entry_offset: u32,
}
#[derive(Debug, Clone, Copy)]
struct ArtifactSpec<'a> {
suffix: &'a str,
kind: &'a str,
classification: &'a str,
}
struct Extractor {
output_dir: PathBuf,
streams: Vec<StreamReport>,
artifacts: Vec<ArtifactReport>,
registry: BTreeMap<u32, LoadedModule>,
seen_streams: HashSet<(u32, String)>,
}
pub fn extract_stage2(options: &ExtractOptions) -> Result<ExtractionReport> {
let input_path = absolute(&options.input)?;
let output_dir = absolute(&options.output_dir)?;
if !input_path.is_file() {
return invalid(format!(
"protected ELF does not exist: {}",
input_path.display()
));
}
if let Some(stage2_output) = &options.stage2_output {
let stage2_output = absolute(stage2_output)?;
if stage2_output == input_path {
return invalid("refusing to overwrite the protected ELF with Stage 2 output");
}
}
std::fs::create_dir_all(&output_dir)
.map_err(|source| Error::io("create Stage 2 output directory", &output_dir, source))?;
let file = File::open(&input_path)
.map_err(|source| Error::io("open protected ELF", &input_path, source))?;
// SAFETY: the mapping is read-only, the file remains open for the mapping
// lifetime, and extraction never mutates or truncates the source.
let source = unsafe { MmapOptions::new().map(&file) }
.map_err(|source| Error::io("map protected ELF", &input_path, source))?;
let stage1 = inspect(
&source,
&input_path,
options.outer_size,
options.cipher_constant,
)?;
if let Some(stage2_output) = &options.stage2_output {
write_atomic(&absolute(stage2_output)?, &stage1.plaintext)?;
}
let core_config =
Module9bConfig::parse_embedded(&stage1.plaintext).map_err(Error::EmbeddedConfig)?;
let bootstrap_end = stage1
.remaining_file_offset
.checked_add(stage1.remaining_size)
.ok_or_else(|| Error::Invalid("Stage 2 bootstrap range overflow".to_owned()))?;
let bootstrap = source
.get(stage1.remaining_file_offset..bootstrap_end)
.ok_or_else(|| Error::Invalid("Stage 2 bootstrap range is outside the ELF".to_owned()))?;
let mut extractor = Extractor {
output_dir: output_dir.clone(),
streams: Vec::new(),
artifacts: Vec::new(),
registry: BTreeMap::new(),
seen_streams: HashSet::new(),
};
extractor.extract_stream(
bootstrap,
0xe2,
0,
None,
Some(stage1.remaining_file_offset),
core_config,
)?;
let module_registry = extractor
.registry
.values()
.map(|module| ModuleRegistryEntry {
command_id: module.command_id,
size: module.image.len(),
sha256: module.sha256.clone(),
depth: module.depth,
record_index: module.record_index,
image_path: module.image_path.clone(),
metadata_path: module.metadata_path.clone(),
init_offset: module.init_offset,
entry_offset: module.entry_offset,
classification: if module.metadata.is_some() {
"module_image".to_owned()
} else {
"decoded_data".to_owned()
},
})
.collect::<Vec<_>>();
let report = ExtractionReport {
format_version: 4,
protected_elf: input_path.display().to_string(),
output_dir: output_dir.display().to_string(),
stage1: stage1_report(&stage1, options.outer_size),
streams: extractor.streams,
artifacts: extractor.artifacts,
errors: Vec::new(),
module_registry,
};
write_json_atomic(&output_dir.join("index.json"), &report)?;
Ok(report)
}
impl Extractor {
fn extract_stream(
&mut self,
stream: &[u8],
stream_id: u32,
depth: usize,
parent: Option<StreamParent>,
source_file_offset: Option<usize>,
config: Module9bConfig,
) -> Result<()> {
let digest = sha256(stream);
if !self.seen_streams.insert((stream_id, digest.clone())) {
return Ok(());
}
let (header, records, table_size) =
parse_record_stream(stream, stream_id).map_err(|source| {
Error::Invalid(format!(
"depth {depth} stream 0x{stream_id:02X} record table: {source}"
))
})?;
let mut stream_report = StreamReport {
depth,
stream_id,
parent,
source_file_offset,
available_size: stream.len(),
descriptor_table_size: table_size,
encrypted_header_words: header.encrypted_words,
decrypted_header_words: header.decrypted_words,
record_state: header.record_state,
sha256: digest,
decoder: decoder_report(
if depth == 0 {
"embedded_stage2"
} else {
"decoded_interpreter"
},
(depth != 0).then_some(stream_id),
&config,
),
records: Vec::with_capacity(records.len()),
};
let mut direct_records = Vec::new();
let mut modules_at_level = BTreeSet::new();
for record in records {
let mut result = record_report(record);
let mut image_data = None;
let mut metadata_data = None;
if !record.direct() && record.image_size != 0 {
let image_source = record_tail(stream, record.image_offset)?;
let image = decode_container(image_source, &config, record.image_size as usize)
.map_err(|source| Error::RecordDecode {
depth,
stream_id,
record_index: record.index,
command_id: record.command_id,
part: "image decode",
source,
})?;
let classification = if record.metadata_size != 0 {
"module_image"
} else {
"decoded_data"
};
let artifact = self.write_artifact(
&record,
depth,
stream_id,
ArtifactSpec {
suffix: "module.bin",
kind: "decoded_container",
classification,
},
&image,
)?;
result.image = Some(artifact.clone());
image_data = Some((image, artifact));
}
if record.metadata_size != 0 {
let metadata_source = record_tail(stream, record.metadata_offset)?;
let metadata =
decode_container(metadata_source, &config, record.metadata_size as usize)
.map_err(|source| Error::RecordDecode {
depth,
stream_id,
record_index: record.index,
command_id: record.command_id,
part: "metadata decode",
source,
})?;
let artifact = self.write_artifact(
&record,
depth,
stream_id,
ArtifactSpec {
suffix: "metadata.bin",
kind: "decoded_metadata",
classification: "decoded_metadata",
},
&metadata,
)?;
result.metadata = Some(artifact.clone());
metadata_data = Some((metadata, artifact));
}
if let Some((image, image_artifact)) = image_data {
let (metadata, metadata_path) = if let Some((data, artifact)) = metadata_data {
(Some(data), Some(artifact.path))
} else {
(None, None)
};
self.register_module(LoadedModule {
sha256: image_artifact.sha256.clone(),
image_path: image_artifact.path.clone(),
metadata_path,
image,
metadata,
depth,
record_index: record.index,
command_id: record.command_id,
init_offset: record.init_offset,
entry_offset: record.entry_offset,
})?;
modules_at_level.insert(record.command_id);
}
if record.direct() && record.image_size != 0 {
direct_records.push((record, stream_report.records.len()));
}
stream_report.records.push(result);
}
let mut children = Vec::new();
for (record, report_index) in direct_records {
let next_stream_id = record.command_id.wrapping_sub(0x10);
if modules_at_level.contains(&next_stream_id) {
stream_report.records[report_index].nested_stream_id = Some(next_stream_id);
children.push((record, next_stream_id));
continue;
}
let direct_data = record_slice(stream, record.image_offset, record.image_size)?;
let artifact = self.write_artifact(
&record,
depth,
stream_id,
ArtifactSpec {
suffix: "direct.bin",
kind: "direct",
classification: "direct_data",
},
direct_data,
)?;
stream_report.records[report_index].image = Some(artifact);
}
self.streams.push(stream_report);
for (record, next_stream_id) in children {
let child_data = record_slice(stream, record.image_offset, record.image_size)?;
let parent = StreamParent {
stream_id,
record_index: record.index,
command_id: record.command_id,
};
let interpreter = self.registry.get(&next_stream_id).ok_or_else(|| {
Error::Invalid(format!(
"depth {depth} stream 0x{stream_id:02X} child 0x{next_stream_id:02X} has no interpreter module"
))
})?;
let interpreter_config =
Module9bConfig::parse(&interpreter.image).map_err(|source| {
Error::InterpreterConfig {
depth: depth + 1,
stream_id: next_stream_id,
interpreter_id: next_stream_id,
source,
}
})?;
self.extract_stream(
child_data,
next_stream_id,
depth + 1,
Some(parent),
None,
interpreter_config,
)?;
}
Ok(())
}
fn register_module(&mut self, module: LoadedModule) -> Result<()> {
if let Some(previous) = self.registry.get(&module.command_id) {
if previous.sha256 != module.sha256 {
return invalid(format!(
"module 0x{:02X} produced conflicting images: {} and {}",
module.command_id, previous.sha256, module.sha256
));
}
return Ok(());
}
self.registry.insert(module.command_id, module);
Ok(())
}
fn write_artifact(
&mut self,
record: &Record,
depth: usize,
stream_id: u32,
spec: ArtifactSpec<'_>,
data: &[u8],
) -> Result<ArtifactReport> {
let digest = sha256(data);
let filename = format!(
"d{depth:02}_s{stream_id:02X}_r{:03}_id{:08X}_{}.{}",
record.index,
record.command_id,
&digest[..12],
spec.suffix
);
let path = self.output_dir.join(filename);
write_atomic(&path, data)?;
let artifact = ArtifactReport {
kind: spec.kind.to_owned(),
path: path
.file_name()
.ok_or_else(|| Error::Invalid("artifact path has no file name".to_owned()))?
.to_string_lossy()
.into_owned(),
size: data.len(),
sha256: digest,
depth,
stream_id,
record_index: Some(record.index),
command_id: Some(record.command_id),
classification: spec.classification.to_owned(),
};
self.artifacts.push(artifact.clone());
Ok(artifact)
}
}
fn record_report(record: Record) -> RecordReport {
RecordReport {
index: record.index,
command_id: record.command_id,
flags: record.flags,
image_offset: record.image_offset,
image_size: record.image_size,
metadata_offset: record.metadata_offset,
metadata_size: record.metadata_size,
id_copy: record.id_copy,
entry_offset: record.entry_offset,
init_offset: record.init_offset,
direct: record.flags & DIRECT_FLAG != 0,
extraction_status: "complete".to_owned(),
image: None,
metadata: None,
nested_stream_id: None,
}
}
fn decoder_report(
kind: &str,
interpreter_id: Option<u32>,
config: &Module9bConfig,
) -> DecoderReport {
DecoderReport {
kind: kind.to_owned(),
interpreter_id,
header_seed: config.header_seed,
container_seed: config.container_seed,
schedule_offset: config.schedule_offset,
aes_key_sha256: sha256(&config.aes_key),
skip_aes: config.skip_aes,
}
}
fn record_slice(stream: &[u8], offset: u32, size: u32) -> Result<&[u8]> {
let offset = usize::try_from(offset)
.map_err(|_| Error::Invalid("record payload offset exceeds usize".to_owned()))?;
let size = usize::try_from(size)
.map_err(|_| Error::Invalid("record payload size exceeds usize".to_owned()))?;
let end = offset
.checked_add(size)
.ok_or_else(|| Error::Invalid("record payload range overflows usize".to_owned()))?;
stream.get(offset..end).ok_or_else(|| {
Error::Invalid(format!(
"record payload range 0x{offset:x}..0x{end:x} exceeds stream 0x{:x}",
stream.len()
))
})
}
fn record_tail(stream: &[u8], offset: u32) -> Result<&[u8]> {
let offset = usize::try_from(offset)
.map_err(|_| Error::Invalid("record container offset exceeds usize".to_owned()))?;
stream.get(offset..).ok_or_else(|| {
Error::Invalid(format!(
"record container offset 0x{offset:x} exceeds stream 0x{:x}",
stream.len()
))
})
}
fn stage1_report(stage1: &Stage1Result, outer_size: usize) -> Stage1Report {
Stage1Report {
section_index: stage1.section_index,
section_type: SHT_LOUSER,
section_offset: stage1.section_offset,
section_size: stage1.section_size,
outer_size,
header_offset: stage1.header_offset,
header_key: stage1.header.key,
payload_offset: stage1.header.payload_offset,
payload_size: stage1.header.payload_size,
payload_key: stage1.header.payload_key,
entry_offset: stage1.header.entry_offset,
protect_size: stage1.header.protect_size,
stage2_file_offset: stage1.payload_file_offset,
stage2_size: stage1.plaintext.len(),
stage2_sha256: sha256(&stage1.plaintext),
remaining_file_offset: stage1.remaining_file_offset,
remaining_size: stage1.remaining_size,
}
}
fn write_json_atomic(path: &Path, value: &impl serde::Serialize) -> Result<()> {
let mut bytes = to_vec_pretty(value)?;
bytes.push(b'\n');
write_atomic(path, &bytes)
}
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
common::write_atomic(path, data)
.map_err(|source| Error::io("write temporary output", path, source))
}
fn absolute(path: &Path) -> Result<PathBuf> {
common::absolute(path).map_err(|source| Error::io("query current directory", path, source))
}
fn sha256(data: &[u8]) -> String {
common::sha256(data)
}
@@ -0,0 +1,19 @@
use std::path::Path;
use senbei_crypto::android::Module9bConfig;
use super::stage1::{self, DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE};
/// Return whether `data` has a supported protected AArch64 IL2CPP layout.
#[must_use]
pub fn is_protected_libil2cpp(data: &[u8]) -> bool {
let Ok(stage1) = stage1::inspect(
data,
Path::new("<probe>"),
DEFAULT_OUTER_SIZE,
DEFAULT_CIPHER_CONSTANT,
) else {
return false;
};
Module9bConfig::parse_embedded(&stage1.plaintext).is_ok()
}
+115
View File
@@ -0,0 +1,115 @@
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct Stage1Report {
pub section_index: usize,
pub section_type: u32,
pub section_offset: usize,
pub section_size: usize,
pub outer_size: usize,
pub header_offset: usize,
pub header_key: u32,
pub payload_offset: u32,
pub payload_size: u32,
pub payload_key: u32,
pub entry_offset: u32,
pub protect_size: u32,
pub stage2_file_offset: usize,
pub stage2_size: usize,
pub stage2_sha256: String,
pub remaining_file_offset: usize,
pub remaining_size: usize,
}
#[derive(Debug, Clone, Serialize)]
pub struct DecoderReport {
pub kind: String,
pub interpreter_id: Option<u32>,
pub header_seed: u32,
pub container_seed: u32,
pub schedule_offset: usize,
pub aes_key_sha256: String,
pub skip_aes: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct ArtifactReport {
pub kind: String,
pub path: String,
pub size: usize,
pub sha256: String,
pub depth: usize,
pub stream_id: u32,
pub record_index: Option<usize>,
pub command_id: Option<u32>,
pub classification: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct RecordReport {
pub index: usize,
pub command_id: u32,
pub flags: u32,
pub image_offset: u32,
pub image_size: u32,
pub metadata_offset: u32,
pub metadata_size: u32,
pub id_copy: u32,
pub entry_offset: u32,
pub init_offset: u32,
pub direct: bool,
pub extraction_status: String,
pub image: Option<ArtifactReport>,
pub metadata: Option<ArtifactReport>,
pub nested_stream_id: Option<u32>,
}
#[derive(Debug, Clone, Serialize)]
pub struct StreamParent {
pub stream_id: u32,
pub record_index: usize,
pub command_id: u32,
}
#[derive(Debug, Clone, Serialize)]
pub struct StreamReport {
pub depth: usize,
pub stream_id: u32,
pub parent: Option<StreamParent>,
pub source_file_offset: Option<usize>,
pub available_size: usize,
pub descriptor_table_size: usize,
pub encrypted_header_words: [u32; 2],
pub decrypted_header_words: [u32; 2],
pub record_state: u32,
pub sha256: String,
pub decoder: DecoderReport,
pub records: Vec<RecordReport>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ModuleRegistryEntry {
pub command_id: u32,
pub size: usize,
pub sha256: String,
pub depth: usize,
pub record_index: usize,
pub image_path: String,
pub metadata_path: Option<String>,
pub init_offset: u32,
pub entry_offset: u32,
pub classification: String,
}
/// Machine-readable output of one complete static Stage 2 extraction.
#[derive(Debug, Clone, Serialize)]
pub struct ExtractionReport {
pub format_version: u32,
pub protected_elf: String,
pub output_dir: String,
pub stage1: Stage1Report,
pub streams: Vec<StreamReport>,
pub artifacts: Vec<ArtifactReport>,
pub errors: Vec<String>,
pub module_registry: Vec<ModuleRegistryEntry>,
}
+236
View File
@@ -0,0 +1,236 @@
use std::path::Path;
use senbei_elf::{AARCH64_MACHINE, Error as ElfError, parse};
use super::error::{Error, Result, invalid};
pub(crate) use senbei_elf::SHT_LOUSER;
pub const DEFAULT_CIPHER_CONSTANT: u32 = 0xbf20_165d;
pub const DEFAULT_OUTER_SIZE: usize = 0x23c;
#[derive(Debug, Clone, Copy)]
pub(crate) struct Stage1Header {
pub key: u32,
pub reserved: u32,
pub payload_offset: u32,
pub payload_size: u32,
pub payload_key: u32,
pub entry_offset: u32,
pub protect_size: u32,
pub size_copy: u32,
}
#[derive(Debug)]
pub(crate) struct Stage1Result {
pub section_index: usize,
pub section_offset: usize,
pub section_size: usize,
pub header_offset: usize,
pub payload_file_offset: usize,
pub remaining_file_offset: usize,
pub remaining_size: usize,
pub header: Stage1Header,
pub plaintext: Vec<u8>,
}
pub(crate) fn inspect(
data: &[u8],
path: &Path,
outer_size: usize,
cipher_constant: u32,
) -> Result<Stage1Result> {
let elf = parse(data).map_err(|source: ElfError| Error::Elf {
path: path.to_path_buf(),
source,
})?;
if elf.header.e_machine != AARCH64_MACHINE {
return invalid(format!(
"expected AArch64 ELF (machine 0x{AARCH64_MACHINE:X}), got 0x{:X}",
elf.header.e_machine
));
}
let matches = elf
.section_headers
.iter()
.enumerate()
.filter(|(_, section)| section.sh_type == SHT_LOUSER)
.collect::<Vec<_>>();
if matches.len() != 1 {
return invalid(format!(
"expected exactly one SHT_LOUSER section, found {}",
matches.len()
));
}
for wanted in senbei_elf::PROBE_SECTION_NAMES {
if !elf.section_headers.iter().any(|section| {
elf.shdr_strtab
.get_at(section.sh_name)
.is_some_and(|name| name == wanted)
}) {
return invalid(format!("protected ELF lacks required section {wanted}"));
}
}
let (section_index, section) = matches[0];
let section_offset = usize::try_from(section.sh_offset)
.map_err(|_| Error::Invalid("SHT_LOUSER offset exceeds usize".to_owned()))?;
let section_size = usize::try_from(section.sh_size)
.map_err(|_| Error::Invalid("SHT_LOUSER size exceeds usize".to_owned()))?;
let section_end = section_offset
.checked_add(section_size)
.ok_or_else(|| Error::Invalid("SHT_LOUSER range overflows usize".to_owned()))?;
if section_end > data.len() {
return invalid("SHT_LOUSER range extends beyond the input file");
}
let header_relative = outer_size;
if outer_size
.checked_add(0x1000)
.is_none_or(|end| end > section_size)
{
return invalid("Stage 1 outer header leaves no complete parameter area");
}
let header_offset = section_offset
.checked_add(header_relative)
.ok_or_else(|| Error::Invalid("Stage 1 header offset overflow".to_owned()))?;
let header_raw = bytes(data, header_offset, 0x1000)?;
let header = decrypt_header(header_raw, cipher_constant)?;
if header.reserved != 0 {
return invalid(format!(
"Stage 1 header reserved word is nonzero: 0x{:x}",
header.reserved
));
}
if header.size_copy != header.payload_size {
return invalid(format!(
"Stage 1 payload size copy 0x{:x} != size 0x{:x}",
header.size_copy, header.payload_size
));
}
let private_size = section_size - outer_size;
let payload_offset = usize::try_from(header.payload_offset)
.map_err(|_| Error::Invalid("Stage 1 payload offset exceeds usize".to_owned()))?;
let payload_size = usize::try_from(header.payload_size)
.map_err(|_| Error::Invalid("Stage 1 payload size exceeds usize".to_owned()))?;
let payload_end = payload_offset
.checked_add(payload_size)
.ok_or_else(|| Error::Invalid("Stage 1 payload range overflow".to_owned()))?;
if payload_offset < 0x20 || payload_end > private_size {
return invalid(format!(
"Stage 1 payload range 0x{payload_offset:x}..0x{payload_end:x} exceeds private size 0x{private_size:x}"
));
}
if payload_size == 0 || payload_size % 4 != 0 {
return invalid(format!(
"Stage 1 payload size must be nonzero and word aligned: 0x{payload_size:x}"
));
}
let entry_offset = usize::try_from(header.entry_offset)
.map_err(|_| Error::Invalid("Stage 1 entry offset exceeds usize".to_owned()))?;
if entry_offset >= payload_size {
return invalid("Stage 1 entry offset is outside the payload");
}
let protect_size = usize::try_from(header.protect_size)
.map_err(|_| Error::Invalid("Stage 1 protect size exceeds usize".to_owned()))?;
if protect_size > payload_size {
return invalid("Stage 1 mprotect length exceeds the payload");
}
let payload_file_offset = header_offset
.checked_add(payload_offset)
.ok_or_else(|| Error::Invalid("Stage 1 payload file offset overflow".to_owned()))?;
let encrypted = bytes(data, payload_file_offset, payload_size)?;
let plaintext = decrypt_words(encrypted, header.payload_key, cipher_constant)?;
let aligned_payload_end = (payload_end + 3) & !3;
let remaining_relative = aligned_payload_end;
if remaining_relative > private_size {
return invalid("aligned Stage 2 cursor exceeds SHT_LOUSER");
}
let remaining_file_offset = section_offset
.checked_add(outer_size)
.and_then(|value| value.checked_add(remaining_relative))
.ok_or_else(|| Error::Invalid("Stage 2 stream offset overflow".to_owned()))?;
Ok(Stage1Result {
section_index,
section_offset,
section_size,
header_offset,
payload_file_offset,
remaining_file_offset,
remaining_size: private_size - remaining_relative,
header,
plaintext,
})
}
fn decrypt_header(raw: &[u8], constant: u32) -> Result<Stage1Header> {
let key = read_u32(raw, 0)?;
let mut decoded = decrypt_words(&raw[..0x20], key, constant)?;
decoded[..4].copy_from_slice(&key.to_le_bytes());
Ok(Stage1Header {
key,
reserved: read_u32(&decoded, 4)?,
payload_offset: read_u32(&decoded, 8)?,
payload_size: read_u32(&decoded, 12)?,
payload_key: read_u32(&decoded, 16)?,
entry_offset: read_u32(&decoded, 20)?,
protect_size: read_u32(&decoded, 24)?,
size_copy: read_u32(&decoded, 28)?,
})
}
fn decrypt_words(ciphertext: &[u8], key: u32, constant: u32) -> Result<Vec<u8>> {
if !ciphertext.len().is_multiple_of(4) {
return invalid("Stage 1 word cipher input is not 4-byte aligned");
}
let mut plaintext = ciphertext.to_vec();
for (index, chunk) in plaintext.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let index = u32::try_from(index)
.map_err(|_| Error::Invalid("Stage 1 word index exceeds u32".to_owned()))?;
let mut word = u32::from_le_bytes(*chunk);
word = word.wrapping_add(index.wrapping_add(3).wrapping_mul(key));
word ^= constant.wrapping_mul(index.wrapping_add(1));
chunk.copy_from_slice(&word.to_le_bytes());
}
Ok(plaintext)
}
fn bytes(data: &[u8], offset: usize, size: usize) -> Result<&[u8]> {
let end = offset
.checked_add(size)
.ok_or_else(|| Error::Invalid("byte range overflow".to_owned()))?;
data.get(offset..end).ok_or_else(|| {
Error::Invalid(format!(
"byte range 0x{offset:x}..0x{end:x} is outside the input"
))
})
}
fn read_u32(data: &[u8], offset: usize) -> Result<u32> {
let bytes = bytes(data, offset, 4)?;
Ok(u32::from_le_bytes(bytes.try_into().map_err(|_| {
Error::Invalid("invalid u32 byte range".to_owned())
})?))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stage1_word_transform_round_trips() {
let key = 0x1234_5678;
let constant = DEFAULT_CIPHER_CONSTANT;
let plain = [0x1122_3344_u32, 0xaabb_ccdd, 0x0102_0304];
let mut cipher = Vec::new();
for (index, value) in plain.into_iter().enumerate() {
let index = index as u32;
let word = (value ^ constant.wrapping_mul(index + 1))
.wrapping_sub((index + 3).wrapping_mul(key));
cipher.extend_from_slice(&word.to_le_bytes());
}
let decoded = decrypt_words(&cipher, key, constant).unwrap();
let expected = plain
.into_iter()
.flat_map(u32::to_le_bytes)
.collect::<Vec<_>>();
assert_eq!(decoded, expected);
}
}
+164
View File
@@ -0,0 +1,164 @@
use senbei_crypto::android::gf32_mul_fixed;
use super::error::{Error, Result, invalid};
pub(crate) const RECORD_SIZE: usize = 0x5c;
pub(crate) const DIRECT_FLAG: u32 = 2;
#[derive(Debug, Clone, Copy)]
pub(crate) struct Record {
pub index: usize,
pub command_id: u32,
pub flags: u32,
pub image_offset: u32,
pub image_size: u32,
pub metadata_offset: u32,
pub metadata_size: u32,
pub id_copy: u32,
pub entry_offset: u32,
pub init_offset: u32,
}
impl Record {
pub(crate) fn direct(self) -> bool {
self.flags & DIRECT_FLAG != 0
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct StreamHeader {
pub encrypted_words: [u32; 2],
pub decrypted_words: [u32; 2],
pub record_state: u32,
}
pub(crate) fn parse_record_stream(
stream: &[u8],
stream_id: u32,
) -> Result<(StreamHeader, Vec<Record>, usize)> {
if stream.len() < 8 {
return invalid(format!(
"stream 0x{stream_id:02X} is shorter than its 8-byte header"
));
}
let cipher0 = read_u32(stream, 0)?;
let cipher1 = read_u32(stream, 4)?;
let key = stream_id.wrapping_mul(0x9d32_3cd7);
let shift = stream_id & 7;
let base = (key >> shift)
.wrapping_add(0x5e72_7d74)
.wrapping_add(key.wrapping_shl(stream_id & 0xb))
.wrapping_add(0xf71e_3005);
let plain0 =
gf32_mul_fixed(cipher0.wrapping_add(0xcbf0_c1d8)) ^ 0xeb_e81dba_u32.wrapping_add(base);
let plain1 = gf32_mul_fixed(cipher1.wrapping_add(cipher0))
^ 0xeb_e81dba_u32.wrapping_mul(5).wrapping_add(base);
let header = StreamHeader {
encrypted_words: [cipher0, cipher1],
decrypted_words: [plain0, plain1],
record_state: plain1.wrapping_add(base),
};
let mut records = Vec::new();
let mut first_payload = stream.len();
for index in 0..256_usize {
let start =
8_usize
.checked_add(index.checked_mul(RECORD_SIZE).ok_or_else(|| {
Error::Invalid("record descriptor offset overflow".to_owned())
})?)
.ok_or_else(|| Error::Invalid("record descriptor offset overflow".to_owned()))?;
let end = start
.checked_add(RECORD_SIZE)
.ok_or_else(|| Error::Invalid("record descriptor end overflow".to_owned()))?;
if end > stream.len() {
return invalid(format!(
"stream 0x{stream_id:02X} descriptor table is truncated at record {index}"
));
}
let record = decrypt_record(&stream[start..end], index, header.record_state)?;
if record.id_copy != 0 && record.command_id != record.id_copy {
return invalid(format!(
"stream 0x{stream_id:02X} record {index} command/id mismatch: 0x{:X} != 0x{:X}",
record.command_id, record.id_copy
));
}
for (offset, size) in [
(record.image_offset, record.image_size),
(record.metadata_offset, record.metadata_size),
] {
if offset != 0 && size != 0 {
let offset = usize::try_from(offset).map_err(|_| {
Error::Invalid(format!(
"stream 0x{stream_id:02X} record {index} payload offset exceeds usize"
))
})?;
if offset >= stream.len() {
return invalid(format!(
"stream 0x{stream_id:02X} record {index} payload offset 0x{offset:x} exceeds stream 0x{:x}",
stream.len()
));
}
first_payload = first_payload.min(offset);
}
}
records.push(record);
if end == first_payload {
return Ok((header, records, first_payload));
}
if end > first_payload {
return invalid(format!(
"stream 0x{stream_id:02X} descriptor table crosses first payload at 0x{first_payload:x}"
));
}
}
invalid(format!(
"stream 0x{stream_id:02X} has no descriptor boundary in 256 records"
))
}
fn decrypt_record(raw: &[u8], index: usize, state: u32) -> Result<Record> {
if raw.len() != RECORD_SIZE {
return invalid(format!(
"record {index} has size 0x{:x}, expected 0x{RECORD_SIZE:x}",
raw.len()
));
}
let product = state.wrapping_add(0x96f6_0b71).wrapping_mul(state);
let index_mask = product.wrapping_shl(((index + 1) & 3) as u32);
let mix = state.wrapping_mul(0x06a5_5bcc).wrapping_add(product);
let mut accumulator = 0x7993_4cf6_u32;
let mut feedback = 0xf02f_7685_u32;
let mut words = [0_u32; RECORD_SIZE / 4];
for (word_index, chunk) in raw.as_chunks::<4>().0.iter().enumerate() {
feedback = feedback.wrapping_mul(feedback);
let cipher = u32::from_le_bytes(*chunk);
let mut value = gf32_mul_fixed(cipher ^ (feedback >> 3)) ^ index_mask;
value = value.wrapping_add(accumulator).wrapping_add(state);
value = value.wrapping_sub(mix >> ((word_index * 4 + 3) & 5));
words[word_index] = value;
accumulator = accumulator.wrapping_add(0xe64d_33d8);
feedback = cipher;
}
Ok(Record {
index,
command_id: words[0],
flags: words[1],
image_offset: words[2],
image_size: words[3],
metadata_offset: words[4],
metadata_size: words[5],
id_copy: words[6],
entry_offset: words[7],
init_offset: words[8],
})
}
fn read_u32(data: &[u8], offset: usize) -> Result<u32> {
let bytes = data.get(offset..offset + 4).ok_or_else(|| {
Error::Invalid(format!("record header range 0x{offset:x} is out of bounds"))
})?;
Ok(u32::from_le_bytes(bytes.try_into().map_err(|_| {
Error::Invalid("invalid record u32 range".to_owned())
})?))
}
+11
View File
@@ -0,0 +1,11 @@
//! Android AArch64 extraction and ELF restoration.
mod common;
mod extract;
mod restore;
pub use extract::{
DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE, Error as ExtractionError, ExtractOptions,
ExtractionReport, extract_stage2, is_protected_libil2cpp,
};
pub use restore::{Error as RestoreError, RestoreOptions, RestoreReport, restore_libil2cpp};
@@ -0,0 +1,105 @@
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use serde_json::Value;
use super::error::{Error, Result, invalid};
const REQUIRED_IDS: [u32; 3] = [0x9b, 0x9d, 0x9e];
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Artifact {
pub path: PathBuf,
pub size: u64,
}
pub(crate) fn load_artifacts(index_path: &Path) -> Result<BTreeMap<u32, Artifact>> {
let text = std::fs::read_to_string(index_path)
.map_err(|error| Error::io("read module index", index_path, error))?;
let document: Value = serde_json::from_str(&text)?;
let root = index_path.parent().unwrap_or_else(|| Path::new("."));
let mut result = BTreeMap::new();
if let Some(items) = document.get("module_registry").and_then(Value::as_array) {
for item in items {
let Some(command_id) = item.get("command_id").and_then(Value::as_u64) else {
continue;
};
let command_id = u32::try_from(command_id)
.map_err(|_| Error::Invalid("module command ID exceeds u32".to_owned()))?;
if !REQUIRED_IDS.contains(&command_id) {
continue;
}
let Some(path) = item.get("image_path").and_then(Value::as_str) else {
continue;
};
let size = item
.get("size")
.and_then(Value::as_u64)
.ok_or_else(|| Error::Invalid(format!("module 0x{command_id:02X} lacks size")))?;
result.insert(
command_id,
Artifact {
path: root.join(path),
size,
},
);
}
}
if let Some(streams) = document.get("streams").and_then(Value::as_array) {
for stream in streams {
let Some(records) = stream.get("records").and_then(Value::as_array) else {
continue;
};
for record in records {
let Some(command_id) = record.get("command_id").and_then(Value::as_u64) else {
continue;
};
let command_id = u32::try_from(command_id)
.map_err(|_| Error::Invalid("record command ID exceeds u32".to_owned()))?;
if !REQUIRED_IDS.contains(&command_id) {
continue;
}
let Some(image) = record.get("image") else {
continue;
};
let Some(path) = image.get("path").and_then(Value::as_str) else {
continue;
};
let size = image.get("size").and_then(Value::as_u64).ok_or_else(|| {
Error::Invalid(format!("record 0x{command_id:02X} lacks image size"))
})?;
result.insert(
command_id,
Artifact {
path: root.join(path),
size,
},
);
}
}
}
let missing = REQUIRED_IDS
.iter()
.filter(|id| !result.contains_key(id))
.map(|id| format!("0x{id:02X}"))
.collect::<Vec<_>>();
if !missing.is_empty() {
return invalid(format!(
"module index lacks required IDs: {}",
missing.join(", ")
));
}
for (&command_id, artifact) in &result {
let metadata = std::fs::metadata(&artifact.path)
.map_err(|error| Error::io("inspect artifact", &artifact.path, error))?;
if !metadata.is_file() || metadata.len() != artifact.size {
return invalid(format!(
"invalid artifact for module 0x{command_id:02X}: {}",
artifact.path.display()
));
}
}
Ok(result)
}
@@ -0,0 +1,37 @@
use std::path::{Path, PathBuf};
/// ELF restoration failure.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{action} `{path}`: {source}")]
Io {
action: &'static str,
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("cannot parse module index: {0}")]
Json(#[from] serde_json::Error),
#[error(transparent)]
Crypto(#[from] senbei_crypto::android::Error),
#[error(transparent)]
Elf(#[from] senbei_elf::Error),
#[error("{0}")]
Invalid(String),
}
impl Error {
pub(crate) fn io(action: &'static str, path: &Path, source: std::io::Error) -> Self {
Self::Io {
action,
path: path.to_path_buf(),
source,
}
}
}
pub(crate) type Result<T> = std::result::Result<T, Error>;
pub(crate) fn invalid<T>(message: impl Into<String>) -> Result<T> {
Err(Error::Invalid(message.into()))
}
+6
View File
@@ -0,0 +1,6 @@
mod artifact;
mod error;
mod pipeline;
pub use error::Error;
pub use pipeline::{RestoreOptions, RestoreReport, restore_libil2cpp};
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
//! Platform-specific unpacking engines.
pub mod android;
pub mod windows;
pub use windows::{
Detected, IntegrityReport, Kind, UnpackError, check_integrity, detect, unpack_auto,
unpack_auto_v, unpack_dll, unpack_dll_v, unpack_exe, unpack_exe_v,
};
/// Deterministic worker-thread cap shared by filesystem scanning and engines.
pub fn thread_cap() -> usize {
if let Ok(value) = std::env::var("SENBEI_THREADS")
&& let Ok(count) = value.trim().parse::<usize>()
&& count >= 1
{
return count;
}
std::thread::available_parallelism()
.map(|count| count.get())
.unwrap_or(1)
}
@@ -149,6 +149,13 @@ pub enum UnpackError {
buffer_len: usize, buffer_len: usize,
}, },
#[error("managed stub {region} restoration failed: {source}")]
ManagedStubRestoreFailed {
region: &'static str,
#[source]
source: senbei_pe::Error,
},
#[error( #[error(
"EXE checksum descriptor at 0x{descriptor:08X} points outside input (offset {offset}, size {size}, input length {image_len})" "EXE checksum descriptor at 0x{descriptor:08X} points outside input (offset {offset}, size {size}, input length {image_len})"
)] )]
@@ -15,23 +15,12 @@ pub fn unpack(input: &[u8]) -> Result<Vec<u8>, UnpackError> {
/// Used by the new-layout managed (CLR) metadata restore to locate the COR20 /// Used by the new-layout managed (CLR) metadata restore to locate the COR20
/// header and BSJB MetaData stream in the original protected file. /// header and BSJB MetaData stream in the original protected file.
fn prot_rva_to_off(file_data: &[u8], pe_header: u32, rva: u32) -> Option<u32> { fn prot_rva_to_off(file_data: &[u8], pe_header: u32, rva: u32) -> Option<u32> {
let nsec = get_u16(file_data, pe_header + 6) as u32; let headers = senbei_pe::parse(file_data).ok()?;
let opt = get_u16(file_data, pe_header + 20) as u32; if headers.pe_offset != pe_header as usize {
let tab = pe_header + 24 + opt; return None;
for i in 0..nsec {
let s = tab + i * 40;
if (s as usize + 24) > file_data.len() {
return None;
}
let va = get_u32(file_data, s + 12);
let vs = get_u32(file_data, s + 8);
let rsz = get_u32(file_data, s + 16);
let rp = get_u32(file_data, s + 20);
if va <= rva && rva < va + vs.max(rsz) {
return Some(rp + (rva - va));
}
} }
None let offset = senbei_pe::rva_to_offset(file_data, headers, rva).ok()?;
u32::try_from(offset).ok()
} }
pub fn unpack_v(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError> { pub fn unpack_v(input: &[u8], verbose: bool) -> Result<Vec<u8>, UnpackError> {
@@ -1,6 +1,27 @@
use super::super::super::layout; use super::super::super::layout;
use super::*; use super::*;
fn stage_key_rounds(data: &[u8], table: u32, slots: usize) -> Result<u32, UnpackError> {
let offset = table as usize;
let size = slots.saturating_mul(16);
let descriptors = offset
.checked_add(size)
.and_then(|end| data.get(offset..end))
.ok_or(UnpackError::BufferRangeOutOfBounds {
operation: BufferOperation::Read,
offset,
size,
buffer_len: data.len(),
})?;
// The loader stops at the first empty helper, even if later slots are nonempty.
Ok(descriptors
.as_chunks::<16>()
.0
.iter()
.take_while(|descriptor| get_u32(descriptor.as_slice(), 4) > 4)
.count() as u32)
}
impl<'a> Unpacker<'a> { impl<'a> Unpacker<'a> {
/// PE32 (32-bit) unpack pipeline. The shared Stage 1/2 setup (info decrypt, /// PE32 (32-bit) unpack pipeline. The shared Stage 1/2 setup (info decrypt,
/// payload decrypt, raw copy, header restore) has already run in `run()` /// payload decrypt, raw copy, header restore) has already run in `run()`
@@ -224,11 +245,15 @@ impl<'a> Unpacker<'a> {
// ---- ForthStage ---- // ---- ForthStage ----
let second_stage_cs = self.calculate_checksum(second_stage_cs_addr); let second_stage_cs = self.calculate_checksum(second_stage_cs_addr);
let dp_base = ss.wrapping_add(dp_base_off);
let forth_key_rounds = stage_key_rounds(&self.decompressed, dp_base, 4)?;
let forth_stage_key = advance_key( let forth_stage_key = advance_key(
get_u32(&self.decompressed, ss.wrapping_add(forth_key_off)), get_u32(&self.decompressed, ss.wrapping_add(forth_key_off)),
4, forth_key_rounds,
); );
let dp_base = ss.wrapping_add(dp_base_off); if verbose {
println!(" fourth-stage key rounds = {forth_key_rounds}");
}
let forth_addr = dp_base.wrapping_add(0x40); let forth_addr = dp_base.wrapping_add(0x40);
let fk = header_checksum ^ second_stage_cs ^ forth_stage_key; let fk = header_checksum ^ second_stage_cs ^ forth_stage_key;
if let Err(reason) = self.decrypt_and_decompress_data(forth_addr, fk, None) { if let Err(reason) = self.decrypt_and_decompress_data(forth_addr, fk, None) {
@@ -313,6 +338,11 @@ impl<'a> Unpacker<'a> {
)?; )?;
let seven_cs = self.calculate_checksum(seven_stage_cs_addr); let seven_cs = self.calculate_checksum(seven_stage_cs_addr);
let eighth_key_rounds =
stage_key_rounds(&self.decompressed, dp_base.wrapping_add(0x80), 4)?;
if verbose {
println!(" eighth-stage key rounds = {eighth_key_rounds}");
}
let eighth_addr = dp_base.wrapping_add(0xC0); let eighth_addr = dp_base.wrapping_add(0xC0);
let eighth_dsz = get_u32(&self.decompressed, eighth_addr.wrapping_add(12)); let eighth_dsz = get_u32(&self.decompressed, eighth_addr.wrapping_add(12));
let eighth_src = get_u32(&self.decompressed, eighth_addr); let eighth_src = get_u32(&self.decompressed, eighth_addr);
@@ -381,7 +411,7 @@ impl<'a> Unpacker<'a> {
self.decompressed[eighth_addr as usize..(eighth_addr + 16) as usize] self.decompressed[eighth_addr as usize..(eighth_addr + 16) as usize]
.copy_from_slice(&eighth_pair_bak); .copy_from_slice(&eighth_pair_bak);
let raw = get_u32(&self.decompressed, seven_start_actual.wrapping_add(ek_off)); let raw = get_u32(&self.decompressed, seven_start_actual.wrapping_add(ek_off));
let test_key = advance_key(raw, 3); let test_key = advance_key(raw, eighth_key_rounds);
let fk8 = header_checksum ^ fifth_cs ^ seven_cs ^ test_key; let fk8 = header_checksum ^ fifth_cs ^ seven_cs ^ test_key;
let result = primitives::decrypt_and_decompress_data( let result = primitives::decrypt_and_decompress_data(
&mut self.decompressed, &mut self.decompressed,
@@ -445,7 +475,7 @@ impl<'a> Unpacker<'a> {
let mut best: Option<(u32 /*dist*/, u32 /*off*/)> = None; let mut best: Option<(u32 /*dist*/, u32 /*off*/)> = None;
let mut o = 0u32; let mut o = 0u32;
let dlen = self.decompressed.len() as u32; let dlen = self.decompressed.len() as u32;
while o + 8 <= eighth_dsz.saturating_sub(0x4B4u32.saturating_sub(0x30)) { while o + 8 <= eighth_dsz {
let fc = get_u32(&self.decompressed, eighth_start.wrapping_add(o)); let fc = get_u32(&self.decompressed, eighth_start.wrapping_add(o));
let sz = get_u32(&self.decompressed, eighth_start.wrapping_add(o + 4)); let sz = get_u32(&self.decompressed, eighth_start.wrapping_add(o + 4));
if fc > info3 if fc > info3
@@ -454,8 +484,9 @@ impl<'a> Unpacker<'a> {
&& (0x10..=0x200).contains(&sz) && (0x10..=0x200).contains(&sz)
&& (sz & 0xF) == 0 && (sz & 0xF) == 0
{ {
// Cluster base must leave room for the +0x4B4 LFSR slot // Compact stages place the decryptor closer to this
// (even if the exact LFSR is later adjusted by scan). // cluster. Only the config fields must fit here; the
// actual LFSR location is trial-validated below.
if o >= 0x30 { if o >= 0x30 {
let base = o - 0x30; let base = o - 0x30;
if base.wrapping_add(0x4C) <= eighth_dsz { if base.wrapping_add(0x4C) <= eighth_dsz {
@@ -1061,3 +1092,36 @@ impl<'a> Unpacker<'a> {
Ok(compact) Ok(compact)
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stage_key_rounds_follow_active_descriptor_prefix() {
for (sizes, expected) in [
([0, 0x45, 0x45, 0x45], 0),
([0x45, 4, 0x45, 0x45], 1),
([0x45, 0x45, 0x45, 3], 3),
([0x45, 0x45, 0x45, 0x45], 4),
] {
let mut data = [0u8; 80];
for (index, size) in sizes.into_iter().enumerate() {
write_u32(&mut data, 16 + index as u32 * 16 + 4, size);
}
assert_eq!(stage_key_rounds(&data, 16, 4).unwrap(), expected);
}
}
#[test]
fn stage_key_rounds_reject_truncated_tables() {
assert!(matches!(
stage_key_rounds(&[0u8; 63], 0, 4),
Err(UnpackError::BufferRangeOutOfBounds { .. })
));
assert!(matches!(
stage_key_rounds(&[0u8; 64], u32::MAX, 4),
Err(UnpackError::BufferRangeOutOfBounds { .. })
));
}
}
@@ -42,47 +42,26 @@ fn rd_u32(d: &[u8], off: u32) -> Option<u32> {
.map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) .map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
} }
/// A parsed section-table entry (only the fields we translate against). /// PE format section data used by the integrity policy.
struct Section { type Section = senbei_pe::Section;
va: u32,
vsize: u32,
raw_ptr: u32,
raw_size: u32,
chars: u32,
}
/// Walk the output's own section table and translate an RVA to a file offset. /// Walk the output's own section table and translate an RVA to a file offset.
/// Works for both memory-image output (raw_ptr == va) and compacted disk /// Works for both memory-image output (raw_ptr == va) and compacted disk
/// output (real raw pointers), because it consults whatever the output declares. /// output (real raw pointers), because it consults whatever the output declares.
/// Returns the offset only if the translated range `[off, off+need)` lies inside /// Returns the offset only if the translated range `[off, off+need)` lies inside
/// the file. /// the file.
fn rva_to_off(secs: &[Section], file_len: usize, rva: u32, need: u32) -> Option<u32> { fn rva_to_off(data: &[u8], headers: senbei_pe::Headers, rva: u32, need: u32) -> Option<u32> {
for s in secs { let offset = u32::try_from(senbei_pe::rva_to_offset(data, headers, rva).ok()?).ok()?;
// The mapped span is the larger of virtual and raw size, so an RVA that let end = offset.checked_add(need)?;
// falls in the virtual tail of a section still resolves. (usize::try_from(end).ok()? <= data.len()).then_some(offset)
let span = s.vsize.max(s.raw_size);
if span == 0 {
continue;
}
if rva >= s.va && rva < s.va.wrapping_add(span) {
let delta = rva - s.va;
let off = s.raw_ptr.checked_add(delta)?;
let end = off.checked_add(need)?;
if (end as usize) <= file_len {
return Some(off);
}
return None;
}
}
None
} }
fn is_executable_rva(secs: &[Section], rva: u32) -> bool { fn is_executable_rva(secs: &[Section], rva: u32) -> bool {
secs.iter().any(|section| { secs.iter().any(|section| {
let span = section.vsize.max(section.raw_size); let span = section.virtual_size.max(section.raw_size);
rva >= section.va rva >= section.virtual_address
&& rva < section.va.wrapping_add(span) && rva < section.virtual_address.wrapping_add(span)
&& (section.chars & 0x2000_0000) != 0 && (section.characteristics & 0x2000_0000) != 0
}) })
} }
@@ -151,7 +130,6 @@ pub fn check(out: &[u8]) -> IntegrityReport {
return r; return r;
} }
}; };
let opt_hdr_size = rd_u16(out, pe_off.wrapping_add(20)).unwrap_or(0) as u32;
let opt = pe_off.wrapping_add(24); let opt = pe_off.wrapping_add(24);
let magic = match rd_u16(out, opt) { let magic = match rd_u16(out, opt) {
Some(v) => v, Some(v) => v,
@@ -181,42 +159,38 @@ pub fn check(out: &[u8]) -> IntegrityReport {
} }
// --- Section table ------------------------------------------------------ // --- Section table ------------------------------------------------------
let sec_table = opt.wrapping_add(opt_hdr_size); let headers = match senbei_pe::parse(out) {
let mut secs: Vec<Section> = Vec::new(); Ok(headers) => headers,
for i in 0..num_sections { Err(_) => {
let base = sec_table.wrapping_add(i * 40); r.issues
// If the table runs past EOF the image is structurally broken. .push("section table extends past end of file".into());
let (vsize, va, raw_size, raw_ptr, chars) = match ( return r;
rd_u32(out, base.wrapping_add(8)),
rd_u32(out, base.wrapping_add(12)),
rd_u32(out, base.wrapping_add(16)),
rd_u32(out, base.wrapping_add(20)),
rd_u32(out, base.wrapping_add(36)),
) {
(Some(a), Some(b), Some(c), Some(d), Some(e)) => (a, b, c, d, e),
_ => {
r.issues
.push("section table extends past end of file".into());
return r;
}
};
// Raw data must lie within the file for compacted (disk-layout) output.
if raw_size != 0 {
let end = raw_ptr.wrapping_add(raw_size) as usize;
if end > file_len {
r.issues.push(format!(
"section #{i} raw data [0x{raw_ptr:X}..0x{end:X}] exceeds file size 0x{file_len:X}"
));
}
} }
secs.push(Section { };
va, let parsed_sections = match senbei_pe::sections(out, headers) {
vsize, Ok(sections) => sections,
raw_ptr, Err(_) => {
raw_size, r.issues
chars, .push("section table extends past end of file".into());
}); return r;
} }
};
let secs: Vec<Section> = parsed_sections
.into_iter()
.enumerate()
.map(|(i, section)| {
if section.raw_size != 0 {
let end = section.raw_offset.wrapping_add(section.raw_size) as usize;
if end > file_len {
r.issues.push(format!(
"section #{i} raw data [0x{:X}..0x{end:X}] exceeds file size 0x{file_len:X}",
section.raw_offset
));
}
}
section
})
.collect();
// --- Managed (CLR) detection ------------------------------------------ // --- Managed (CLR) detection ------------------------------------------
// The COR20 (CLR) data directory, when present and non-zero, marks a managed // The COR20 (CLR) data directory, when present and non-zero, marks a managed
@@ -266,7 +240,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
r.issues.push("entry point RVA is zero".into()); r.issues.push("entry point RVA is zero".into());
} }
} else if !is_managed { } else if !is_managed {
match rva_to_off(&secs, file_len, ep, 16) { match rva_to_off(out, headers, ep, 16) {
None => { None => {
r.issues.push(format!( r.issues.push(format!(
"entry point RVA 0x{ep:X} does not map into any section" "entry point RVA 0x{ep:X} does not map into any section"
@@ -288,8 +262,10 @@ pub fn check(out: &[u8]) -> IntegrityReport {
} }
// The entry must live in an executable section. // The entry must live in an executable section.
let exec = secs.iter().any(|s| { let exec = secs.iter().any(|s| {
let span = s.vsize.max(s.raw_size); let span = s.virtual_size.max(s.raw_size);
ep >= s.va && ep < s.va.wrapping_add(span) && (s.chars & 0x2000_0000) != 0 ep >= s.virtual_address
&& ep < s.virtual_address.wrapping_add(span)
&& (s.characteristics & 0x2000_0000) != 0
}); });
if !exec { if !exec {
r.issues.push(format!( r.issues.push(format!(
@@ -316,7 +292,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if !is_managed { if !is_managed {
let imp_rva = rd_u32(out, dd_base.wrapping_add(8)).unwrap_or(0); let imp_rva = rd_u32(out, dd_base.wrapping_add(8)).unwrap_or(0);
if imp_rva != 0 { if imp_rva != 0 {
match rva_to_off(&secs, file_len, imp_rva, 20) { match rva_to_off(out, headers, imp_rva, 20) {
None => r.issues.push(format!( None => r.issues.push(format!(
"import directory RVA 0x{imp_rva:X} does not map into any section" "import directory RVA 0x{imp_rva:X} does not map into any section"
)), )),
@@ -331,7 +307,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
if name_rva == 0 { if name_rva == 0 {
break; break;
} }
match rva_to_off(&secs, file_len, name_rva, 1) { match rva_to_off(out, headers, name_rva, 1) {
None => r.issues.push(format!( None => r.issues.push(format!(
"import descriptor {i} DLL name RVA 0x{name_rva:X} does not map into any section" "import descriptor {i} DLL name RVA 0x{name_rva:X} does not map into any section"
)), )),
@@ -359,7 +335,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
// still refuses to load. Validate: COR20 cb == 0x48, and the MetaData stream // still refuses to load. Validate: COR20 cb == 0x48, and the MetaData stream
// begins with the "BSJB" signature. // begins with the "BSJB" signature.
if is_managed { if is_managed {
match rva_to_off(&secs, file_len, clr_rva, 0x48) { match rva_to_off(out, headers, clr_rva, 0x48) {
None => r.issues.push(format!( None => r.issues.push(format!(
"CLR (COR20) directory RVA 0x{clr_rva:X} does not map into any section" "CLR (COR20) directory RVA 0x{clr_rva:X} does not map into any section"
)), )),
@@ -373,7 +349,7 @@ pub fn check(out: &[u8]) -> IntegrityReport {
// MetaData RVA/size live at COR20 + 0x08 / + 0x0C. // MetaData RVA/size live at COR20 + 0x08 / + 0x0C.
let md_rva = rd_u32(out, coff.wrapping_add(8)).unwrap_or(0); let md_rva = rd_u32(out, coff.wrapping_add(8)).unwrap_or(0);
if md_rva != 0 { if md_rva != 0 {
match rva_to_off(&secs, file_len, md_rva, 4) { match rva_to_off(out, headers, md_rva, 4) {
None => r.issues.push(format!( None => r.issues.push(format!(
"CLR MetaData RVA 0x{md_rva:X} does not map into any section" "CLR MetaData RVA 0x{md_rva:X} does not map into any section"
)), )),
@@ -416,11 +392,11 @@ mod tests {
fn executable_text() -> Vec<Section> { fn executable_text() -> Vec<Section> {
vec![Section { vec![Section {
va: 0x1000, virtual_address: 0x1000,
vsize: 0x4000, virtual_size: 0x4000,
raw_ptr: 0x1000, raw_offset: 0x1000,
raw_size: 0x4000, raw_size: 0x4000,
chars: 0x6000_0020, characteristics: 0x6000_0020,
}] }]
} }
@@ -11,11 +11,11 @@ use senbei_crypto::primitives;
use std::cell::RefCell; use std::cell::RefCell;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
pub use crate::thread_cap;
pub use dll::{unpack_dll, unpack_dll_v}; pub use dll::{unpack_dll, unpack_dll_v};
pub use error::*; pub use error::*;
pub use exe::{unpack as unpack_exe, unpack_v as unpack_exe_v}; pub use exe::{unpack as unpack_exe, unpack_v as unpack_exe_v};
pub use integrity::{IntegrityReport, check as check_integrity}; pub use integrity::{IntegrityReport, check as check_integrity};
pub use parallel::thread_cap;
/// Maximum plausible PE `SizeOfImage` we are willing to allocate a zero buffer /// Maximum plausible PE `SizeOfImage` we are willing to allocate a zero buffer
/// for. Guards against a corrupt/crafted header requesting a multi-gigabyte /// for. Guards against a corrupt/crafted header requesting a multi-gigabyte
@@ -350,8 +350,8 @@ mod tests {
}; };
assert_eq!(message, "test panic"); assert_eq!(message, "test panic");
assert!( assert!(
file.ends_with("senbei-pe/src/engine/mod.rs") file.ends_with("senbei-engine/src/windows/mod.rs")
|| file.ends_with("senbei-pe\\src\\engine\\mod.rs") || file.ends_with("senbei-engine\\src\\windows\\mod.rs")
); );
assert!(line > 0); assert!(line > 0);
assert!(column > 0); assert!(column > 0);
@@ -382,8 +382,8 @@ mod tests {
}; };
assert_eq!(message, "worker panic"); assert_eq!(message, "worker panic");
assert!( assert!(
file.ends_with("senbei-pe/src/engine/mod.rs") file.ends_with("senbei-engine/src/windows/mod.rs")
|| file.ends_with("senbei-pe\\src\\engine\\mod.rs") || file.ends_with("senbei-engine\\src\\windows\\mod.rs")
); );
assert!(line > 0); assert!(line > 0);
assert!(column > 0); assert!(column > 0);
@@ -19,20 +19,6 @@
use std::sync::Mutex; use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
/// Worker-thread cap. `SENBEI_THREADS` overrides it (`1` forces the sequential
/// path); otherwise the host's available parallelism; otherwise 1.
pub fn thread_cap() -> usize {
if let Ok(v) = std::env::var("SENBEI_THREADS")
&& let Ok(n) = v.trim().parse::<usize>()
&& n >= 1
{
return n;
}
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
}
/// Run `f(i, span_base, span)` for every block `i`, fanning out across worker /// Run `f(i, span_base, span)` for every block `i`, fanning out across worker
/// threads when the spans are disjoint and worthwhile, else sequentially. /// threads when the spans are disjoint and worthwhile, else sequentially.
/// ///
@@ -102,7 +88,7 @@ where
} }
} }
let cap = thread_cap(); let cap = crate::thread_cap();
let per = min_per_thread.max(1); let per = min_per_thread.max(1);
let workers = if cap > 1 && n >= per.saturating_mul(2) { let workers = if cap > 1 && n >= per.saturating_mul(2) {
cap.min(n / per) cap.min(n / per)
+8 -1
View File
@@ -7,11 +7,18 @@ description = "Filesystem, scanning, logging, and CLI orchestration for Senbei"
[dependencies] [dependencies]
anyhow.workspace = true anyhow.workspace = true
senbei-crypto.workspace = true
indicatif.workspace = true indicatif.workspace = true
memmap2.workspace = true
owo-colors.workspace = true owo-colors.workspace = true
senbei-metadata.workspace = true senbei-engine.workspace = true
senbei-elf.workspace = true
senbei-pe.workspace = true senbei-pe.workspace = true
senbei-metadata.workspace = true
sha2.workspace = true
tempfile.workspace = true
walkdir.workspace = true walkdir.workspace = true
zip.workspace = true
[target.'cfg(windows)'.dependencies] [target.'cfg(windows)'.dependencies]
windows.workspace = true windows.workspace = true
+462
View File
@@ -0,0 +1,462 @@
//! Android target orchestration: protected AArch64 shared libraries (`.so`),
//! app packages (`.apk` / `.apks` / `.xapk`), and the Android variant of the
//! il2cpp method-token obfuscation.
//!
//! The protection scheme hollows out an ELF64/AArch64 shared object and moves
//! the original bytes into an encrypted payload appended as a `SHT_LOUSER`
//! section; restoration extracts the stage-2 module set
//! ([`senbei_engine::android`]) and rebuilds the static image
//! ([`senbei_engine::android`]). Some il2cpp builds additionally embed their
//! metadata blob — XOR-wrapped, with no standalone `global-metadata.dat` in
//! the assets — inside the library's data section; after a successful restore
//! the blob is located by content and unwrapped
//! ([`senbei_metadata::android::extract_embedded_metadata`]).
//!
//! All functions in this module are native filesystem orchestration; the web
//! app (wasm) never touches them.
use std::collections::HashSet;
use std::fs::File;
use std::io::{BufWriter, Read, Seek, Write};
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use memmap2::{Mmap, MmapOptions};
use senbei_crypto::hex_digest;
use senbei_engine::android::{ExtractOptions, extract_stage2, is_protected_libil2cpp};
use senbei_engine::android::{RestoreOptions, restore_libil2cpp};
use sha2::{Digest, Sha256};
use zip::ZipArchive;
pub use crate::METADATA_FILE_NAME;
/// Package extensions recognised as Android app packages. Packages are
/// *containers*: membership is decided by extension plus the ZIP magic, while
/// only `.so` and `global-metadata.dat` entries are read.
const PACKAGE_EXTENSIONS: [&str; 3] = ["apk", "apks", "xapk"];
pub(crate) fn is_package_name(path: &Path) -> bool {
path.extension()
.and_then(|value| value.to_str())
.is_some_and(|value| {
PACKAGE_EXTENSIONS
.iter()
.any(|ext| value.eq_ignore_ascii_case(ext))
})
}
pub(crate) fn is_so_name(path: &Path) -> bool {
path.extension()
.and_then(|value| value.to_str())
.is_some_and(|value| value.eq_ignore_ascii_case("so"))
}
pub(crate) fn is_android_entry_name(path: &Path) -> bool {
path.file_name()
.and_then(|name| name.to_str())
.is_some_and(|name| name.eq_ignore_ascii_case(METADATA_FILE_NAME))
|| is_so_name(path)
}
/// Whether `prefix` (the first bytes of a file) is an ELF64/AArch64 image.
/// Only those can be protected Android libraries, so the folder scan uses this
/// cheap check to decide when the full-file protection probe is worth its
/// read.
pub fn is_elf64_aarch64(prefix: &[u8]) -> bool {
senbei_elf::is_aarch64_prefix(prefix)
}
/// Whether `path` is an Android app package: a recognised package extension
/// and the local-file-header zip magic in `prefix`.
pub fn is_app_package(path: &Path, prefix: &[u8]) -> bool {
is_package_name(path) && prefix.starts_with(b"PK\x03\x04")
}
/// Probe a file on disk: true when it is a protected AArch64 library.
/// Reads the whole file (the payload section is found through the
/// section-header table at the end); call only after [`is_elf64_aarch64`]
/// has matched a prefix.
pub fn is_protected_so_file(path: &Path) -> bool {
let Ok(file) = File::open(path) else {
return false;
};
let Ok(bytes) = map_read_only(&file, path) else {
return false;
};
is_elf64_aarch64(&bytes) && is_protected_libil2cpp(&bytes)
}
pub fn file_content_identity(path: &Path) -> std::io::Result<String> {
let file = File::open(path)?;
// SAFETY: the file remains open for the mapping lifetime and the mapping
// is read-only.
let bytes = unsafe { MmapOptions::new().map(&file)? };
Ok(content_identity(&bytes))
}
/// Restore one protected `.so` to `dest`.
///
/// The stage-2 module set is extracted into a temporary workspace (it is an
/// implementation detail of the two-phase restore, not user-facing output).
/// Returns the unwrapped embedded metadata blob when the restored image
/// carries one (see the module docs); the caller decides where to write it.
pub fn restore_so_file(input: &Path, dest: &Path, verbose: bool) -> Result<Option<Vec<u8>>> {
let temporary = tempfile::tempdir().context("create stage-2 workspace")?;
let stage2_dir = temporary.path().join("stage2");
extract_stage2(&ExtractOptions::with_defaults(
input.to_path_buf(),
stage2_dir.clone(),
))
.context("extract stage-1/stage-2 payload")?;
restore_libil2cpp(&RestoreOptions {
input: input.to_path_buf(),
output: dest.to_path_buf(),
index: stage2_dir.join("index.json"),
dump_auxiliary: None,
outer_only: false,
preserve_entrypoint: false,
verbose,
})
.context("restore protected library")?;
let restored =
std::fs::read(dest).with_context(|| format!("read restored `{}`", dest.display()))?;
Ok(senbei_metadata::android::extract_embedded_metadata(
&restored,
))
}
/// Content identity for cross-source deduplication: the same library may
/// appear loose in a tree, in its `.apk`, and again in an `.apks`/`.xapk`
/// bundle — restore it once, at the highest-priority source's destination.
pub fn content_identity(data: &[u8]) -> String {
let mut digest = Sha256::new();
digest.update(data);
hex_digest(&digest.finalize())
}
/// Restore an il2cpp metadata blob (Android seeded permutation first, then the
/// structural remap used by the Windows builds).
///
/// The Android variant obfuscates MethodDef RIDs with a keyed five-round
/// permutation; the correct seed is recovered by intersecting per-image key
/// residues, and the restore *validates* every restored RID against its
/// canonical per-module index — so an unusable seed fails loudly and the
/// caller falls through to the structural remap, which targets the same
/// canonical form. Both paths are no-ops (`remapped == 0`) on an
/// already-clean blob.
pub fn restore_metadata_bytes(data: &[u8]) -> anyhow::Result<(Vec<u8>, senbei_metadata::Report)> {
if let Ok(discovery) = senbei_metadata::android::discover_method_token_seeds(data)
&& matches!(discovery.version, 29 | 31 | 39)
{
let mut seeds = discovery.seed_candidates.clone();
if seeds.is_empty() {
seeds.push(senbei_metadata::android::DEFAULT_METHOD_TOKEN_SEED);
}
// Trial-and-validate: a wrong seed fails the restore's full-coverage
// RID check, so ambiguous candidates cost one extra pass each and a
// build with an unseeded permutation falls through to the structural
// remap rather than producing a silently wrong file.
for seed in seeds {
if let Ok((out, report)) = senbei_metadata::android::restore_method_tokens(data, seed) {
return Ok((
out,
senbei_metadata::Report {
version: report.version,
methods: report.methods,
remapped: report.changed_tokens,
modules: report.images_with_methods,
},
));
}
}
}
let (out, report) = senbei_metadata::deobfuscate(data).map_err(anyhow::Error::new)?;
Ok((out, report))
}
/// What happened to one archive entry (or one loose Android target).
#[derive(Debug)]
pub struct EntryOutcome {
/// Human-readable source label, e.g. `base.apk::lib/arm64-v8a/libil2cpp.so`.
pub label: String,
/// Where the restored bytes were written (meaningless unless `status` is
/// `Restored`).
pub dest: PathBuf,
pub kind: EntryKind,
pub status: EntryStatus,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntryKind {
/// A protected shared library, restored.
So,
/// An il2cpp metadata blob, de-obfuscated (`remapped` tokens changed).
Metadata { remapped: usize },
/// A metadata blob unwrapped from a restored library's data section.
EmbeddedMetadata,
}
#[derive(Debug)]
pub enum EntryStatus {
Restored,
/// Byte-identical content was already restored from a higher-priority
/// source; no output written.
Duplicate,
/// Content-probed but not a target (unprotected library).
NotTarget,
/// A metadata blob whose tokens were already canonical; no copy written.
Unchanged,
/// Recognised as a target but the restore failed.
Failed(anyhow::Error),
}
/// Restore every protected library and metadata blob inside one app package.
///
/// `rel` is the package's path relative to the scanned root (or its bare file
/// name in single-file mode); outputs mirror the package's internal layout
/// under `out_root/rel/`, with [`crate::job::out_name`] renaming. `seen`
/// carries content identities already restored from higher-priority sources
/// (loose files first, then `.apk`, then bundles) across the whole run.
pub fn restore_package(
package: &Path,
rel: &Path,
out_root: &Path,
seen: &mut HashSet<String>,
verbose: bool,
) -> Result<Vec<EntryOutcome>> {
let bundle = package
.extension()
.and_then(|value| value.to_str())
.is_some_and(|value| {
value.eq_ignore_ascii_case("apks") || value.eq_ignore_ascii_case("xapk")
});
let mut archive = open_package(package)?;
let temporary = tempfile::tempdir().context("create package workspace")?;
let mut outcomes = Vec::new();
let mut direct = Vec::new();
let mut nested = Vec::new();
for index in 0..archive.len() {
let (name, is_dir) = {
let entry = archive.by_index(index)?;
(entry.enclosed_name(), entry.is_dir())
};
if is_dir {
continue;
}
let Some(name) = name else {
bail!("unsafe entry path in package `{}`", package.display());
};
if bundle {
if name
.extension()
.and_then(|value| value.to_str())
.is_some_and(|value| value.eq_ignore_ascii_case("apk"))
{
nested.push((index, name));
}
} else {
if is_android_entry_name(&name) {
direct.push((index, name));
}
}
}
for (index, name) in direct {
let label = format!("{}::{}", rel.display(), name.display());
let dest = out_root.join(rel).join(crate::job::out_name(&name));
let mut entry_outcomes = restore_package_entry(
&mut archive,
index,
&label,
&dest,
&temporary,
seen,
verbose,
)
.with_context(|| format!("extract `{label}`"))?;
outcomes.append(&mut entry_outcomes);
}
for (index, name) in nested {
let nested_label = rel.join(&name);
let nested_path = extract_entry(&mut archive, index, &temporary, &nested_label)
.with_context(|| format!("extract `{}`", nested_label.display()))?;
let mut nested_archive = open_package(&nested_path)?;
let mut entries = Vec::new();
for nested_index in 0..nested_archive.len() {
let (entry_name, is_dir) = {
let entry = nested_archive.by_index(nested_index)?;
(entry.enclosed_name(), entry.is_dir())
};
if !is_dir {
let Some(entry_name) = entry_name else {
bail!("unsafe entry path in `{}`", nested_label.display());
};
if is_android_entry_name(&entry_name) {
entries.push((nested_index, entry_name));
}
}
}
// Keep the nested package's stem in the output layout so two splits
// carrying same-named entries cannot collide.
let base = rel.join(name.with_extension(""));
for (nested_index, entry_name) in entries {
let label = format!("{}::{}", nested_label.display(), entry_name.display());
let dest = out_root.join(&base).join(crate::job::out_name(&entry_name));
let mut entry_outcomes = restore_package_entry(
&mut nested_archive,
nested_index,
&label,
&dest,
&temporary,
seen,
verbose,
)
.with_context(|| format!("extract `{label}`"))?;
outcomes.append(&mut entry_outcomes);
}
}
Ok(outcomes)
}
/// Probe one extracted package entry and restore it when it is a target.
/// Returns one outcome per produced/consumed artifact: the entry itself, plus
/// an `EmbeddedMetadata` outcome when the restored library carried a blob.
fn restore_package_entry<R: Read + Seek>(
archive: &mut ZipArchive<R>,
index: usize,
label: &str,
dest: &Path,
temporary: &tempfile::TempDir,
seen: &mut HashSet<String>,
verbose: bool,
) -> Result<Vec<EntryOutcome>> {
let entry_path = extract_entry(archive, index, temporary, Path::new(label))?;
let entry_file =
File::open(&entry_path).with_context(|| format!("open extracted `{label}`"))?;
let entry_data = map_read_only(&entry_file, &entry_path)?;
let is_so = is_elf64_aarch64(&entry_data) && is_protected_libil2cpp(&entry_data);
let is_meta = !is_so && senbei_metadata::is_metadata(&entry_data);
let outcome = |kind, status| EntryOutcome {
label: label.to_owned(),
dest: dest.to_path_buf(),
kind,
status,
};
if !is_so && !is_meta {
return Ok(vec![outcome(EntryKind::So, EntryStatus::NotTarget)]);
}
if !seen.insert(content_identity(&entry_data)) {
let kind = if is_so {
EntryKind::So
} else {
EntryKind::Metadata { remapped: 0 }
};
return Ok(vec![outcome(kind, EntryStatus::Duplicate)]);
}
if is_so {
drop(entry_data);
drop(entry_file);
return Ok(match restore_so_file(&entry_path, dest, verbose) {
Ok(embedded) => {
let mut outcomes = vec![outcome(EntryKind::So, EntryStatus::Restored)];
if let Some(blob) = embedded {
let meta_dest = embedded_metadata_dest(dest);
let status = match write_metadata_blob(&meta_dest, &blob) {
Ok(()) => EntryStatus::Restored,
Err(error) => EntryStatus::Failed(error),
};
outcomes.push(EntryOutcome {
label: format!("{label} (embedded metadata)"),
dest: meta_dest,
kind: EntryKind::EmbeddedMetadata,
status,
});
}
outcomes
}
Err(error) => vec![outcome(EntryKind::So, EntryStatus::Failed(error))],
});
}
// Metadata entry: write only when the restore actually changed tokens —
// a clean blob needs no copy (same contract as loose metadata files).
let kind_and_status = match restore_metadata_bytes(&entry_data) {
Ok((out, report)) if report.remapped > 0 => {
let kind = EntryKind::Metadata {
remapped: report.remapped,
};
match write_metadata_blob(dest, &out) {
Ok(()) => (kind, EntryStatus::Restored),
Err(error) => (kind, EntryStatus::Failed(error)),
}
}
Ok(_) => (EntryKind::Metadata { remapped: 0 }, EntryStatus::Unchanged),
Err(error) => (
EntryKind::Metadata { remapped: 0 },
EntryStatus::Failed(error),
),
};
Ok(vec![outcome(kind_and_status.0, kind_and_status.1)])
}
/// Output path for a metadata blob unwrapped from a restored library: next to
/// the library, under the standard file name (with the usual `.unpack` infix).
pub fn embedded_metadata_dest(restored_so: &Path) -> PathBuf {
let dir = restored_so.parent().unwrap_or_else(|| Path::new("."));
dir.join(crate::job::out_name(Path::new(METADATA_FILE_NAME)))
}
/// Write a metadata blob, creating the parent directory. The restore writes
/// its own output atomically; metadata blobs use the shared orchestration
/// atomic writer to keep the same mid-write failure semantics.
fn write_metadata_blob(dest: &Path, data: &[u8]) -> Result<()> {
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("create `{}`", parent.display()))?;
}
crate::atomic::write_atomic(dest, data)
.map_err(anyhow::Error::from)
.context("write metadata output")
}
fn open_package(path: &Path) -> Result<ZipArchive<std::fs::File>> {
let file = std::fs::File::open(path).with_context(|| format!("open `{}`", path.display()))?;
ZipArchive::new(file).with_context(|| format!("read package `{}`", path.display()))
}
/// Stream one package entry to a temporary, seekable file. The Android engine
/// needs random access to ELF section tables, while the ZIP reader itself is
/// consumed directly without creating an in-memory compressed or decompressed
/// copy.
fn extract_entry<R: Read + Seek>(
archive: &mut ZipArchive<R>,
index: usize,
temporary: &tempfile::TempDir,
label: &Path,
) -> Result<PathBuf> {
let mut entry = archive.by_index(index)?;
let key = format!("{}-{index:08x}", label.display());
// `:` appears in `package::entry` labels and is invalid in Windows file
// names; sanitize every path-ish separator.
let destination = temporary.path().join(key.replace(['\\', '/', ':'], "_"));
let output_size = entry.size();
let mut output = BufWriter::new(std::fs::File::create(&destination)?);
let written = std::io::copy(&mut entry, &mut output)?;
output.flush()?;
if written != output_size {
bail!(
"entry `{key}` decompressed to 0x{:x}, expected 0x{output_size:x}",
written
);
}
Ok(destination)
}
fn map_read_only(file: &File, path: &Path) -> Result<Mmap> {
// SAFETY: the file descriptor remains open for the returned mapping's
// lifetime, and this mapping is read-only.
unsafe { MmapOptions::new().map(file) }
.with_context(|| format!("map extracted `{}`", path.display()))
}
+16
View File
@@ -0,0 +1,16 @@
//! Shared atomic filesystem writes for native orchestration.
use std::path::{Path, PathBuf};
/// Write `bytes` through a sibling temporary file and replace `dest` only after
/// the complete write succeeds.
pub(crate) fn write_atomic(dest: &Path, bytes: &[u8]) -> std::io::Result<()> {
let mut temporary_name = dest.as_os_str().to_os_string();
temporary_name.push(".senbei-tmp");
let temporary = PathBuf::from(temporary_name);
let result = std::fs::write(&temporary, bytes).and_then(|()| std::fs::rename(&temporary, dest));
if result.is_err() {
let _ = std::fs::remove_file(&temporary);
}
result
}
+342 -537
View File
@@ -1,328 +1,12 @@
use senbei_pe as unpacker;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
/// Crackproof header key table lives at this fixed file offset. For the use crate::atomic::write_atomic;
/// external-companion layout, the companion payload aligns to the stub here. pub use crate::windows::{
const HEADER_OFF: usize = 4096; UnpackedImage, unpack_bytes, unpack_bytes_force_exe, unpack_one, unpack_one_v,
};
/// Build the unpacker input for `input`, transparently handling the
/// **external-companion** layout used by some il2cpp games.
///
/// In that layout a protected module is split into a thin on-disk loader stub
/// (`Foo.dll`, whose code sections are stripped to one page) plus an encrypted
/// `Foo.dll._` companion holding the real payload. The companion is byte-for-byte
/// the stub's payload region starting at the Crackproof header (offset 4096), so
/// `stub[..4096] ++ companion` reconstructs the ordinary embedded-payload file
/// the existing pipelines already unpack. The runtime loader does exactly this:
/// it maps `Foo.dll._` and feeds it through the standard Crackproof unpack.
///
/// The splice fires only when a sibling `<input>._` exists *and* its first 32
/// bytes equal the stub's header at offset 4096 — a precise signal that the
/// companion is this stub's payload. Otherwise the file is returned untouched,
/// so normal (embedded-payload) inputs are unaffected.
fn read_unpacker_input(input: &Path) -> std::io::Result<UnpackerInput> {
let stub = std::fs::read(input)?;
// Companion path: append "._" to the full file name (Foo.dll -> Foo.dll._).
let companion = match input.file_name() {
Some(name) => {
let mut n = name.to_os_string();
n.push("._");
input.with_file_name(n)
}
None => {
return Ok(UnpackerInput {
bytes: stub,
stub: None,
});
}
};
if !companion.is_file() {
return Ok(UnpackerInput {
bytes: stub,
stub: None,
});
}
let comp = std::fs::read(&companion)?;
match splice_companion(&stub, &comp) {
// A splice fired: keep the stub so its plaintext export table can be
// overlaid onto the unpacked image (the companion does not carry it).
Some(spliced) => Ok(UnpackerInput {
bytes: spliced,
stub: Some(stub),
}),
None => Ok(UnpackerInput {
bytes: stub,
stub: None,
}),
}
}
/// The bytes fed to the unpacker, plus the original loader stub when the input
/// was reconstructed from an external companion. The stub is retained because
/// the crackproof loader rebuilds the PE export table at runtime from data kept
/// in the stub — that table is *not* present in the encrypted companion, so the
/// unpacked image needs it overlaid from the stub afterwards
/// (see [`overlay_exports_from_stub`]).
struct UnpackerInput {
bytes: Vec<u8>,
stub: Option<Vec<u8>>,
}
/// Overlay the PE export table from the loader `stub` onto the unpacked image
/// `out`, for the external-companion layout.
///
/// In that layout the encrypted companion carries the real `.text`/`il2cpp`
/// payload but **not** a usable export directory: the crackproof loader rebuilds
/// exports at runtime from the plaintext copy retained in the stub's `.rdata`.
/// Statically, the spliced input therefore decrypts to a garbage export
/// directory (`NumberOfFunctions` etc. are ciphertext), which makes downstream
/// tools (IL2CppDumper, IDA) choke when they parse it. The fix does what the
/// loader does: copy the export-directory region byte-for-byte from the stub to
/// the same RVA in the unpacked image.
///
/// No-op (leaves `out` untouched) if there is no export directory, or if the
/// region cannot be mapped in either image — so a malformed stub can never
/// corrupt an otherwise-good unpack.
fn overlay_exports_from_stub(out: &mut [u8], stub: &[u8]) {
let (export_rva, export_size) = match pe_export_dir(out) {
Some(v) if v.1 != 0 => v,
_ => return,
};
let dst = match rva_to_file_off(out, export_rva) {
Some(o) => o,
None => return,
};
let src = match rva_to_file_off(stub, export_rva) {
Some(o) => o,
None => return,
};
let n = export_size as usize;
if dst + n <= out.len() && src + n <= stub.len() {
out[dst..dst + n].copy_from_slice(&stub[src..src + n]);
}
}
/// Restore the TLS directory from the loader `stub` onto the unpacked image
/// `out`, for the external-companion layout.
///
/// Crackproof strips the whole `IMAGE_TLS_DIRECTORY` from the encrypted payload
/// — the data-directory entry, the directory struct, the raw-data template, and
/// the base relocations for the struct's four 64-bit pointer fields — and
/// re-installs TLS itself from data kept in the stub when it loads the module.
/// A statically-unpacked DLL is loaded by the ordinary Windows loader instead,
/// which needs a valid TLS directory or it never allocates a TLS slot for the
/// module nor writes `_tls_index`. The module's C++ `thread_local` accesses then
/// read a garbage TLS slot — observed as a `0xC0000005` deep in IL2CPP type
/// resolution (a TypeDef token used as a raw `s_TypeInfoTable` index).
///
/// The stub retains the full plaintext `.rdata` (only `.text`/`il2cpp` are
/// stripped to one page), so the directory struct and its raw-data template are
/// copied back byte-for-byte at their RVAs, the data-directory entry is taken
/// from the stub header (the unpacked image's was overwritten with the zeroed
/// saved-header blob), and four DIR64 relocations are appended to `.reloc`.
///
/// No-op if the stub declares no TLS directory or if any required region cannot
/// be mapped/relocated — so it can never corrupt an otherwise-good unpack.
fn restore_tls_from_stub(out: &mut [u8], stub: &[u8]) {
let pe = match read_u32(out, 0x3C) {
Some(v) => v as usize,
None => return,
};
if out.get(pe..pe + 4) != Some(&b"PE\0\0"[..]) {
return;
}
// This restore is PE32+-only: it copies a 40-byte IMAGE_TLS_DIRECTORY64,
// converts fields with a 64-bit image base, and appends DIR64 relocs. A
// PE32 module needs the 24-byte struct / DIR32 handling (the unpacker core
// does that itself — see `restore_pe32_tls_from_stub`), so bail rather than
// read the data directories at the wrong (PE32+) offset and write garbage.
if read_u16(out, pe + 24) != Some(0x20B) {
return;
}
// TLS is data-directory index 9 (PE32+ directories at optional header +112).
let tls_dd = match pe.checked_add(24 + 112 + 9 * 8) {
Some(v) => v,
None => return,
};
// The genuine entry survives in the stub header; the unpacked image's copy
// was clobbered by the (zeroed-TLS) saved-header blob.
let (tls_rva, tls_size) = match (read_u32(stub, tls_dd), read_u32(stub, tls_dd + 4)) {
(Some(r), Some(s)) if r != 0 && s != 0 => (r, s),
_ => return, // module has no TLS — nothing to restore
};
// Image base (PE32+, optional header +24) converts the struct's absolute VAs
// back to RVAs for the raw-data template overlay.
let image_base = match read_u64(out, pe + 24 + 24) {
Some(v) => v,
None => return,
};
// 1) Overlay the IMAGE_TLS_DIRECTORY struct from the stub at its RVA.
let dst = match rva_to_file_off(out, tls_rva) {
Some(o) => o,
None => return,
};
let src = match rva_to_file_off(stub, tls_rva) {
Some(o) => o,
None => return,
};
let n = tls_size as usize;
if dst.checked_add(n).is_none_or(|e| e > out.len())
|| src.checked_add(n).is_none_or(|e| e > stub.len())
{
return;
}
out[dst..dst + n].copy_from_slice(&stub[src..src + n]);
// 2) Restore the data-directory entry so the loader processes TLS at all.
write_u32_at(out, tls_dd, tls_rva);
write_u32_at(out, tls_dd + 4, tls_size);
// 3) Overlay the raw-data template [StartAddressOfRawData, EndAddressOfRawData).
if let (Some(start_va), Some(end_va)) = (read_u64(out, dst), read_u64(out, dst + 8))
&& end_va > start_va
&& start_va >= image_base
{
let tpl_rva = (start_va - image_base) as u32;
let tpl_len = (end_va - start_va) as usize;
if let (Some(td), Some(ts)) = (
rva_to_file_off(out, tpl_rva),
rva_to_file_off(stub, tpl_rva),
) && td.checked_add(tpl_len).is_some_and(|e| e <= out.len())
&& ts.checked_add(tpl_len).is_some_and(|e| e <= stub.len())
{
out[td..td + tpl_len].copy_from_slice(&stub[ts..ts + tpl_len]);
}
}
// 4) Append DIR64 relocations for the struct's four 64-bit pointer fields
// (Start/End/Index/CallBacks at +0/+8/+0x10/+0x18). Without them the
// loader would leave preferred-base VAs in a rebased image.
add_tls_relocs(out, pe, tls_rva);
}
/// Append a single base-relocation block covering the four 64-bit pointer fields
/// of the TLS directory struct at `tls_rva`. The block is written immediately
/// after the existing relocation table (which must be free space and in bounds)
/// and the BaseReloc directory size is grown to include it. No-op if the table
/// is absent, the fields straddle a relocation page, or the slot is not free.
fn add_tls_relocs(out: &mut [u8], pe: usize, tls_rva: u32) {
let reloc_dd = pe + 24 + 112 + 5 * 8; // BaseReloc = directory index 5
let (reloc_rva, reloc_size) = match (read_u32(out, reloc_dd), read_u32(out, reloc_dd + 4)) {
(Some(r), Some(s)) if r != 0 => (r, s),
_ => return,
};
// All four fields (last at +0x18) must share one 0x1000 relocation page.
let page = tls_rva & !0xFFF;
if (tls_rva.wrapping_add(0x18)) & !0xFFF != page {
return;
}
const BLOCK: usize = 8 + 4 * 2; // header + four DIR64 entries
let at = match rva_to_file_off(out, reloc_rva.wrapping_add(reloc_size)) {
Some(o) => o,
None => return,
};
if at.checked_add(BLOCK).is_none_or(|e| e > out.len()) {
return;
}
if out[at..at + BLOCK].iter().any(|&b| b != 0) {
return; // refuse to clobber existing data
}
write_u32_at(out, at, page);
write_u32_at(out, at + 4, BLOCK as u32);
for (i, off) in [0u32, 8, 0x10, 0x18].iter().enumerate() {
let entry = (10u16 << 12) | (((tls_rva.wrapping_add(*off)) & 0xFFF) as u16);
let p = at + 8 + i * 2;
out[p..p + 2].copy_from_slice(&entry.to_le_bytes());
}
write_u32_at(out, reloc_dd + 4, reloc_size.wrapping_add(BLOCK as u32));
}
/// Read the Export data-directory (RVA, size) from a PE image, or `None` if the
/// headers are too short/invalid to parse.
fn pe_export_dir(buf: &[u8]) -> Option<(u32, u32)> {
let pe = read_u32(buf, 0x3C)? as usize;
if buf.get(pe..pe + 4)? != b"PE\0\0" {
return None;
}
// Optional header at pe+24; data directories start at +96 on PE32 (0x10B)
// and +112 on PE32+ (0x20B); Export is index 0.
let dd_base = match read_u16(buf, pe + 24)? {
0x20B => 112,
0x10B => 96,
_ => return None,
};
let dd = pe.checked_add(24 + dd_base)?;
Some((read_u32(buf, dd)?, read_u32(buf, dd + 4)?))
}
/// Map an RVA to a file offset using the PE section table. Returns `None` if no
/// section contains the RVA or the headers cannot be parsed.
fn rva_to_file_off(buf: &[u8], rva: u32) -> Option<usize> {
let pe = read_u32(buf, 0x3C)? as usize;
if buf.get(pe..pe + 4)? != b"PE\0\0" {
return None;
}
let nsec = read_u16(buf, pe + 6)? as usize;
let opt_size = read_u16(buf, pe + 20)? as usize;
let sh = pe.checked_add(24)?.checked_add(opt_size)?;
for i in 0..nsec {
let o = sh.checked_add(i.checked_mul(40)?)?;
let vsz = read_u32(buf, o + 8)?;
let va = read_u32(buf, o + 12)?;
let raw = read_u32(buf, o + 20)?;
if rva >= va && rva < va.wrapping_add(vsz.max(1)) {
return Some((rva - va).wrapping_add(raw) as usize);
}
}
None
}
fn read_u32(buf: &[u8], off: usize) -> Option<u32> {
let b = buf.get(off..off + 4)?;
Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
fn read_u16(buf: &[u8], off: usize) -> Option<u16> {
let b = buf.get(off..off + 2)?;
Some(u16::from_le_bytes([b[0], b[1]]))
}
fn read_u64(buf: &[u8], off: usize) -> Option<u64> {
let b = buf.get(off..off + 8)?;
Some(u64::from_le_bytes([
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
]))
}
/// Write a little-endian `u32` at `off`, silently doing nothing if out of bounds.
fn write_u32_at(buf: &mut [u8], off: usize, val: u32) {
if let Some(slot) = buf.get_mut(off..off + 4) {
slot.copy_from_slice(&val.to_le_bytes());
}
}
/// Splice a stub and its external-companion payload into the embedded-payload
/// form the pipelines expect, or `None` if `comp` is not this stub's payload.
///
/// The companion is byte-for-byte the stub's payload region from the Crackproof
/// header (offset 4096) onward, so the result is `stub[..4096] ++ comp`. The
/// splice fires only when the first 32 bytes of `comp` equal the stub's header
/// at offset 4096 — a 32-byte match on the key-table/magic region that confirms
/// the pairing and leaves ordinary (non-companion) inputs untouched.
fn splice_companion(stub: &[u8], comp: &[u8]) -> Option<Vec<u8>> {
let hdr_end = HEADER_OFF + 32;
if stub.len() >= hdr_end && comp.len() >= 32 && stub[HEADER_OFF..hdr_end] == comp[..32] {
let mut spliced = Vec::with_capacity(HEADER_OFF + comp.len());
spliced.extend_from_slice(&stub[..HEADER_OFF]);
spliced.extend_from_slice(comp);
return Some(spliced);
}
None
}
/// Summary of a folder-mode run. /// Summary of a folder-mode run.
#[derive(Default)]
pub struct Summary { pub struct Summary {
pub unpacked: usize, pub unpacked: usize,
pub skipped: usize, pub skipped: usize,
@@ -331,12 +15,29 @@ pub struct Summary {
/// — likely to crash at runtime (e.g. 0xC0000005). Counted in addition to /// — likely to crash at runtime (e.g. 0xC0000005). Counted in addition to
/// `unpacked` (a suspect file is still written). /// `unpacked` (a suspect file is still written).
pub suspect: usize, pub suspect: usize,
/// il2cpp `global-metadata.dat` files de-obfuscated (method tokens remapped). /// il2cpp `global-metadata.dat` files de-obfuscated (method tokens remapped),
/// including blobs unwrapped from restored Android libraries.
pub metadata: usize, pub metadata: usize,
/// Android app packages (`.apk`/`.apks`/`.xapk`) opened and searched.
pub packages: usize,
/// Wall-clock duration of the folder run in milliseconds. /// Wall-clock duration of the folder run in milliseconds.
pub duration_ms: u128, pub duration_ms: u128,
} }
impl Summary {
/// The summary line shared by CLI output and the log file.
pub fn line(&self) -> String {
let mut line = format!(
"{} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
self.unpacked, self.skipped, self.errors, self.suspect, self.metadata
);
if self.packages > 0 {
line.push_str(&format!(" · {} packages", self.packages));
}
line
}
}
/// Default output root for a folder unpack: `<root>/unpack`. /// Default output root for a folder unpack: `<root>/unpack`.
pub fn default_out_root_for_folder(root: &Path) -> PathBuf { pub fn default_out_root_for_folder(root: &Path) -> PathBuf {
root.join("unpack") root.join("unpack")
@@ -385,11 +86,8 @@ pub fn run_folder_v(
/// Like [`run_folder_v`], but with the scan pre-filter explicitly controlled. /// Like [`run_folder_v`], but with the scan pre-filter explicitly controlled.
/// ///
/// When `scan_all` is true every regular file under `root` is opened and /// When `scan_all` is true selected target names below the minimum size are
/// content-probed, instead of skipping ones the free directory metadata already /// also opened and content-probed. Other filenames are never opened.
/// rules out (extensionless, too small to hold a Crackproof key table, or a
/// bulk-asset extension). See [`crate::scan::find_targets_opts`] — exhaustive
/// scanning is dramatically slower on asset-heavy trees.
pub fn run_folder_opts( pub fn run_folder_opts(
root: &Path, root: &Path,
out_dir: Option<&Path>, out_dir: Option<&Path>,
@@ -416,12 +114,15 @@ pub fn run_folder_opts(
log.step(&format!("out {}", out_root.display())); log.step(&format!("out {}", out_root.display()));
Some(log) Some(log)
}; };
// Single merged directory walk: returns Crackproof unpack candidates and // Single merged directory walk: returns Crackproof unpack candidates, il2cpp
// il2cpp metadata blobs from one traversal (see // metadata blobs, and Android targets from one traversal (see
// [`crate::scan::find_targets_opts`]). Files the free directory metadata // [`crate::scan::find_targets_opts`]). Files the free directory metadata
// already rules out are never opened — on asset-heavy trees the per-file // already rules out are never opened — on asset-heavy trees the per-file
// open+read latency, not the traversal, is the whole cost. // open+read latency, not the traversal, is the whole cost.
let (candidates, metas, scan_stats) = crate::scan::find_targets_opts(root, scan_all); let scan = crate::scan::find_targets_opts(root, scan_all);
let candidates = scan.crackproof.as_slice();
let metas = scan.metadata.as_slice();
let scan_stats = &scan.stats;
// Files the scan could not classify are potential missed targets, not // Files the scan could not classify are potential missed targets, not
// clean skips: an unreadable directory or a locked il2cpp game assembly must // clean skips: an unreadable directory or a locked il2cpp game assembly must
// fail the run (exit 1) rather than report "0 errors" over a partial scan. // fail the run (exit 1) rather than report "0 errors" over a partial scan.
@@ -453,21 +154,22 @@ pub fn run_folder_opts(
// Verbose mode prints multi-line `[N/9]` step output per file straight to // Verbose mode prints multi-line `[N/9]` step output per file straight to
// stdout; an active progress bar would be clobbered by it, so hide the bar // stdout; an active progress bar would be clobbered by it, so hide the bar
// (its per-file ok/err lines still print) when verbose is on. // (its per-file ok/err lines still print) when verbose is on.
let bar = crate::ui::progress(candidates.len() as u64, quiet >= 1 || verbose); let android_targets = scan.android_so.len() + scan.android_packages.len();
let bar = crate::ui::progress(
(candidates.len() + android_targets) as u64,
quiet >= 1 || verbose,
);
let mut s = Summary { let mut s = Summary {
unpacked: 0,
skipped: scan_stats.skipped, skipped: scan_stats.skipped,
errors: scan_failed, errors: scan_failed,
suspect: 0, ..Summary::default()
metadata: 0,
duration_ms: 0,
}; };
// Silence the default panic hook's stderr spew during per-file processing. // Silence the default panic hook's stderr spew during per-file processing.
let default_hook = std::panic::take_hook(); let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {})); // suppress "thread panicked" messages std::panic::set_hook(Box::new(|_| {})); // suppress "thread panicked" messages
for input in &candidates { for input in candidates {
let rel = rel_in_tree(root, input); let rel = rel_in_tree(root, input);
let dest = out_root.join(out_name(&rel)); let dest = out_root.join(out_name(&rel));
@@ -515,14 +217,146 @@ pub fn run_folder_opts(
bar.inc(1); bar.inc(1);
} }
// Android pass: protected AArch64 libraries and app packages. Loose `.so`
// files restore first so the cross-source dedup keeps them over a copy
// inside a package (loose beats `.apk` beats `.apks`/`.xapk` bundle).
let mut android_seen = std::collections::HashSet::new();
// Hashing a protected library costs a full read, so only pay it when a
// duplicate source can actually exist in this run.
let android_dedup = scan.android_so.len() > 1 || !scan.android_packages.is_empty();
for input in &scan.android_so {
let rel = rel_in_tree(root, input);
let dest = out_root.join(out_name(&rel));
// Unreadable here is fine: the restore reports the same error.
if android_dedup
&& let Ok(identity) = crate::android::file_content_identity(input)
&& !android_seen.insert(identity)
{
s.skipped += 1;
if let Some(log) = &log {
log.step(&format!("SKIP {rel:?}: duplicate of an earlier target"));
}
bar.inc(1);
continue;
}
let input_owned = input.clone();
let dest_owned = dest.clone();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
crate::android::restore_so_file(&input_owned, &dest_owned, verbose_steps)
}));
match result {
Ok(Ok(embedded)) => {
s.unpacked += 1;
crate::ui::ok_label(
&bar,
suppress_file_lines,
&rel.display().to_string(),
"So",
&dest,
);
if let Some(log) = &log {
log.step(&format!("OK {rel:?} -> {dest:?} (Android SO)"));
}
match write_embedded_metadata(embedded, &dest) {
Ok(Some(meta_dest)) => {
s.metadata += 1;
crate::ui::ok_label(
&bar,
suppress_file_lines,
&format!("{} (embedded metadata)", rel.display()),
"metadata",
&meta_dest,
);
if let Some(log) = &log {
log.step(&format!("META {rel:?} (embedded) -> {meta_dest:?}"));
}
}
Ok(None) => {}
Err(e) => {
s.errors += 1;
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
log.step(&format!("ERR {rel:?}: embedded metadata: {e:#}"));
}
}
}
}
Ok(Err(e)) => {
s.errors += 1;
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
log.step(&format!("ERR {rel:?}: {e:#}"));
}
}
Err(panic) => {
s.errors += 1;
let e = anyhow::anyhow!("unexpected panic: {}", panic_payload(&panic));
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
log.step(&format!(
"ERR {rel:?}: panic during restore: {}",
panic_payload(&panic)
));
}
}
}
bar.inc(1);
}
for package in &scan.android_packages {
let rel = rel_in_tree(root, package);
s.packages += 1;
let package_owned = package.clone();
let rel_owned = rel.clone().into_owned();
let out_root_owned = out_root.clone();
let mut seen_taken = std::mem::take(&mut android_seen);
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let outcomes = crate::android::restore_package(
&package_owned,
&rel_owned,
&out_root_owned,
&mut seen_taken,
verbose_steps,
);
(outcomes, seen_taken)
}));
match result {
Ok((Ok(outcomes), seen_back)) => {
android_seen = seen_back;
apply_package_outcomes(outcomes, &mut s, &bar, suppress_file_lines, &log);
}
Ok((Err(e), seen_back)) => {
android_seen = seen_back;
s.errors += 1;
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
log.step(&format!("ERR {rel:?}: {e:#}"));
}
}
Err(panic) => {
// The dedup set may be in an unknown state after a panic; a
// re-scan costs a duplicate restore at worst, never corruption.
let e = anyhow::anyhow!("unexpected panic: {}", panic_payload(&panic));
s.errors += 1;
crate::ui::err(&bar, suppress_file_lines, &rel, &e);
if let Some(log) = &log {
log.step(&format!(
"ERR {rel:?}: panic during package restore: {}",
panic_payload(&panic)
));
}
}
}
bar.inc(1);
}
// il2cpp metadata pass. Crackproof's `-GMD` option obfuscates the method // il2cpp metadata pass. Crackproof's `-GMD` option obfuscates the method
// tokens in `global-metadata.dat`; de-obfuscate any we find so the unpacked // tokens in `global-metadata.dat`; de-obfuscate any we find so the unpacked
// il2cpp game assembly resolves methods instead of indexing its per-module // il2cpp game assembly resolves methods instead of indexing its per-module
// tables out of bounds (see [`senbei_metadata`]). This is additive to the // tables out of bounds (see [`senbei_metadata`]). This is additive to the
// Crackproof module unpack above — the metadata blob is not itself a // Crackproof module unpack above — the metadata blob is not itself a
// Crackproof file. // Crackproof file.
for meta in metas { for meta in metas.iter() {
let rel = rel_in_tree(root, &meta); let rel = rel_in_tree(root, meta);
let dest = out_root.join(out_name(&rel)); let dest = out_root.join(out_name(&rel));
let meta_owned = meta.clone(); let meta_owned = meta.clone();
let dest_owned = dest.clone(); let dest_owned = dest.clone();
@@ -604,10 +438,7 @@ pub fn run_folder_opts(
s.duration_ms = t0.elapsed().as_millis(); s.duration_ms = t0.elapsed().as_millis();
if let Some(log) = &log { if let Some(log) = &log {
log.step(&format!("done in {} ms", s.duration_ms)); log.step(&format!("done in {} ms", s.duration_ms));
log.step(&format!( log.step(&format!("summary: {}", s.line()));
"summary: {} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
s.unpacked, s.skipped, s.errors, s.suspect, s.metadata
));
} }
Ok(s) Ok(s)
} }
@@ -646,23 +477,28 @@ pub fn run_file_v(
let name = out_name(Path::new(input.file_name().unwrap_or_default())); let name = out_name(Path::new(input.file_name().unwrap_or_default()));
let dest = out_root.join(name); let dest = out_root.join(name);
let mut s = Summary { let mut s = Summary::default();
unpacked: 0,
skipped: 0,
errors: 0,
suspect: 0,
metadata: 0,
duration_ms: 0,
};
let is_meta = { let prefix = {
use std::io::Read; use std::io::Read;
let mut buf = [0u8; 4]; let mut buf = vec![0u8; 8 * 1024];
std::fs::File::open(input) match std::fs::File::open(input).and_then(|mut f| f.read(&mut buf).map(|n| (buf, n))) {
.and_then(|mut f| f.read_exact(&mut buf)) Ok((buf, n)) => {
.map(|_| senbei_metadata::is_metadata(&buf)) let mut b = buf;
.unwrap_or(false) b.truncate(n);
b
}
Err(_) => Vec::new(),
}
}; };
let is_meta = senbei_metadata::is_metadata(&prefix);
// Android single-file targets are routed by content: a protected AArch64
// library probe needs the whole file (its payload section is found through
// the section-header table at the end), while a package is a container
// handled entry-by-entry. Anything else falls through to the PE pipeline.
let is_android_so =
crate::android::is_elf64_aarch64(&prefix) && crate::android::is_protected_so_file(input);
let is_android_package = !is_android_so && crate::android::is_app_package(input, &prefix);
if is_meta { if is_meta {
match deobfuscate_metadata_to(input, &dest, verbose && quiet == 0) { match deobfuscate_metadata_to(input, &dest, verbose && quiet == 0) {
@@ -706,6 +542,77 @@ pub fn run_file_v(
} }
} }
} }
} else if is_android_so {
match crate::android::restore_so_file(input, &dest, verbose && quiet == 0) {
Ok(embedded) => {
s.unpacked = 1;
if let Some(log) = &log {
log.step(&format!("OK {:?} -> {:?} (Android SO)", input, dest));
}
if quiet == 0 {
println!("✓ So {} -> {}", input.display(), dest.display());
}
match write_embedded_metadata(embedded, &dest) {
Ok(Some(meta_dest)) => {
s.metadata += 1;
if let Some(log) = &log {
log.step(&format!("META {:?} (embedded) -> {:?}", input, meta_dest));
}
if quiet == 0 {
println!(
"✓ metadata {} (embedded) -> {}",
input.display(),
meta_dest.display()
);
}
}
Ok(None) => {}
Err(e) => {
s.errors += 1;
if let Some(log) = &log {
log.step(&format!("ERR {:?}: embedded metadata: {e:#}", input));
}
if quiet == 0 {
eprintln!("error: embedded metadata: {e:#}");
}
}
}
}
Err(e) => {
s.errors = 1;
if let Some(log) = &log {
log.step(&format!("ERR {:?}: {e:#}", input));
}
if quiet == 0 {
eprintln!("error: {e:#}");
}
}
}
} else if is_android_package {
s.packages = 1;
let rel = PathBuf::from(input.file_name().unwrap_or_default());
let mut seen = std::collections::HashSet::new();
match crate::android::restore_package(
input,
&rel,
&out_root,
&mut seen,
verbose && quiet == 0,
) {
Ok(outcomes) => {
let bar = crate::ui::progress(0, true);
apply_package_outcomes(outcomes, &mut s, &bar, quiet >= 1, &log);
}
Err(e) => {
s.errors = 1;
if let Some(log) = &log {
log.step(&format!("ERR {:?}: {e:#}", input));
}
if quiet == 0 {
eprintln!("error: {e:#}");
}
}
}
} else { } else {
match unpack_one_v(input, &dest, verbose && quiet == 0) { match unpack_one_v(input, &dest, verbose && quiet == 0) {
Ok((kind, report)) => { Ok((kind, report)) => {
@@ -748,10 +655,7 @@ pub fn run_file_v(
s.duration_ms = t0.elapsed().as_millis(); s.duration_ms = t0.elapsed().as_millis();
if let Some(log) = &log { if let Some(log) = &log {
log.step(&format!("done in {} ms", s.duration_ms)); log.step(&format!("done in {} ms", s.duration_ms));
log.step(&format!( log.step(&format!("summary: {}", s.line()));
"summary: {} unpacked · {} skipped · {} errors · {} suspect · {} metadata",
s.unpacked, s.skipped, s.errors, s.suspect, s.metadata
));
} }
Ok(s) Ok(s)
} }
@@ -815,139 +719,6 @@ fn unsupported_version(e: &anyhow::Error) -> Option<u32> {
None None
} }
/// Write `bytes` to `dest` atomically: a sibling temp file, then a rename.
/// A direct `std::fs::write` truncates the destination first, so a mid-write
/// failure (disk full, AV lock, quota) destroys a previously good unpack at
/// the same path; the temp+rename keeps the old file until the new one is
/// complete. Best-effort temp cleanup on failure.
fn write_atomic(dest: &Path, bytes: &[u8]) -> std::io::Result<()> {
let mut tmp_name = dest.as_os_str().to_os_string();
tmp_name.push(".senbei-tmp");
let tmp = PathBuf::from(tmp_name);
let r = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, dest));
if r.is_err() {
let _ = std::fs::remove_file(&tmp);
}
r
}
/// Detect `bytes` and run the right pipeline. Spliced external companions use
/// the EXE pipeline directly because that layout is definitionally EXE-style.
///
/// Routing spliced inputs straight to the EXE pipeline is safe: the
/// companion layout is definitionally the EXE-style shell (the runtime
/// loader maps the companion and runs the standard shell unpack), so the DLL
/// pipeline probe can never be right for it. Output bytes are identical to the
/// DLL-first + EXE-fallback route for every input that route handles.
fn unpack_spliced_or_auto(
bytes: &[u8],
spliced: bool,
force_exe: bool,
verbose: bool,
) -> Result<(unpacker::Kind, Vec<u8>), unpacker::UnpackError> {
if spliced || force_exe {
let detected = unpacker::detect(bytes).ok_or(unpacker::UnpackError::NotCrackproof)?;
let out = unpacker::unpack_exe_v(bytes, verbose)?;
return Ok((detected.kind, out));
}
unpacker::unpack_auto_v(bytes, verbose)
}
/// Unpack a single file to `dest`. Returns the Kind and integrity report on success.
pub fn unpack_one(
input: &Path,
dest: &Path,
) -> anyhow::Result<(unpacker::Kind, unpacker::IntegrityReport)> {
unpack_one_v(input, dest, false)
}
/// Outcome of a byte-level unpack ([`unpack_bytes`]): the image, its detected
/// kind, and its integrity report. No file I/O is involved.
pub struct UnpackedImage {
pub kind: unpacker::Kind,
pub bytes: Vec<u8>,
pub integrity: unpacker::IntegrityReport,
/// True when the input was reconstructed from an external companion (the
/// `._` layout), i.e. the export/TLS overlays ran.
pub companion: bool,
}
/// Unpack in-memory `input` bytes, optionally paired with an external
/// companion payload `companion` (the `<input>._` file's contents).
///
/// This is the in-memory counterpart of [`unpack_one_v`]: splice a matching
/// companion, unpack, overlay the export table and TLS directory from the stub,
/// then run the static integrity check.
pub fn unpack_bytes(
input: &[u8],
companion: Option<&[u8]>,
) -> Result<UnpackedImage, unpacker::UnpackError> {
unpack_bytes_impl(input, companion, false)
}
/// Like [`unpack_bytes`], but forces the EXE pipeline (no DLL-pipeline
/// probe). This is the web app's recovery path: the DLL-first probe relies
/// on `catch_unwind` to reject EXE-shell-layout DLLs, and panics cannot be
/// caught on wasm — the probe traps the whole call. The web app runs each
/// unpack in a disposable Web Worker and retries trapped DLLs with this
/// entry point, reproducing the CLI's dll-first/exe-fallback routing.
pub fn unpack_bytes_force_exe(
input: &[u8],
companion: Option<&[u8]>,
) -> Result<UnpackedImage, unpacker::UnpackError> {
unpack_bytes_impl(input, companion, true)
}
fn unpack_bytes_impl(
input: &[u8],
companion: Option<&[u8]>,
force_exe: bool,
) -> Result<UnpackedImage, unpacker::UnpackError> {
let spliced = companion.and_then(|c| splice_companion(input, c));
let bytes: &[u8] = spliced.as_deref().unwrap_or(input);
let (kind, mut out) = unpack_spliced_or_auto(bytes, spliced.is_some(), force_exe, false)?;
if spliced.is_some() {
overlay_exports_from_stub(&mut out, input);
restore_tls_from_stub(&mut out, input);
}
let integrity = unpacker::check_integrity(&out);
Ok(UnpackedImage {
kind,
bytes: out,
integrity,
companion: spliced.is_some(),
})
}
/// Like [`unpack_one`], but prints detailed `[N/9]` step progress (and a final
/// `Write to <dest>` line) to stdout when `verbose` is true.
pub fn unpack_one_v(
input: &Path,
dest: &Path,
verbose: bool,
) -> anyhow::Result<(unpacker::Kind, unpacker::IntegrityReport)> {
let UnpackerInput { bytes, stub } = read_unpacker_input(input)?;
let (kind, mut out) = unpack_spliced_or_auto(&bytes, stub.is_some(), false, verbose)?;
// External-companion layout: restore the export table from the stub, which
// the encrypted companion does not carry (the loader rebuilds it at runtime).
if let Some(stub) = stub {
overlay_exports_from_stub(&mut out, &stub);
// ...and the TLS directory, which Crackproof strips from the payload and
// re-installs at runtime; the ordinary loader needs it or thread_local
// access crashes (see [`restore_tls_from_stub`]).
restore_tls_from_stub(&mut out, &stub);
}
let report = unpacker::check_integrity(&out);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
write_atomic(dest, &out)?;
if verbose {
println!("Write to {}", dest.display());
}
Ok((kind, report))
}
/// De-obfuscate an il2cpp `global-metadata.dat` to `dest`. /// De-obfuscate an il2cpp `global-metadata.dat` to `dest`.
/// ///
/// Crackproof's `-GMD` option scrambles each `Il2CppMethodDefinition`'s token /// Crackproof's `-GMD` option scrambles each `Il2CppMethodDefinition`'s token
@@ -966,10 +737,13 @@ pub fn deobfuscate_metadata_to(
verbose: bool, verbose: bool,
) -> anyhow::Result<senbei_metadata::Report> { ) -> anyhow::Result<senbei_metadata::Report> {
let data = std::fs::read(input)?; let data = std::fs::read(input)?;
// Preserve the metadata::Error in the chain (rather than stringifying it) // The Android seeded-permutation variant is tried first (it validates
// so the folder driver can apply its unsupported-version policy. // every restored RID); the structural remap is the fallback and the
let (out, report) = senbei_metadata::deobfuscate(&data) // Windows path. The [`senbei_metadata::Error`] is preserved in the chain
.map_err(|e| anyhow::Error::new(e).context(format!("{input:?}")))?; // (rather than stringified) so the folder driver can apply its
// unsupported-version policy.
let (out, report) = crate::android::restore_metadata_bytes(&data)
.map_err(|e| e.context(format!("{input:?}")))?;
if report.remapped > 0 { if report.remapped > 0 {
if let Some(parent) = dest.parent() { if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?; std::fs::create_dir_all(parent)?;
@@ -982,6 +756,77 @@ pub fn deobfuscate_metadata_to(
Ok(report) Ok(report)
} }
/// Write an embedded metadata blob (unwrapped from a restored Android
/// library) next to the restored library. Returns the destination when a
/// blob was written.
fn write_embedded_metadata(
embedded: Option<Vec<u8>>,
so_dest: &Path,
) -> anyhow::Result<Option<PathBuf>> {
let Some(blob) = embedded else {
return Ok(None);
};
let dest = crate::android::embedded_metadata_dest(so_dest);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
write_atomic(&dest, &blob)?;
Ok(Some(dest))
}
/// Fold one package's per-entry outcomes into the run summary, UI, and log.
fn apply_package_outcomes(
outcomes: Vec<crate::android::EntryOutcome>,
s: &mut Summary,
bar: &indicatif::ProgressBar,
quiet: bool,
log: &Option<crate::logfile::Log>,
) {
use crate::android::{EntryKind, EntryStatus};
for outcome in outcomes {
match outcome.status {
EntryStatus::Restored => {
match outcome.kind {
EntryKind::So => {
s.unpacked += 1;
crate::ui::ok_label(bar, quiet, &outcome.label, "So", &outcome.dest);
}
EntryKind::Metadata { remapped } => {
s.metadata += 1;
crate::ui::metadata(
bar,
quiet,
Path::new(&outcome.label),
remapped,
&outcome.dest,
);
}
EntryKind::EmbeddedMetadata => {
s.metadata += 1;
crate::ui::ok_label(bar, quiet, &outcome.label, "metadata", &outcome.dest);
}
}
if let Some(log) = log {
log.step(&format!("OK {} -> {:?}", outcome.label, outcome.dest));
}
}
EntryStatus::Duplicate | EntryStatus::NotTarget | EntryStatus::Unchanged => {
s.skipped += 1;
if let Some(log) = log {
log.step(&format!("SKIP {} ({:?})", outcome.label, outcome.kind));
}
}
EntryStatus::Failed(e) => {
s.errors += 1;
crate::ui::err(bar, quiet, Path::new(&outcome.label), &e);
if let Some(log) = log {
log.step(&format!("ERR {}: {e:#}", outcome.label));
}
}
}
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -1002,44 +847,4 @@ mod tests {
let rel = rel_in_tree(root, under); let rel = rel_in_tree(root, under);
assert_eq!(rel.as_ref(), Path::new(r"bin\app.exe")); assert_eq!(rel.as_ref(), Path::new(r"bin\app.exe"));
} }
fn stub_with_header(header: &[u8; 32], extra: usize) -> Vec<u8> {
let mut s = vec![0u8; HEADER_OFF];
s.extend_from_slice(header);
s.extend_from_slice(&vec![0xAAu8; extra]);
s
}
#[test]
fn splices_when_header_matches() {
let header = [7u8; 32];
let stub = stub_with_header(&header, 16);
// Companion: same 32-byte header, then the real (longer) payload.
let mut comp = header.to_vec();
comp.extend_from_slice(&[0x42u8; 1000]);
let out = splice_companion(&stub, &comp).expect("should splice");
assert_eq!(out.len(), HEADER_OFF + comp.len());
assert_eq!(&out[..HEADER_OFF], &stub[..HEADER_OFF]);
assert_eq!(&out[HEADER_OFF..], &comp[..]);
}
#[test]
fn no_splice_when_header_differs() {
let stub = stub_with_header(&[7u8; 32], 16);
let mut comp = vec![9u8; 32]; // different header
comp.extend_from_slice(&[0x42u8; 1000]);
assert!(splice_companion(&stub, &comp).is_none());
}
#[test]
fn no_splice_when_too_short() {
let short_stub = vec![0u8; HEADER_OFF + 8]; // < HEADER_OFF + 32
let comp = vec![0u8; 64];
assert!(splice_companion(&short_stub, &comp).is_none());
let stub = stub_with_header(&[1u8; 32], 0);
let short_comp = vec![1u8; 16]; // < 32
assert!(splice_companion(&stub, &short_comp).is_none());
}
} }
+6
View File
@@ -1,7 +1,13 @@
//! Filesystem and command-line orchestration. //! Filesystem and command-line orchestration.
/// File name of an IL2CPP metadata blob shared by both platform scanners.
pub const METADATA_FILE_NAME: &str = "global-metadata.dat";
pub mod android;
mod atomic;
pub mod job; pub mod job;
pub mod logfile; pub mod logfile;
pub mod pause; pub mod pause;
pub mod scan; pub mod scan;
pub mod ui; pub mod ui;
pub mod windows;
+159 -185
View File
@@ -1,4 +1,4 @@
use senbei_pe::detect; use senbei_engine::detect;
use std::io::Read; use std::io::Read;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use walkdir::WalkDir; use walkdir::WalkDir;
@@ -16,7 +16,7 @@ const DETECT_PREFIX: u64 = 8 * 1024;
/// Smallest file that can possibly be a target, so anything shorter is skipped /// Smallest file that can possibly be a target, so anything shorter is skipped
/// without ever being opened. /// without ever being opened.
/// ///
/// A Crackproof module needs ≥ 4128 bytes for [`senbei_pe::detect`]'s key /// A Crackproof module needs ≥ 4128 bytes for [`senbei_engine::detect`]'s key
/// table (it reads the dword at 4124), so the bound is exact for the unpack /// table (it reads the dword at 4124), so the bound is exact for the unpack
/// path. An il2cpp `global-metadata.dat` only needs 4 bytes to match its magic, /// path. An il2cpp `global-metadata.dat` only needs 4 bytes to match its magic,
/// but its header alone runs to offset 0xB0 and the images/types/methods tables /// but its header alone runs to offset 0xB0 and the images/types/methods tables
@@ -25,85 +25,10 @@ const DETECT_PREFIX: u64 = 8 * 1024;
/// processable is lost. /// processable is lost.
const MIN_SIZE: u64 = 4128; const MIN_SIZE: u64 = 4128;
/// File extensions that are bulk data by construction and can never be a PE fn is_metadata_name(path: &Path) -> bool {
/// image or an il2cpp metadata blob. path.file_name()
/// .and_then(|name| name.to_str())
/// This is deliberately a **deny**-list, not an executable allow-list: unknown .is_some_and(|name| name.eq_ignore_ascii_case(crate::METADATA_FILE_NAME))
/// extensions are still probed. Extensionless files are handled separately by
/// [`denied_name`] because asset stores commonly contain tens of thousands of
/// extensionless chunks; exhaustive probing remains available through
/// `--scan-all`.
///
/// Set `SENBEI_SCAN_ALL=1` (or pass `--scan-all`) to probe every file regardless.
const DENY_EXT: &[&str] = &[
// Unity and other engine asset containers
"ab",
"bundle",
"unity3d",
"manifest",
"resource",
"ress",
"assets",
"sharedassets",
// audio / video / image / font
"acb",
"awb",
"usm",
"wav",
"ogg",
"mp3",
"mp4",
"avi",
"png",
"jpg",
"jpeg",
"bmp",
"gif",
"tga",
"dds",
"svg",
"ttf",
"otf",
// text, markup, config, logs
"xml",
"json",
"txt",
"csv",
"md",
"toml",
"ini",
"yml",
"yaml",
"log",
"html",
"htm",
"css",
"aspx",
"browser",
"config",
"sig",
"map",
"pdb",
// rhythm-game chart/score data
"ma2",
"sr",
];
/// Whether `path` can be skipped from its name alone. Extensionless files and
/// files whose extension is on [`DENY_EXT`] are not opened during a default
/// scan. `--scan-all` remains available when exhaustive probing is required.
fn denied_name(path: &Path) -> bool {
let Some(ext) = path.extension() else {
return true;
};
let Some(ext) = ext.to_str() else {
return false;
};
// Extensions are ASCII in practice; compare case-insensitively without
// allocating for the overwhelmingly common non-match.
DENY_EXT
.iter()
.any(|d| d.len() == ext.len() && d.eq_ignore_ascii_case(ext))
} }
/// Content classification of a single file. /// Content classification of a single file.
@@ -115,6 +40,25 @@ enum Class {
Crackproof, Crackproof,
/// An il2cpp `global-metadata.dat` (de-obfuscation target). /// An il2cpp `global-metadata.dat` (de-obfuscation target).
Metadata, Metadata,
/// A protected AArch64 shared library (Android restore target).
AndroidSo,
/// An Android app package (`.apk`/`.apks`/`.xapk`) — a container whose
/// entries are content-probed individually during the Android pass.
AndroidPackage,
}
/// Everything one [`find_targets_opts`] walk found, plus non-target tallies.
#[derive(Default)]
pub struct ScanResult {
/// Crackproof-protected PE files.
pub crackproof: Vec<PathBuf>,
/// il2cpp `global-metadata.dat` blobs.
pub metadata: Vec<PathBuf>,
/// Protected AArch64 shared libraries.
pub android_so: Vec<PathBuf>,
/// Android app packages (containers restored entry-by-entry).
pub android_packages: Vec<PathBuf>,
pub stats: ScanStats,
} }
/// Walk `root` recursively (skipping any directory literally named `"unpack"`) /// Walk `root` recursively (skipping any directory literally named `"unpack"`)
@@ -132,21 +76,19 @@ enum Class {
/// per-file I/O latency, not bandwidth (that tree lives on a user-mode virtual /// per-file I/O latency, not bandwidth (that tree lives on a user-mode virtual
/// disk that tops out near 1,300 IOPS). Thread count barely moves it either. /// disk that tops out near 1,300 IOPS). Thread count barely moves it either.
/// ///
/// So the only lever is **probing fewer files**, which is what [`MIN_SIZE`] and /// So the only lever is **probing fewer files**, which is what the target-name
/// [`DENY_EXT`] do — both decided from the free directory metadata, before any /// filter and [`MIN_SIZE`] do — both decided before any file is opened.
/// file is opened. On that tree they cut 46,446 probes to 1,814 and the scan
/// from ~40 s to ~2 s while still finding every target.
/// ///
/// The surviving probes (open + short read + magic test) are fanned out across /// The selected probes (open + short read + magic test) are fanned out across
/// worker threads. Directory traversal itself stays serial (one cheap `readdir` /// worker threads. Directory traversal itself stays serial because it only
/// pass, no file opens) because it feeds the parallel probe. /// collects names and sizes before the parallel probe.
/// ///
/// Thread count follows [`crate::unpacker::parallel::thread_cap`] (honoring /// Thread count follows [`senbei_engine::thread_cap`] (honoring
/// `SENBEI_THREADS`, `1` = fully sequential). Output order is independent of /// `SENBEI_THREADS`, `1` = fully sequential). Output order is independent of
/// thread count: each worker owns a disjoint contiguous slice of the path list /// thread count: each worker owns a disjoint contiguous slice of the path list
/// and writes the matching disjoint slice of the class list, so results are /// and writes the matching disjoint slice of the class list, so results are
/// deterministic. /// deterministic.
pub fn find_targets(root: &Path) -> (Vec<PathBuf>, Vec<PathBuf>, ScanStats) { pub fn find_targets(root: &Path) -> ScanResult {
find_targets_opts(root, scan_all_env()) find_targets_opts(root, scan_all_env())
} }
@@ -167,9 +109,8 @@ pub struct ScanStats {
} }
/// [`find_targets`], but with the pre-filter explicitly controlled. When /// [`find_targets`], but with the pre-filter explicitly controlled. When
/// `scan_all` is true every regular file is probed, restoring the exhaustive /// `scan_all` is true selected target names below [`MIN_SIZE`] are also probed.
/// (and on asset-heavy trees, far slower) behavior. pub fn find_targets_opts(root: &Path, scan_all: bool) -> ScanResult {
pub fn find_targets_opts(root: &Path, scan_all: bool) -> (Vec<PathBuf>, Vec<PathBuf>, ScanStats) {
// Phase 1: serial traversal collecting regular-file paths only. No file is // Phase 1: serial traversal collecting regular-file paths only. No file is
// opened here; `readdir` is fast relative to the content probe that follows, // opened here; `readdir` is fast relative to the content probe that follows,
// and `entry.metadata()` is served from the directory entry on Windows, so // and `entry.metadata()` is served from the directory entry on Windows, so
@@ -193,7 +134,7 @@ pub fn find_targets_opts(root: &Path, scan_all: bool) -> (Vec<PathBuf>, Vec<Path
// Skip reparse-point directories (junctions, symlink-dirs): they point // Skip reparse-point directories (junctions, symlink-dirs): they point
// outside the scanned tree — walking one would silently unpack an // outside the scanned tree — walking one would silently unpack an
// entire foreign tree (e.g. a `samples` junction into the golden corpus). // entire foreign tree (e.g. a `samples` junction into the golden corpus).
!is_reparse_point(e) !crate::windows::is_reparse_point(e)
}) { }) {
let entry = match entry { let entry = match entry {
Ok(e) => e, Ok(e) => e,
@@ -205,12 +146,17 @@ pub fn find_targets_opts(root: &Path, scan_all: bool) -> (Vec<PathBuf>, Vec<Path
if !entry.file_type().is_file() { if !entry.file_type().is_file() {
continue; continue;
} }
if crate::windows::is_companion(entry.path()) {
continue;
}
if !is_metadata_name(entry.path())
&& !crate::windows::is_pe_extension(entry.path())
&& !crate::android::is_so_name(entry.path())
&& !crate::android::is_package_name(entry.path())
{
continue;
}
if !scan_all { if !scan_all {
// Name checks come first so extensionless asset chunks never
// trigger even an explicit metadata query.
if denied_name(entry.path()) {
continue;
}
// Skip on directory metadata alone — never open these. // Skip on directory metadata alone — never open these.
let too_small = entry let too_small = entry
.metadata() .metadata()
@@ -228,7 +174,7 @@ pub fn find_targets_opts(root: &Path, scan_all: bool) -> (Vec<PathBuf>, Vec<Path
// `Some(Class::None)` means "probed, matched neither detector". // `Some(Class::None)` means "probed, matched neither detector".
let n = paths.len(); let n = paths.len();
let mut class: Vec<Option<Class>> = vec![Some(Class::None); n]; let mut class: Vec<Option<Class>> = vec![Some(Class::None); n];
let workers = senbei_pe::thread_cap().clamp(1, n.max(1)); let workers = senbei_engine::thread_cap().clamp(1, n.max(1));
if workers <= 1 { if workers <= 1 {
for (p, c) in paths.iter().zip(class.iter_mut()) { for (p, c) in paths.iter().zip(class.iter_mut()) {
*c = classify(p); *c = classify(p);
@@ -246,44 +192,28 @@ pub fn find_targets_opts(root: &Path, scan_all: bool) -> (Vec<PathBuf>, Vec<Path
}); });
} }
let mut candidates = Vec::new(); let mut result = ScanResult {
let mut metadata = Vec::new(); stats,
..ScanResult::default()
};
for (p, c) in paths.into_iter().zip(class) { for (p, c) in paths.into_iter().zip(class) {
match c { match c {
Some(Class::Crackproof) => candidates.push(p), Some(Class::Crackproof) => result.crackproof.push(p),
Some(Class::Metadata) => metadata.push(p), Some(Class::Metadata) => result.metadata.push(p),
Some(Class::None) => stats.skipped += 1, Some(Class::AndroidSo) => result.android_so.push(p),
Some(Class::AndroidPackage) => result.android_packages.push(p),
Some(Class::None) => result.stats.skipped += 1,
// Unreadable / panicking probe: NOT skipped — the scan could not // Unreadable / panicking probe: NOT skipped — the scan could not
// classify it, so it may be a target we failed to unpack. // classify it, so it may be a target we failed to unpack.
None => stats.probe_errors += 1, None => result.stats.probe_errors += 1,
} }
} }
(candidates, metadata, stats) result
} }
/// True if a walked directory entry is a reparse point (junction or symlink). /// Whether the size pre-filter is disabled via `SENBEI_SCAN_ALL`. Any value
/// /// other than `0`/empty enables probing small selected target names. It never
/// `DirEntry::file_type` only flags true symlinks; NTFS junctions report as /// expands the platform filename boundary.
/// ordinary directories, so without this check the walker descends into them.
/// Off-Windows there are no junctions — symlink dirs are already excluded
/// because `follow_links` is off (their `file_type().is_dir()` is false).
#[cfg(windows)]
fn is_reparse_point(e: &walkdir::DirEntry) -> bool {
use std::os::windows::fs::MetadataExt;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
e.metadata()
.map(|m| m.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0)
.unwrap_or(false)
}
#[cfg(not(windows))]
fn is_reparse_point(_e: &walkdir::DirEntry) -> bool {
false
}
/// Whether the scan pre-filter is disabled via `SENBEI_SCAN_ALL`. Any value
/// other than `0`/empty turns exhaustive scanning on. The `--scan-all` flag is
/// ORed with this.
pub fn scan_all_env() -> bool { pub fn scan_all_env() -> bool {
match std::env::var("SENBEI_SCAN_ALL") { match std::env::var("SENBEI_SCAN_ALL") {
Ok(v) => !matches!(v.trim(), "" | "0"), Ok(v) => !matches!(v.trim(), "" | "0"),
@@ -291,11 +221,11 @@ pub fn scan_all_env() -> bool {
} }
} }
/// Classify one file by content. Reads a short prefix once and tests the /// Classify one named candidate by content. Reads a short prefix once and tests
/// Crackproof detector first, then the il2cpp metadata magic. Returns `None` /// the detector for that platform. Returns `None` when the file could not be classified at
/// when the file could not be classified at all — an I/O error opening it /// all — an I/O error opening it (locked, permissions) or a panic inside a
/// (locked, permissions) or a panic inside a detector — so the caller counts /// detector — so the caller counts it as a probe error rather than a clean
/// it as a probe error rather than a clean "not a target" skip. /// "not a target" skip.
/// ///
/// The detector is wrapped in `catch_unwind` because a panic in a scan worker /// The detector is wrapped in `catch_unwind` because a panic in a scan worker
/// thread would otherwise abort the whole folder run (a scoped-thread panic /// thread would otherwise abort the whole folder run (a scoped-thread panic
@@ -304,16 +234,30 @@ pub fn scan_all_env() -> bool {
/// ///
/// A Crackproof PE never matches the metadata magic (it is a PE, not a /// A Crackproof PE never matches the metadata magic (it is a PE, not a
/// metadata blob) and vice versa, so the order is immaterial. /// metadata blob) and vice versa, so the order is immaterial.
///
/// The Android library probe needs more than the prefix: the protection
/// payload lives in a section found via the section-header table at the *end*
/// of the file, so an ELF64/AArch64 prefix triggers a full-file read. Only
/// selected `.so` images pay for it.
fn classify(path: &Path) -> Option<Class> { fn classify(path: &Path) -> Option<Class> {
let head = read_prefix(path, DETECT_PREFIX)?; let head = read_prefix(path, DETECT_PREFIX)?;
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
if detect(&head).is_some() { if crate::android::is_package_name(path) && crate::android::is_app_package(path, &head) {
Class::Crackproof return Class::AndroidPackage;
} else if senbei_metadata::is_metadata(&head) {
Class::Metadata
} else {
Class::None
} }
if is_metadata_name(path) && senbei_metadata::is_metadata(&head) {
return Class::Metadata;
}
if crate::windows::is_pe_extension(path) && detect(&head).is_some() {
return Class::Crackproof;
}
if crate::android::is_so_name(path)
&& crate::android::is_elf64_aarch64(&head)
&& crate::android::is_protected_so_file(path)
{
return Class::AndroidSo;
}
Class::None
})); }));
r.ok() r.ok()
} }
@@ -332,55 +276,56 @@ mod tests {
use super::*; use super::*;
#[test] #[test]
fn denies_bulk_asset_extensions_case_insensitively() { fn candidate_names_are_platform_specific() {
for p in ["a.ab", "a.XML", "a.Acb", "a.ma2", "a.manifest", "a.PNG"] { for p in [
assert!(denied_name(Path::new(p)), "{p} should be denied"); "daemon.exe",
"GameLib.DLL",
"libil2cpp.so",
"global-metadata.dat",
] {
assert!(
is_metadata_name(Path::new(p))
|| crate::windows::is_pe_extension(Path::new(p))
|| crate::android::is_so_name(Path::new(p)),
"{p} should be a candidate"
);
} }
}
#[test]
fn denies_extensionless_files() {
for p in ["asset", "level0", "0123456789abcdef"] {
assert!(denied_name(Path::new(p)), "{p} should be denied");
}
}
#[test]
fn never_denies_what_a_target_can_be_named() {
// Unknown extensions must still be probed. This keeps the filter a
// narrow deny-list rather than an executable-extension allow-list.
for p in [ for p in [
"app.exe.bak", "app.exe.bak",
"managed.dll.bak", "managed.dll.bak",
"daemon.exe", "libil2cpp.so.bak",
"GameLib.dll", "global-metadata.bin",
"global-metadata.dat", "asset",
"a.so", "a.ab",
"a.bin",
] { ] {
assert!(!denied_name(Path::new(p)), "{p} must still be probed"); assert!(
!is_metadata_name(Path::new(p))
&& !crate::windows::is_pe_extension(Path::new(p))
&& !crate::android::is_so_name(Path::new(p)),
"{p} must not be a candidate"
);
} }
} }
#[test] #[test]
fn extensionless_targets_require_exhaustive_scan() { fn extensionless_targets_are_not_candidates() {
let td = tempfile::tempdir().unwrap(); let td = tempfile::tempdir().unwrap();
let root = td.path(); let root = td.path();
let mut blob = vec![0u8; MIN_SIZE as usize + 1]; let mut blob = vec![0u8; MIN_SIZE as usize + 1];
blob[..4].copy_from_slice(&0xFAB1_1BAFu32.to_le_bytes()); blob[..4].copy_from_slice(&0xFAB1_1BAFu32.to_le_bytes());
std::fs::write(root.join("metadata"), &blob).unwrap(); std::fs::write(root.join("metadata"), &blob).unwrap();
let (_, filtered, _) = find_targets_opts(root, false); let filtered = find_targets_opts(root, false);
assert!(filtered.is_empty()); assert!(filtered.metadata.is_empty());
let (_, exhaustive, _) = find_targets_opts(root, true); let exhaustive = find_targets_opts(root, true);
assert_eq!(exhaustive.len(), 1); assert!(exhaustive.metadata.is_empty());
} }
/// A file below the Crackproof key-table bound is skipped without being /// A selected file below the Crackproof key-table bound is skipped without
/// opened, but a large non-asset file is still probed. /// being opened, while `scan_all` probes it.
#[test] #[test]
fn prefilter_skips_small_and_denied_files_only() { fn prefilter_skips_small_selected_files_only() {
let td = tempfile::tempdir().unwrap(); let td = tempfile::tempdir().unwrap();
let root = td.path(); let root = td.path();
std::fs::write(root.join("tiny.dll"), vec![0u8; 100]).unwrap(); std::fs::write(root.join("tiny.dll"), vec![0u8; 100]).unwrap();
@@ -388,15 +333,15 @@ mod tests {
std::fs::write(root.join("plain.dll"), vec![0u8; 100_000]).unwrap(); std::fs::write(root.join("plain.dll"), vec![0u8; 100_000]).unwrap();
// None of them are Crackproof, so both modes find nothing; the point is // None of them are Crackproof, so both modes find nothing; the point is
// that the filtered walk does not panic and honors `scan_all`. // that only the selected names are considered and `scan_all` controls
let (c, m, _) = find_targets_opts(root, false); // the size floor.
assert!(c.is_empty() && m.is_empty()); let scan = find_targets_opts(root, false);
let (c, m, _) = find_targets_opts(root, true); assert!(scan.crackproof.is_empty() && scan.metadata.is_empty());
assert!(c.is_empty() && m.is_empty()); let scan = find_targets_opts(root, true);
assert!(scan.crackproof.is_empty() && scan.metadata.is_empty());
} }
/// An il2cpp metadata blob is found by the filtered scan: `.dat` is not on /// An exact `global-metadata.dat` name is found by the filtered scan.
/// the deny-list and a real one is far above `MIN_SIZE`.
#[test] #[test]
fn finds_metadata_through_the_prefilter() { fn finds_metadata_through_the_prefilter() {
let td = tempfile::tempdir().unwrap(); let td = tempfile::tempdir().unwrap();
@@ -407,9 +352,9 @@ mod tests {
// Same magic but too small to be processable — skipped by the size floor. // Same magic but too small to be processable — skipped by the size floor.
std::fs::write(root.join("stub.dat"), &blob[..64]).unwrap(); std::fs::write(root.join("stub.dat"), &blob[..64]).unwrap();
let (_, m, _) = find_targets_opts(root, false); let scan = find_targets_opts(root, false);
assert_eq!(m.len(), 1); assert_eq!(scan.metadata.len(), 1);
assert!(m[0].ends_with("global-metadata.dat")); assert!(scan.metadata[0].ends_with("global-metadata.dat"));
} }
/// Review regression: a previous output tree is pruned case-insensitively /// Review regression: a previous output tree is pruned case-insensitively
@@ -428,12 +373,41 @@ mod tests {
// A big non-target file at the root: probed, then skipped. // A big non-target file at the root: probed, then skipped.
std::fs::write(root.join("plain.dll"), vec![0u8; 100_000]).unwrap(); std::fs::write(root.join("plain.dll"), vec![0u8; 100_000]).unwrap();
let (c, m, stats) = find_targets_opts(root, false); let scan = find_targets_opts(root, false);
assert!( assert!(
c.is_empty() && m.is_empty(), scan.crackproof.is_empty() && scan.metadata.is_empty(),
"old output tree must be pruned" "old output tree must be pruned"
); );
assert_eq!(stats.skipped, 1, "the probed non-target counts as skipped"); assert_eq!(
assert_eq!(stats.walk_errors, 0); scan.stats.skipped, 1,
"the probed non-target counts as skipped"
);
assert_eq!(scan.stats.walk_errors, 0);
}
#[test]
fn companion_payload_is_not_counted_as_skipped() {
let td = tempfile::tempdir().unwrap();
let root = td.path();
std::fs::write(root.join("app.exe"), vec![0u8; MIN_SIZE as usize]).unwrap();
std::fs::write(root.join("app.exe._"), vec![0u8; MIN_SIZE as usize]).unwrap();
let scan = find_targets_opts(root, false);
assert_eq!(scan.stats.skipped, 1, "only the stub was probed");
assert!(crate::windows::is_companion(&root.join("app.exe._")));
}
#[test]
fn scan_all_keeps_the_platform_name_boundary() {
let td = tempfile::tempdir().unwrap();
let root = td.path();
let mut metadata = vec![0_u8; MIN_SIZE as usize];
metadata[..4].copy_from_slice(&0xFAB1_1BAFu32.to_le_bytes());
std::fs::write(root.join("renamed.bin"), &metadata).unwrap();
std::fs::write(root.join("global-metadata.dat"), &metadata).unwrap();
let scan = find_targets_opts(root, true);
assert_eq!(scan.metadata.len(), 1);
assert!(scan.metadata[0].ends_with("global-metadata.dat"));
} }
} }
+14 -8
View File
@@ -1,6 +1,6 @@
use indicatif::{ProgressBar, ProgressStyle}; use indicatif::{ProgressBar, ProgressStyle};
use owo_colors::OwoColorize; use owo_colors::OwoColorize;
use senbei_pe::{IntegrityReport, Kind}; use senbei_engine::{IntegrityReport, Kind};
use std::path::Path; use std::path::Path;
/// Create a progress bar for `n` items. Hidden when `quiet` is true. /// Create a progress bar for `n` items. Hidden when `quiet` is true.
@@ -19,16 +19,22 @@ pub fn progress(n: u64, quiet: bool) -> ProgressBar {
/// Print a green success line, suspending the progress bar. /// Print a green success line, suspending the progress bar.
pub fn ok(bar: &ProgressBar, quiet: bool, rel: &Path, kind: Kind, dest: &Path) { pub fn ok(bar: &ProgressBar, quiet: bool, rel: &Path, kind: Kind, dest: &Path) {
ok_label(
bar,
quiet,
&rel.display().to_string(),
&format!("{kind:?}"),
dest,
);
}
/// Print a green success line with a free-form kind label (Android targets),
/// suspending the progress bar.
pub fn ok_label(bar: &ProgressBar, quiet: bool, rel: &str, label: &str, dest: &Path) {
if quiet { if quiet {
return; return;
} }
let msg = format!( let msg = format!("{} {} {} -> {}", "".green(), label, rel, dest.display());
"{} {:?} {} -> {}",
"".green(),
kind,
rel.display(),
dest.display()
);
bar.suspend(|| println!("{msg}")); bar.suspend(|| println!("{msg}"));
} }
+677
View File
@@ -0,0 +1,677 @@
//! Windows filesystem adapter for PE companion payloads and byte APIs.
use senbei_engine as unpacker;
use std::path::Path;
use crate::atomic::write_atomic;
pub(crate) fn is_pe_extension(path: &Path) -> bool {
path.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| ext.eq_ignore_ascii_case("exe") || ext.eq_ignore_ascii_case("dll"))
}
pub(crate) fn is_companion(path: &Path) -> bool {
let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
return false;
};
let Some(stub_name) = name.strip_suffix("._") else {
return false;
};
is_pe_extension(Path::new(stub_name))
}
/// Return whether a directory entry is an NTFS reparse point. The scanner keeps
/// this host-specific check in the Windows adapter while the traversal itself
/// remains platform-neutral.
#[cfg(windows)]
pub(crate) fn is_reparse_point(entry: &walkdir::DirEntry) -> bool {
use std::os::windows::fs::MetadataExt;
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
entry
.metadata()
.map(|metadata| metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0)
.unwrap_or(false)
}
#[cfg(not(windows))]
pub(crate) fn is_reparse_point(_entry: &walkdir::DirEntry) -> bool {
false
}
/// Crackproof header key table lives at this fixed file offset. For the
/// external-companion layout, the companion payload aligns to the stub here.
const HEADER_OFF: usize = 4096;
/// Build the unpacker input for `input`, transparently handling the
/// **external-companion** layout used by some il2cpp games.
///
/// In that layout a protected module is split into a thin on-disk loader stub
/// (`Foo.dll`, whose code sections are stripped to one page) plus an encrypted
/// `Foo.dll._` companion holding the real payload. The companion is byte-for-byte
/// the stub's payload region starting at the Crackproof header (offset 4096), so
/// `stub[..4096] ++ companion` reconstructs the ordinary embedded-payload file
/// the existing pipelines already unpack. The runtime loader does exactly this:
/// it maps `Foo.dll._` and feeds it through the standard Crackproof unpack.
///
/// The splice fires only when a sibling `<input>._` exists *and* its first 32
/// bytes equal the stub's header at offset 4096 — a precise signal that the
/// companion is this stub's payload. Otherwise the file is returned untouched,
/// so normal (embedded-payload) inputs are unaffected.
pub(crate) fn read_unpacker_input(input: &Path) -> std::io::Result<UnpackerInput> {
let stub = std::fs::read(input)?;
// Companion path: append "._" to the full file name (Foo.dll -> Foo.dll._).
let companion = match input.file_name() {
Some(name) => {
let mut n = name.to_os_string();
n.push("._");
input.with_file_name(n)
}
None => {
return Ok(UnpackerInput {
bytes: stub,
stub: None,
});
}
};
if !companion.is_file() {
return Ok(UnpackerInput {
bytes: stub,
stub: None,
});
}
let comp = std::fs::read(&companion)?;
match splice_companion(&stub, &comp) {
// A splice fired: keep the stub so its plaintext export table can be
// overlaid onto the unpacked image (the companion does not carry it).
Some(spliced) => Ok(UnpackerInput {
bytes: spliced,
stub: Some(stub),
}),
None => Ok(UnpackerInput {
bytes: stub,
stub: None,
}),
}
}
/// The bytes fed to the unpacker, plus the original loader stub when the input
/// was reconstructed from an external companion. The stub is retained because
/// the crackproof loader rebuilds the PE export table at runtime from data kept
/// in the stub — that table is *not* present in the encrypted companion, so the
/// unpacked image needs it overlaid from the stub afterwards
/// (see [`overlay_exports_from_stub`]).
pub(crate) struct UnpackerInput {
pub(crate) bytes: Vec<u8>,
pub(crate) stub: Option<Vec<u8>>,
}
/// Overlay the PE export table from the loader `stub` onto the unpacked image
/// `out`, for the external-companion layout.
///
/// In that layout the encrypted companion carries the real `.text`/`il2cpp`
/// payload but **not** a usable export directory: the crackproof loader rebuilds
/// exports at runtime from the plaintext copy retained in the stub's `.rdata`.
/// Statically, the spliced input therefore decrypts to a garbage export
/// directory (`NumberOfFunctions` etc. are ciphertext), which makes downstream
/// tools (IL2CppDumper, IDA) choke when they parse it. The fix does what the
/// loader does: copy the export-directory region byte-for-byte from the stub to
/// the same RVA in the unpacked image.
///
/// No-op (leaves `out` untouched) if there is no export directory, or if the
/// region cannot be mapped in either image — so a malformed stub can never
/// corrupt an otherwise-good unpack.
pub(crate) fn overlay_exports_from_stub(out: &mut [u8], stub: &[u8]) {
let (export_rva, export_size) = match pe_export_dir(out) {
Some(v) if v.1 != 0 => v,
_ => return,
};
let dst = match rva_to_file_off(out, export_rva) {
Some(o) => o,
None => return,
};
let src = match rva_to_file_off(stub, export_rva) {
Some(o) => o,
None => return,
};
let n = export_size as usize;
if dst + n <= out.len() && src + n <= stub.len() {
out[dst..dst + n].copy_from_slice(&stub[src..src + n]);
}
}
/// Restore the CLR regions retained by an external-companion loader stub.
/// Method bodies come from the unpacked payload and must not be overlaid.
fn restore_managed_from_stub(out: &mut [u8], stub: &[u8]) -> Result<(), unpacker::UnpackError> {
let failure =
|region, source| unpacker::UnpackError::ManagedStubRestoreFailed { region, source };
let source_headers = senbei_pe::parse(stub).map_err(|e| failure("PE headers", e))?;
let (clr_rva, clr_size) = senbei_pe::data_directory(stub, source_headers, 14)
.map_err(|e| failure("CLR directory", e))?;
if clr_rva == 0 && clr_size == 0 {
return Ok(());
}
if clr_rva == 0 || clr_size < 0x48 {
return Err(failure("CLR directory", senbei_pe::Error::Invalid));
}
let destination_headers = senbei_pe::parse(out).map_err(|e| failure("output PE headers", e))?;
senbei_pe::data_directory(out, destination_headers, 14)
.map_err(|e| failure("output CLR directory", e))?;
let cor = senbei_pe::rva_range(stub, source_headers, clr_rva, 0x48)
.map_err(|e| failure("COR20 header", e))?;
if read_u32(stub, cor.start) != Some(0x48) {
return Err(failure("COR20 header", senbei_pe::Error::Invalid));
}
let range_pair = |rva, size, region| {
let source = senbei_pe::rva_range(stub, source_headers, rva, size)
.map_err(|e| failure(region, e))?;
let destination = senbei_pe::rva_range(out, destination_headers, rva, size)
.map_err(|e| failure(region, e))?;
Ok::<_, unpacker::UnpackError>((source, destination))
};
let mut copies = vec![range_pair(clr_rva, 0x48, "COR20 header")?];
for (field, region) in [
(0x08, "metadata"),
(0x18, "resources"),
(0x20, "strong-name signature"),
(0x28, "code-manager table"),
(0x30, "vtable fixups"),
(0x38, "export address jumps"),
(0x40, "managed native header"),
] {
let rva = read_u32(stub, cor.start + field)
.ok_or_else(|| failure(region, senbei_pe::Error::OutOfBounds))?;
let size = read_u32(stub, cor.start + field + 4)
.ok_or_else(|| failure(region, senbei_pe::Error::OutOfBounds))?;
if field != 0x08 && rva == 0 && size == 0 {
continue;
}
if rva == 0 || size == 0 {
return Err(failure(region, senbei_pe::Error::Invalid));
}
let (source, destination) = range_pair(rva, size, region)?;
if field == 0x08 && !stub[source.clone()].starts_with(b"BSJB") {
return Err(failure(region, senbei_pe::Error::Invalid));
}
if field == 0x30 {
if !size.is_multiple_of(8) {
return Err(failure(region, senbei_pe::Error::Invalid));
}
for fixup in stub[source.clone()].as_chunks::<8>().0 {
let slots_rva =
u32::from_le_bytes(fixup[..4].try_into().expect("eight-byte fixup"));
let count = u16::from_le_bytes([fixup[4], fixup[5]]) as u32;
let flags = u16::from_le_bytes([fixup[6], fixup[7]]);
let width = match flags & 3 {
1 => 4,
2 => 8,
_ => return Err(failure(region, senbei_pe::Error::Invalid)),
};
if count != 0 {
copies.push(range_pair(slots_rva, count * width, "vtable slots")?);
}
}
}
copies.push((source, destination));
}
// Validate all referenced ranges before changing the output.
for (source, destination) in copies {
out[destination].copy_from_slice(&stub[source]);
}
let directory = destination_headers.pe_offset
+ 24
+ if destination_headers.is_pe32_plus {
112
} else {
96
}
+ 14 * 8;
out[directory..directory + 4].copy_from_slice(&clr_rva.to_le_bytes());
out[directory + 4..directory + 8].copy_from_slice(&clr_size.to_le_bytes());
Ok(())
}
/// Restore the TLS directory from the loader `stub` onto the unpacked image
/// `out`, for the external-companion layout.
///
/// Crackproof strips the whole `IMAGE_TLS_DIRECTORY` from the encrypted payload
/// — the data-directory entry, the directory struct, the raw-data template, and
/// the base relocations for the struct's four 64-bit pointer fields — and
/// re-installs TLS itself from data kept in the stub when it loads the module.
/// A statically-unpacked DLL is loaded by the ordinary Windows loader instead,
/// which needs a valid TLS directory or it never allocates a TLS slot for the
/// module nor writes `_tls_index`. The module's C++ `thread_local` accesses then
/// read a garbage TLS slot — observed as a `0xC0000005` deep in IL2CPP type
/// resolution (a TypeDef token used as a raw `s_TypeInfoTable` index).
///
/// The stub retains the full plaintext `.rdata` (only `.text`/`il2cpp` are
/// stripped to one page), so the directory struct and its raw-data template are
/// copied back byte-for-byte at their RVAs, the data-directory entry is taken
/// from the stub header (the unpacked image's was overwritten with the zeroed
/// saved-header blob), and four DIR64 relocations are appended to `.reloc`.
///
/// No-op if the stub declares no TLS directory or if any required region cannot
/// be mapped/relocated — so it can never corrupt an otherwise-good unpack.
pub(crate) fn restore_tls_from_stub(out: &mut [u8], stub: &[u8]) {
let pe = match read_u32(out, 0x3C) {
Some(v) => v as usize,
None => return,
};
if out.get(pe..pe + 4) != Some(&b"PE\0\0"[..]) {
return;
}
// This restore is PE32+-only: it copies a 40-byte IMAGE_TLS_DIRECTORY64,
// converts fields with a 64-bit image base, and appends DIR64 relocs. A
// PE32 module needs the 24-byte struct / DIR32 handling (the unpacker core
// does that itself — see `restore_pe32_tls_from_stub`), so bail rather than
// read the data directories at the wrong (PE32+) offset and write garbage.
if read_u16(out, pe + 24) != Some(0x20B) {
return;
}
// TLS is data-directory index 9 (PE32+ directories at optional header +112).
let tls_dd = match pe.checked_add(24 + 112 + 9 * 8) {
Some(v) => v,
None => return,
};
// The genuine entry survives in the stub header; the unpacked image's copy
// was clobbered by the (zeroed-TLS) saved-header blob.
let (tls_rva, tls_size) = match (read_u32(stub, tls_dd), read_u32(stub, tls_dd + 4)) {
(Some(r), Some(s)) if r != 0 && s != 0 => (r, s),
_ => return, // module has no TLS — nothing to restore
};
// Image base (PE32+, optional header +24) converts the struct's absolute VAs
// back to RVAs for the raw-data template overlay.
let image_base = match read_u64(out, pe + 24 + 24) {
Some(v) => v,
None => return,
};
// 1) Overlay the IMAGE_TLS_DIRECTORY struct from the stub at its RVA.
let dst = match rva_to_file_off(out, tls_rva) {
Some(o) => o,
None => return,
};
let src = match rva_to_file_off(stub, tls_rva) {
Some(o) => o,
None => return,
};
let n = tls_size as usize;
if dst.checked_add(n).is_none_or(|e| e > out.len())
|| src.checked_add(n).is_none_or(|e| e > stub.len())
{
return;
}
out[dst..dst + n].copy_from_slice(&stub[src..src + n]);
// 2) Restore the data-directory entry so the loader processes TLS at all.
write_u32_at(out, tls_dd, tls_rva);
write_u32_at(out, tls_dd + 4, tls_size);
// 3) Overlay the raw-data template [StartAddressOfRawData, EndAddressOfRawData).
if let (Some(start_va), Some(end_va)) = (read_u64(out, dst), read_u64(out, dst + 8))
&& end_va > start_va
&& start_va >= image_base
{
let tpl_rva = (start_va - image_base) as u32;
let tpl_len = (end_va - start_va) as usize;
if let (Some(td), Some(ts)) = (
rva_to_file_off(out, tpl_rva),
rva_to_file_off(stub, tpl_rva),
) && td.checked_add(tpl_len).is_some_and(|e| e <= out.len())
&& ts.checked_add(tpl_len).is_some_and(|e| e <= stub.len())
{
out[td..td + tpl_len].copy_from_slice(&stub[ts..ts + tpl_len]);
}
}
// 4) Append DIR64 relocations for the struct's four 64-bit pointer fields
// (Start/End/Index/CallBacks at +0/+8/+0x10/+0x18). Without them the
// loader would leave preferred-base VAs in a rebased image.
add_tls_relocs(out, pe, tls_rva);
}
/// Append a single base-relocation block covering the four 64-bit pointer fields
/// of the TLS directory struct at `tls_rva`. The block is written immediately
/// after the existing relocation table (which must be free space and in bounds)
/// and the BaseReloc directory size is grown to include it. No-op if the table
/// is absent, the fields straddle a relocation page, or the slot is not free.
fn add_tls_relocs(out: &mut [u8], pe: usize, tls_rva: u32) {
let reloc_dd = pe + 24 + 112 + 5 * 8; // BaseReloc = directory index 5
let (reloc_rva, reloc_size) = match (read_u32(out, reloc_dd), read_u32(out, reloc_dd + 4)) {
(Some(r), Some(s)) if r != 0 => (r, s),
_ => return,
};
// All four fields (last at +0x18) must share one 0x1000 relocation page.
let page = tls_rva & !0xFFF;
if (tls_rva.wrapping_add(0x18)) & !0xFFF != page {
return;
}
const BLOCK: usize = 8 + 4 * 2; // header + four DIR64 entries
let at = match rva_to_file_off(out, reloc_rva.wrapping_add(reloc_size)) {
Some(o) => o,
None => return,
};
if at.checked_add(BLOCK).is_none_or(|e| e > out.len()) {
return;
}
if out[at..at + BLOCK].iter().any(|&b| b != 0) {
return; // refuse to clobber existing data
}
write_u32_at(out, at, page);
write_u32_at(out, at + 4, BLOCK as u32);
for (i, off) in [0u32, 8, 0x10, 0x18].iter().enumerate() {
let entry = (10u16 << 12) | (((tls_rva.wrapping_add(*off)) & 0xFFF) as u16);
let p = at + 8 + i * 2;
out[p..p + 2].copy_from_slice(&entry.to_le_bytes());
}
write_u32_at(out, reloc_dd + 4, reloc_size.wrapping_add(BLOCK as u32));
}
/// Read the Export data-directory (RVA, size) from a PE image, or `None` if the
/// headers are too short/invalid to parse.
fn pe_export_dir(buf: &[u8]) -> Option<(u32, u32)> {
let headers = senbei_pe::parse(buf).ok()?;
senbei_pe::data_directory(buf, headers, 0).ok()
}
/// Map an RVA to a file offset using the PE section table. Returns `None` if no
/// section contains the RVA or the headers cannot be parsed.
fn rva_to_file_off(buf: &[u8], rva: u32) -> Option<usize> {
let headers = senbei_pe::parse(buf).ok()?;
senbei_pe::rva_to_offset(buf, headers, rva).ok()
}
fn read_u32(buf: &[u8], off: usize) -> Option<u32> {
let b = buf.get(off..off + 4)?;
Some(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
fn read_u16(buf: &[u8], off: usize) -> Option<u16> {
let b = buf.get(off..off + 2)?;
Some(u16::from_le_bytes([b[0], b[1]]))
}
fn read_u64(buf: &[u8], off: usize) -> Option<u64> {
let b = buf.get(off..off + 8)?;
Some(u64::from_le_bytes([
b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
]))
}
/// Write a little-endian `u32` at `off`, silently doing nothing if out of bounds.
fn write_u32_at(buf: &mut [u8], off: usize, val: u32) {
if let Some(slot) = buf.get_mut(off..off + 4) {
slot.copy_from_slice(&val.to_le_bytes());
}
}
/// Splice a stub and its external-companion payload into the embedded-payload
/// form the pipelines expect, or `None` if `comp` is not this stub's payload.
///
/// The companion is byte-for-byte the stub's payload region from the Crackproof
/// header (offset 4096) onward, so the result is `stub[..4096] ++ comp`. The
/// splice fires only when the first 32 bytes of `comp` equal the stub's header
/// at offset 4096 — a 32-byte match on the key-table/magic region that confirms
/// the pairing and leaves ordinary (non-companion) inputs untouched.
pub(crate) fn splice_companion(stub: &[u8], comp: &[u8]) -> Option<Vec<u8>> {
let hdr_end = HEADER_OFF + 32;
if stub.len() >= hdr_end && comp.len() >= 32 && stub[HEADER_OFF..hdr_end] == comp[..32] {
let mut spliced = Vec::with_capacity(HEADER_OFF + comp.len());
spliced.extend_from_slice(&stub[..HEADER_OFF]);
spliced.extend_from_slice(comp);
return Some(spliced);
}
None
}
/// Detect `bytes` and run the right pipeline. Spliced external companions use
/// the EXE pipeline directly because that layout is definitionally EXE-style.
///
/// Routing spliced inputs straight to the EXE pipeline is safe: the
/// companion layout is definitionally the EXE-style shell (the runtime
/// loader maps the companion and runs the standard shell unpack), so the DLL
/// pipeline probe can never be right for it. Output bytes are identical to the
/// DLL-first + EXE-fallback route for every input that route handles.
pub(crate) fn unpack_spliced_or_auto(
bytes: &[u8],
spliced: bool,
force_exe: bool,
verbose: bool,
) -> Result<(unpacker::Kind, Vec<u8>), unpacker::UnpackError> {
if spliced || force_exe {
let detected = unpacker::detect(bytes).ok_or(unpacker::UnpackError::NotCrackproof)?;
let out = unpacker::unpack_exe_v(bytes, verbose)?;
return Ok((detected.kind, out));
}
unpacker::unpack_auto_v(bytes, verbose)
}
/// Unpack a single file to `dest`. Returns the Kind and integrity report on success.
pub fn unpack_one(
input: &Path,
dest: &Path,
) -> anyhow::Result<(unpacker::Kind, unpacker::IntegrityReport)> {
unpack_one_v(input, dest, false)
}
/// Outcome of a byte-level unpack ([`unpack_bytes`]): the image, its detected
/// kind, and its integrity report. No file I/O is involved.
pub struct UnpackedImage {
pub kind: unpacker::Kind,
pub bytes: Vec<u8>,
pub integrity: unpacker::IntegrityReport,
/// True when the input was reconstructed from an external companion (the
/// `._` layout), i.e. the export/TLS overlays ran.
pub companion: bool,
}
/// Unpack in-memory `input` bytes, optionally paired with an external
/// companion payload `companion` (the `<input>._` file's contents).
///
/// This is the in-memory counterpart of [`unpack_one_v`]: splice a matching
/// companion, unpack, overlay the export table and TLS directory from the stub,
/// then run the static integrity check.
pub fn unpack_bytes(
input: &[u8],
companion: Option<&[u8]>,
) -> Result<UnpackedImage, unpacker::UnpackError> {
unpack_bytes_impl(input, companion, false)
}
/// Like [`unpack_bytes`], but forces the EXE pipeline (no DLL-pipeline
/// probe). This is the web app's recovery path: the DLL-first probe relies
/// on `catch_unwind` to reject EXE-shell-layout DLLs, and panics cannot be
/// caught on wasm — the probe traps the whole call. The web app runs each
/// unpack in a disposable Web Worker and retries trapped DLLs with this
/// entry point, reproducing the CLI's dll-first/exe-fallback routing.
pub fn unpack_bytes_force_exe(
input: &[u8],
companion: Option<&[u8]>,
) -> Result<UnpackedImage, unpacker::UnpackError> {
unpack_bytes_impl(input, companion, true)
}
fn unpack_bytes_impl(
input: &[u8],
companion: Option<&[u8]>,
force_exe: bool,
) -> Result<UnpackedImage, unpacker::UnpackError> {
let spliced = companion.and_then(|c| splice_companion(input, c));
let bytes: &[u8] = spliced.as_deref().unwrap_or(input);
let (kind, mut out) = unpack_spliced_or_auto(bytes, spliced.is_some(), force_exe, false)?;
if spliced.is_some() {
overlay_exports_from_stub(&mut out, input);
restore_tls_from_stub(&mut out, input);
restore_managed_from_stub(&mut out, input)?;
}
let integrity = unpacker::check_integrity(&out);
Ok(UnpackedImage {
kind,
bytes: out,
integrity,
companion: spliced.is_some(),
})
}
/// Like [`unpack_one`], but prints detailed `[N/9]` step progress (and a final
/// `Write to <dest>` line) to stdout when `verbose` is true.
pub fn unpack_one_v(
input: &Path,
dest: &Path,
verbose: bool,
) -> anyhow::Result<(unpacker::Kind, unpacker::IntegrityReport)> {
let UnpackerInput { bytes, stub } = read_unpacker_input(input)?;
let (kind, mut out) = unpack_spliced_or_auto(&bytes, stub.is_some(), false, verbose)?;
// External-companion layout: restore the export table from the stub, which
// the encrypted companion does not carry (the loader rebuilds it at runtime).
if let Some(stub) = stub {
overlay_exports_from_stub(&mut out, &stub);
// ...and the TLS directory, which Crackproof strips from the payload and
// re-installs at runtime; the ordinary loader needs it or thread_local
// access crashes (see [`restore_tls_from_stub`]).
restore_tls_from_stub(&mut out, &stub);
restore_managed_from_stub(&mut out, &stub)?;
}
let report = unpacker::check_integrity(&out);
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
write_atomic(dest, &out)?;
if verbose {
println!("Write to {}", dest.display());
}
Ok((kind, report))
}
#[cfg(test)]
mod tests {
use super::*;
const HEADER_OFF: usize = 4096;
fn stub_with_header(header: &[u8; 32], extra: usize) -> Vec<u8> {
let mut stub = vec![0_u8; HEADER_OFF];
stub.extend_from_slice(header);
stub.extend_from_slice(&vec![0xAA_u8; extra]);
stub
}
#[test]
fn splices_when_header_matches() {
let header = [7_u8; 32];
let stub = stub_with_header(&header, 16);
let mut companion = header.to_vec();
companion.extend_from_slice(&[0x42_u8; 1000]);
let output = splice_companion(&stub, &companion).expect("should splice");
assert_eq!(output.len(), HEADER_OFF + companion.len());
assert_eq!(&output[..HEADER_OFF], &stub[..HEADER_OFF]);
assert_eq!(&output[HEADER_OFF..], &companion[..]);
}
#[test]
fn no_splice_when_header_differs() {
let stub = stub_with_header(&[7_u8; 32], 16);
let mut companion = vec![9_u8; 32];
companion.extend_from_slice(&[0x42_u8; 1000]);
assert!(splice_companion(&stub, &companion).is_none());
}
#[test]
fn no_splice_when_too_short() {
let short_stub = vec![0_u8; HEADER_OFF + 8];
let companion = vec![0_u8; 64];
assert!(splice_companion(&short_stub, &companion).is_none());
let stub = stub_with_header(&[1_u8; 32], 0);
let short_companion = vec![1_u8; 16];
assert!(splice_companion(&stub, &short_companion).is_none());
}
fn managed_fixture(is_pe32_plus: bool, raw: usize) -> Vec<u8> {
let mut data = vec![0; raw + 0x600];
data[..2].copy_from_slice(b"MZ");
data[0x80..0x84].copy_from_slice(b"PE\0\0");
let optional_size = if is_pe32_plus { 0xf0u16 } else { 0xe0 };
let section = 0x98 + optional_size as usize;
let dirs = 0x98 + if is_pe32_plus { 112 } else { 96 };
for (offset, value) in [
(0x86, 1u16),
(0x94, optional_size),
(0x98, if is_pe32_plus { 0x20b } else { 0x10b }),
(raw + 0x204, 2),
(raw + 0x206, if is_pe32_plus { 2 } else { 1 }),
] {
data[offset..offset + 2].copy_from_slice(&value.to_le_bytes());
}
for (offset, value) in [
(0x3c, 0x80u32),
(0xd0, 0x3000),
(0xd4, 0x400),
(dirs + 14 * 8, 0x2010),
(dirs + 14 * 8 + 4, 0x48),
(section + 8, 0x600),
(section + 12, 0x2000),
(section + 16, 0x600),
(section + 20, raw as u32),
(raw + 0x10, 0x48),
(raw + 0x18, 0x2100),
(raw + 0x1c, 0x20),
(raw + 0x28, 0x2180),
(raw + 0x2c, 8),
(raw + 0x40, 0x2200),
(raw + 0x44, 8),
(raw + 0x200, 0x2280),
(raw + 0x280, 0x0600_0001),
] {
data[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}
data[raw + 0x100..raw + 0x104].copy_from_slice(b"BSJB");
data[raw + 0x180..raw + 0x188].copy_from_slice(b"resource");
data
}
#[test]
fn managed_companion_restores_rva_mapped_regions_without_overwriting_il() {
for is_pe32_plus in [false, true] {
let stub = managed_fixture(is_pe32_plus, 0x600);
let mut out = managed_fixture(is_pe32_plus, 0x400);
out[0x400..].fill(0xcc);
restore_managed_from_stub(&mut out, &stub).unwrap();
for (offset, size) in [
(0x10, 0x48),
(0x100, 0x20),
(0x180, 8),
(0x200, 8),
(0x280, if is_pe32_plus { 16 } else { 8 }),
] {
assert_eq!(
&out[0x400 + offset..0x400 + offset + size],
&stub[0x600 + offset..0x600 + offset + size]
);
}
assert!(out[0x700..0x740].iter().all(|&b| b == 0xcc));
}
}
#[test]
fn managed_companion_rejects_invalid_metadata_and_unbacked_vtable_slots() {
for broken_metadata in [true, false] {
let mut stub = managed_fixture(false, 0x600);
if broken_metadata {
stub[0x700..0x704].fill(0);
} else {
stub[0x800..0x804].copy_from_slice(&0x2600u32.to_le_bytes());
}
let mut out = managed_fixture(false, 0x400);
let before = out.clone();
assert!(matches!(
restore_managed_from_stub(&mut out, &stub),
Err(unpacker::UnpackError::ManagedStubRestoreFailed { .. })
));
assert_eq!(out, before);
}
}
}
+4
View File
@@ -4,3 +4,7 @@ version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
description = "Unity il2cpp metadata de-obfuscation for Senbei" description = "Unity il2cpp metadata de-obfuscation for Senbei"
[dependencies]
serde.workspace = true
thiserror.workspace = true
+137
View File
@@ -0,0 +1,137 @@
//! Extraction of the embedded-metadata packaging variant.
//!
//! Some protected il2cpp builds ship no `global-metadata.dat` in the app's
//! assets at all. Instead a slim metadata blob (an older header format with
//! custom record layouts) is embedded in the protected library's data section
//! and wrapped in a per-word XOR layer: a 0x100-byte header whose 64 words each
//! carry their own key, followed by exactly 256 segments with one u32 key each
//! at irregular boundaries. At runtime the protector's il2cpp-side modules
//! regenerate the keys and unwrap the blob in place; the keys are stored
//! nowhere in the image.
//!
//! For the one observed build using this variant the full keystream was
//! recovered from a ciphertext/plaintext pair and is embedded in
//! [`crate::keystream`]. Extraction is therefore content-gated: the wrapped
//! header's first plaintext words are known constants, so a restored image that
//! does not contain them (every other build) is skipped cheaply and nothing is
//! written.
//!
//! The unwrapped blob stores its patched sanity/version fields byte-swapped;
//! they are rewritten to the standard il2cpp metadata magic and version so the
//! output is a well-formed `global-metadata.dat`.
use super::keystream::{HEADER_KEYS, SEGMENTS};
/// Standard il2cpp metadata sanity magic written over the patched header.
const STANDARD_MAGIC: u32 = 0xfab1_1baf;
/// Standard header version matching the blob's record layout.
const STANDARD_VERSION: u32 = 24;
/// Plaintext of the first two wrapped header words (the byte-swapped patched
/// sanity/version pair). Also the probe pattern: a restored image contains the
/// embedded blob iff `word[0] ^ HEADER_KEYS[0]` and `word[1] ^ HEADER_KEYS[1]`
/// equal these constants at some 4-aligned offset.
const PROBE_WORDS: [u32; 2] = [0x9732_ca38, 0xbac4_374f];
/// Size of the wrapped blob: the last segment's end offset.
pub fn embedded_metadata_size() -> usize {
SEGMENTS[SEGMENTS.len() - 1].0 as usize
}
/// Locate and unwrap the embedded metadata blob in a restored library image.
///
/// Returns a standalone, well-formed `global-metadata.dat`, or `None` when the
/// image carries no blob wrapped with the known keystream.
pub fn extract_embedded_metadata(image: &[u8]) -> Option<Vec<u8>> {
let total = embedded_metadata_size();
let offset = find_wrapped_header(image)?;
let blob = image.get(offset..offset.checked_add(total)?)?;
let mut out = blob.to_vec();
for (i, &key) in HEADER_KEYS.iter().enumerate() {
xor_word(&mut out, 4 * i, key);
}
let mut pos = 0x100_usize;
for &(end, key) in &SEGMENTS {
let end = end as usize;
let mut o = pos;
while o + 4 <= end {
xor_word(&mut out, o, key);
o += 4;
}
pos = end;
}
out[0..4].copy_from_slice(&STANDARD_MAGIC.to_le_bytes());
out[4..8].copy_from_slice(&STANDARD_VERSION.to_le_bytes());
Some(out)
}
/// Scan `image` for the wrapped header probe pattern (4-aligned).
fn find_wrapped_header(image: &[u8]) -> Option<usize> {
let mut off = 0;
while off + 8 <= image.len() {
let word = u32::from_le_bytes(image[off..off + 4].try_into().ok()?);
if word ^ HEADER_KEYS[0] == PROBE_WORDS[0] {
let next = u32::from_le_bytes(image[off + 4..off + 8].try_into().ok()?);
if next ^ HEADER_KEYS[1] == PROBE_WORDS[1] {
return Some(off);
}
}
off += 4;
}
None
}
fn xor_word(data: &mut [u8], offset: usize, key: u32) {
let word = u32::from_le_bytes(data[offset..offset + 4].try_into().expect("word in bounds"));
data[offset..offset + 4].copy_from_slice(&(word ^ key).to_le_bytes());
}
#[cfg(test)]
mod tests {
use super::*;
/// Wrap a synthetic blob with the keystream, then unwrap it back.
#[test]
fn roundtrip_wrapped_blob() {
let total = embedded_metadata_size();
let mut image = vec![0_u8; total + 0x40];
// Plaintext blob: standard probe words, then a ramp.
image[0..4].copy_from_slice(&PROBE_WORDS[0].to_le_bytes());
image[4..8].copy_from_slice(&PROBE_WORDS[1].to_le_bytes());
for o in (8..total).step_by(4) {
let v = (o as u32).wrapping_mul(0x9e37_79b1);
image[o..o + 4].copy_from_slice(&v.to_le_bytes());
}
// Wrap with the keystream.
for (i, &key) in HEADER_KEYS.iter().enumerate() {
xor_word(&mut image, 4 * i, key);
}
let mut pos = 0x100_usize;
for &(end, key) in &SEGMENTS {
let mut o = pos;
while o + 4 <= end as usize {
xor_word(&mut image, o, key);
o += 4;
}
pos = end as usize;
}
let out = extract_embedded_metadata(&image).expect("blob found");
assert_eq!(out.len(), total);
// Header rewritten to the standard magic/version…
assert_eq!(&out[0..4], &STANDARD_MAGIC.to_le_bytes());
assert_eq!(&out[4..8], &STANDARD_VERSION.to_le_bytes());
// …and the body round-trips.
for o in (8..total).step_by(4) {
let v = (o as u32).wrapping_mul(0x9e37_79b1);
assert_eq!(&out[o..o + 4], &v.to_le_bytes(), "word at {o:#x}");
}
}
#[test]
fn no_blob_in_plain_data() {
let image = vec![0xAB_u8; 0x1000];
assert!(extract_embedded_metadata(&image).is_none());
}
}
+274
View File
@@ -0,0 +1,274 @@
/// Per-word XOR keystream for the embedded-metadata packaging variant,
/// recovered from a ciphertext/plaintext pair of one observed build.
/// Key derivation for future builds is untraced; other builds simply do
/// not match the header probe and are left untouched.
pub(crate) const HEADER_KEYS: [u32; 64] = [
0x39184c70, 0xd901afd4, 0x19b98815, 0x132906ed, 0x663e8ace, 0x299b1952, 0xe5404ab8, 0xd93b331c,
0xb67d3761, 0x42da9259, 0xc29c7a59, 0x17cb841c, 0xd0bcb9c6, 0x21db779b, 0x43874deb, 0x89bf697b,
0x0b7f97b4, 0xbe1c59f7, 0xc653ad92, 0x8cdf4336, 0x5e0b6b68, 0x1bd4d668, 0x7250ed61, 0x31a36491,
0xaf144dcd, 0xc1e387d0, 0x9d6df5b7, 0x78514f32, 0xc2648cbf, 0x3b8272a5, 0xd2053679, 0x4b18af77,
0x71b9ebdd, 0x0094daaa, 0xf3adfed8, 0xc0d082bc, 0xae5e523c, 0xa8dec0be, 0x090a7784, 0x2c0483d6,
0x95f0e8f7, 0x234de6d4, 0xa7464527, 0x3b1c531d, 0xc2b31d82, 0xe1c60be0, 0x3d65a0c2, 0x2ea7d77a,
0x4ababadb, 0xce484b16, 0x59ab3f99, 0x10a9a463, 0x70e2f78a, 0x0ed71c9c, 0xf8996b2e, 0xff637928,
0xf413313d, 0x77c57bf9, 0xdab41dba, 0x0cd2ccbc, 0x3b2fbde3, 0x0b19b14d, 0xd2645dbc, 0x318113d4,
];
/// (segment end offset, segment key) pairs; offsets relative to blob start.
pub(crate) const SEGMENTS: [(u32, u32); 256] = [
(0x3915c, 0xbb5dda1a),
(0x736b4, 0x906dbe0f),
(0xaedc4, 0x1e4ca8bd),
(0xc506c, 0xe603cb21),
(0xdfe34, 0x93bec702),
(0xe8f10, 0x9a9f429f),
(0x139088, 0x125a8b3f),
(0x20bd30, 0x69a6395f),
(0x20c548, 0xca807b9a),
(0x20c774, 0x8b8880c4),
(0x300518, 0x48087852),
(0x36c07c, 0x32aa7b5b),
(0x448b7c, 0x2e668589),
(0x4592b0, 0x292e07d9),
(0x45d374, 0x83b0a0ef),
(0x474520, 0x8983245d),
(0x47a1d4, 0xefb941b7),
(0x4bdc74, 0x7c3b3458),
(0x4c34c8, 0xee0a87b3),
(0x4f1068, 0xf6a2069f),
(0x51601c, 0x2e83612b),
(0x549d40, 0xb413a58f),
(0x56a714, 0x95596da3),
(0x573c98, 0x68513e8d),
(0x59d058, 0xc4ff5f9a),
(0x5c4b34, 0x249ed022),
(0x5f19bc, 0xc27272d3),
(0x5f47c8, 0xd73aa37b),
(0x627df4, 0x002334ba),
(0x648f54, 0x868bb6c9),
(0x6718a4, 0x17ff0ef4),
(0x6a88b8, 0x22cfbc5f),
(0x742dbc, 0x152072dd),
(0x75603c, 0xbd31be45),
(0x783238, 0x45911d6a),
(0x7b94d8, 0x6f281add),
(0x800060, 0xcf58c8d0),
(0x819b50, 0xb40f0276),
(0x82dea4, 0x1a1a8402),
(0x880210, 0xf2c0824a),
(0x8e4f08, 0x86c9ba90),
(0x8ea544, 0x0e928544),
(0x931454, 0xc3fa017b),
(0x94eb70, 0x1dbe612a),
(0x95993c, 0x902498fe),
(0x98d2b0, 0xb7760451),
(0x992034, 0x711cddfc),
(0x9e14a0, 0x8bd95e64),
(0xa1d2d0, 0xbfdce920),
(0xa21ed8, 0x90cf0372),
(0xa4d2b8, 0x91e88c9c),
(0xa76f8c, 0x9c721e61),
(0xac5ba4, 0xbda16e3e),
(0xaf070c, 0xe02b6799),
(0xaf3a78, 0x32953b4e),
(0xb32510, 0x47ea48db),
(0xb46550, 0x1443e512),
(0xb54998, 0x9e123a75),
(0xb5e24c, 0xe11a8efd),
(0xb625cc, 0x3facfbf4),
(0xb66ec8, 0x76c0c452),
(0xb67ad0, 0x4de4ed6c),
(0xb7ba5c, 0xe622d97a),
(0xb85a90, 0x6f564f8b),
(0xbff8b8, 0x3e25d671),
(0xc03e50, 0x3563fc2b),
(0xc6e958, 0xda8bc3b0),
(0xc87f7c, 0x5a9d2269),
(0xcb36a4, 0x0ab420cc),
(0xcbe4d0, 0x9bbb091e),
(0xccd7dc, 0x9e4fd577),
(0xd078c0, 0x4b655ae1),
(0xd275dc, 0x5ca2a2f4),
(0xd2c840, 0xdb437f0d),
(0xd3296c, 0x66487f75),
(0xd7cbe8, 0xf5427945),
(0xd8e0a0, 0x9a65bdb6),
(0xda2ed4, 0x46dea4b3),
(0xda6f1c, 0xb9916a02),
(0xdee9ac, 0x18800a5c),
(0xe3673c, 0x4afab3cd),
(0xe65420, 0x52e80204),
(0xe861f8, 0x639a02d7),
(0xeb61c0, 0x21077eba),
(0xed51dc, 0x17be91d8),
(0xf048a4, 0xd30cc8cb),
(0xf3b274, 0xdfb43f3f),
(0xf76ac8, 0x63a8b363),
(0xf84b64, 0x16508a16),
(0xf8bb2c, 0x22ce110d),
(0xfb3390, 0xf09a4eb2),
(0xff07bc, 0xd2bb0e2c),
(0x102d32c, 0xb424012c),
(0x10795b0, 0x07338bb9),
(0x108d65c, 0x5d68f86e),
(0x10ce528, 0x1826c952),
(0x10d3528, 0xa7473860),
(0x10dca58, 0x92435967),
(0x1115c78, 0x061200f4),
(0x1171098, 0x94f538a1),
(0x117ebf0, 0xd8731d88),
(0x1186638, 0x4381b3f9),
(0x118afdc, 0xf25ff376),
(0x11ee3b4, 0x29605488),
(0x11f182c, 0x04367932),
(0x11f41dc, 0xaeaccadd),
(0x11ff0f4, 0x7c4d358e),
(0x120caac, 0xacbc8412),
(0x12437cc, 0x3e0ac7e9),
(0x124edf8, 0x06f523fd),
(0x1263ba0, 0x0a1b9763),
(0x12943f0, 0x24a86ba4),
(0x12d9230, 0x0cd82e2e),
(0x12fd9b4, 0xf3903fb9),
(0x135a198, 0x2887f4a3),
(0x1366180, 0x9f0d7ca5),
(0x13680a4, 0x61e9a459),
(0x13a1b44, 0xe61623a4),
(0x13a860c, 0xdc44c798),
(0x13c024c, 0xc90f7be6),
(0x1475c00, 0xc2f338b3),
(0x1480aa8, 0xb7b0609e),
(0x14fb82c, 0x748e3939),
(0x1511184, 0x98426fcf),
(0x153c144, 0x1a452d5d),
(0x1547838, 0x7dd360e9),
(0x15565d4, 0x1d8f093b),
(0x156e298, 0x102a1524),
(0x159df70, 0xe42613f7),
(0x15a13d0, 0xafc5fdc6),
(0x15e7f24, 0x84fcd342),
(0x15f0878, 0x55038958),
(0x1614210, 0xe0602ae4),
(0x1631b3c, 0xce2765f6),
(0x164eb70, 0xf772dac5),
(0x1688b68, 0x5f1a72c9),
(0x16d5f8c, 0x7c77747d),
(0x16e76dc, 0xac0e16fb),
(0x1726374, 0x4a1e7fd7),
(0x173455c, 0x870856b4),
(0x17697d8, 0xbb2f0a5c),
(0x176ed60, 0xc937b386),
(0x1784fa8, 0x5e676ab2),
(0x17ae3a0, 0xdbf662a1),
(0x1866c7c, 0x4e3f1a7d),
(0x186b844, 0xe30fce60),
(0x18b507c, 0xdfc73c88),
(0x18c2f64, 0xb7ee08e0),
(0x18c8010, 0xd1471a25),
(0x18de290, 0x292e6310),
(0x19140d0, 0x9f346f05),
(0x192c590, 0xf1eb61bf),
(0x194fca0, 0x8888b1df),
(0x1959d34, 0x92b89d15),
(0x196c0c4, 0x5e152de5),
(0x19a5710, 0x866e7bfa),
(0x19abfd4, 0x3084ae26),
(0x19b1550, 0x0581836f),
(0x19b7214, 0xeefc34eb),
(0x19c523c, 0xc980335d),
(0x19dc4c0, 0x019084e6),
(0x19dfb8c, 0xdb1a21a7),
(0x19fbf3c, 0xec84cc17),
(0x1a29b18, 0xcb31da7d),
(0x1a4c670, 0xc5fe570e),
(0x1a97024, 0xbbd80964),
(0x1ac33bc, 0xe186586d),
(0x1acd124, 0x1e413252),
(0x1ad9bac, 0x48fc4c75),
(0x1b1b728, 0x8071d7a5),
(0x1b31d78, 0x9d958013),
(0x1badb24, 0x2f236951),
(0x1bccc00, 0x7023c620),
(0x1bdab2c, 0x88b1e4b8),
(0x1c000dc, 0x9e43291a),
(0x1c9f0cc, 0x27a7d592),
(0x1cd1328, 0x9c0bcc88),
(0x1cd79a0, 0x63e0ed75),
(0x1d0e484, 0xf51a0d3d),
(0x1d17b10, 0xbfd2a7ac),
(0x1d930c4, 0xf6b9e877),
(0x1db115c, 0xf3eb7e37),
(0x1df16b4, 0x682326ff),
(0x1e389c0, 0xea11f566),
(0x1eb7e48, 0x3dc5fa76),
(0x1ec38fc, 0x296ffc1d),
(0x1ee87a0, 0x1b9f7fd4),
(0x1f19f88, 0x78972e8f),
(0x1f33a0c, 0x390c2deb),
(0x1f4e0fc, 0xe05e8c6b),
(0x1f5a718, 0x367432ae),
(0x1f61dcc, 0x7063e58a),
(0x1f85878, 0x21c00cea),
(0x1fc043c, 0x2676aaaa),
(0x1ffdb94, 0xc270eb02),
(0x202a618, 0x3a98aed2),
(0x2037b34, 0x115d5afc),
(0x203d92c, 0x11bced76),
(0x203da14, 0xf2628105),
(0x2066014, 0x97f32700),
(0x208a908, 0xa68e2f71),
(0x20ab8ac, 0x1daa2a78),
(0x20ba504, 0x73919ef6),
(0x20e71e0, 0x0b3fd1d3),
(0x2102278, 0x6c123def),
(0x21166dc, 0xee354161),
(0x2126478, 0x299493f4),
(0x2137090, 0x05ae2007),
(0x2148270, 0x34b52663),
(0x21482ac, 0xe381b5b6),
(0x21813b8, 0x94244de1),
(0x21a41e8, 0x02c38df5),
(0x21a8c4c, 0xf72700dd),
(0x21abbac, 0x34c2e7b5),
(0x21bcb24, 0x442739ad),
(0x21cbe84, 0x6e40d22c),
(0x21e2798, 0xdbf774d0),
(0x21f892c, 0xe90f1e0c),
(0x222beec, 0xa27f27f3),
(0x22394f4, 0x7f999a4f),
(0x22437ec, 0xf12d28f8),
(0x22480b0, 0xf58f3a7d),
(0x2261a0c, 0x89b28301),
(0x22a76c8, 0x1fe501e2),
(0x22b2018, 0xf079db5f),
(0x22cc610, 0xaf7d17b7),
(0x22cd4f8, 0x71c010cb),
(0x22d016c, 0x4a8daed0),
(0x22e1c04, 0xe1201aca),
(0x22f9994, 0xf3f0e4ee),
(0x2384f5c, 0x6b8a5eb1),
(0x23d5ecc, 0x5298a9c4),
(0x23e15b0, 0xc7bf0afb),
(0x23e248c, 0x2d67fecf),
(0x2407898, 0x4eef422a),
(0x241695c, 0x33ba9ce8),
(0x243e8b0, 0x833c1d2c),
(0x2460b64, 0x819c96ee),
(0x247caec, 0x0ebccbd6),
(0x24832b4, 0xf789d4b6),
(0x24938b8, 0x9f63baeb),
(0x24a7c64, 0x3384e552),
(0x24bce94, 0x7bfec208),
(0x24bd8f4, 0x9b5260cc),
(0x24ce8ec, 0xaf854888),
(0x24e741c, 0xda82f062),
(0x254401c, 0xbb1a5d5a),
(0x25a6a64, 0x24d202d3),
(0x2617878, 0x6ac71e5f),
(0x2617df0, 0x0e76bd90),
(0x268e9b8, 0x874d931c),
(0x26a8848, 0xefefd680),
(0x26e4f10, 0xfc2799f7),
(0x26e93d8, 0x1930ad55),
(0x26eea84, 0xfa2f742f),
(0x2701f30, 0xed9b92c4),
];
File diff suppressed because it is too large Load Diff
+11
View File
@@ -0,0 +1,11 @@
//! Static IL2CPP metadata restoration interfaces.
mod embedded;
mod keystream;
mod method_tokens;
pub use embedded::{embedded_metadata_size, extract_embedded_metadata};
pub use method_tokens::{
DEFAULT_METHOD_TOKEN_SEED, Error, ImageKeyDiscovery, Report, SeedDiscoveryReport,
discover_method_token_seeds, restore_method_tokens,
};
+12
View File
@@ -0,0 +1,12 @@
//! Shared IL2CPP metadata header primitives.
/// IL2CPP global-metadata sanity magic.
pub(crate) const MAGIC: u32 = 0xFAB1_1BAF;
/// Cheap check used by both platform scanners before opening a full metadata
/// file.
#[must_use]
pub fn is_metadata(data: &[u8]) -> bool {
data.get(0..4)
.is_some_and(|bytes| u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) == MAGIC)
}
+7 -3
View File
@@ -1,5 +1,9 @@
//! Unity il2cpp metadata de-obfuscation. //! Unity il2cpp metadata restoration.
mod metadata; pub mod android;
mod common;
mod structural;
pub mod windows;
pub use metadata::*; pub use common::is_metadata;
pub use structural::*;
@@ -27,8 +27,7 @@
//! metadata (its tokens already equal `local_index + 1`), so it is safe to run on //! metadata (its tokens already equal `local_index + 1`), so it is safe to run on
//! any il2cpp game — `remapped == 0` then reports that nothing changed. //! any il2cpp game — `remapped == 0` then reports that nothing changed.
/// il2cpp `global-metadata.dat` sanity magic (`Il2CppGlobalMetadataHeader.sanity`). use crate::common::MAGIC;
const MAGIC: u32 = 0xFAB1_1BAF;
/// Metadata format version this de-obfuscator understands. The struct strides /// Metadata format version this de-obfuscator understands. The struct strides
/// and header field offsets below are specific to it; other versions are left /// and header field offsets below are specific to it; other versions are left
+3
View File
@@ -0,0 +1,3 @@
//! Compatibility namespace for the shared structural metadata transform.
pub use crate::structural::*;
+1 -2
View File
@@ -3,8 +3,7 @@ name = "senbei-pe"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
description = "PE detection, unpacking, and validation for Senbei" description = "PE format parsing and address mapping for Senbei"
[dependencies] [dependencies]
senbei-crypto.workspace = true
thiserror.workspace = true thiserror.workspace = true
+231 -3
View File
@@ -1,5 +1,233 @@
//! PE detection, unpacking, and structural validation. //! Basic PE format parsing and address mapping.
mod engine; use thiserror::Error;
pub use engine::*; #[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum Error {
#[error("input is not a PE image")]
Invalid,
#[error("PE range is outside the input")]
OutOfBounds,
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Section {
pub virtual_address: u32,
pub virtual_size: u32,
pub raw_offset: u32,
pub raw_size: u32,
pub characteristics: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Headers {
pub pe_offset: usize,
pub is_pe32_plus: bool,
pub image_base: u64,
pub size_of_image: u32,
pub entry_rva: u32,
pub sections_offset: usize,
pub sections: u16,
}
pub fn parse(data: &[u8]) -> Result<Headers> {
if data.get(0..2) != Some(b"MZ") {
return Err(Error::Invalid);
}
let pe_offset = read_u32(data, 0x3c)? as usize;
if data.get(pe_offset..pe_offset + 4) != Some(b"PE\0\0") {
return Err(Error::Invalid);
}
let sections = read_u16(data, pe_offset + 6)?;
let optional_size = read_u16(data, pe_offset + 20)? as usize;
let optional = pe_offset.checked_add(24).ok_or(Error::OutOfBounds)?;
let magic = read_u16(data, optional)?;
let is_pe32_plus = magic == 0x20b;
if !is_pe32_plus && magic != 0x10b {
return Err(Error::Invalid);
}
let entry_rva = read_u32(data, optional + 16)?;
let image_base = if is_pe32_plus {
read_u64(data, optional + 24)?
} else {
read_u32(data, optional + 28)? as u64
};
let size_of_image = read_u32(data, optional + 56)?;
let sections_offset = optional
.checked_add(optional_size)
.ok_or(Error::OutOfBounds)?;
let table_size = usize::from(sections)
.checked_mul(40)
.ok_or(Error::OutOfBounds)?;
data.get(sections_offset..sections_offset + table_size)
.ok_or(Error::OutOfBounds)?;
Ok(Headers {
pe_offset,
is_pe32_plus,
image_base,
size_of_image,
entry_rva,
sections_offset,
sections,
})
}
pub fn sections(data: &[u8], headers: Headers) -> Result<Vec<Section>> {
(0..headers.sections)
.map(|index| {
let offset = headers
.sections_offset
.checked_add(usize::from(index) * 40)
.ok_or(Error::OutOfBounds)?;
Ok(Section {
virtual_size: read_u32(data, offset + 8)?,
virtual_address: read_u32(data, offset + 12)?,
raw_size: read_u32(data, offset + 16)?,
raw_offset: read_u32(data, offset + 20)?,
characteristics: read_u32(data, offset + 36)?,
})
})
.collect()
}
/// Read one PE data-directory entry as `(RVA, size)`.
pub fn data_directory(data: &[u8], headers: Headers, index: u16) -> Result<(u32, u32)> {
let directory_base = headers
.pe_offset
.checked_add(24)
.and_then(|offset| offset.checked_add(if headers.is_pe32_plus { 112 } else { 96 }))
.ok_or(Error::OutOfBounds)?;
let offset = directory_base
.checked_add(
usize::from(index)
.checked_mul(8)
.ok_or(Error::OutOfBounds)?,
)
.ok_or(Error::OutOfBounds)?;
Ok((read_u32(data, offset)?, read_u32(data, offset + 4)?))
}
/// Return the COFF characteristics bit field.
pub fn characteristics(data: &[u8], headers: Headers) -> Result<u16> {
read_u16(
data,
headers
.pe_offset
.checked_add(22)
.ok_or(Error::OutOfBounds)?,
)
}
pub fn rva_to_offset(data: &[u8], headers: Headers, rva: u32) -> Result<usize> {
if rva < headers.sections_offset as u32 {
return Ok(rva as usize);
}
for section in sections(data, headers)? {
let span = section.virtual_size.max(section.raw_size);
if rva >= section.virtual_address && rva < section.virtual_address.saturating_add(span) {
let offset = section
.raw_offset
.checked_add(rva - section.virtual_address)
.ok_or(Error::OutOfBounds)? as usize;
if offset < data.len() {
return Ok(offset);
}
}
}
Err(Error::OutOfBounds)
}
/// Map a complete RVA range backed by file bytes in the headers or one section.
/// Unlike a virtual mapping, this rejects a section's zero-filled tail.
pub fn rva_range(
data: &[u8],
headers: Headers,
rva: u32,
size: u32,
) -> Result<std::ops::Range<usize>> {
let header_size = read_u32(data, headers.pe_offset + 24 + 60)?;
let offset = if rva < header_size && size <= header_size - rva {
rva
} else {
sections(data, headers)?
.into_iter()
.find_map(|section| {
let delta = rva.checked_sub(section.virtual_address)?;
if delta >= section.raw_size || size > section.raw_size - delta {
return None;
}
section.raw_offset.checked_add(delta)
})
.ok_or(Error::OutOfBounds)?
} as usize;
let end = offset
.checked_add(size as usize)
.ok_or(Error::OutOfBounds)?;
data.get(offset..end).ok_or(Error::OutOfBounds)?;
Ok(offset..end)
}
fn read_u16(data: &[u8], offset: usize) -> Result<u16> {
let bytes: [u8; 2] = data
.get(offset..offset + 2)
.ok_or(Error::OutOfBounds)?
.try_into()
.map_err(|_| Error::OutOfBounds)?;
Ok(u16::from_le_bytes(bytes))
}
fn read_u32(data: &[u8], offset: usize) -> Result<u32> {
let bytes: [u8; 4] = data
.get(offset..offset + 4)
.ok_or(Error::OutOfBounds)?
.try_into()
.map_err(|_| Error::OutOfBounds)?;
Ok(u32::from_le_bytes(bytes))
}
fn read_u64(data: &[u8], offset: usize) -> Result<u64> {
let bytes: [u8; 8] = data
.get(offset..offset + 8)
.ok_or(Error::OutOfBounds)?
.try_into()
.map_err(|_| Error::OutOfBounds)?;
Ok(u64::from_le_bytes(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rva_ranges_require_file_backing_for_every_byte() {
let mut data = [0u8; 0x400];
let headers = Headers {
pe_offset: 0x40,
is_pe32_plus: false,
image_base: 0,
size_of_image: 0x2000,
entry_rva: 0x1000,
sections_offset: 0x100,
sections: 1,
};
for (offset, value) in [
(0x94, 0x200u32),
(0x108, 0x100),
(0x10c, 0x1000),
(0x110, 0x80),
(0x114, 0x200),
] {
data[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}
assert_eq!(rva_range(&data, headers, 0x1000, 0x80), Ok(0x200..0x280));
assert_eq!(rva_range(&data, headers, 0x100, 0x100), Ok(0x100..0x200));
for (rva, size) in [(0x1070, 0x20), (0x1080, 1), (0x1f0, 0x20), (u32::MAX, 4)] {
assert_eq!(
rva_range(&data, headers, rva, size),
Err(Error::OutOfBounds)
);
}
}
}
+416 -8
View File
@@ -2,12 +2,38 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "aes"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"
dependencies = [
"cipher",
"cpubits",
"cpufeatures",
]
[[package]] [[package]]
name = "anyhow" name = "anyhow"
version = "1.0.104" version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "bitflags"
version = "2.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.20.3" version = "3.20.3"
@@ -20,6 +46,16 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"crypto-common",
"inout",
]
[[package]] [[package]]
name = "console" name = "console"
version = "0.16.4" version = "0.16.4"
@@ -42,12 +78,93 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "const-oid"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8498c871161e1742aaa9d52551b2d6ebdd4c3d45a3be423e3728f33b955be550"
dependencies = [
"cfg-if",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
]
[[package]] [[package]]
name = "encode_unicode" name = "encode_unicode"
version = "1.0.0" version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "flate2"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"zlib-rs",
]
[[package]] [[package]]
name = "futures-core" name = "futures-core"
version = "0.3.34" version = "0.3.34"
@@ -72,6 +189,53 @@ dependencies = [
"slab", "slab",
] ]
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "goblin"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17582616a7718cca54cec18e534a76c7c4aec11a8b9a85695712f262fd15a4c8"
dependencies = [
"log",
"plain",
"scroll",
]
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "hybrid-array"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
dependencies = [
"typenum",
]
[[package]]
name = "indexmap"
version = "2.14.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07aa2048142242915a31d35844fb311e0e53fcca590c3a0a40dcf1b841fa09eb"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]] [[package]]
name = "indicatif" name = "indicatif"
version = "0.18.6" version = "0.18.6"
@@ -85,6 +249,21 @@ dependencies = [
"web-time", "web-time",
] ]
[[package]]
name = "inout"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
dependencies = [
"hybrid-array",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.104" version = "0.3.104"
@@ -102,6 +281,33 @@ version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "log"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "memmap2"
version = "0.9.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@@ -120,6 +326,12 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "plain"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
[[package]] [[package]]
name = "portable-atomic" name = "portable-atomic"
version = "1.15.0" version = "1.15.0"
@@ -144,6 +356,25 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rustix"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.23" version = "1.0.23"
@@ -160,49 +391,163 @@ dependencies = [
] ]
[[package]] [[package]]
name = "senbei-crypto" name = "scroll"
version = "1.1.0" version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1257cd4248b4132760d6524d6dda4e053bc648c9070b960929bf50cfb1e7add"
dependencies = [ dependencies = [
"scroll_derive",
]
[[package]]
name = "scroll_derive"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1a36a382ed65dbcc0ab47fd5e9a94112417ccd34560a392ef3b7b0f0ec39148"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.4",
]
[[package]]
name = "senbei-crypto"
version = "1.3.0"
dependencies = [
"aes",
"thiserror",
]
[[package]]
name = "senbei-elf"
version = "1.3.0"
dependencies = [
"goblin",
"thiserror",
]
[[package]]
name = "senbei-engine"
version = "1.3.0"
dependencies = [
"memmap2",
"senbei-crypto",
"senbei-elf",
"senbei-pe",
"serde",
"serde_json",
"sha2",
"tempfile",
"thiserror", "thiserror",
] ]
[[package]] [[package]]
name = "senbei-io" name = "senbei-io"
version = "1.1.0" version = "1.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"indicatif", "indicatif",
"libc", "libc",
"memmap2",
"owo-colors", "owo-colors",
"senbei-crypto",
"senbei-elf",
"senbei-engine",
"senbei-metadata", "senbei-metadata",
"senbei-pe", "senbei-pe",
"sha2",
"tempfile",
"walkdir", "walkdir",
"windows", "windows",
"zip",
] ]
[[package]] [[package]]
name = "senbei-metadata" name = "senbei-metadata"
version = "1.1.0" version = "1.3.0"
dependencies = [
"serde",
"thiserror",
]
[[package]] [[package]]
name = "senbei-pe" name = "senbei-pe"
version = "1.1.0" version = "1.3.0"
dependencies = [ dependencies = [
"senbei-crypto",
"thiserror", "thiserror",
] ]
[[package]] [[package]]
name = "senbei-wasm" name = "senbei-wasm"
version = "1.1.0" version = "1.3.0"
dependencies = [ dependencies = [
"console_error_panic_hook", "console_error_panic_hook",
"senbei-engine",
"senbei-io", "senbei-io",
"senbei-metadata", "senbei-metadata",
"senbei-pe",
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.4",
]
[[package]]
name = "serde_json"
version = "1.0.151"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sha2"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]] [[package]]
name = "slab" name = "slab"
version = "0.4.12" version = "0.4.12"
@@ -231,6 +576,19 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]] [[package]]
name = "thiserror" name = "thiserror"
version = "2.0.20" version = "2.0.20"
@@ -251,6 +609,18 @@ dependencies = [
"syn 3.0.4", "syn 3.0.4",
] ]
[[package]]
name = "typed-path"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.24" version = "1.0.24"
@@ -461,3 +831,41 @@ checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
dependencies = [ dependencies = [
"windows-link", "windows-link",
] ]
[[package]]
name = "zip"
version = "8.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
dependencies = [
"crc32fast",
"flate2",
"indexmap",
"memchr",
"typed-path",
"zopfli",
]
[[package]]
name = "zlib-rs"
version = "0.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34b31d188d9d685a4f9c7b46d6e36631b07058d2cfe190267adce54dc230bf12"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
[[package]]
name = "zopfli"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
dependencies = [
"bumpalo",
"crc32fast",
"log",
"simd-adler32",
]
+3 -2
View File
@@ -1,7 +1,8 @@
[package] [package]
name = "senbei-wasm" name = "senbei-wasm"
version = "1.1.0" version = "1.3.0"
edition = "2024" edition = "2024"
rust-version = "1.98.1"
description = "WebAssembly bindings for senbei (browser frontend assets live in web/)" description = "WebAssembly bindings for senbei (browser frontend assets live in web/)"
license = "AGPL-3.0-only" license = "AGPL-3.0-only"
@@ -11,7 +12,7 @@ crate-type = ["cdylib"]
[dependencies] [dependencies]
senbei-io = { path = "../senbei-io" } senbei-io = { path = "../senbei-io" }
senbei-metadata = { path = "../senbei-metadata" } senbei-metadata = { path = "../senbei-metadata" }
senbei-pe = { path = "../senbei-pe" } senbei-engine = { path = "../senbei-engine" }
wasm-bindgen = "0.2" wasm-bindgen = "0.2"
console_error_panic_hook = "0.1" console_error_panic_hook = "0.1"
+6 -6
View File
@@ -101,12 +101,12 @@ impl MetadataResult {
} }
} }
fn kind_str(kind: senbei_pe::Kind) -> &'static str { fn kind_str(kind: senbei_engine::Kind) -> &'static str {
match kind { match kind {
senbei_pe::Kind::NativeExe => "native-exe", senbei_engine::Kind::NativeExe => "native-exe",
senbei_pe::Kind::ManagedExe => "managed-exe", senbei_engine::Kind::ManagedExe => "managed-exe",
senbei_pe::Kind::NativeDll => "native-dll", senbei_engine::Kind::NativeDll => "native-dll",
senbei_pe::Kind::ManagedDll => "managed-dll", senbei_engine::Kind::ManagedDll => "managed-dll",
} }
} }
@@ -120,7 +120,7 @@ pub fn detect(input: &[u8]) -> Option<String> {
if senbei_metadata::is_metadata(input) { if senbei_metadata::is_metadata(input) {
return Some("metadata".to_string()); return Some("metadata".to_string());
} }
senbei_pe::detect(input).map(|d| kind_str(d.kind).to_string()) senbei_engine::detect(input).map(|d| kind_str(d.kind).to_string())
} }
/// Unpack a protected module. /// Unpack a protected module.
+10 -61
View File
@@ -1,76 +1,25 @@
# Senbei web # Senbei Web
Senbei running in the browser: the unpacker core compiled to WebAssembly, Senbei runs in the browser through the `senbei-wasm` crate. Files are read locally, unpacked in a worker, and offered back as downloads; no server receives input bytes.
wrapped in a small static page. Everything is client-side — files are read
into the page, unpacked locally, and offered back as downloads. Nothing is
uploaded; there is no server component.
## Features ## Features
- A legal notice is shown as a blocking dialog on page open; the tool is - Protected `.exe` and `.dll` files produce `<name>.unpack.*` downloads.
unusable until it is acknowledged. - External `.exe._` and `.dll._` companions are paired by filename.
- Dropped files land in a file list, not unpacked immediately: review the - `global-metadata.dat` produces `global-metadata.unpack.dat` when tokens change.
batch, remove mistakes, then press **Unpack**. A module and its `._` - Each output receives the same static integrity check as the CLI.
companion can be dropped in any order (or in separate drops) — companions
auto-pair by name (`Foo.dll._``Foo.dll`) and show as a badge on the
module's row; removing a module removes its companion too.
- Rows show state at a glance: black while staged, an animated blue bar
while unpacking, green on success (with a download button) and red on
failure.
- Drop one or more protected `.exe` / `.dll` modules → get `<name>.unpack.*`
downloads.
- Drop an il2cpp `global-metadata.dat` → de-obfuscated
`global-metadata.unpack.dat` (only when tokens actually change).
- Each output passes the same static integrity check as the CLI; suspect
outputs are flagged with the specific defects found.
## Architecture notes Every unpack uses a disposable Web Worker so a WebAssembly trap cannot freeze the page. A trapped DLL can be retried through the forced-EXE path, matching native routing.
- Every unpack runs in a **disposable Web Worker** (fresh wasm instance per ## Build
file): the UI stays responsive on 100 MB+ modules, and a wasm trap is
isolated to that worker.
- **Why workers matter for correctness:** the DLL-first routing probe relies
on `catch_unwind` to reject EXE-shell-layout DLLs, and panics cannot be
caught in WebAssembly — the probe traps the whole call. When a DLL unpack
traps, the app retries once in a new worker with the forced-EXE pipeline
(`unpack_file_force_exe`), reproducing the CLI's dll-first/exe-fallback
outcome. Spliced companion inputs skip the probe entirely (they are always
EXE-shell layout), exactly like the CLI.
- Rust panic messages are forwarded to the browser console
(`console_error_panic_hook`) — check devtools when reporting an issue.
## Building
Requires a Rust toolchain (`rust-toolchain.toml` in the repo root pins one,
including the `wasm32-unknown-unknown` target) and
[wasm-pack](https://rustwasm.github.io/wasm-pack/installer/).
```cmd ```cmd
cd senbei-wasm cd senbei-wasm
wasm-pack build --target web --release --out-dir ../web/pkg wasm-pack build --target web --release --out-dir ../web/pkg
``` ```
This produces `web/pkg/` (git-ignored). Then serve the `web/` directory with Serve `web/` with a static HTTP server, for example `python -m http.server -d web 8000`. Opening `index.html` with `file://` does not work because browser modules require HTTP.
any static file server and open `index.html`:
```cmd
python -m http.server -d web 8000
:: -> http://localhost:8000
```
(Opening `index.html` via `file://` won't work — ES modules require HTTP.)
## Layout ## Layout
``` `senbei-wasm/src/lib.rs` contains the bindings. `web/app.js` manages the dropzone and downloads, `web/worker.js` runs one unpack job per worker, and `web/pkg/` contains ignored wasm-pack output.
senbei-wasm/ the senbei-wasm cdylib crate (own Cargo.lock, outside the
workspace; depends on the senbei-pe/-io/-metadata crates)
└── src/lib.rs #[wasm_bindgen] bindings: detect / unpack_file /
unpack_file_force_exe / deobfuscate_metadata
web/
├── index.html the page
├── app.js dropzone, file list, worker orchestration, downloads
├── worker.js one-shot unpack worker (fresh wasm instance per file)
├── style.css
└── pkg/ wasm-pack output (git-ignored; build from senbei-wasm/)
```