15 Commits
Author SHA1 Message Date
Momoko-Ayase ba380a5774 docs: point README at GitBook and restore the legal-notice heading [skip ci]
Product docs already live on crackproof-research; keep a minimal README
(usage, legal notice, license) so CI can still extract LEGAL-NOTICE.md.
2026-09-15 23:27:24 +08:00
Momoko-Ayase d6224e639c chore: bump version to 1.3.1 2026-09-10 20:58:44 +08:00
Momoko-Ayase 9b8024b132 fix(windows): re-arm neutralized TLS field relocations for PE32 DLLs
The packer demotes the four base-relocation entries covering the TLS
directory's VA fields to IMAGE_REL_BASED_ABSOLUTE padding, because its
own loader fixes TLS up by hand. Restored verbatim, a DLL mapped off its
preferred base keeps stale VAs in its TLS directory and the OS loader
faults in LdrpAllocateTlsEntry while writing the TLS slot index through
the unrelocated AddressOfIndex (observed as a 0xc0000005 startup
failure).

Walk the restored BaseReloc blocks and promote those entries back to
IMAGE_REL_BASED_HIGHLOW, gated on is_dll so EXE output stays
byte-identical.
2026-09-10 20:42:39 +08:00
Momoko-Ayase 512a627066 web: recognize Android targets and point users at the CLI
Dropping an .apk/.apks/.xapk package or a .so library reported
"not recognized — will be skipped", which reads as "not protected"
when the real gap is that the Android pipeline (filesystem
orchestration in senbei-io) has no wasm build. These files now get an
explicit android pseudo-kind at staging time: the row explains that
the CLI handles them, and they neither enable the Unpack button nor
error out mid-run.
2026-09-10 09:32:58 +08:00
Momoko-Ayase a230c37281 web: stack file-row status below the name on narrow screens
On phone-width viewports the right-aligned status column shared a flex
line with a long file name and wrapped one word per line. Below 560px
the row now wraps: name and action icons keep the first line and the
status takes a full-width line underneath.
2026-09-10 09:29:23 +08:00
Momoko-Ayase 4f59e25652 ci: declare rustfmt/clippy components in rust-toolchain.toml
The 1.98.1 pin installs without rustfmt and clippy, so the fmt and
clippy jobs fail at the shim before running. Listing the components in
the toolchain file makes rustup auto-install them on every host,
including the CI runners that invoke cargo with no setup action.
2026-09-10 09:28:50 +08:00
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
82 changed files with 3573 additions and 2618 deletions
+20 -78
View File
@@ -1,98 +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 and protected 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.
Android (AArch64) shared libraries: a Cargo workspace with a pure, panic-free,
no-I/O PE unpacker core (`senbei-pe/`, built on `senbei-crypto/`), il2cpp Read the [Senbei design notes](https://xn--ri8h.gitbook.io/crackproof-research/senbei) before changing architecture or pipeline boundaries.
metadata de-obfuscators (`senbei-metadata/` for the Windows structural
variant, `senbei-android-metadata/` for the Android seeded-permutation and
embedded-blob variants), the native-only Android pipeline
(`senbei-android-crypto/`, `senbei-android-engine/`, `senbei-android-elf/`),
filesystem/CLI orchestration (`senbei-io/`, including the Android
single-library/package glue in `senbei-io/src/android.rs`), 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). The
Android corpus lives in `samples/android/` (one extracted app tree per
subdirectory) and is covered by `tests/android_samples.rs`;
`SENBEI_ANDROID_SAMPLES` overrides that location. Do not
delete `samples/` with `rm -rf` — it may be a junction; use git
worktree-aware cleanup.
## Hard rules ## Crate Boundaries
- **The PE unpacker core stays pure**: `senbei-pe` and `senbei-crypto` have no `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/`.
file I/O, no `unsafe`, no panics across the public boundary, no
platform-specific code. Everything `senbei-wasm` compiles must keep building
for `wasm32-unknown-unknown` (`cargo check --target wasm32-unknown-unknown`
at the workspace root covers it — the Android crates do compile to wasm, but
nothing on the wasm path calls them).
- **The Android crates are native-only orchestration-style crates**:
`senbei-android-engine`/`senbei-android-elf` memory-map inputs and write a
module workspace to disk (the restore is a two-phase design consuming that
workspace). Keep them off the web app's code paths; `senbei-io`'s
`android.rs` is the only caller the CLI uses.
- **`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. Product documentation lives at <https://xn--ri8h.gitbook.io/crackproof-research/senbei>; update that site (not this repository) 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
+38 -71
View File
@@ -2,12 +2,6 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]] [[package]]
name = "aes" name = "aes"
version = "0.9.3" version = "0.9.3"
@@ -158,8 +152,6 @@ version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [ dependencies = [
"crc32fast",
"miniz_oxide",
"zlib-rs", "zlib-rs",
] ]
@@ -306,16 +298,6 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@@ -418,53 +400,11 @@ dependencies = [
"syn 3.0.4", "syn 3.0.4",
] ]
[[package]]
name = "senbei-android-crypto"
version = "1.2.0"
dependencies = [
"aes",
"thiserror",
]
[[package]]
name = "senbei-android-elf"
version = "1.2.0"
dependencies = [
"memmap2",
"senbei-android-crypto",
"serde",
"serde_json",
"sha2",
"tempfile",
"thiserror",
]
[[package]]
name = "senbei-android-engine"
version = "1.2.0"
dependencies = [
"goblin",
"memmap2",
"senbei-android-crypto",
"serde",
"serde_json",
"sha2",
"tempfile",
"thiserror",
]
[[package]]
name = "senbei-android-metadata"
version = "1.2.0"
dependencies = [
"serde",
"thiserror",
]
[[package]] [[package]]
name = "senbei-cli" name = "senbei-cli"
version = "1.2.0" version = "1.3.1"
dependencies = [ dependencies = [
"senbei-engine",
"senbei-io", "senbei-io",
"senbei-metadata", "senbei-metadata",
"sha2", "sha2",
@@ -473,23 +413,47 @@ dependencies = [
[[package]] [[package]]
name = "senbei-crypto" name = "senbei-crypto"
version = "1.2.0" version = "1.3.1"
dependencies = [ dependencies = [
"aes",
"thiserror",
]
[[package]]
name = "senbei-elf"
version = "1.3.1"
dependencies = [
"goblin",
"thiserror",
]
[[package]]
name = "senbei-engine"
version = "1.3.1"
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.2.0" version = "1.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"flate2",
"indicatif", "indicatif",
"libc", "libc",
"memmap2",
"owo-colors", "owo-colors",
"senbei-android-elf", "senbei-crypto",
"senbei-android-engine", "senbei-elf",
"senbei-android-metadata", "senbei-engine",
"senbei-metadata", "senbei-metadata",
"senbei-pe", "senbei-pe",
"sha2", "sha2",
@@ -501,13 +465,16 @@ dependencies = [
[[package]] [[package]]
name = "senbei-metadata" name = "senbei-metadata"
version = "1.2.0" version = "1.3.1"
dependencies = [
"serde",
"thiserror",
]
[[package]] [[package]]
name = "senbei-pe" name = "senbei-pe"
version = "1.2.0" version = "1.3.1"
dependencies = [ dependencies = [
"senbei-crypto",
"thiserror", "thiserror",
] ]
+6 -11
View File
@@ -1,11 +1,9 @@
[workspace] [workspace]
members = [ members = [
"senbei-android-crypto",
"senbei-android-elf",
"senbei-android-engine",
"senbei-android-metadata",
"senbei-cli", "senbei-cli",
"senbei-crypto", "senbei-crypto",
"senbei-elf",
"senbei-engine",
"senbei-io", "senbei-io",
"senbei-metadata", "senbei-metadata",
"senbei-pe", "senbei-pe",
@@ -17,15 +15,14 @@ exclude = ["senbei-wasm"]
resolver = "2" resolver = "2"
[workspace.package] [workspace.package]
version = "1.2.0" version = "1.3.1"
edition = "2024" edition = "2024"
rust-version = "1.85" rust-version = "1.98.1"
license = "AGPL-3.0-only" license = "AGPL-3.0-only"
[workspace.dependencies] [workspace.dependencies]
aes = "0.9" aes = "0.9"
anyhow = "1" anyhow = "1"
flate2 = "1"
goblin = "0.10" goblin = "0.10"
indicatif = "0.18" indicatif = "0.18"
libc = "0.2" libc = "0.2"
@@ -43,11 +40,9 @@ windows = { version = "0.62", features = [
"Win32_System_SystemInformation", "Win32_System_SystemInformation",
] } ] }
zip = { version = "8", default-features = false, features = ["deflate"] } zip = { version = "8", default-features = false, features = ["deflate"] }
senbei-android-crypto = { path = "senbei-android-crypto" }
senbei-android-elf = { path = "senbei-android-elf" }
senbei-android-engine = { path = "senbei-android-engine" }
senbei-android-metadata = { path = "senbei-android-metadata" }
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" }
+19 -76
View File
@@ -1,89 +1,32 @@
# Senbei # Senbei
A static unpacker for Crackproof-protected 64-bit and 32-bit PE files and A static unpacker for CrackProof-protected Windows PE files and Android AArch64 shared libraries.
protected Android (AArch64) shared libraries. Point it at a file, an app
package, 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._ > _"Crackproof"? It's senbei (煎餅 — rice cracker). Cracks itself._
Senbei reads a protected `.exe` or `.dll`, replays the unpacking algorithm ## Usage
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 ```cmd
progress bar, and a run log. A browser version (WebAssembly, fully client-side) cargo build --release
lives in [`web/`](web/). senbei protected.exe
senbei game.apk
senbei "C:\Games\MyGame"
```
Outputs are written below an `unpack` directory unless `--out` is supplied.
Full documentation: <https://xn--ri8h.gitbook.io/crackproof-research/senbei>
## Legal notice and intended use ## Legal notice and intended use
**Read this before using Senbei.** **Read this before using Senbei.**
- Senbei is a research and interoperability tool. It exists to enable lawful - Senbei is a research and interoperability tool. It exists to enable lawful reverse engineering, security research, preservation, and interoperability with software you already legitimately possess.
reverse engineering, security research, preservation, and interoperability - **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.
with software you already legitimately possess. - 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, and distributes no cracks or copyrighted content. (One Android packaging variant's embedded metadata layer is unwrapped with an XOR keystream recovered from a ciphertext/plaintext pair during analysis of a single build; that keystream is research output shipped with the unpacker, not a vendor-distributed key, and builds it doesn't match are left alone.)
- **Only process binaries you own or are explicitly authorized to analyze.** - Senbei does not enable online play, license fraud, or cheating, and must not be used to redistribute decrypted binaries. Do not upload outputs anywhere.
Depending on your jurisdiction and license agreements, circumventing - The authors provide this software "as is", without warranty of any kind, and accept no liability for misuse. See [LICENSE](LICENSE) (AGPL-3.0).
technological protection measures may be restricted (for example under - "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.
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, and
distributes no cracks or copyrighted content. (One Android packaging
variant's embedded metadata layer is unwrapped with an XOR keystream
recovered from a ciphertext/plaintext pair during analysis of a single
build; that keystream is research output shipped with the unpacker, not a
vendor-distributed key, and builds it doesn't match are left alone.)
- 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
| Kind | Description |
| --- | --- |
| `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. |
| Android `.so` | Protected AArch64 shared library, statically restored (hollowed sections + stripped dynamic tables rebuilt). |
| `.apk` / `.apks` / `.xapk` | App packages; protected entries inside are restored, preserving the package's internal layout. |
Detection is content-based (header key-table at offset 4096, magic `KONN`),
not extension-based — app packages are the one exception, recognised by
extension plus the zip magic because they are containers. Anything
unrecognized is left untouched.
## Quick start
```cmd
cargo build --release
senbei protected.exe
:: -> unpack\protected.unpack.exe
senbei game.apk
:: -> unpack\game.apk\lib\arm64-v8a\libil2cpp.unpack.so
senbei "C:\Games\MyGame"
:: -> C:\Games\MyGame\unpack\... (recursive, skips non-targets)
```
Every output is sanity-checked statically; structurally broken results are
flagged as suspect rather than silently trusted.
## Documentation
- [Usage reference](docs/usage.md) — CLI flags, exit codes, integrity check
- [Design](docs/design.md) — architecture, routing, and error model
- [Development](docs/development.md) — building, testing, environment variables
- [Web version](web/README.md) — run Senbei in a browser
## License ## License
-238
View File
@@ -1,238 +0,0 @@
# Design
Senbei is a fully static unpacker: it replays the unpacking algorithm on the
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
Senbei is a Cargo workspace split into a pure core and thin shells around it:
- **`senbei-pe/`** — the core. Pure functions over byte slices: no file I/O,
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-android-crypto/`** — container primitives of the Android
(AArch64) protection scheme: the word/record ciphers, the GF(2³²)
transform, the AES-augmented segment transform, and the Huffman/LZ decoder.
- **`senbei-android-engine/`** — stage-1/stage-2 extraction: finds the
appended payload section, decrypts the stage-1 header and stage-2 payload,
and walks the recursive record streams to decode every module. Native-only
(memory-maps the input, writes the module set to a workspace directory).
- **`senbei-android-elf/`** — the restore: replays the decoded target-image
and fixup containers onto a hollowed ELF and rebuilds the dynamic-linker
tables (hash tables, symbols, relocations) the protector stripped.
Native-only.
- **`senbei-android-metadata/`** — the Android metadata variants: the seeded
five-round MethodDef-RID permutation restore (v31), seed discovery, and the
embedded-metadata XOR unwrap (`keystream.rs`).
- **`senbei-io/`** — filesystem and orchestration: recursive folder scanning,
per-run log file, progress bar, Explorer-friendly exit pause, the
single-file/folder orchestration in `job.rs` (incl. the wasm-safe in-memory
byte API used by the web frontend), and `android.rs` — the Android
single-library / folder / app-package orchestration.
- **`senbei-cli/`** — the `senbei` binary: argument parsing + dispatch. The
integration test suite (incl. the golden corpus test) lives in
`senbei-cli/tests/`.
```
senbei-cli/
└── 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)
├── android.rs Android single-library / folder / package
│ orchestration, cross-source dedup
├── scan.rs recursive target discovery (PE + metadata + Android)
├── 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/
├── primitives.rs decrypt_data* steps, key derivation
├── bytecode.rs bytecode VM
├── tables.rs constant tables
└── crc32.rs checksum
senbei-pe/src/engine/ pure, panic-free, no-I/O core
├── mod.rs detection + unpack_auto dispatch
├── error.rs structured error taxonomy
├── integrity.rs static post-unpack sanity check
├── parallel.rs deterministic block-parallel fan-out
├── layout/ layout discovery + validation
│ ├── dd8.rs .text dd8 key-formula + shift selection
│ ├── discovery.rs layout candidate discovery (trial-and-validate)
│ └── image.rs PE image reconstruction helpers
├── exe/
│ ├── pipeline.rs EXE pipeline (PE32+ and PE32 orchestration)
│ └── pipeline/pe32.rs PE32-specific EXE restore
└── dll/
└── pipeline.rs native + managed DLL pipeline
senbei-android-crypto/src/
└── protector.rs container ciphers, GF(2^32), Huffman/LZ decoder
senbei-android-engine/src/
├── stage1.rs payload-section discovery + stage-1 header/payload
├── stream.rs record-stream parsing
├── extract.rs recursive module extraction (writes the workspace)
├── probe.rs protected-library content probe
└── report.rs machine-readable extraction report
senbei-android-elf/src/
├── restore.rs image restore + dynamic-table rebuild
├── layout.rs ELF layout parsing
├── artifact.rs module-workspace index loading
└── hash.rs SysV/GNU hash table rebuild
senbei-android-metadata/src/
├── method_tokens.rs seeded RID permutation restore + seed discovery
├── embedded.rs embedded-metadata blob locate + XOR unwrap
└── keystream.rs recovered keystream table (one observed build)
```
## Detection and routing
Detection is content-based (`unpacker::detect`), never extension-based: the
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`). The folder scan additionally
classifies Android targets: an ELF64/AArch64 prefix promotes the file to a
full protection probe (`senbei_android_engine::is_protected_libil2cpp`), and a
package extension plus zip magic marks an app package for container
extraction.
`unpack_auto` then dispatches:
- `NativeExe` / `ManagedExe` → the EXE pipeline (handles both PE32+ and
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
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
Some builds split a protected module into an on-disk loader stub plus an
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
Both pipelines are **heuristic with trial-and-validate**: where a layout
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
includes a small VM (`bytecode.rs`) that generates and interprets those
programs rather than hardcoding each variant's constants.
## The Android pipeline
The Android scheme hollows an ELF64/AArch64 shared object: section bodies are
zeroed in the file and the original bytes move into an encrypted payload
appended as a `SHT_LOUSER` section (invisible to the dynamic loader). Restore
is two-phase:
1. **Extract** (`senbei-android-engine`): decrypt the stage-1 parameter block
and stage-2 payload from the payload section, then walk the recursive
record streams — each decoded module may interpret a further nested stream
— into a temporary module workspace with a JSON index.
2. **Restore** (`senbei-android-elf`): decode the target-image container onto
a copy of the hollowed file, apply the compact fixup database (the
relocations stripped from `.rela.dyn`), and rebuild the dynamic-linker
tables the loader needs (SysV/GNU hash, symbol and string tables,
`.rela.dyn`/`.rela.plt`). Validation is structural and total: mismatched
container sizes, descriptor bounds, or a rebuilt table overhanging its
section fail the restore rather than emit a broken image.
il2cpp metadata comes in three shapes, all routed through
`job::deobfuscate_metadata_to` / `android::restore_metadata_bytes`:
- **structural (Windows `-GMD`)**: sparse method tokens remapped to the
contiguous per-module range, keyless, idempotent (`senbei-metadata`).
- **seeded permutation (Android v31)**: MethodDef RIDs permuted by a keyed
five-round transform; the seed is recovered by intersecting per-image key
residues, and the restore validates every RID — a wrong seed errors and the
structural remap takes over (`senbei-android-metadata`).
- **embedded blob**: no metadata file in the app at all; a slim blob sits in
the library's data section under a per-word XOR layer. After a restore the
blob is located by content (two known plaintext header words against the
embedded keystream) and unwrapped to a standalone `global-metadata.dat`.
Key derivation is untraced — the shipped keystream covers the one observed
build, and other builds simply never match the probe.
Packages (`.apk`/`.apks`/`.xapk`) are containers, not targets: entries are
extracted to a temporary workspace and content-probed like loose files.
Cross-source duplicates (a library loose in the tree *and* inside its
package) are restored once, preferring the loose file, then the `.apk`, then
bundle splits.
## Integrity check
Every produced image passes through `integrity::check` — a static, execution-
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
Section decrypt/decompress blocks write disjoint output spans and read only
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
The public API never panics: every pipeline runs under a `catch_unwind`
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.
-126
View File
@@ -1,126 +0,0 @@
# Development
## Building
Requires a Rust toolchain (MSVC backend is the default on Windows;
`rustup-init.exe` from <https://rustup.rs> installs it). The pinned toolchain
and targets are in `rust-toolchain.toml`.
```cmd
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
```cmd
cargo test --release
```
The suite covers CLI behavior, detection, the folder driver, the run log, and
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
> 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)
- `DD8_SHIFT` — override the `decrypt_data8` page-XOR shift (`99` skips dd8
entirely).
- `SEL_DIAG` — print the dd8 selector's scores: the per-shift `0xCC` counts and
the plaintext baseline they are compared against (PE32+), and the per-formula
counts, baseline and net gain (PE32).
- `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).
- `SENBEI_ANDROID_SAMPLES` — override the Android corpus location (default
`samples/android/`; see `samples/README.md`). The Android corpus test pins
restored outputs with SHA-256 sidecar files next to each protected input
and documents known restore gaps with empty `<base>.restore-fails` markers.
## Conventions
- The `senbei-pe/` core (and its `senbei-crypto/` base) is pure: no file I/O,
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
```
senbei/
├── Cargo.toml workspace root (members: the senbei-* crates)
├── rust-toolchain.toml pinned toolchain + targets
├── senbei-cli/ senbei binary (default member)
│ └── tests/ CLI, detection, golden, and folder tests
├── senbei-pe/ pure unpacker core (see docs/design.md)
├── senbei-crypto/ crypto/compression primitives
├── senbei-metadata/ il2cpp metadata de-obfuscation
├── senbei-io/ filesystem, scanning, CLI orchestration
├── senbei-wasm/ WebAssembly bindings crate (own Cargo.lock,
│ outside the workspace; builds into web/pkg/)
├── samples/ local-only test corpus (git-ignored)
├── web/ static browser frontend assets (+ built pkg/)
├── docs/ usage, design, and development documentation
└── .github/ CI workflows and issue templates
```
## Web build
See [web/README.md](../web/README.md). In short:
```cmd
cd senbei-wasm
wasm-pack build --target web --release --out-dir ../web/pkg
```
then serve `web/` statically and open `index.html`. Everything runs
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.
-163
View File
@@ -1,163 +0,0 @@
# Usage
```
senbei <file|folder> [--out DIR] [-v|--verbose] [-q|--quiet]... [--scan-all]
[--no-log] [--no-pause] [-V|--version] [-h|--help]
```
Real runs print `Senbei <version>` once at start. Use `-V` / `--version` to
print the version and exit.
## Single file
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
senbei app.exe
:: -> unpack\app.unpack.exe
:: -> unpack\senbei-YYYYMMDD-HHMMSS.log
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
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.
## Android targets
Senbei also restores Android (AArch64) protected shared libraries and app
packages:
- **`.so`** — a protected library is hollowed out on disk: its original
sections live in an encrypted payload appended to the file, and senbei
rebuilds the static image from it. Output: `libil2cpp.unpack.so`.
- **`.apk`** — entries are extracted to a temporary workspace and
content-probed like loose files; protected libraries and metadata blobs
inside are restored to `<out>/<apk name>/<entry path>`.
- **`.apks` / `.xapk`** — split-package bundles; each nested `.apk` is opened
and searched the same way, under `<out>/<bundle name>/<split name>/...`.
When a restored il2cpp library carries its metadata embedded in its data
section (no standalone `global-metadata.dat` in the app at all), senbei
unwraps the blob and writes it next to the library as
`global-metadata.unpack.dat`. One observed packaging variant wraps the blob in
a per-word XOR layer whose keys are generated at runtime and stored nowhere;
senbei ships the keystream recovered from the one build known to use it and
content-probes for it — builds with a different keystream are silently
skipped (the library itself is still fully restored).
The same content may appear loose in a folder, in its `.apk`, and in a bundle
side by side: identical content is restored once, at the loose file's
destination. A restored library is validated structurally by the restore
itself (the rebuild refuses inconsistent layouts); a protected library that
fails validation counts as an error, not a suspect.
## Folder mode
Senbei walks the directory recursively, skips any subdirectory literally named
`unpack`, and unpacks every file it recognises as protected (by content, not
extension — renamed files and `.bak` backups are still found; packages are the
one exception, recognised by extension plus the zip magic because they are
containers). 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
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
`._` 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,
counted, and logged, and the run continues. Folder mode finishes with a summary
line, then duration:
```
12 unpacked · 3 skipped · 0 errors · 1 suspect · 2 metadata
done in 1234 ms
```
The `packages` count appears (as `· N packages`) only when Android app
packages were processed.
## Integrity check
(PE outputs only — Android restores carry their own structural validation; see
[Android targets](#android-targets).)
A successful unpack is not always a runnable one: a layout heuristic can pick
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:
- malformed DOS/PE headers, bad optional-header magic, implausible section
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
| Flag | Behavior |
| --- | --- |
| `--out DIR` | Write outputs (and the log, unless `--no-log`) under `DIR`. |
| `-v`, `--verbose` | Print detailed per-stage progress (and the destination path) for each file — `[N/9]` stages for PE targets, container/segment lines for Android libraries. In folder mode this replaces the progress bar. |
| `-q`, `--quiet` | Once: hide progress bar and per-file lines; keep banner, summary, and duration. Twice (`-q -q`): suppress all stdio (exit code only). |
| `--no-log` | Do not write `senbei-*.log`. Console output is unchanged by this flag alone. |
| `--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. |
| `--no-pause` | Skip the "Press Enter to exit" prompt (for scripted runs). |
| `-V`, `--version` | Print `Senbei <version>` and exit. |
| `-h`, `--help` | Show usage. |
On Windows, when launched from Explorer (the process owns its console) senbei
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 |
| --- | --- |
| `0` | Success (single file restored, or folder run with no errors). |
| `1` | At least one file failed, a scan probe was unreadable, or a single-file unpack errored. |
| `2` | Usage error: no path given, unknown option, missing `--out` value, or multiple input paths (help printed). |
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.
+5 -1
View File
@@ -1,3 +1,7 @@
[toolchain] [toolchain]
channel = "stable" channel = "1.98.1"
# CI invokes rustfmt/clippy through the rustup shim with no setup action, so
# the pinned toolchain must declare its components here — the runner images
# only preinstall them for their default toolchain.
components = ["rustfmt", "clippy"]
targets = ["x86_64-pc-windows-msvc", "wasm32-unknown-unknown"] targets = ["x86_64-pc-windows-msvc", "wasm32-unknown-unknown"]
+15 -97
View File
@@ -1,105 +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.
## Android corpus (`samples/android/`)
The `android/` subfolder holds Android samples, one **extracted app tree** per
subdirectory (the layout an APK unpacks to: `lib/<abi>/*.so`,
`assets/.../global-metadata.dat`, ...). The test
(`tests/android_samples.rs`) finds protected AArch64 libraries by content and
restores them through the real pipeline. `SENBEI_ANDROID_SAMPLES` overrides
the corpus location.
Sidecar conventions (all next to the protected `.so` input):
| File | Meaning |
| ---- | ------- |
| `<base>.golden.so.sha256` | Expected SHA-256 of the restored library |
| `<base>.golden.metadata.sha256` | Expected SHA-256 of the unwrapped embedded metadata blob (when the library carries one) |
| `<base>.restore-fails` | Empty marker: this input's restore is a known gap and *must* fail (a future fix fails the test, prompting marker removal) |
A missing sidecar is a warning (with the computed digest printed, ready to
promote), never a failure. App packages (`.apk`/`.apks`/`.xapk`) dropped into
a tree are exercised by folder mode as containers.
-301
View File
@@ -1,301 +0,0 @@
use crate::error::{Error, Result, invalid};
pub(crate) const SHT_NOBITS: u32 = 8;
pub(crate) const SHT_LOUSER: u32 = 0x8000_0000;
pub(crate) const SHF_ALLOC: u64 = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LoadSegment {
pub offset: u64,
pub virtual_address: u64,
pub file_size: u64,
pub memory_size: u64,
pub flags: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) 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(crate) struct ElfLayout {
pub entrypoint: u64,
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)? != 0xb7 {
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)? != 1 {
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)?,
};
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()
));
}
};
Ok(Self {
entrypoint,
program_headers,
section_headers,
section_name_index,
private_section_index,
})
}
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 section_names(&self, data: &[u8]) -> Result<Vec<String>> {
let table = self.section_headers[self.section_name_index];
let strings = slice_u64(data, table.offset, table.size)?;
self.section_headers
.iter()
.map(|section| {
let offset = section.name as usize;
if offset >= strings.len() {
return Ok(String::new());
}
let end = strings[offset..]
.iter()
.position(|&byte| byte == 0)
.map_or(strings.len(), |length| offset + length);
Ok(String::from_utf8_lossy(&strings[offset..end]).into_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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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()))
}
-10
View File
@@ -1,10 +0,0 @@
//! Static restoration of the current protected AArch64 `libil2cpp.so`.
mod artifact;
mod error;
mod hash;
mod layout;
mod restore;
pub use error::Error;
pub use restore::{RestoreOptions, RestoreReport, restore_libil2cpp};
-20
View File
@@ -1,20 +0,0 @@
[package]
name = "senbei-android-engine"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "Static Stage 1 and Stage 2 extraction for Senbei Android"
[dependencies]
goblin.workspace = true
memmap2.workspace = true
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
tempfile.workspace = true
thiserror.workspace = true
senbei-android-crypto.workspace = true
[lints]
workspace = true
-14
View File
@@ -1,14 +0,0 @@
[package]
name = "senbei-android-metadata"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
description = "IL2CPP metadata restoration for Senbei Android"
[dependencies]
serde.workspace = true
thiserror.workspace = true
[lints]
workspace = true
+1
View File
@@ -13,6 +13,7 @@ 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
+2 -3
View File
@@ -104,8 +104,7 @@ fn print_help() {
\x20 these" \x20 these"
); );
println!( println!(
" --scan-all probe every file in a folder, including ones the scan\n\ " --scan-all probe selected .exe/.dll/.so/metadata names below the\n\
\x20 pre-filter skips (under 4128 bytes, extensionless,\n\ \x20 size floor; other filenames remain excluded."
\x20 or a bulk-asset extension). Much slower on large trees."
); );
} }
+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
@@ -1,4 +1,4 @@
//! Cryptographic and container primitives used by Senbei Android. //! Android container cryptography and decoding primitives.
mod protector; mod protector;
@@ -359,7 +359,7 @@ pub struct HuffmanLzDecoder {
impl HuffmanLzDecoder { impl HuffmanLzDecoder {
/// Build the full 16-bit prefix lookup used by the static decoder. /// Build the full 16-bit prefix lookup used by the static decoder.
pub fn new(tree: &[u8]) -> Result<Self> { pub fn new(tree: &[u8]) -> Result<Self> {
if tree.len() < 256 * 3 || tree.len() % 3 != 0 { if tree.len() < 256 * 3 || !tree.len().is_multiple_of(3) {
return invalid(format!("invalid Huffman tree size 0x{:x}", tree.len())); return invalid(format!("invalid Huffman tree size 0x{:x}", tree.len()));
} }
let mut result = Self { let mut result = Self {
@@ -552,7 +552,7 @@ pub fn transform_segment(
let mut state = seed; let mut state = seed;
let mut left = 0xe34e_ac63_u32; let mut left = 0xe34e_ac63_u32;
let mut right = 0x07b4_8238_u32; let mut right = 0x07b4_8238_u32;
for (index, chunk) in transformed.chunks_exact_mut(4).enumerate() { for (index, chunk) in transformed.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let index32 = u32::try_from(index) let index32 = u32::try_from(index)
.map_err(|_| Error::Invalid("segment word index exceeds u32".to_owned()))?; .map_err(|_| Error::Invalid("segment word index exceeds u32".to_owned()))?;
left = state left = state
@@ -564,10 +564,7 @@ pub fn transform_segment(
.wrapping_add(right.wrapping_sub(0x1605_a81c).wrapping_mul(right)) .wrapping_add(right.wrapping_sub(0x1605_a81c).wrapping_mul(right))
.wrapping_shl(index32 & 7); .wrapping_shl(index32 & 7);
state = left ^ right; state = left ^ right;
let bytes: [u8; 4] = chunk let mut value = u32::from_le_bytes(*chunk);
.try_into()
.map_err(|_| Error::Invalid("invalid transformed word".to_owned()))?;
let mut value = u32::from_le_bytes(bytes);
value = value.wrapping_add(0xb43b_9baf_u32.wrapping_mul(index32 & 0x0d)); value = value.wrapping_add(0xb43b_9baf_u32.wrapping_mul(index32 & 0x0d));
value ^= 0xaf57_f7fb_u32.wrapping_mul(index32 & 3); value ^= 0xaf57_f7fb_u32.wrapping_mul(index32 & 3);
value = value.wrapping_sub(state) ^ state; value = value.wrapping_sub(state) ^ state;
@@ -577,13 +574,10 @@ pub fn transform_segment(
if decrypt_aes { if decrypt_aes {
let cipher = Aes256::new_from_slice(aes_key) let cipher = Aes256::new_from_slice(aes_key)
.map_err(|_| Error::Invalid("invalid AES-256 key length".to_owned()))?; .map_err(|_| Error::Invalid("invalid AES-256 key length".to_owned()))?;
let aligned_size = transformed.len() & !0x0f;
let mut previous = [0_u8; 16]; let mut previous = [0_u8; 16];
for chunk in transformed[..aligned_size].chunks_exact_mut(16) { for chunk in transformed.as_chunks_mut::<16>().0 {
let mut ciphertext = [0_u8; 16]; let ciphertext = *chunk;
ciphertext.copy_from_slice(chunk); cipher.decrypt_block((&mut *chunk).into());
// chunk is exactly one block (chunks_exact_mut(16)).
cipher.decrypt_block(chunk.try_into().expect("chunk is one block"));
for (byte, prior) in chunk.iter_mut().zip(previous) { for (byte, prior) in chunk.iter_mut().zip(previous) {
*byte ^= prior; *byte ^= prior;
} }
+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! {
@@ -1,13 +1,13 @@
[package] [package]
name = "senbei-android-crypto" name = "senbei-elf"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
license.workspace = true license.workspace = true
description = "Protector container primitives for Senbei Android" description = "ELF format parsing and structural utilities for Senbei"
[dependencies] [dependencies]
aes.workspace = true goblin.workspace = true
thiserror.workspace = true thiserror.workspace = true
[lints] [lints]
@@ -1,7 +1,7 @@
use crate::error::{Error, Result, invalid}; use crate::{Error, Result, invalid};
#[must_use] #[must_use]
pub(crate) fn elf_hash(name: &[u8]) -> u32 { pub fn elf_hash(name: &[u8]) -> u32 {
let mut value = 0_u32; let mut value = 0_u32;
for &byte in name { for &byte in name {
value = value.wrapping_shl(4).wrapping_add(u32::from(byte)); value = value.wrapping_shl(4).wrapping_add(u32::from(byte));
@@ -15,13 +15,13 @@ pub(crate) fn elf_hash(name: &[u8]) -> u32 {
} }
#[must_use] #[must_use]
pub(crate) fn gnu_hash(name: &[u8]) -> u32 { pub fn gnu_hash(name: &[u8]) -> u32 {
name.iter().fold(5381_u32, |value, &byte| { name.iter().fold(5381_u32, |value, &byte| {
value.wrapping_mul(33).wrapping_add(u32::from(byte)) value.wrapping_mul(33).wrapping_add(u32::from(byte))
}) })
} }
pub(crate) fn build_sysv_hash(names: &[Vec<u8>]) -> Result<Vec<u8>> { pub fn build_sysv_hash(names: &[Vec<u8>]) -> Result<Vec<u8>> {
if names.len() < 2 { if names.len() < 2 {
return invalid("dynamic symbol table is unexpectedly empty"); return invalid("dynamic symbol table is unexpectedly empty");
} }
@@ -60,7 +60,7 @@ pub(crate) fn build_sysv_hash(names: &[Vec<u8>]) -> Result<Vec<u8>> {
Ok(output) Ok(output)
} }
pub(crate) fn build_gnu_hash(names: &[Vec<u8>]) -> Result<Vec<u8>> { pub fn build_gnu_hash(names: &[Vec<u8>]) -> Result<Vec<u8>> {
let hashes = names let hashes = names
.iter() .iter()
.skip(1) .skip(1)
+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(_))));
}
}
@@ -1,10 +1,10 @@
[package] [package]
name = "senbei-android-elf" name = "senbei-engine"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
rust-version.workspace = true rust-version.workspace = true
license.workspace = true license.workspace = true
description = "AArch64 ELF restoration for Senbei Android" description = "Platform unpacking engines for Senbei"
[dependencies] [dependencies]
memmap2.workspace = true memmap2.workspace = true
@@ -13,7 +13,9 @@ serde_json.workspace = true
sha2.workspace = true sha2.workspace = true
tempfile.workspace = true tempfile.workspace = true
thiserror.workspace = true thiserror.workspace = true
senbei-android-crypto.workspace = true senbei-crypto.workspace = true
senbei-elf.workspace = true
senbei-pe.workspace = true
[lints] [lints]
workspace = true 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())
}
@@ -14,12 +14,12 @@ pub enum Error {
Elf { Elf {
path: PathBuf, path: PathBuf,
#[source] #[source]
source: goblin::error::Error, source: senbei_elf::Error,
}, },
#[error("serialize extraction index: {0}")] #[error("serialize extraction index: {0}")]
Json(#[from] serde_json::Error), Json(#[from] serde_json::Error),
#[error("embedded Stage 2 decoder configuration: {0}")] #[error("embedded Stage 2 decoder configuration: {0}")]
EmbeddedConfig(#[source] senbei_android_crypto::Error), EmbeddedConfig(#[source] senbei_crypto::android::Error),
#[error( #[error(
"depth {depth} stream 0x{stream_id:02X} interpreter 0x{interpreter_id:02X} configuration: {source}" "depth {depth} stream 0x{stream_id:02X} interpreter 0x{interpreter_id:02X} configuration: {source}"
)] )]
@@ -28,7 +28,7 @@ pub enum Error {
stream_id: u32, stream_id: u32,
interpreter_id: u32, interpreter_id: u32,
#[source] #[source]
source: senbei_android_crypto::Error, source: senbei_crypto::android::Error,
}, },
#[error( #[error(
"depth {depth} stream 0x{stream_id:02X} record {record_index} command 0x{command_id:02X} {part}: {source}" "depth {depth} stream 0x{stream_id:02X} record {record_index} command 0x{command_id:02X} {part}: {source}"
@@ -40,7 +40,7 @@ pub enum Error {
command_id: u32, command_id: u32,
part: &'static str, part: &'static str,
#[source] #[source]
source: senbei_android_crypto::Error, source: senbei_crypto::android::Error,
}, },
#[error("{0}")] #[error("{0}")]
Invalid(String), Invalid(String),
@@ -1,14 +1,12 @@
//! Pure-static Stage 1 decryption and recursive Stage 2 module extraction.
mod error; mod error;
mod extract; mod pipeline;
mod probe; mod probe;
mod report; mod report;
mod stage1; mod stage1;
mod stream; mod stream;
pub use error::Error; pub use error::Error;
pub use extract::{ExtractOptions, extract_stage2}; pub use pipeline::{ExtractOptions, extract_stage2};
pub use probe::is_protected_libil2cpp; pub use probe::is_protected_libil2cpp;
pub use report::ExtractionReport; pub use report::ExtractionReport;
pub use stage1::{DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE}; pub use stage1::{DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE};
@@ -1,23 +1,21 @@
use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs::{File, create_dir_all}; use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use memmap2::MmapOptions; use memmap2::MmapOptions;
use senbei_android_crypto::{Module9bConfig, decode_container}; use senbei_crypto::android::{Module9bConfig, decode_container};
use serde_json::to_vec_pretty; use serde_json::to_vec_pretty;
use sha2::{Digest, Sha256};
use tempfile::NamedTempFile;
use crate::error::{Error, Result, invalid}; use super::super::common;
use crate::report::{ use super::error::{Error, Result, invalid};
use super::report::{
ArtifactReport, DecoderReport, ExtractionReport, ModuleRegistryEntry, RecordReport, ArtifactReport, DecoderReport, ExtractionReport, ModuleRegistryEntry, RecordReport,
Stage1Report, StreamParent, StreamReport, Stage1Report, StreamParent, StreamReport,
}; };
use crate::stage1::{ use super::stage1::{
DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE, SHT_LOUSER, Stage1Result, inspect, DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE, SHT_LOUSER, Stage1Result, inspect,
}; };
use crate::stream::{DIRECT_FLAG, Record, parse_record_stream}; use super::stream::{DIRECT_FLAG, Record, parse_record_stream};
/// Inputs and output locations for one complete static Stage 2 extraction. /// Inputs and output locations for one complete static Stage 2 extraction.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -86,7 +84,7 @@ pub fn extract_stage2(options: &ExtractOptions) -> Result<ExtractionReport> {
return invalid("refusing to overwrite the protected ELF with Stage 2 output"); return invalid("refusing to overwrite the protected ELF with Stage 2 output");
} }
} }
create_dir_all(&output_dir) std::fs::create_dir_all(&output_dir)
.map_err(|source| Error::io("create Stage 2 output directory", &output_dir, source))?; .map_err(|source| Error::io("create Stage 2 output directory", &output_dir, source))?;
let file = File::open(&input_path) let file = File::open(&input_path)
@@ -497,42 +495,14 @@ fn write_json_atomic(path: &Path, value: &impl serde::Serialize) -> Result<()> {
} }
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> { fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
let parent = path.parent().unwrap_or_else(|| Path::new(".")); common::write_atomic(path, data)
create_dir_all(parent) .map_err(|source| Error::io("write temporary output", path, source))
.map_err(|source| Error::io("create output directory", parent, source))?;
let mut temporary = NamedTempFile::new_in(parent)
.map_err(|source| Error::io("create temporary output", parent, source))?;
temporary
.write_all(data)
.and_then(|()| temporary.as_file().sync_all())
.map_err(|source| Error::io("write temporary output", temporary.path(), source))?;
temporary
.persist(path)
.map_err(|error| Error::io("replace output", path, error.error))?;
Ok(())
} }
fn absolute(path: &Path) -> Result<PathBuf> { fn absolute(path: &Path) -> Result<PathBuf> {
if path.is_absolute() { common::absolute(path).map_err(|source| Error::io("query current directory", path, source))
Ok(path.to_path_buf())
} else {
std::env::current_dir()
.map(|current| current.join(path))
.map_err(|source| Error::io("query current directory", path, source))
}
} }
fn sha256(data: &[u8]) -> String { fn sha256(data: &[u8]) -> String {
let mut digest = Sha256::new(); common::sha256(data)
digest.update(data);
hex_digest(&digest.finalize())
}
/// Lowercase hex of a digest output (sha2 0.11's `Array` no longer formats as
/// hex directly).
fn hex_digest(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len() * 2);
for byte in data {
out.push_str(&format!("{byte:02x}"));
}
out
} }
@@ -1,15 +1,12 @@
use std::path::Path; use std::path::Path;
use senbei_android_crypto::Module9bConfig; use senbei_crypto::android::Module9bConfig;
use crate::stage1::{self, DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE}; use super::stage1::{self, DEFAULT_CIPHER_CONSTANT, DEFAULT_OUTER_SIZE};
/// Return whether `data` has a supported protected AArch64 IL2CPP layout. /// Return whether `data` has a supported protected AArch64 IL2CPP layout.
#[must_use] #[must_use]
pub fn is_protected_libil2cpp(data: &[u8]) -> bool { pub fn is_protected_libil2cpp(data: &[u8]) -> bool {
if !stage1::looks_protected(data) {
return false;
}
let Ok(stage1) = stage1::inspect( let Ok(stage1) = stage1::inspect(
data, data,
Path::new("<probe>"), Path::new("<probe>"),
@@ -1,44 +1,13 @@
use std::path::Path; use std::path::Path;
use goblin::elf::{Elf, header::EM_AARCH64}; use senbei_elf::{AARCH64_MACHINE, Error as ElfError, parse};
use crate::error::{Error, Result, invalid}; use super::error::{Error, Result, invalid};
pub(crate) const SHT_LOUSER: u32 = 0x8000_0000; pub(crate) use senbei_elf::SHT_LOUSER;
pub const DEFAULT_CIPHER_CONSTANT: u32 = 0xbf20_165d; pub const DEFAULT_CIPHER_CONSTANT: u32 = 0xbf20_165d;
pub const DEFAULT_OUTER_SIZE: usize = 0x23c; pub const DEFAULT_OUTER_SIZE: usize = 0x23c;
pub(crate) fn looks_protected(data: &[u8]) -> bool {
let Ok(elf) = Elf::parse(data) else {
return false;
};
if elf.header.e_machine != EM_AARCH64
|| elf
.section_headers
.iter()
.filter(|section| section.sh_type == SHT_LOUSER)
.count()
!= 1
{
return false;
}
[
".dynsym",
".dynstr",
".gnu.hash",
".gnu.version",
".gnu.version_r",
]
.into_iter()
.all(|wanted| {
elf.section_headers.iter().any(|section| {
elf.shdr_strtab
.get_at(section.sh_name)
.is_some_and(|name| name == wanted)
})
})
}
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub(crate) struct Stage1Header { pub(crate) struct Stage1Header {
pub key: u32, pub key: u32,
@@ -70,13 +39,13 @@ pub(crate) fn inspect(
outer_size: usize, outer_size: usize,
cipher_constant: u32, cipher_constant: u32,
) -> Result<Stage1Result> { ) -> Result<Stage1Result> {
let elf = Elf::parse(data).map_err(|source| Error::Elf { let elf = parse(data).map_err(|source: ElfError| Error::Elf {
path: path.to_path_buf(), path: path.to_path_buf(),
source, source,
})?; })?;
if elf.header.e_machine != EM_AARCH64 { if elf.header.e_machine != AARCH64_MACHINE {
return invalid(format!( return invalid(format!(
"expected AArch64 ELF (machine 0x{EM_AARCH64:X}), got 0x{:X}", "expected AArch64 ELF (machine 0x{AARCH64_MACHINE:X}), got 0x{:X}",
elf.header.e_machine elf.header.e_machine
)); ));
} }
@@ -92,6 +61,15 @@ pub(crate) fn inspect(
matches.len() 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_index, section) = matches[0];
let section_offset = usize::try_from(section.sh_offset) let section_offset = usize::try_from(section.sh_offset)
.map_err(|_| Error::Invalid("SHT_LOUSER offset exceeds usize".to_owned()))?; .map_err(|_| Error::Invalid("SHT_LOUSER offset exceeds usize".to_owned()))?;
@@ -199,18 +177,14 @@ fn decrypt_header(raw: &[u8], constant: u32) -> Result<Stage1Header> {
} }
fn decrypt_words(ciphertext: &[u8], key: u32, constant: u32) -> Result<Vec<u8>> { fn decrypt_words(ciphertext: &[u8], key: u32, constant: u32) -> Result<Vec<u8>> {
if ciphertext.len() % 4 != 0 { if !ciphertext.len().is_multiple_of(4) {
return invalid("Stage 1 word cipher input is not 4-byte aligned"); return invalid("Stage 1 word cipher input is not 4-byte aligned");
} }
let mut plaintext = ciphertext.to_vec(); let mut plaintext = ciphertext.to_vec();
for (index, chunk) in plaintext.chunks_exact_mut(4).enumerate() { for (index, chunk) in plaintext.as_chunks_mut::<4>().0.iter_mut().enumerate() {
let index = u32::try_from(index) let index = u32::try_from(index)
.map_err(|_| Error::Invalid("Stage 1 word index exceeds u32".to_owned()))?; .map_err(|_| Error::Invalid("Stage 1 word index exceeds u32".to_owned()))?;
let mut word = u32::from_le_bytes( let mut word = u32::from_le_bytes(*chunk);
chunk
.try_into()
.map_err(|_| Error::Invalid("Stage 1 word has an invalid size".to_owned()))?,
);
word = word.wrapping_add(index.wrapping_add(3).wrapping_mul(key)); word = word.wrapping_add(index.wrapping_add(3).wrapping_mul(key));
word ^= constant.wrapping_mul(index.wrapping_add(1)); word ^= constant.wrapping_mul(index.wrapping_add(1));
chunk.copy_from_slice(&word.to_le_bytes()); chunk.copy_from_slice(&word.to_le_bytes());
@@ -1,6 +1,6 @@
use senbei_android_crypto::gf32_mul_fixed; use senbei_crypto::android::gf32_mul_fixed;
use crate::error::{Error, Result, invalid}; use super::error::{Error, Result, invalid};
pub(crate) const RECORD_SIZE: usize = 0x5c; pub(crate) const RECORD_SIZE: usize = 0x5c;
pub(crate) const DIRECT_FLAG: u32 = 2; pub(crate) const DIRECT_FLAG: u32 = 2;
@@ -130,13 +130,9 @@ fn decrypt_record(raw: &[u8], index: usize, state: u32) -> Result<Record> {
let mut accumulator = 0x7993_4cf6_u32; let mut accumulator = 0x7993_4cf6_u32;
let mut feedback = 0xf02f_7685_u32; let mut feedback = 0xf02f_7685_u32;
let mut words = [0_u32; RECORD_SIZE / 4]; let mut words = [0_u32; RECORD_SIZE / 4];
for (word_index, chunk) in raw.chunks_exact(4).enumerate() { for (word_index, chunk) in raw.as_chunks::<4>().0.iter().enumerate() {
feedback = feedback.wrapping_mul(feedback); feedback = feedback.wrapping_mul(feedback);
let cipher = u32::from_le_bytes( let cipher = u32::from_le_bytes(*chunk);
chunk
.try_into()
.map_err(|_| Error::Invalid("record word has an invalid size".to_owned()))?,
);
let mut value = gf32_mul_fixed(cipher ^ (feedback >> 3)) ^ index_mask; let mut value = gf32_mul_fixed(cipher ^ (feedback >> 3)) ^ index_mask;
value = value.wrapping_add(accumulator).wrapping_add(state); value = value.wrapping_add(accumulator).wrapping_add(state);
value = value.wrapping_sub(mix >> ((word_index * 4 + 3) & 5)); value = value.wrapping_sub(mix >> ((word_index * 4 + 3) & 5));
+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};
@@ -3,7 +3,7 @@ use std::path::{Path, PathBuf};
use serde_json::Value; use serde_json::Value;
use crate::error::{Error, Result, invalid}; use super::error::{Error, Result, invalid};
const REQUIRED_IDS: [u32; 3] = [0x9b, 0x9d, 0x9e]; const REQUIRED_IDS: [u32; 3] = [0x9b, 0x9d, 0x9e];
@@ -13,7 +13,9 @@ pub enum Error {
#[error("cannot parse module index: {0}")] #[error("cannot parse module index: {0}")]
Json(#[from] serde_json::Error), Json(#[from] serde_json::Error),
#[error(transparent)] #[error(transparent)]
Crypto(#[from] senbei_android_crypto::Error), Crypto(#[from] senbei_crypto::android::Error),
#[error(transparent)]
Elf(#[from] senbei_elf::Error),
#[error("{0}")] #[error("{0}")]
Invalid(String), Invalid(String),
} }
+6
View File
@@ -0,0 +1,6 @@
mod artifact;
mod error;
mod pipeline;
pub use error::Error;
pub use pipeline::{RestoreOptions, RestoreReport, restore_libil2cpp};
@@ -5,42 +5,26 @@ use std::path::{Path, PathBuf};
use std::time::Instant; use std::time::Instant;
use memmap2::{Mmap, MmapMut, MmapOptions}; use memmap2::{Mmap, MmapMut, MmapOptions};
use senbei_android_crypto::{ use senbei_crypto::android::{
ContainerHeader, HuffmanLzDecoder, Module9bConfig, ProtectedDescriptor, transform_segment, ContainerHeader, HuffmanLzDecoder, Module9bConfig, ProtectedDescriptor, transform_segment,
}; };
use serde::Serialize; use serde::Serialize;
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use tempfile::NamedTempFile; use tempfile::NamedTempFile;
use crate::artifact::load_artifacts; use super::super::common;
use crate::error::{Error, Result, invalid}; use super::artifact::load_artifacts;
use crate::hash::{build_gnu_hash, build_sysv_hash}; use super::error::{Error, Result, invalid};
use crate::layout::{ use senbei_elf::{
ElfLayout, SHF_ALLOC, SHT_LOUSER, SHT_NOBITS, SectionHeader, align_up, read_i64, read_u32, DT_GNU_HASH, DT_HASH, DT_JMPREL, DT_PLTRELSZ, DT_RELA, DT_RELACOUNT, DT_RELASZ, DT_STRSZ,
read_u64, slice, slice_u64, usize_from_u64, DT_STRTAB, DT_SYMTAB, DT_VERNEED, DT_VERSYM, ELF64_RELA_SIZE, ELF64_SYMBOL_SIZE, ElfLayout,
LoadSegment, PF_R, R_AARCH64_ABS64, R_AARCH64_GLOB_DAT, R_AARCH64_JUMP_SLOT,
R_AARCH64_RELATIVE, SHF_ALLOC, SHT_LOUSER, SHT_NOBITS, SectionHeader, VER_NDX_GLOBAL, align_up,
build_gnu_hash, build_sysv_hash, read_i64, read_u32, read_u64, slice, slice_u64,
usize_from_u64,
}; };
const CHUNK_SIZE: usize = 16 * 1024 * 1024; const CHUNK_SIZE: usize = 16 * 1024 * 1024;
const ELF64_SYMBOL_SIZE: usize = 0x18;
const ELF64_RELA_SIZE: usize = 0x18;
const R_AARCH64_ABS64: u32 = 0x101;
const R_AARCH64_GLOB_DAT: u32 = 0x401;
const R_AARCH64_JUMP_SLOT: u32 = 0x402;
const R_AARCH64_RELATIVE: u32 = 0x403;
const VER_NDX_GLOBAL: u16 = 1;
const DT_PLTRELSZ: u64 = 2;
const DT_HASH: u64 = 4;
const DT_STRTAB: u64 = 5;
const DT_SYMTAB: u64 = 6;
const DT_RELA: u64 = 7;
const DT_RELASZ: u64 = 8;
const DT_STRSZ: u64 = 10;
const DT_JMPREL: u64 = 23;
const DT_GNU_HASH: u64 = 0x6fff_fef5;
const DT_VERSYM: u64 = 0x6fff_fff0;
const DT_RELACOUNT: u64 = 0x6fff_fff9;
const DT_VERNEED: u64 = 0x6fff_fffe;
/// Inputs and optional diagnostics for one `libil2cpp.so` restoration. /// Inputs and optional diagnostics for one `libil2cpp.so` restoration.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@@ -100,6 +84,12 @@ pub struct PlacementReport {
pub size: usize, pub size: usize,
} }
struct TablePayload {
name: &'static str,
alignment: u64,
data: Vec<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ElfMaterializationReport { pub struct ElfMaterializationReport {
pub hidden_symbols: HiddenSymbolReport, pub hidden_symbols: HiddenSymbolReport,
@@ -181,9 +171,7 @@ fn read_file(path: &Path) -> Result<Vec<u8>> {
} }
fn sha256_bytes(data: &[u8]) -> String { fn sha256_bytes(data: &[u8]) -> String {
let mut digest = Sha256::new(); common::sha256(data)
digest.update(data);
hex_digest(&digest.finalize())
} }
fn sha256_file(path: &Path) -> Result<String> { fn sha256_file(path: &Path) -> Result<String> {
@@ -199,7 +187,7 @@ fn sha256_file(path: &Path) -> Result<String> {
} }
digest.update(&buffer[..read]); digest.update(&buffer[..read]);
} }
Ok(hex_digest(&digest.finalize())) Ok(senbei_crypto::hex_digest(&digest.finalize()))
} }
fn copy_range(source: &[u8], output: &mut File, size: usize, path: &Path) -> Result<()> { fn copy_range(source: &[u8], output: &mut File, size: usize, path: &Path) -> Result<()> {
@@ -280,7 +268,7 @@ impl FileLayoutWriter<'_> {
"decoded write 0x{virtual_address:x}..0x{end:x} is not covered by PT_LOAD memory" "decoded write 0x{virtual_address:x}..0x{end:x} is not covered by PT_LOAD memory"
)); ));
} }
usize_from_u64(written, "written byte count") Ok(usize_from_u64(written, "written byte count")?)
} }
} }
@@ -432,6 +420,9 @@ impl AuxiliaryElfImage {
relocation2_offset: words[10], relocation2_offset: words[10],
relocation2_count: words[11], relocation2_count: words[11],
}; };
if result.dynsym_count == 0 {
return invalid("auxiliary dynamic symbol table has no null entry");
}
if result.relocation1_offset != 0x40 { if result.relocation1_offset != 0x40 {
return invalid("auxiliary relocation table does not follow its header"); return invalid("auxiliary relocation table does not follow its header");
} }
@@ -470,9 +461,6 @@ impl AuxiliaryElfImage {
)); ));
} }
} }
if result.dynsym_count < 2 {
return invalid("auxiliary dynamic symbol table is empty");
}
if slice(data, result.dynsym_offset as usize, ELF64_SYMBOL_SIZE)? if slice(data, result.dynsym_offset as usize, ELF64_SYMBOL_SIZE)?
.iter() .iter()
.any(|&byte| byte != 0) .any(|&byte| byte != 0)
@@ -489,7 +477,8 @@ fn restore_hidden_symbols(
dynstr: SectionHeader, dynstr: SectionHeader,
patch_data: &[u8], patch_data: &[u8],
) -> Result<(Vec<u8>, Vec<u8>, HiddenSymbolReport)> { ) -> Result<(Vec<u8>, Vec<u8>, HiddenSymbolReport)> {
if dynsym.entry_size != ELF64_SYMBOL_SIZE as u64 || dynsym.size % ELF64_SYMBOL_SIZE as u64 != 0 if dynsym.entry_size != ELF64_SYMBOL_SIZE as u64
|| !dynsym.size.is_multiple_of(ELF64_SYMBOL_SIZE as u64)
{ {
return invalid("unexpected .dynsym entry layout"); return invalid("unexpected .dynsym entry layout");
} }
@@ -596,11 +585,13 @@ fn restore_hidden_symbols(
} }
fn dynamic_symbol_names(symbols: &[u8], strings: &[u8]) -> Result<Vec<Vec<u8>>> { fn dynamic_symbol_names(symbols: &[u8], strings: &[u8]) -> Result<Vec<Vec<u8>>> {
if symbols.len() % ELF64_SYMBOL_SIZE != 0 { if !symbols.len().is_multiple_of(ELF64_SYMBOL_SIZE) {
return invalid("dynamic symbol table is not entry-aligned"); return invalid("dynamic symbol table is not entry-aligned");
} }
symbols symbols
.chunks_exact(ELF64_SYMBOL_SIZE) .as_chunks::<ELF64_SYMBOL_SIZE>()
.0
.iter()
.map(|symbol| { .map(|symbol| {
let name_offset = read_u32(symbol, 0)? as usize; let name_offset = read_u32(symbol, 0)? as usize;
Ok(read_c_string(strings, name_offset, strings.len())?.to_vec()) Ok(read_c_string(strings, name_offset, strings.len())?.to_vec())
@@ -710,7 +701,7 @@ fn patch_dynamic_tags(
dynamic: SectionHeader, dynamic: SectionHeader,
values: &BTreeMap<u64, u64>, values: &BTreeMap<u64, u64>,
) -> Result<()> { ) -> Result<()> {
if dynamic.size % 0x10 != 0 { if !dynamic.size.is_multiple_of(0x10) {
return invalid(".dynamic size is not entry-aligned"); return invalid(".dynamic size is not entry-aligned");
} }
let start = usize_from_u64(dynamic.offset, ".dynamic offset")?; let start = usize_from_u64(dynamic.offset, ".dynamic offset")?;
@@ -743,20 +734,31 @@ fn patch_dynamic_tags(
Ok(()) Ok(())
} }
fn dynamic_contains_tag(output: &[u8], dynamic: SectionHeader, wanted: u64) -> Result<bool> {
if !dynamic.size.is_multiple_of(0x10) {
return invalid(".dynamic size is not entry-aligned");
}
let start = usize_from_u64(dynamic.offset, ".dynamic offset")?;
let size = usize_from_u64(dynamic.size, ".dynamic size")?;
let end = start
.checked_add(size)
.ok_or_else(|| Error::Invalid(".dynamic end overflow".to_owned()))?;
slice(output, start, size)?;
for offset in (start..end).step_by(0x10) {
let tag = read_u64(output, offset)?;
if tag == wanted {
return Ok(true);
}
if tag == 0 {
break;
}
}
Ok(false)
}
fn required_section_indices(names: &[String]) -> Result<HashMap<&'static str, usize>> { fn required_section_indices(names: &[String]) -> Result<HashMap<&'static str, usize>> {
const REQUIRED: [&str; 9] = [ let mut result = HashMap::with_capacity(senbei_elf::DYNAMIC_SECTION_NAMES.len());
".dynsym", for required in senbei_elf::DYNAMIC_SECTION_NAMES {
".gnu.version",
".gnu.version_r",
".gnu.hash",
".dynstr",
".rela.dyn",
".rela.plt",
".dynamic",
".rodata",
];
let mut result = HashMap::with_capacity(REQUIRED.len());
for required in REQUIRED {
let indices = names let indices = names
.iter() .iter()
.enumerate() .enumerate()
@@ -785,13 +787,182 @@ fn required_section_indices(names: &[String]) -> Result<HashMap<&'static str, us
Ok(result) Ok(result)
} }
fn metadata_capacity_end(
layout: &ElfLayout,
indices: &HashMap<&'static str, usize>,
metadata_start: u64,
) -> Result<u64> {
let table_indices = indices.values().copied().collect::<HashSet<_>>();
let file_end = layout.private_section()?.offset;
let next_section = layout
.section_headers
.iter()
.enumerate()
.filter(|(index, section)| {
!table_indices.contains(index)
&& section.section_type != SHT_NOBITS
&& section.size != 0
&& section.offset >= metadata_start
})
.map(|(_, section)| section.offset)
.min()
.unwrap_or(file_end);
let capacity_end = next_section.min(file_end);
// A zero-length window is a valid result: the caller can move the whole
// table set to a new PT_LOAD instead of overwriting an adjacent section.
Ok(capacity_end.max(metadata_start))
}
fn metadata_mapping_length(
source: &[u8],
layout: &ElfLayout,
auxiliary_data: &[u8],
) -> Result<usize> {
let names = layout.section_names(source)?;
let indices = required_section_indices(&names)?;
let section = |name: &'static str| -> SectionHeader { layout.section_headers[indices[name]] };
let dynsym = section(".dynsym");
let versym = section(".gnu.version");
let verneed = section(".gnu.version_r");
let dynstr = section(".dynstr");
let rela_dyn = section(".rela.dyn");
let rela_plt = section(".rela.plt");
if dynsym.entry_size != ELF64_SYMBOL_SIZE as u64
|| dynsym.size % ELF64_SYMBOL_SIZE as u64 != 0
|| versym.entry_size != 2
|| rela_dyn.entry_size != ELF64_RELA_SIZE as u64
|| rela_plt.entry_size != ELF64_RELA_SIZE as u64
|| rela_dyn.size % ELF64_RELA_SIZE as u64 != 0
|| rela_plt.size % ELF64_RELA_SIZE as u64 != 0
{
return invalid("unexpected dynamic-table entry layout");
}
let auxiliary = AuxiliaryElfImage::parse(auxiliary_data)?;
let old_symbol_count = usize_from_u64(
dynsym.size / ELF64_SYMBOL_SIZE as u64,
"dynamic symbol count",
)?;
let appended_count =
usize::try_from(auxiliary.dynsym_count.checked_sub(1).ok_or_else(|| {
Error::Invalid("auxiliary symbol table has no null entry".to_owned())
})?)
.map_err(|_| Error::Invalid("auxiliary symbol count exceeds usize".to_owned()))?;
let new_symbol_count = old_symbol_count
.checked_add(appended_count)
.ok_or_else(|| Error::Invalid("merged dynamic symbol count overflow".to_owned()))?;
let merged_dynstr_size = usize_from_u64(dynstr.size, ".dynstr size")?
.checked_add(auxiliary.dynstr_size as usize)
.ok_or_else(|| Error::Invalid("merged dynamic string size overflow".to_owned()))?;
let merged_rela_dyn_count =
usize_from_u64(rela_dyn.size / ELF64_RELA_SIZE as u64, ".rela.dyn count")?
.checked_add(auxiliary.relocation1_count as usize)
.and_then(|count| count.checked_add(auxiliary.relocation2_count as usize))
.ok_or_else(|| Error::Invalid("merged .rela.dyn count overflow".to_owned()))?;
let merged_rela_plt_count =
usize_from_u64(rela_plt.size / ELF64_RELA_SIZE as u64, ".rela.plt count")?
.checked_add(auxiliary.relocation2_count as usize)
.ok_or_else(|| Error::Invalid("merged .rela.plt count overflow".to_owned()))?;
let gnu_hash_size = 28_usize
.checked_add(
new_symbol_count
.checked_sub(1)
.ok_or_else(|| {
Error::Invalid("dynamic symbol table is unexpectedly empty".to_owned())
})?
.checked_mul(4)
.ok_or_else(|| Error::Invalid("GNU hash size overflow".to_owned()))?,
)
.ok_or_else(|| Error::Invalid("GNU hash size overflow".to_owned()))?;
let sysv_hash_size = indices.contains_key(".hash").then(|| {
new_symbol_count
.checked_mul(2)
.and_then(|count| count.checked_add(2))
.and_then(|count| count.checked_mul(4))
.ok_or_else(|| Error::Invalid("SysV hash size overflow".to_owned()))
});
let sysv_hash_size = match sysv_hash_size {
Some(size) => size?,
None => 0,
};
let mut cursor = 0_u64;
for (size, alignment) in [
(
new_symbol_count
.checked_mul(ELF64_SYMBOL_SIZE)
.ok_or_else(|| Error::Invalid("merged .dynsym size overflow".to_owned()))?,
8,
),
(
usize_from_u64(versym.size, ".gnu.version size")?
.checked_add(appended_count.checked_mul(2).ok_or_else(|| {
Error::Invalid("merged .gnu.version size overflow".to_owned())
})?)
.ok_or_else(|| Error::Invalid("merged .gnu.version size overflow".to_owned()))?,
2,
),
(usize_from_u64(verneed.size, ".gnu.version_r size")?, 4),
(gnu_hash_size, 8),
(sysv_hash_size, 4),
(merged_dynstr_size, 1),
(
merged_rela_dyn_count
.checked_mul(ELF64_RELA_SIZE)
.ok_or_else(|| Error::Invalid("merged .rela.dyn size overflow".to_owned()))?,
8,
),
(
merged_rela_plt_count
.checked_mul(ELF64_RELA_SIZE)
.ok_or_else(|| Error::Invalid("merged .rela.plt size overflow".to_owned()))?,
8,
),
] {
cursor = align_up(cursor, alignment)?;
cursor = cursor
.checked_add(size as u64)
.ok_or_else(|| Error::Invalid("dynamic-table reserve overflow".to_owned()))?;
}
let extension_alignment = layout.load_alignment()?;
let extension_start = align_up(layout.private_section()?.offset, extension_alignment)?;
let end = extension_start
.checked_add(cursor)
.ok_or_else(|| Error::Invalid("dynamic-table mapping end overflow".to_owned()))?;
Ok(usize_from_u64(end, "dynamic-table mapping length")?)
}
fn table_placements(
tables: &[TablePayload],
start: u64,
) -> Result<(BTreeMap<String, PlacementReport>, u64)> {
let mut cursor = start;
let mut placements = BTreeMap::new();
for table in tables {
cursor = align_up(cursor, table.alignment)?;
placements.insert(
table.name.to_owned(),
PlacementReport {
offset: cursor,
size: table.data.len(),
},
);
cursor = cursor
.checked_add(table.data.len() as u64)
.ok_or_else(|| Error::Invalid("rebuilt ELF metadata end overflow".to_owned()))?;
}
Ok((placements, cursor))
}
fn table_end(tables: &[TablePayload], start: u64) -> Result<u64> {
table_placements(tables, start).map(|(_, end)| end)
}
fn materialize_static_elf_tables( fn materialize_static_elf_tables(
output: &mut [u8], output: &mut [u8],
source: &[u8], source: &[u8],
layout: &ElfLayout, layout: &ElfLayout,
symbol_patch_data: &[u8], symbol_patch_data: &[u8],
auxiliary_data: &[u8], auxiliary_data: &[u8],
) -> Result<(ElfLayout, ElfMaterializationReport)> { ) -> Result<(ElfLayout, ElfMaterializationReport, u64)> {
let names = layout.section_names(source)?; let names = layout.section_names(source)?;
let indices = required_section_indices(&names)?; let indices = required_section_indices(&names)?;
let section = |name: &'static str| -> SectionHeader { layout.section_headers[indices[name]] }; let section = |name: &'static str| -> SectionHeader { layout.section_headers[indices[name]] };
@@ -802,7 +973,6 @@ fn materialize_static_elf_tables(
let rela_dyn = section(".rela.dyn"); let rela_dyn = section(".rela.dyn");
let rela_plt = section(".rela.plt"); let rela_plt = section(".rela.plt");
let dynamic = section(".dynamic"); let dynamic = section(".dynamic");
let rodata = section(".rodata");
let (old_symbols, old_strings, hidden_symbols) = let (old_symbols, old_strings, hidden_symbols) =
restore_hidden_symbols(output, dynsym, dynstr, symbol_patch_data)?; restore_hidden_symbols(output, dynsym, dynstr, symbol_patch_data)?;
@@ -819,7 +989,11 @@ fn materialize_static_elf_tables(
auxiliary.dynstr_offset as usize, auxiliary.dynstr_offset as usize,
auxiliary.dynstr_size as usize, auxiliary.dynstr_size as usize,
)?; )?;
let appended_count = auxiliary.dynsym_count as usize - 1; let appended_count =
usize::try_from(auxiliary.dynsym_count.checked_sub(1).ok_or_else(|| {
Error::Invalid("auxiliary symbol table has no null entry".to_owned())
})?)
.map_err(|_| Error::Invalid("auxiliary symbol count exceeds usize".to_owned()))?;
let mut appended_symbols = Vec::with_capacity(appended_count * ELF64_SYMBOL_SIZE); let mut appended_symbols = Vec::with_capacity(appended_count * ELF64_SYMBOL_SIZE);
for index in 1..auxiliary.dynsym_count as usize { for index in 1..auxiliary.dynsym_count as usize {
let offset = auxiliary.dynsym_offset as usize + index * ELF64_SYMBOL_SIZE; let offset = auxiliary.dynsym_offset as usize + index * ELF64_SYMBOL_SIZE;
@@ -926,11 +1100,6 @@ fn materialize_static_elf_tables(
let rela_dyn_count = merged_rela_dyn.len() / ELF64_RELA_SIZE; let rela_dyn_count = merged_rela_dyn.len() / ELF64_RELA_SIZE;
let rela_plt_count = merged_rela_plt.len() / ELF64_RELA_SIZE; let rela_plt_count = merged_rela_plt.len() / ELF64_RELA_SIZE;
struct TablePayload {
name: &'static str,
alignment: u64,
data: Vec<u8>,
}
let mut tables = vec![ let mut tables = vec![
TablePayload { TablePayload {
name: ".dynsym", name: ".dynsym",
@@ -977,34 +1146,52 @@ fn materialize_static_elf_tables(
data: merged_rela_plt, data: merged_rela_plt,
}, },
]); ]);
let metadata_start = dynsym.offset; let mut placement_layout = layout.clone();
let mut cursor = metadata_start; let mut metadata_start = dynsym.offset;
let mut placements = BTreeMap::new(); let (mut placements, mut cursor) = table_placements(&tables, metadata_start)?;
for table in &tables { let mut capacity_end = metadata_capacity_end(layout, &indices, metadata_start)?;
cursor = align_up(cursor, table.alignment)?; if cursor > capacity_end {
placements.insert( let alignment = layout.load_alignment()?;
table.name.to_owned(), let extension_start = align_up(layout.private_section()?.offset, alignment)?;
PlacementReport { let extension_end = table_end(&tables, extension_start)?;
offset: cursor, let extension_size = extension_end
size: table.data.len(), .checked_sub(extension_start)
.ok_or_else(|| Error::Invalid("dynamic-table extension underflow".to_owned()))?;
let extension_address = align_up(layout.load_end()?, alignment)?;
placement_layout = layout.append_load_segment(
output,
LoadSegment {
offset: extension_start,
virtual_address: extension_address,
file_size: extension_size,
memory_size: extension_size,
flags: PF_R,
alignment,
}, },
); )?;
cursor = cursor metadata_start = extension_start;
.checked_add(table.data.len() as u64) (placements, cursor) = table_placements(&tables, metadata_start)?;
.ok_or_else(|| Error::Invalid("rebuilt ELF metadata end overflow".to_owned()))?; capacity_end = cursor;
} }
if cursor > rodata.offset { let zero_start = usize_from_u64(dynsym.offset, "metadata start")?;
return invalid(format!( let zero_end = usize_from_u64(
"rebuilt ELF tables end at 0x{cursor:x}, beyond .rodata 0x{:x}", metadata_capacity_end(layout, &indices, dynsym.offset)?,
rodata.offset "metadata capacity end",
)); )?;
}
let zero_start = usize_from_u64(metadata_start, "metadata start")?;
let zero_end = usize_from_u64(rodata.offset, ".rodata offset")?;
output output
.get_mut(zero_start..zero_end) .get_mut(zero_start..zero_end)
.ok_or_else(|| Error::Invalid("metadata capacity exceeds output mapping".to_owned()))? .ok_or_else(|| Error::Invalid("metadata capacity exceeds output mapping".to_owned()))?
.fill(0); .fill(0);
if metadata_start != dynsym.offset {
let extension_start = usize_from_u64(metadata_start, "dynamic-table extension start")?;
let extension_end = usize_from_u64(cursor, "dynamic-table extension end")?;
output
.get_mut(extension_start..extension_end)
.ok_or_else(|| {
Error::Invalid("dynamic-table extension exceeds output mapping".to_owned())
})?
.fill(0);
}
let mut updated_sections = layout.section_headers.clone(); let mut updated_sections = layout.section_headers.clone();
for table in &tables { for table in &tables {
@@ -1021,8 +1208,8 @@ fn materialize_static_elf_tables(
.copy_from_slice(&table.data); .copy_from_slice(&table.data);
let index = indices[table.name]; let index = indices[table.name];
let mut updated = updated_sections[index]; let mut updated = updated_sections[index];
updated.address = updated.address = placement_layout
layout.file_offset_to_virtual_address(placement.offset, table.data.len() as u64)?; .file_offset_to_virtual_address(placement.offset, table.data.len() as u64)?;
updated.offset = placement.offset; updated.offset = placement.offset;
updated.size = table.data.len() as u64; updated.size = table.data.len() as u64;
updated_sections[index] = updated; updated_sections[index] = updated;
@@ -1039,16 +1226,23 @@ fn materialize_static_elf_tables(
(DT_JMPREL, section_address(".rela.plt")), (DT_JMPREL, section_address(".rela.plt")),
(DT_GNU_HASH, section_address(".gnu.hash")), (DT_GNU_HASH, section_address(".gnu.hash")),
(DT_VERSYM, section_address(".gnu.version")), (DT_VERSYM, section_address(".gnu.version")),
(DT_RELACOUNT, relative_count as u64),
(DT_VERNEED, section_address(".gnu.version_r")), (DT_VERNEED, section_address(".gnu.version_r")),
]); ]);
if dynamic_contains_tag(output, dynamic, DT_RELACOUNT)? {
dynamic_values.insert(DT_RELACOUNT, relative_count as u64);
}
if indices.contains_key(".hash") { if indices.contains_key(".hash") {
dynamic_values.insert(DT_HASH, section_address(".hash")); dynamic_values.insert(DT_HASH, section_address(".hash"));
} }
patch_dynamic_tags(output, dynamic, &dynamic_values)?; patch_dynamic_tags(output, dynamic, &dynamic_values)?;
let mut restored_layout = layout.clone(); let mut restored_layout = placement_layout;
restored_layout.section_headers = updated_sections; restored_layout.section_headers = updated_sections;
let data_end = if metadata_start == dynsym.offset {
layout.private_section()?.offset
} else {
cursor
};
Ok(( Ok((
restored_layout, restored_layout,
ElfMaterializationReport { ElfMaterializationReport {
@@ -1065,10 +1259,11 @@ fn materialize_static_elf_tables(
relative_prefix_count: relative_count, relative_prefix_count: relative_count,
metadata_start, metadata_start,
metadata_end: cursor, metadata_end: cursor,
metadata_capacity_end: rodata.offset, metadata_capacity_end: capacity_end,
metadata_slack: rodata.offset - cursor, metadata_slack: capacity_end.saturating_sub(cursor),
placements, placements,
}, },
data_end,
)) ))
} }
@@ -1090,9 +1285,13 @@ fn finalize_clean_elf(
temporary_path: &Path, temporary_path: &Path,
source: &[u8], source: &[u8],
layout: &ElfLayout, layout: &ElfLayout,
data_start: u64,
preserve_entrypoint: bool, preserve_entrypoint: bool,
) -> Result<CleaningReport> { ) -> Result<CleaningReport> {
let private = layout.private_section()?; let private = layout.private_section()?;
if data_start < private.offset {
return invalid("ELF data start precedes the private section");
}
let names = layout.section_names(source)?; let names = layout.section_names(source)?;
if layout.private_section_index + 1 != layout.section_headers.len() { if layout.private_section_index + 1 != layout.section_headers.len() {
return invalid("SHT_LOUSER section is not the final section"); return invalid("SHT_LOUSER section is not the final section");
@@ -1100,7 +1299,7 @@ fn finalize_clean_elf(
let retained = &layout.section_headers[..layout.private_section_index]; let retained = &layout.section_headers[..layout.private_section_index];
let mut updated = Vec::with_capacity(retained.len()); let mut updated = Vec::with_capacity(retained.len());
stream stream
.seek(SeekFrom::Start(private.offset)) .seek(SeekFrom::Start(data_start))
.map_err(|error| Error::io("seek temporary output", temporary_path, error))?; .map_err(|error| Error::io("seek temporary output", temporary_path, error))?;
for &section in retained { for &section in retained {
if section.section_type == SHT_NOBITS || section.flags & SHF_ALLOC != 0 || section.size == 0 if section.section_type == SHT_NOBITS || section.flags & SHF_ALLOC != 0 || section.size == 0
@@ -1222,14 +1421,13 @@ fn validate_restored_binary(
rela_plt.size / ELF64_RELA_SIZE as u64, rela_plt.size / ELF64_RELA_SIZE as u64,
"restored PLT relocation count", "restored PLT relocation count",
)?; )?;
if let Some(expected) = materialization { if let Some(expected) = materialization
if dynamic_symbols != expected.new_symbol_count && (dynamic_symbols != expected.new_symbol_count
|| dynamic_relocations != expected.rela_dyn_count || dynamic_relocations != expected.rela_dyn_count
|| pltgot_relocations != expected.rela_plt_count || pltgot_relocations != expected.rela_plt_count)
{ {
return invalid("restored ELF table counts do not match materialization report"); return invalid("restored ELF table counts do not match materialization report");
} }
}
Ok(ValidationReport { Ok(ValidationReport {
format: "ELF64".to_owned(), format: "ELF64".to_owned(),
machine: "AARCH64".to_owned(), machine: "AARCH64".to_owned(),
@@ -1243,29 +1441,11 @@ fn validate_restored_binary(
} }
fn absolute(path: &Path) -> Result<PathBuf> { fn absolute(path: &Path) -> Result<PathBuf> {
if path.is_absolute() { common::absolute(path).map_err(|error| Error::io("query current directory", path, error))
Ok(path.to_path_buf())
} else {
std::env::current_dir()
.map(|current| current.join(path))
.map_err(|error| Error::io("query current directory", path, error))
}
} }
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> { fn write_atomic(path: &Path, data: &[u8]) -> Result<()> {
let parent = path.parent().unwrap_or_else(|| Path::new(".")); common::write_atomic(path, data).map_err(|error| Error::io("write temporary file", path, error))
std::fs::create_dir_all(parent)
.map_err(|error| Error::io("create output directory", parent, error))?;
let mut temporary = NamedTempFile::new_in(parent)
.map_err(|error| Error::io("create temporary file", parent, error))?;
temporary
.write_all(data)
.and_then(|_| temporary.as_file().sync_all())
.map_err(|error| Error::io("write temporary file", temporary.path(), error))?;
temporary
.persist(path)
.map_err(|error| Error::io("replace output", path, error.error))?;
Ok(())
} }
/// Restore the current protected `libil2cpp.so` without executing protector code. /// Restore the current protected `libil2cpp.so` without executing protector code.
@@ -1363,9 +1543,9 @@ pub fn restore_libil2cpp(options: &RestoreOptions) -> Result<RestoreReport> {
.map_err(|error| Error::io("size temporary output", &temporary_path, error))?; .map_err(|error| Error::io("size temporary output", &temporary_path, error))?;
let mut restored_layout = layout.clone(); let mut restored_layout = layout.clone();
let mut auxiliary_data = None;
let mut auxiliary_stats = None; let mut auxiliary_stats = None;
let mut materialization = None; let mut materialization = None;
let mut temporary_end = private.offset;
let primary_stats; let primary_stats;
{ {
let mut output = map_mut(temporary.as_file(), private_size, &temporary_path)?; let mut output = map_mut(temporary.as_file(), private_size, &temporary_path)?;
@@ -1384,6 +1564,11 @@ pub fn restore_libil2cpp(options: &RestoreOptions) -> Result<RestoreReport> {
options.verbose, options.verbose,
|address, data| writer.write(address, data), |address, data| writer.write(address, data),
)?; )?;
output
.flush()
.map_err(|error| Error::io("flush restored image", &temporary_path, error))?;
}
if !options.outer_only { if !options.outer_only {
if options.verbose { if options.verbose {
eprintln!("Decoding auxiliary 0x9D ELF materialization container..."); eprintln!("Decoding auxiliary 0x9D ELF materialization container...");
@@ -1396,9 +1581,9 @@ pub fn restore_libil2cpp(options: &RestoreOptions) -> Result<RestoreReport> {
options.verbose, options.verbose,
|offset, data| { |offset, data| {
let start = usize_from_u64(offset, "auxiliary write offset")?; let start = usize_from_u64(offset, "auxiliary write offset")?;
let end = start.checked_add(data.len()).ok_or_else(|| { let end = start
Error::Invalid("auxiliary decoded write overflow".to_owned()) .checked_add(data.len())
})?; .ok_or_else(|| Error::Invalid("auxiliary decoded write overflow".to_owned()))?;
let destination = decoded.get_mut(start..end).ok_or_else(|| { let destination = decoded.get_mut(start..end).ok_or_else(|| {
Error::Invalid("auxiliary decoded write is out of range".to_owned()) Error::Invalid("auxiliary decoded write is out of range".to_owned())
})?; })?;
@@ -1409,10 +1594,20 @@ pub fn restore_libil2cpp(options: &RestoreOptions) -> Result<RestoreReport> {
if let Some(path) = &options.dump_auxiliary { if let Some(path) = &options.dump_auxiliary {
write_atomic(&absolute(path)?, &decoded)?; write_atomic(&absolute(path)?, &decoded)?;
} }
let mapping_length = metadata_mapping_length(&source, &layout, &decoded)?;
if mapping_length < private_size {
return invalid("dynamic-table mapping is shorter than the ELF image");
}
temporary
.as_file()
.set_len(mapping_length as u64)
.map_err(|error| Error::io("extend temporary output", &temporary_path, error))?;
if options.verbose { if options.verbose {
eprintln!("Rebuilding static ELF dynamic-linker tables..."); eprintln!("Rebuilding static ELF dynamic-linker tables...");
} }
let (new_layout, report) = materialize_static_elf_tables( {
let mut output = map_mut(temporary.as_file(), mapping_length, &temporary_path)?;
let (new_layout, report, data_end) = materialize_static_elf_tables(
&mut output, &mut output,
&source, &source,
&layout, &layout,
@@ -1422,19 +1617,23 @@ pub fn restore_libil2cpp(options: &RestoreOptions) -> Result<RestoreReport> {
restored_layout = new_layout; restored_layout = new_layout;
materialization = Some(report); materialization = Some(report);
auxiliary_stats = Some(stats); auxiliary_stats = Some(stats);
auxiliary_data = Some(decoded); temporary_end = data_end;
}
output output
.flush() .flush()
.map_err(|error| Error::io("flush restored image", &temporary_path, error))?; .map_err(|error| Error::io("flush restored image", &temporary_path, error))?;
} }
drop(auxiliary_data); temporary
.as_file()
.set_len(temporary_end)
.map_err(|error| Error::io("trim temporary output", &temporary_path, error))?;
}
let cleaning = finalize_clean_elf( let cleaning = finalize_clean_elf(
temporary.as_file_mut(), temporary.as_file_mut(),
&temporary_path, &temporary_path,
&source, &source,
&restored_layout, &restored_layout,
temporary_end,
options.preserve_entrypoint, options.preserve_entrypoint,
)?; )?;
let validation = { let validation = {
@@ -1480,12 +1679,45 @@ pub fn restore_libil2cpp(options: &RestoreOptions) -> Result<RestoreReport> {
elapsed_seconds: started.elapsed().as_secs_f64(), elapsed_seconds: started.elapsed().as_secs_f64(),
}) })
} }
/// Lowercase hex of a digest output (sha2 0.11's `Array` no longer formats as #[cfg(test)]
/// hex directly). mod tests {
fn hex_digest(data: &[u8]) -> String { use super::*;
let mut out = String::with_capacity(data.len() * 2);
for byte in data { fn auxiliary_image(symbol_count: u32) -> Vec<u8> {
out.push_str(&format!("{byte:02x}")); let mut data = vec![0_u8; 0x279];
let words = [
0x40_u32,
0,
0x40,
0,
0x278,
1,
0x260,
symbol_count,
0x40,
3,
0x90,
19,
0,
0,
0xb7,
0,
];
for (index, word) in words.into_iter().enumerate() {
data[index * 4..index * 4 + 4].copy_from_slice(&word.to_le_bytes());
}
data
}
#[test]
fn auxiliary_accepts_null_only_dynamic_symbol_table() {
let parsed = AuxiliaryElfImage::parse(&auxiliary_image(1)).expect("null-only dynsym");
assert_eq!(parsed.dynsym_count, 1);
}
#[test]
fn auxiliary_rejects_missing_null_dynamic_symbol() {
let error = AuxiliaryElfImage::parse(&auxiliary_image(0)).expect_err("missing null symbol");
assert!(error.to_string().contains("no null entry"));
} }
out
} }
+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;
for i in 0..nsec {
let s = tab + i * 40;
if (s as usize + 24) > file_data.len() {
return None; return None;
} }
let va = get_u32(file_data, s + 12); let offset = senbei_pe::rva_to_offset(file_data, headers, rva).ok()?;
let vs = get_u32(file_data, s + 8); u32::try_from(offset).ok()
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
} }
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 {
@@ -945,6 +976,58 @@ impl<'a> Unpacker<'a> {
} }
} }
// ---- Re-arm TLS field base relocations (PE32 DLL) ----
// The packer neutralizes the four relocations covering the TLS
// directory's VA fields (Start/EndAddressOfRawData, AddressOfIndex,
// AddressOfCallBacks) by demoting them to IMAGE_REL_BASED_ABSOLUTE
// padding, because its own loader fixes TLS up by hand. Restored
// verbatim, a DLL mapped off its preferred base keeps stale VAs in its
// TLS directory, and the OS loader faults in LdrpAllocateTlsEntry when
// it writes the TLS slot index through the unrelocated AddressOfIndex.
// Promote those entries back to IMAGE_REL_BASED_HIGHLOW. EXE output
// is untouched: its BaseReloc directory is zeroed above, and its
// goldens must stay byte-identical.
if is_dll && tls_dir_rva > 0 {
let reloc_rva = get_u32(&self.decompressed, exe_pe.wrapping_add(0xA0));
let reloc_size = get_u32(&self.decompressed, exe_pe.wrapping_add(0xA4));
let reloc_end = reloc_rva.wrapping_add(reloc_size);
let dlen = self.decompressed.len() as u32;
if reloc_rva > 0 && reloc_size >= 8 && reloc_end <= dlen {
let mut rearmed = 0u32;
let mut block = reloc_rva;
while block.wrapping_add(8) <= reloc_end {
let page = get_u32(&self.decompressed, block);
let block_size = get_u32(&self.decompressed, block.wrapping_add(4));
if block_size < 8
|| !block_size.is_multiple_of(2)
|| block.wrapping_add(block_size) > reloc_end
{
break;
}
let entries = (block_size - 8) / 2;
for i in 0..entries {
let entry_off = block.wrapping_add(8).wrapping_add(i.wrapping_mul(2));
let entry = get_u16(&self.decompressed, entry_off);
let entry_rva = page.wrapping_add((entry & 0x0FFF) as u32);
// IMAGE_REL_BASED_ABSOLUTE with a real offset is
// neutralized, not padding (padding keeps offset 0).
if entry >> 12 == 0
&& entry & 0x0FFF != 0
&& entry_rva >= tls_dir_rva
&& entry_rva < tls_dir_rva.wrapping_add(16)
{
write_u16(&mut self.decompressed, entry_off, (entry | 0x3000) as u32);
rearmed = rearmed.wrapping_add(1);
}
}
block = block.wrapping_add(block_size);
}
if verbose && rearmed > 0 {
println!(" re-armed {} TLS field relocations", rearmed);
}
}
}
// ---- Import table (PE32, 4-byte thunks) ---- // ---- Import table (PE32, 4-byte thunks) ----
if verbose { if verbose {
println!("[8/9] Decrypting import strings (PE32)..."); println!("[8/9] Decrypting import strings (PE32)...");
@@ -1061,3 +1144,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);
// If the table runs past EOF the image is structurally broken.
let (vsize, va, raw_size, raw_ptr, chars) = match (
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 r.issues
.push("section table extends past end of file".into()); .push("section table extends past end of file".into());
return r; return r;
} }
}; };
// Raw data must lie within the file for compacted (disk-layout) output. let parsed_sections = match senbei_pe::sections(out, headers) {
if raw_size != 0 { Ok(sections) => sections,
let end = raw_ptr.wrapping_add(raw_size) as usize; Err(_) => {
r.issues
.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 { if end > file_len {
r.issues.push(format!( r.issues.push(format!(
"section #{i} raw data [0x{raw_ptr:X}..0x{end:X}] exceeds file size 0x{file_len:X}" "section #{i} raw data [0x{:X}..0x{end:X}] exceeds file size 0x{file_len:X}",
section.raw_offset
)); ));
} }
} }
secs.push(Section { section
va, })
vsize, .collect();
raw_ptr,
raw_size,
chars,
});
}
// --- 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)
+5 -5
View File
@@ -7,14 +7,14 @@ description = "Filesystem, scanning, logging, and CLI orchestration for Senbei"
[dependencies] [dependencies]
anyhow.workspace = true anyhow.workspace = true
flate2.workspace = true senbei-crypto.workspace = true
indicatif.workspace = true indicatif.workspace = true
memmap2.workspace = true
owo-colors.workspace = true owo-colors.workspace = true
senbei-android-elf.workspace = true senbei-engine.workspace = true
senbei-android-engine.workspace = true senbei-elf.workspace = true
senbei-android-metadata.workspace = true
senbei-metadata.workspace = true
senbei-pe.workspace = true senbei-pe.workspace = true
senbei-metadata.workspace = true
sha2.workspace = true sha2.workspace = true
tempfile.workspace = true tempfile.workspace = true
walkdir.workspace = true walkdir.workspace = true
@@ -5,59 +5,71 @@
//! The protection scheme hollows out an ELF64/AArch64 shared object and moves //! The protection scheme hollows out an ELF64/AArch64 shared object and moves
//! the original bytes into an encrypted payload appended as a `SHT_LOUSER` //! the original bytes into an encrypted payload appended as a `SHT_LOUSER`
//! section; restoration extracts the stage-2 module set //! section; restoration extracts the stage-2 module set
//! ([`senbei_android_engine`]) and rebuilds the static image //! ([`senbei_engine::android`]) and rebuilds the static image
//! ([`senbei_android_elf`]). Some il2cpp builds additionally embed their //! ([`senbei_engine::android`]). Some il2cpp builds additionally embed their
//! metadata blob — XOR-wrapped, with no standalone `global-metadata.dat` in //! metadata blob — XOR-wrapped, with no standalone `global-metadata.dat` in
//! the assets — inside the library's data section; after a successful restore //! the assets — inside the library's data section; after a successful restore
//! the blob is located by content and unwrapped //! the blob is located by content and unwrapped
//! ([`senbei_android_metadata::extract_embedded_metadata`]). //! ([`senbei_metadata::android::extract_embedded_metadata`]).
//! //!
//! All functions in this module are native filesystem orchestration; the web //! All functions in this module are native filesystem orchestration; the web
//! app (wasm) never touches them. //! app (wasm) never touches them.
use std::collections::HashSet; use std::collections::HashSet;
use std::io::Read; use std::fs::File;
use std::io::{BufWriter, Read, Seek, Write};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use flate2::read::DeflateDecoder; use memmap2::{Mmap, MmapOptions};
use senbei_android_elf::{RestoreOptions, restore_libil2cpp}; use senbei_crypto::hex_digest;
use senbei_android_engine::{ExtractOptions, extract_stage2, is_protected_libil2cpp}; use senbei_engine::android::{ExtractOptions, extract_stage2, is_protected_libil2cpp};
use senbei_engine::android::{RestoreOptions, restore_libil2cpp};
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
use zip::ZipArchive; use zip::ZipArchive;
/// File name of an il2cpp metadata blob (a platform-standard technology name). pub use crate::METADATA_FILE_NAME;
pub const METADATA_FILE_NAME: &str = "global-metadata.dat";
/// Package extensions recognised as Android app packages. Packages are /// Package extensions recognised as Android app packages. Packages are
/// *containers*: membership is decided by extension plus the zip magic, while /// *containers*: membership is decided by extension plus the ZIP magic, while
/// every file pulled out of one is still content-probed like a loose file. /// only `.so` and `global-metadata.dat` entries are read.
const PACKAGE_EXTENSIONS: [&str; 3] = ["apk", "apks", "xapk"]; 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. /// 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 /// 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 /// cheap check to decide when the full-file protection probe is worth its
/// read. /// read.
pub fn is_elf64_aarch64(prefix: &[u8]) -> bool { pub fn is_elf64_aarch64(prefix: &[u8]) -> bool {
prefix.len() >= 20 senbei_elf::is_aarch64_prefix(prefix)
&& prefix[0..4] == [0x7f, b'E', b'L', b'F']
&& prefix[4] == 2 // ELFCLASS64
&& prefix[5] == 1 // ELFDATA2LSB
&& u16::from_le_bytes([prefix[18], prefix[19]]) == 0xB7 // EM_AARCH64
} }
/// Whether `path` is an Android app package: a recognised package extension /// Whether `path` is an Android app package: a recognised package extension
/// and the local-file-header zip magic in `prefix`. /// and the local-file-header zip magic in `prefix`.
pub fn is_app_package(path: &Path, prefix: &[u8]) -> bool { pub fn is_app_package(path: &Path, prefix: &[u8]) -> bool {
let is_package_ext = path is_package_name(path) && prefix.starts_with(b"PK\x03\x04")
.extension()
.and_then(|value| value.to_str())
.is_some_and(|value| {
PACKAGE_EXTENSIONS
.iter()
.any(|ext| value.eq_ignore_ascii_case(ext))
});
is_package_ext && prefix.starts_with(b"PK\x03\x04")
} }
/// Probe a file on disk: true when it is a protected AArch64 library. /// Probe a file on disk: true when it is a protected AArch64 library.
@@ -65,12 +77,23 @@ pub fn is_app_package(path: &Path, prefix: &[u8]) -> bool {
/// section-header table at the end); call only after [`is_elf64_aarch64`] /// section-header table at the end); call only after [`is_elf64_aarch64`]
/// has matched a prefix. /// has matched a prefix.
pub fn is_protected_so_file(path: &Path) -> bool { pub fn is_protected_so_file(path: &Path) -> bool {
let Ok(bytes) = std::fs::read(path) else { let Ok(file) = File::open(path) else {
return false;
};
let Ok(bytes) = map_read_only(&file, path) else {
return false; return false;
}; };
is_elf64_aarch64(&bytes) && is_protected_libil2cpp(&bytes) 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`. /// Restore one protected `.so` to `dest`.
/// ///
/// The stage-2 module set is extracted into a temporary workspace (it is an /// The stage-2 module set is extracted into a temporary workspace (it is an
@@ -97,7 +120,7 @@ pub fn restore_so_file(input: &Path, dest: &Path, verbose: bool) -> Result<Optio
.context("restore protected library")?; .context("restore protected library")?;
let restored = let restored =
std::fs::read(dest).with_context(|| format!("read restored `{}`", dest.display()))?; std::fs::read(dest).with_context(|| format!("read restored `{}`", dest.display()))?;
Ok(senbei_android_metadata::extract_embedded_metadata( Ok(senbei_metadata::android::extract_embedded_metadata(
&restored, &restored,
)) ))
} }
@@ -122,20 +145,19 @@ pub fn content_identity(data: &[u8]) -> String {
/// canonical form. Both paths are no-ops (`remapped == 0`) on an /// canonical form. Both paths are no-ops (`remapped == 0`) on an
/// already-clean blob. /// already-clean blob.
pub fn restore_metadata_bytes(data: &[u8]) -> anyhow::Result<(Vec<u8>, senbei_metadata::Report)> { pub fn restore_metadata_bytes(data: &[u8]) -> anyhow::Result<(Vec<u8>, senbei_metadata::Report)> {
if let Ok(discovery) = senbei_android_metadata::discover_method_token_seeds(data) if let Ok(discovery) = senbei_metadata::android::discover_method_token_seeds(data)
&& discovery.version == 31 && matches!(discovery.version, 29 | 31 | 39)
&& discovery.images.iter().any(|image| !image.clean)
{ {
let mut seeds = discovery.seed_candidates.clone(); let mut seeds = discovery.seed_candidates.clone();
if seeds.is_empty() { if seeds.is_empty() {
seeds.push(senbei_android_metadata::DEFAULT_METHOD_TOKEN_SEED); seeds.push(senbei_metadata::android::DEFAULT_METHOD_TOKEN_SEED);
} }
// Trial-and-validate: a wrong seed fails the restore's full-coverage // Trial-and-validate: a wrong seed fails the restore's full-coverage
// RID check, so ambiguous candidates cost one extra pass each and a // RID check, so ambiguous candidates cost one extra pass each and a
// build with an unseeded permutation falls through to the structural // build with an unseeded permutation falls through to the structural
// remap rather than producing a silently wrong file. // remap rather than producing a silently wrong file.
for seed in seeds { for seed in seeds {
if let Ok((out, report)) = senbei_android_metadata::restore_method_tokens(data, seed) { if let Ok((out, report)) = senbei_metadata::android::restore_method_tokens(data, seed) {
return Ok(( return Ok((
out, out,
senbei_metadata::Report { senbei_metadata::Report {
@@ -234,22 +256,29 @@ pub fn restore_package(
nested.push((index, name)); nested.push((index, name));
} }
} else { } else {
if is_android_entry_name(&name) {
direct.push((index, name)); direct.push((index, name));
} }
} }
drop(archive); }
for (index, name) in direct { for (index, name) in direct {
let label = format!("{}::{}", rel.display(), name.display()); let label = format!("{}::{}", rel.display(), name.display());
let dest = out_root.join(rel).join(crate::job::out_name(&name)); let dest = out_root.join(rel).join(crate::job::out_name(&name));
let mut entry_outcomes = let mut entry_outcomes = restore_package_entry(
restore_package_entry(package, index, &label, &dest, &temporary, seen, verbose) &mut archive,
index,
&label,
&dest,
&temporary,
seen,
verbose,
)
.with_context(|| format!("extract `{label}`"))?; .with_context(|| format!("extract `{label}`"))?;
outcomes.append(&mut entry_outcomes); outcomes.append(&mut entry_outcomes);
} }
for (index, name) in nested { for (index, name) in nested {
let nested_label = rel.join(&name); let nested_label = rel.join(&name);
let nested_path = extract_entry(package, index, &temporary, &nested_label) let nested_path = extract_entry(&mut archive, index, &temporary, &nested_label)
.with_context(|| format!("extract `{}`", nested_label.display()))?; .with_context(|| format!("extract `{}`", nested_label.display()))?;
let mut nested_archive = open_package(&nested_path)?; let mut nested_archive = open_package(&nested_path)?;
let mut entries = Vec::new(); let mut entries = Vec::new();
@@ -262,10 +291,11 @@ pub fn restore_package(
let Some(entry_name) = entry_name else { let Some(entry_name) = entry_name else {
bail!("unsafe entry path in `{}`", nested_label.display()); bail!("unsafe entry path in `{}`", nested_label.display());
}; };
if is_android_entry_name(&entry_name) {
entries.push((nested_index, entry_name)); entries.push((nested_index, entry_name));
} }
} }
drop(nested_archive); }
// Keep the nested package's stem in the output layout so two splits // Keep the nested package's stem in the output layout so two splits
// carrying same-named entries cannot collide. // carrying same-named entries cannot collide.
let base = rel.join(name.with_extension("")); let base = rel.join(name.with_extension(""));
@@ -273,7 +303,7 @@ pub fn restore_package(
let label = format!("{}::{}", nested_label.display(), entry_name.display()); let label = format!("{}::{}", nested_label.display(), entry_name.display());
let dest = out_root.join(&base).join(crate::job::out_name(&entry_name)); let dest = out_root.join(&base).join(crate::job::out_name(&entry_name));
let mut entry_outcomes = restore_package_entry( let mut entry_outcomes = restore_package_entry(
&nested_path, &mut nested_archive,
nested_index, nested_index,
&label, &label,
&dest, &dest,
@@ -291,8 +321,8 @@ pub fn restore_package(
/// Probe one extracted package entry and restore it when it is a target. /// Probe one extracted package entry and restore it when it is a target.
/// Returns one outcome per produced/consumed artifact: the entry itself, plus /// Returns one outcome per produced/consumed artifact: the entry itself, plus
/// an `EmbeddedMetadata` outcome when the restored library carried a blob. /// an `EmbeddedMetadata` outcome when the restored library carried a blob.
fn restore_package_entry( fn restore_package_entry<R: Read + Seek>(
package: &Path, archive: &mut ZipArchive<R>,
index: usize, index: usize,
label: &str, label: &str,
dest: &Path, dest: &Path,
@@ -300,11 +330,13 @@ fn restore_package_entry(
seen: &mut HashSet<String>, seen: &mut HashSet<String>,
verbose: bool, verbose: bool,
) -> Result<Vec<EntryOutcome>> { ) -> Result<Vec<EntryOutcome>> {
let entry_path = extract_entry(package, index, temporary, Path::new(label))?; let entry_path = extract_entry(archive, index, temporary, Path::new(label))?;
let data = std::fs::read(&entry_path).with_context(|| format!("read extracted `{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(&data) && is_protected_libil2cpp(&data); let is_so = is_elf64_aarch64(&entry_data) && is_protected_libil2cpp(&entry_data);
let is_meta = !is_so && senbei_metadata::is_metadata(&data); let is_meta = !is_so && senbei_metadata::is_metadata(&entry_data);
let outcome = |kind, status| EntryOutcome { let outcome = |kind, status| EntryOutcome {
label: label.to_owned(), label: label.to_owned(),
dest: dest.to_path_buf(), dest: dest.to_path_buf(),
@@ -314,7 +346,7 @@ fn restore_package_entry(
if !is_so && !is_meta { if !is_so && !is_meta {
return Ok(vec![outcome(EntryKind::So, EntryStatus::NotTarget)]); return Ok(vec![outcome(EntryKind::So, EntryStatus::NotTarget)]);
} }
if !seen.insert(content_identity(&data)) { if !seen.insert(content_identity(&entry_data)) {
let kind = if is_so { let kind = if is_so {
EntryKind::So EntryKind::So
} else { } else {
@@ -324,6 +356,8 @@ fn restore_package_entry(
} }
if is_so { if is_so {
drop(entry_data);
drop(entry_file);
return Ok(match restore_so_file(&entry_path, dest, verbose) { return Ok(match restore_so_file(&entry_path, dest, verbose) {
Ok(embedded) => { Ok(embedded) => {
let mut outcomes = vec![outcome(EntryKind::So, EntryStatus::Restored)]; let mut outcomes = vec![outcome(EntryKind::So, EntryStatus::Restored)];
@@ -348,7 +382,7 @@ fn restore_package_entry(
// Metadata entry: write only when the restore actually changed tokens — // Metadata entry: write only when the restore actually changed tokens —
// a clean blob needs no copy (same contract as loose metadata files). // a clean blob needs no copy (same contract as loose metadata files).
let kind_and_status = match restore_metadata_bytes(&data) { let kind_and_status = match restore_metadata_bytes(&entry_data) {
Ok((out, report)) if report.remapped > 0 => { Ok((out, report)) if report.remapped > 0 => {
let kind = EntryKind::Metadata { let kind = EntryKind::Metadata {
remapped: report.remapped, remapped: report.remapped,
@@ -375,14 +409,14 @@ pub fn embedded_metadata_dest(restored_so: &Path) -> PathBuf {
} }
/// Write a metadata blob, creating the parent directory. The restore writes /// Write a metadata blob, creating the parent directory. The restore writes
/// its own output atomically; metadata blobs go through the job layer's /// its own output atomically; metadata blobs use the shared orchestration
/// atomic write to share the mid-write failure semantics. /// atomic writer to keep the same mid-write failure semantics.
fn write_metadata_blob(dest: &Path, data: &[u8]) -> Result<()> { fn write_metadata_blob(dest: &Path, data: &[u8]) -> Result<()> {
if let Some(parent) = dest.parent() { if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent) std::fs::create_dir_all(parent)
.with_context(|| format!("create `{}`", parent.display()))?; .with_context(|| format!("create `{}`", parent.display()))?;
} }
crate::job::write_atomic(dest, data) crate::atomic::write_atomic(dest, data)
.map_err(anyhow::Error::from) .map_err(anyhow::Error::from)
.context("write metadata output") .context("write metadata output")
} }
@@ -392,50 +426,37 @@ fn open_package(path: &Path) -> Result<ZipArchive<std::fs::File>> {
ZipArchive::new(file).with_context(|| format!("read package `{}`", path.display())) ZipArchive::new(file).with_context(|| format!("read package `{}`", path.display()))
} }
/// Extract one package entry to the temporary workspace, streaming stored /// Stream one package entry to a temporary, seekable file. The Android engine
/// entries and inflating deflated ones by hand so compression-method /// needs random access to ELF section tables, while the ZIP reader itself is
/// surprises fail loudly instead of producing a truncated file. /// consumed directly without creating an in-memory compressed or decompressed
fn extract_entry( /// copy.
package: &Path, fn extract_entry<R: Read + Seek>(
archive: &mut ZipArchive<R>,
index: usize, index: usize,
temporary: &tempfile::TempDir, temporary: &tempfile::TempDir,
label: &Path, label: &Path,
) -> Result<PathBuf> { ) -> Result<PathBuf> {
let mut archive = open_package(package)?; let mut entry = archive.by_index(index)?;
let mut entry = archive.by_index_raw(index)?;
let key = format!("{}-{index:08x}", label.display()); let key = format!("{}-{index:08x}", label.display());
// `:` appears in `package::entry` labels and is invalid in Windows file // `:` appears in `package::entry` labels and is invalid in Windows file
// names; sanitize every path-ish separator. // names; sanitize every path-ish separator.
let destination = temporary.path().join(key.replace(['\\', '/', ':'], "_")); let destination = temporary.path().join(key.replace(['\\', '/', ':'], "_"));
let compressed_size = usize::try_from(entry.compressed_size()) let output_size = entry.size();
.map_err(|_| anyhow::anyhow!("entry compressed size exceeds usize"))?; let mut output = BufWriter::new(std::fs::File::create(&destination)?);
let output_size = let written = std::io::copy(&mut entry, &mut output)?;
usize::try_from(entry.size()).map_err(|_| anyhow::anyhow!("entry size exceeds usize"))?; output.flush()?;
let mut compressed = vec![0_u8; compressed_size]; if written != output_size {
entry.read_exact(&mut compressed)?;
let mut output = Vec::with_capacity(output_size);
match entry.compression() {
zip::CompressionMethod::Stored => output.extend_from_slice(&compressed),
zip::CompressionMethod::Deflated => {
DeflateDecoder::new(compressed.as_slice()).read_to_end(&mut output)?;
}
method => bail!("unsupported compression method {method:?} in entry `{key}`"),
}
if output.len() != output_size {
bail!( bail!(
"entry `{key}` decompressed to 0x{:x}, expected 0x{output_size:x}", "entry `{key}` decompressed to 0x{:x}, expected 0x{output_size:x}",
output.len() written
); );
} }
std::fs::write(&destination, &output)?;
Ok(destination) Ok(destination)
} }
/// Lowercase hex of a digest output (sha2 0.11's `Array` no longer formats as
/// hex directly). fn map_read_only(file: &File, path: &Path) -> Result<Mmap> {
fn hex_digest(data: &[u8]) -> String { // SAFETY: the file descriptor remains open for the returned mapping's
let mut out = String::with_capacity(data.len() * 2); // lifetime, and this mapping is read-only.
for byte in data { unsafe { MmapOptions::new().map(file) }
out.push_str(&format!("{byte:02x}")); .with_context(|| format!("map extracted `{}`", path.display()))
}
out
} }
+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
}
+10 -505
View File
@@ -1,326 +1,9 @@
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)] #[derive(Default)]
@@ -403,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>,
@@ -549,8 +229,8 @@ pub fn run_folder_opts(
let dest = out_root.join(out_name(&rel)); let dest = out_root.join(out_name(&rel));
// Unreadable here is fine: the restore reports the same error. // Unreadable here is fine: the restore reports the same error.
if android_dedup if android_dedup
&& let Ok(bytes) = std::fs::read(input) && let Ok(identity) = crate::android::file_content_identity(input)
&& !android_seen.insert(crate::android::content_identity(&bytes)) && !android_seen.insert(identity)
{ {
s.skipped += 1; s.skipped += 1;
if let Some(log) = &log { if let Some(log) = &log {
@@ -816,10 +496,8 @@ pub fn run_file_v(
// library probe needs the whole file (its payload section is found through // 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 // 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. // handled entry-by-entry. Anything else falls through to the PE pipeline.
let is_android_so = crate::android::is_elf64_aarch64(&prefix) let is_android_so =
&& std::fs::read(input) crate::android::is_elf64_aarch64(&prefix) && crate::android::is_protected_so_file(input);
.map(|bytes| senbei_android_engine::is_protected_libil2cpp(&bytes))
.unwrap_or(false);
let is_android_package = !is_android_so && crate::android::is_app_package(input, &prefix); let is_android_package = !is_android_so && crate::android::is_app_package(input, &prefix);
if is_meta { if is_meta {
@@ -1041,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.
pub(crate) 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
@@ -1302,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());
}
} }
+5
View File
@@ -1,8 +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; 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;
+96 -165
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.
@@ -151,16 +76,14 @@ pub struct ScanResult {
/// 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
@@ -186,8 +109,7 @@ 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) -> ScanResult {
// 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,
@@ -212,7 +134,7 @@ pub fn find_targets_opts(root: &Path, scan_all: bool) -> ScanResult {
// 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,
@@ -224,12 +146,17 @@ pub fn find_targets_opts(root: &Path, scan_all: bool) -> ScanResult {
if !entry.file_type().is_file() { if !entry.file_type().is_file() {
continue; continue;
} }
if !scan_all { if crate::windows::is_companion(entry.path()) {
// Name checks come first so extensionless asset chunks never
// trigger even an explicit metadata query.
if denied_name(entry.path()) {
continue; 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 {
// 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()
@@ -247,7 +174,7 @@ pub fn find_targets_opts(root: &Path, scan_all: bool) -> ScanResult {
// `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);
@@ -284,29 +211,9 @@ pub fn find_targets_opts(root: &Path, scan_all: bool) -> ScanResult {
result 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"),
@@ -314,9 +221,8 @@ 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, then the /// the detector for that platform. Returns `None` when the file could not be classified at
/// Android probes. Returns `None` when the file could not be classified at
/// all — an I/O error opening it (locked, permissions) or a panic inside a /// all — an I/O error opening it (locked, permissions) or a panic inside a
/// detector — so the caller counts it as a probe error rather than a clean /// detector — so the caller counts it as a probe error rather than a clean
/// "not a target" skip. /// "not a target" skip.
@@ -332,27 +238,25 @@ pub fn scan_all_env() -> bool {
/// The Android library probe needs more than the prefix: the protection /// 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* /// 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 /// of the file, so an ELF64/AArch64 prefix triggers a full-file read. Only
/// aarch64 images pay for it — a handful of `.so` files per app tree, against /// selected `.so` images pay for it.
/// tens of thousands of assets the free name/size checks already rejected.
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) {
return Class::Crackproof; return Class::AndroidPackage;
} }
if senbei_metadata::is_metadata(&head) { if is_metadata_name(path) && senbei_metadata::is_metadata(&head) {
return Class::Metadata; return Class::Metadata;
} }
if crate::android::is_elf64_aarch64(&head) if crate::windows::is_pe_extension(path) && detect(&head).is_some() {
&& std::fs::read(path) return Class::Crackproof;
.map(|bytes| senbei_android_engine::is_protected_libil2cpp(&bytes)) }
.unwrap_or(false) if crate::android::is_so_name(path)
&& crate::android::is_elf64_aarch64(&head)
&& crate::android::is_protected_so_file(path)
{ {
return Class::AndroidSo; return Class::AndroidSo;
} }
if crate::android::is_app_package(path, &head) {
return Class::AndroidPackage;
}
Class::None Class::None
})); }));
r.ok() r.ok()
@@ -372,38 +276,39 @@ 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];
@@ -414,13 +319,13 @@ mod tests {
assert!(filtered.metadata.is_empty()); assert!(filtered.metadata.is_empty());
let exhaustive = find_targets_opts(root, true); let exhaustive = find_targets_opts(root, true);
assert_eq!(exhaustive.metadata.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();
@@ -428,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
// the size floor.
let scan = find_targets_opts(root, false); let scan = find_targets_opts(root, false);
assert!(scan.crackproof.is_empty() && scan.metadata.is_empty()); assert!(scan.crackproof.is_empty() && scan.metadata.is_empty());
let scan = find_targets_opts(root, true); let scan = find_targets_opts(root, true);
assert!(scan.crackproof.is_empty() && scan.metadata.is_empty()); 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();
@@ -479,4 +384,30 @@ mod tests {
); );
assert_eq!(scan.stats.walk_errors, 0); 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"));
}
} }
+1 -1
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.
+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
@@ -20,7 +20,7 @@
//! they are rewritten to the standard il2cpp metadata magic and version so the //! they are rewritten to the standard il2cpp metadata magic and version so the
//! output is a well-formed `global-metadata.dat`. //! output is a well-formed `global-metadata.dat`.
use crate::keystream::{HEADER_KEYS, SEGMENTS}; use super::keystream::{HEADER_KEYS, SEGMENTS};
/// Standard il2cpp metadata sanity magic written over the patched header. /// Standard il2cpp metadata sanity magic written over the patched header.
const STANDARD_MAGIC: u32 = 0xfab1_1baf; const STANDARD_MAGIC: u32 = 0xfab1_1baf;
@@ -1,17 +1,17 @@
//! Static restoration of protected IL2CPP v31 method tokens. //! Static restoration of protected IL2CPP method tokens for verified layouts.
use serde::Serialize; use serde::Serialize;
use crate::common::MAGIC;
/// Seed embedded in the current `libil2cpp` module `0x0C`. /// Seed embedded in the current `libil2cpp` module `0x0C`.
pub const DEFAULT_METHOD_TOKEN_SEED: u32 = 0xa6fa_e968; pub const DEFAULT_METHOD_TOKEN_SEED: u32 = 0xa6fa_e968;
const MAGIC: u32 = 0xfab1_1baf; const SUPPORTED_V29: u32 = 29;
const SUPPORTED_VERSION: u32 = 31; const SUPPORTED_V31: u32 = 31;
const HDR_METHODS: usize = 0x30; const HDR_METHODS: usize = 0x30;
const HDR_TYPES: usize = 0xa0; const HDR_TYPES: usize = 0xa0;
const HDR_IMAGES: usize = 0xa8; const HDR_IMAGES: usize = 0xa8;
const METHOD_STRIDE: usize = 0x24;
const METHOD_TOKEN_OFFSET: usize = 0x18;
const TYPE_STRIDE: usize = 0x58; const TYPE_STRIDE: usize = 0x58;
const TYPE_METHOD_START_OFFSET: usize = 0x24; const TYPE_METHOD_START_OFFSET: usize = 0x24;
const TYPE_METHOD_COUNT_OFFSET: usize = 0x40; const TYPE_METHOD_COUNT_OFFSET: usize = 0x40;
@@ -20,6 +20,33 @@ const IMAGE_TYPE_START_OFFSET: usize = 0x08;
const IMAGE_TYPE_COUNT_OFFSET: usize = 0x0c; const IMAGE_TYPE_COUNT_OFFSET: usize = 0x0c;
const METHOD_TOKEN_TABLE: u32 = 0x0600_0000; const METHOD_TOKEN_TABLE: u32 = 0x0600_0000;
// The aliases keep the v31 synthetic fixtures readable; production paths use
// the version-specific layout returned by `layout_for_version`.
#[cfg(test)]
const METHOD_STRIDE: usize = 0x24;
#[cfg(test)]
const METHOD_TOKEN_OFFSET: usize = 0x18;
#[derive(Clone, Copy)]
struct Layout {
method_stride: usize,
method_token_offset: usize,
}
fn layout_for_version(version: u32) -> Option<Layout> {
match version {
SUPPORTED_V29 => Some(Layout {
method_stride: 0x20,
method_token_offset: 0x14,
}),
SUPPORTED_V31 => Some(Layout {
method_stride: 0x24,
method_token_offset: 0x18,
}),
_ => None,
}
}
/// Summary of one metadata restoration pass. /// Summary of one metadata restoration pass.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)] #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Report { pub struct Report {
@@ -171,20 +198,23 @@ pub fn restore_method_tokens(data: &[u8], seed: u32) -> Result<(Vec<u8>, Report)
return Err(Error::NotMetadata); return Err(Error::NotMetadata);
} }
let version = read_u32(data, 4)?; let version = read_u32(data, 4)?;
if version != SUPPORTED_VERSION { if version == 39 {
return Err(Error::UnsupportedVersion(version)); return restore_v39(data, seed);
} }
let Some(layout) = layout_for_version(version) else {
return Err(Error::UnsupportedVersion(version));
};
let (method_offset, method_size) = table(data, HDR_METHODS)?; let (method_offset, method_size) = table(data, HDR_METHODS)?;
let (type_offset, type_size) = table(data, HDR_TYPES)?; let (type_offset, type_size) = table(data, HDR_TYPES)?;
let (image_offset, image_size) = table(data, HDR_IMAGES)?; let (image_offset, image_size) = table(data, HDR_IMAGES)?;
if method_size % METHOD_STRIDE != 0 if method_size % layout.method_stride != 0
|| type_size % TYPE_STRIDE != 0 || type_size % TYPE_STRIDE != 0
|| image_size % IMAGE_STRIDE != 0 || image_size % IMAGE_STRIDE != 0
{ {
return malformed("v31 table size is not divisible by its entry stride"); return malformed("method/type/image table size is not divisible by its entry stride");
} }
let method_count = method_size / METHOD_STRIDE; let method_count = method_size / layout.method_stride;
let type_count = type_size / TYPE_STRIDE; let type_count = type_size / TYPE_STRIDE;
let image_count = image_size / IMAGE_STRIDE; let image_count = image_size / IMAGE_STRIDE;
let mut owners = vec![u32::MAX; method_count]; let mut owners = vec![u32::MAX; method_count];
@@ -264,7 +294,8 @@ pub fn restore_method_tokens(data: &[u8], seed: u32) -> Result<(Vec<u8>, Report)
let mut tokens = Vec::with_capacity(methods.len()); let mut tokens = Vec::with_capacity(methods.len());
let mut image_already_clean = true; let mut image_already_clean = true;
for &method_index in &methods { for &method_index in &methods {
let token_offset = method_offset + method_index * METHOD_STRIDE + METHOD_TOKEN_OFFSET; let token_offset =
method_offset + method_index * layout.method_stride + layout.method_token_offset;
let token = read_u32(data, token_offset)?; let token = read_u32(data, token_offset)?;
if token & 0xff00_0000 != METHOD_TOKEN_TABLE { if token & 0xff00_0000 != METHOD_TOKEN_TABLE {
return malformed(format!( return malformed(format!(
@@ -357,7 +388,7 @@ pub fn restore_method_tokens(data: &[u8], seed: u32) -> Result<(Vec<u8>, Report)
)) ))
} }
/// Discover seeds compatible with the known v31 five-round RID permutation. /// Discover seeds compatible with the known five-round RID permutation.
/// ///
/// This is diagnostic and does not modify metadata. It enumerates the only /// This is diagnostic and does not modify metadata. It enumerates the only
/// possible per-image key residues and intersects them over the 32-bit seed /// possible per-image key residues and intersects them over the 32-bit seed
@@ -368,23 +399,26 @@ pub fn discover_method_token_seeds(data: &[u8]) -> Result<SeedDiscoveryReport> {
return Err(Error::NotMetadata); return Err(Error::NotMetadata);
} }
let version = read_u32(data, 4)?; let version = read_u32(data, 4)?;
if version != SUPPORTED_VERSION { if version == 39 {
return discover_v39(data);
}
let Some(layout) = layout_for_version(version) else {
return Ok(SeedDiscoveryReport { return Ok(SeedDiscoveryReport {
version, version,
images: Vec::new(), images: Vec::new(),
seed_candidates: Vec::new(), seed_candidates: Vec::new(),
}); });
} };
let (method_offset, method_size) = table(data, HDR_METHODS)?; let (method_offset, method_size) = table(data, HDR_METHODS)?;
let (type_offset, type_size) = table(data, HDR_TYPES)?; let (type_offset, type_size) = table(data, HDR_TYPES)?;
let (image_offset, image_size) = table(data, HDR_IMAGES)?; let (image_offset, image_size) = table(data, HDR_IMAGES)?;
if method_size % METHOD_STRIDE != 0 if method_size % layout.method_stride != 0
|| type_size % TYPE_STRIDE != 0 || type_size % TYPE_STRIDE != 0
|| image_size % IMAGE_STRIDE != 0 || image_size % IMAGE_STRIDE != 0
{ {
return malformed("v31 table size is not divisible by its entry stride"); return malformed("method/type/image table size is not divisible by its entry stride");
} }
let method_count = method_size / METHOD_STRIDE; let method_count = method_size / layout.method_stride;
let type_count = type_size / TYPE_STRIDE; let type_count = type_size / TYPE_STRIDE;
let image_count = image_size / IMAGE_STRIDE; let image_count = image_size / IMAGE_STRIDE;
let mut reports = Vec::with_capacity(image_count); let mut reports = Vec::with_capacity(image_count);
@@ -446,7 +480,7 @@ pub fn discover_method_token_seeds(data: &[u8]) -> Result<SeedDiscoveryReport> {
for method_index in methods { for method_index in methods {
let token = read_u32( let token = read_u32(
data, data,
method_offset + method_index * METHOD_STRIDE + METHOD_TOKEN_OFFSET, method_offset + method_index * layout.method_stride + layout.method_token_offset,
)?; )?;
if token & 0xff00_0000 != METHOD_TOKEN_TABLE { if token & 0xff00_0000 != METHOD_TOKEN_TABLE {
return validation(format!( return validation(format!(
@@ -550,6 +584,458 @@ fn decrypt_rid_with_key(rid: u32, low: u32, high: u32, key: u32) -> u32 {
value + low value + low
} }
const V39_METHODS: usize = 5;
const V39_PARAMETERS: usize = 10;
const V39_GENERIC_CONTAINERS: usize = 14;
const V39_INTERFACE_OFFSETS: usize = 18;
const V39_TYPES: usize = 19;
const V39_IMAGES: usize = 20;
#[derive(Debug, Clone, Copy)]
struct V39Layout {
method_offset: usize,
method_count: usize,
method_stride: usize,
method_token_offset: usize,
type_definition_index_width: usize,
type_offset: usize,
type_count: usize,
type_stride: usize,
type_method_start_offset: usize,
type_method_count_offset: usize,
image_offset: usize,
image_count: usize,
image_stride: usize,
}
fn v39_section(data: &[u8], index: usize) -> Result<(usize, usize, usize)> {
let header = 8_usize
.checked_add(
index
.checked_mul(12)
.ok_or_else(|| Error::Malformed("v39 section header offset overflow".to_owned()))?,
)
.ok_or_else(|| Error::Malformed("v39 section header offset overflow".to_owned()))?;
let offset = read_u32(data, header)? as usize;
let size = read_u32(data, header + 4)? as usize;
let count = read_u32(data, header + 8)? as usize;
bytes(data, offset, size)?;
Ok((offset, size, count))
}
fn v39_index_width(count: usize) -> usize {
if count <= u8::MAX as usize {
1
} else if count <= u16::MAX as usize {
2
} else {
4
}
}
fn read_v39_index(data: &[u8], offset: usize, width: usize) -> Result<usize> {
match width {
1 => Ok(bytes(data, offset, 1)?[0] as usize),
2 => Ok(read_u16(data, offset)? as usize),
4 => Ok(read_u32(data, offset)? as usize),
_ => malformed("v39 index has an unsupported width"),
}
}
fn parse_v39(data: &[u8]) -> Result<V39Layout> {
let (method_offset, method_size, method_count) = v39_section(data, V39_METHODS)?;
let (_, parameter_size, parameter_count) = v39_section(data, V39_PARAMETERS)?;
let (_, _, generic_count) = v39_section(data, V39_GENERIC_CONTAINERS)?;
let (_interface_offset, interface_size, interface_count) =
v39_section(data, V39_INTERFACE_OFFSETS)?;
let (type_offset, type_size, type_count) = v39_section(data, V39_TYPES)?;
let (image_offset, image_size, image_count) = v39_section(data, V39_IMAGES)?;
let parameter_index_width = v39_index_width(parameter_count);
let generic_container_index_width = v39_index_width(generic_count);
let type_definition_index_width = v39_index_width(type_count);
let type_index_width = if interface_count == 0 {
4
} else {
let element_size = interface_size
.checked_div(interface_count)
.ok_or_else(|| Error::Malformed("v39 interface-offset size is invalid".to_owned()))?;
element_size
.checked_sub(4)
.filter(|width| matches!(width, 1 | 2 | 4))
.ok_or_else(|| Error::Malformed("v39 type-index width is invalid".to_owned()))?
};
let method_stride = 20_usize
.checked_add(type_definition_index_width)
.and_then(|size| size.checked_add(type_index_width))
.and_then(|size| size.checked_add(parameter_index_width))
.and_then(|size| size.checked_add(generic_container_index_width))
.ok_or_else(|| Error::Malformed("v39 method stride overflow".to_owned()))?;
let type_stride = 68_usize
.checked_add(
type_index_width
.checked_mul(3)
.ok_or_else(|| Error::Malformed("v39 type stride overflow".to_owned()))?,
)
.and_then(|size| size.checked_add(generic_container_index_width))
.ok_or_else(|| Error::Malformed("v39 type stride overflow".to_owned()))?;
let image_stride = 32_usize
.checked_add(
type_definition_index_width
.checked_mul(2)
.ok_or_else(|| Error::Malformed("v39 image stride overflow".to_owned()))?,
)
.ok_or_else(|| Error::Malformed("v39 image stride overflow".to_owned()))?;
if method_count.checked_mul(method_stride) != Some(method_size)
|| type_count.checked_mul(type_stride) != Some(type_size)
|| image_count.checked_mul(image_stride) != Some(image_size)
|| parameter_count == 0 && parameter_size != 0
{
return malformed("v39 table size does not match its compact entry layout");
}
let type_method_start_offset = 16_usize
.checked_add(
type_index_width
.checked_mul(3)
.ok_or_else(|| Error::Malformed("v39 type method offset overflow".to_owned()))?,
)
.and_then(|offset| offset.checked_add(generic_container_index_width))
.ok_or_else(|| Error::Malformed("v39 type method offset overflow".to_owned()))?;
let type_method_count_offset = type_method_start_offset
.checked_add(7 * 4)
.ok_or_else(|| Error::Malformed("v39 type method count offset overflow".to_owned()))?;
let method_token_offset = 4_usize
.checked_add(type_definition_index_width)
.and_then(|offset| offset.checked_add(type_index_width))
.and_then(|offset| offset.checked_add(4))
.and_then(|offset| offset.checked_add(parameter_index_width))
.and_then(|offset| offset.checked_add(generic_container_index_width))
.ok_or_else(|| Error::Malformed("v39 method token offset overflow".to_owned()))?;
if method_token_offset
.checked_add(4)
.is_none_or(|end| end > method_stride)
|| type_method_count_offset
.checked_add(2)
.is_none_or(|end| end > type_stride)
{
return malformed("v39 compact layout fields exceed their records");
}
// Touch the section base so malformed headers fail before any output copy.
Ok(V39Layout {
method_offset,
method_count,
method_stride,
method_token_offset,
type_definition_index_width,
type_offset,
type_count,
type_stride,
type_method_start_offset,
type_method_count_offset,
image_offset,
image_count,
image_stride,
})
}
fn v39_image_methods(data: &[u8], layout: V39Layout, image: usize) -> Result<Vec<usize>> {
let image_base = layout
.image_offset
.checked_add(
image
.checked_mul(layout.image_stride)
.ok_or_else(|| Error::Malformed("v39 image offset overflow".to_owned()))?,
)
.ok_or_else(|| Error::Malformed("v39 image offset overflow".to_owned()))?;
let type_start = read_v39_index(data, image_base + 8, layout.type_definition_index_width)?;
let type_count = read_u32(data, image_base + 8 + layout.type_definition_index_width)? as usize;
let type_end = type_start
.checked_add(type_count)
.ok_or_else(|| Error::Malformed("v39 image type range overflow".to_owned()))?;
if type_end > layout.type_count {
return malformed("v39 image type range exceeds the type table");
}
let mut methods = Vec::new();
for type_index in type_start..type_end {
let type_base = layout
.type_offset
.checked_add(
type_index
.checked_mul(layout.type_stride)
.ok_or_else(|| Error::Malformed("v39 type offset overflow".to_owned()))?,
)
.ok_or_else(|| Error::Malformed("v39 type offset overflow".to_owned()))?;
let method_start = read_u32(data, type_base + layout.type_method_start_offset)?;
let method_count = read_u16(data, type_base + layout.type_method_count_offset)? as usize;
if method_start == u32::MAX || method_count == 0 {
continue;
}
let method_start = method_start as usize;
let method_end = method_start
.checked_add(method_count)
.ok_or_else(|| Error::Malformed("v39 type method range overflow".to_owned()))?;
if method_end > layout.method_count {
return malformed("v39 type method range exceeds the method table");
}
methods.extend(method_start..method_end);
}
Ok(methods)
}
#[allow(clippy::too_many_arguments)]
fn v39_report(
layout: V39Layout,
changed_tokens: usize,
images_with_methods: usize,
visited_methods: usize,
already_correct_before: usize,
correct_after: usize,
transformed_images: usize,
seed: u32,
) -> Report {
Report {
version: 39,
seed: format!("0x{seed:08X}"),
encryption_status: if changed_tokens == 0 {
"clean".to_owned()
} else {
"encrypted".to_owned()
},
images: layout.image_count,
images_with_methods,
types: layout.type_count,
methods: layout.method_count,
visited_methods,
already_correct_before,
correct_after,
changed_tokens,
transformed_images,
}
}
fn restore_v39(data: &[u8], seed: u32) -> Result<(Vec<u8>, Report)> {
let layout = parse_v39(data)?;
let mut owners = vec![u32::MAX; layout.method_count];
let mut output = data.to_vec();
let mut images_with_methods = 0;
let mut visited_methods = 0;
let mut already_correct_before = 0;
let mut correct_after = 0;
let mut changed_tokens = 0;
let mut transformed_images = 0;
for image in 0..layout.image_count {
let methods = v39_image_methods(data, layout, image)?;
if methods.is_empty() {
continue;
}
images_with_methods += 1;
visited_methods += methods.len();
let method_base = *methods.iter().min().ok_or_else(|| {
Error::Malformed("v39 nonempty image lost its method minimum".to_owned())
})?;
let method_last = *methods.iter().max().ok_or_else(|| {
Error::Malformed("v39 nonempty image lost its method maximum".to_owned())
})?;
if method_last - method_base + 1 != methods.len() {
return validation(format!("v39 image {image} method block is not contiguous"));
}
for &method in &methods {
if owners[method] != u32::MAX {
return malformed(format!("v39 method {method} belongs to multiple images"));
}
owners[method] = image as u32;
}
let mut tokens = Vec::with_capacity(methods.len());
let mut clean = true;
for method in methods {
let offset =
layout.method_offset + method * layout.method_stride + layout.method_token_offset;
let token = read_u32(data, offset)?;
if token & 0xff00_0000 != METHOD_TOKEN_TABLE {
return malformed(format!("v39 method {method} has a non-MethodDef token"));
}
let expected = (method - method_base + 1) as u32;
let rid = token & 0x00ff_ffff;
if rid == expected {
already_correct_before += 1;
} else {
clean = false;
}
tokens.push((offset, token, expected));
}
if clean {
correct_after += tokens.len();
continue;
}
transformed_images += 1;
let low = tokens
.iter()
.map(|(_, token, _)| token & 0x00ff_ffff)
.min()
.unwrap();
let high = tokens
.iter()
.map(|(_, token, _)| token & 0x00ff_ffff)
.max()
.unwrap();
if high - low + 1 != tokens.len() as u32 {
return validation(format!(
"v39 image {image} RID interval is not a permutation"
));
}
for (offset, token, expected) in tokens {
let restored = decrypt_rid(token & 0x00ff_ffff, low, high, seed)?;
if restored != expected {
return validation(format!(
"v39 restored RID {restored} != expected {expected}"
));
}
let restored_token = METHOD_TOKEN_TABLE | restored;
if restored_token != token {
output[offset..offset + 4].copy_from_slice(&restored_token.to_le_bytes());
changed_tokens += 1;
}
correct_after += 1;
}
}
if owners.contains(&u32::MAX) {
return malformed("v39 method definitions are not all owned by an image");
}
if visited_methods != layout.method_count || correct_after != layout.method_count {
return validation(format!(
"v39 method coverage mismatch: visited={visited_methods}, correct={correct_after}, total={}",
layout.method_count
));
}
Ok((
output,
v39_report(
layout,
changed_tokens,
images_with_methods,
visited_methods,
already_correct_before,
correct_after,
transformed_images,
seed,
),
))
}
fn discover_v39(data: &[u8]) -> Result<SeedDiscoveryReport> {
let layout = parse_v39(data)?;
let mut reports = Vec::with_capacity(layout.image_count);
for image in 0..layout.image_count {
let methods = v39_image_methods(data, layout, image)?;
if methods.is_empty() {
reports.push(ImageKeyDiscovery {
image,
method_count: 0,
modulus: 0,
clean: true,
seed_residues: Vec::new(),
});
continue;
}
let base = *methods.iter().min().unwrap();
let last = *methods.iter().max().unwrap();
if last - base + 1 != methods.len() {
return validation(format!("v39 image {image} method block is not contiguous"));
}
let values = methods
.iter()
.map(|&method| {
let offset = layout.method_offset
+ method * layout.method_stride
+ layout.method_token_offset;
let token = read_u32(data, offset)?;
if token & 0xff00_0000 != METHOD_TOKEN_TABLE {
return malformed(format!("v39 method {method} has a non-MethodDef token"));
}
Ok((token & 0x00ff_ffff, (method - base + 1) as u32))
})
.collect::<Result<Vec<_>>>()?;
let count = u32::try_from(values.len())
.map_err(|_| Error::Validation("v39 image method count exceeds u32".to_owned()))?;
let clean = values.iter().all(|(rid, expected)| rid == expected);
if clean {
reports.push(ImageKeyDiscovery {
image,
method_count: count,
modulus: count / 2,
clean: true,
seed_residues: Vec::new(),
});
continue;
}
let low = values.iter().map(|(rid, _)| *rid).min().unwrap();
let high = values.iter().map(|(rid, _)| *rid).max().unwrap();
if high - low + 1 != count || count < 2 {
return validation(format!(
"v39 image {image} RID interval is not a permutation"
));
}
let half = count / 2;
let quarter = count / 4;
let mut residues = Vec::new();
for residue in 0..half {
let key = quarter + residue;
if values
.iter()
.all(|(rid, expected)| decrypt_rid_with_key(*rid, low, high, key) == *expected)
{
residues.push(residue);
}
}
reports.push(ImageKeyDiscovery {
image,
method_count: count,
modulus: half,
clean: false,
seed_residues: residues,
});
}
let constraints = reports
.iter()
.filter(|image| !image.clean)
.collect::<Vec<_>>();
let mut candidates = Vec::new();
if let Some(anchor) = constraints.iter().max_by_key(|image| image.modulus) {
// Returning every 32-bit seed is not representable for tiny synthetic
// images (for example, a two-entry image has billions of candidates).
// The caller still tries the known default seed and validates it fully.
if anchor.modulus < 1024 {
return Ok(SeedDiscoveryReport {
version: 39,
images: reports,
seed_candidates: candidates,
});
}
for &residue in &anchor.seed_residues {
let modulus = u64::from(anchor.modulus);
let mut candidate = u64::from(residue);
while candidate <= u64::from(u32::MAX) {
if constraints.iter().all(|image| {
image.modulus != 0
&& image
.seed_residues
.iter()
.any(|value| candidate % u64::from(image.modulus) == u64::from(*value))
}) {
candidates.push(candidate as u32);
}
candidate = candidate.saturating_add(modulus);
}
}
}
candidates.sort_unstable();
candidates.dedup();
Ok(SeedDiscoveryReport {
version: 39,
images: reports,
seed_candidates: candidates,
})
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -575,7 +1061,7 @@ mod tests {
let methods = types + 2 * TYPE_STRIDE; let methods = types + 2 * TYPE_STRIDE;
let mut data = vec![0_u8; methods + tokens.len() * METHOD_STRIDE]; let mut data = vec![0_u8; methods + tokens.len() * METHOD_STRIDE];
put_u32(&mut data, 0, MAGIC); put_u32(&mut data, 0, MAGIC);
put_u32(&mut data, 4, SUPPORTED_VERSION); put_u32(&mut data, 4, SUPPORTED_V31);
put_u32(&mut data, HDR_METHODS, methods as u32); put_u32(&mut data, HDR_METHODS, methods as u32);
put_u32( put_u32(
&mut data, &mut data,
@@ -628,6 +1114,50 @@ mod tests {
} }
} }
#[test]
fn restores_v29_method_tokens_with_legacy_method_layout() {
let method_stride = 0x20;
let method_token_offset = 0x14;
let hdr = 0x100usize;
let images = hdr;
let types = images + IMAGE_STRIDE;
let methods = types + 2 * TYPE_STRIDE;
let mut data = vec![0_u8; methods + 7 * method_stride];
put_u32(&mut data, 0, MAGIC);
put_u32(&mut data, 4, SUPPORTED_V29);
put_u32(&mut data, HDR_METHODS, methods as u32);
put_u32(&mut data, HDR_METHODS + 4, (7 * method_stride) as u32);
put_u32(&mut data, HDR_TYPES, types as u32);
put_u32(&mut data, HDR_TYPES + 4, (2 * TYPE_STRIDE) as u32);
put_u32(&mut data, HDR_IMAGES, images as u32);
put_u32(&mut data, HDR_IMAGES + 4, IMAGE_STRIDE as u32);
put_u32(&mut data, images + IMAGE_TYPE_START_OFFSET, 0);
put_u32(&mut data, images + IMAGE_TYPE_COUNT_OFFSET, 2);
put_u32(&mut data, types + TYPE_METHOD_START_OFFSET, 0);
put_u16(&mut data, types + TYPE_METHOD_COUNT_OFFSET, 3);
put_u32(&mut data, types + TYPE_STRIDE + TYPE_METHOD_START_OFFSET, 3);
put_u16(&mut data, types + TYPE_STRIDE + TYPE_METHOD_COUNT_OFFSET, 4);
for expected in 1..=7 {
let encrypted = encrypted_rid(expected, 7, DEFAULT_METHOD_TOKEN_SEED);
put_u32(
&mut data,
methods + (expected as usize - 1) * method_stride + method_token_offset,
METHOD_TOKEN_TABLE | encrypted,
);
}
let (restored, report) =
restore_method_tokens(&data, DEFAULT_METHOD_TOKEN_SEED).expect("v29 restore");
assert_eq!(report.version, SUPPORTED_V29);
assert_eq!(report.changed_tokens, 7);
for expected in 1..=7 {
let offset = methods + (expected as usize - 1) * method_stride + method_token_offset;
assert_eq!(
read_u32(&restored, offset).unwrap(),
METHOD_TOKEN_TABLE | expected
);
}
}
#[test] #[test]
fn clean_metadata_is_idempotent() { fn clean_metadata_is_idempotent() {
let tokens = (1..=7) let tokens = (1..=7)
@@ -656,4 +1186,66 @@ mod tests {
Err(Error::Validation(_)) Err(Error::Validation(_))
)); ));
} }
#[test]
fn restores_compact_v39_method_tokens_without_touching_other_fields() {
let method_stride = 25;
let type_stride = 75;
let image_stride = 34;
let method_offset = 0x400;
let type_offset = 0x600;
let image_offset = 0x700;
let method_count = 7_u32;
let mut data = vec![0_u8; image_offset + image_stride];
put_u32(&mut data, 0, MAGIC);
put_u32(&mut data, 4, 39);
let section = |data: &mut [u8], index: usize, offset: usize, size: usize, count: usize| {
let header = 8 + index * 12;
put_u32(data, header, offset as u32);
put_u32(data, header + 4, size as u32);
put_u32(data, header + 8, count as u32);
};
section(
&mut data,
V39_METHODS,
method_offset,
method_stride * method_count as usize,
method_count as usize,
);
section(&mut data, V39_PARAMETERS, 0x300, 1, 1);
section(&mut data, V39_GENERIC_CONTAINERS, 0x320, 1, 1);
section(&mut data, V39_INTERFACE_OFFSETS, 0x340, 6, 1);
section(&mut data, V39_TYPES, type_offset, type_stride, 1);
section(&mut data, V39_IMAGES, image_offset, image_stride, 1);
data.resize(image_offset + image_stride, 0);
// Compact v39 type definition: firstMethod at offset 23, methodCount at 51.
put_u32(&mut data, type_offset + 23, 0);
put_u16(&mut data, type_offset + 51, method_count as u16);
// Compact v39 image definition: firstTypeIndex (one byte) and typeCount.
data[image_offset + 8] = 0;
put_u32(&mut data, image_offset + 9, 1);
for expected in 1..=method_count {
let token = METHOD_TOKEN_TABLE
| encrypted_rid(expected, method_count, DEFAULT_METHOD_TOKEN_SEED);
put_u32(
&mut data,
method_offset + (expected as usize - 1) * method_stride + 13,
token,
);
}
let (out, report) =
restore_method_tokens(&data, DEFAULT_METHOD_TOKEN_SEED).expect("v39 restore");
assert_eq!(report.version, 39);
assert_eq!(report.changed_tokens, method_count as usize);
for expected in 1..=method_count {
let offset = method_offset + (expected as usize - 1) * method_stride + 13;
assert_eq!(
read_u32(&out, offset).unwrap(),
METHOD_TOKEN_TABLE | expected
);
}
let discovery = discover_method_token_seeds(&data).expect("v39 discovery");
assert_eq!(discovery.version, 39);
assert!(discovery.seed_candidates.is_empty());
}
} }
+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)
);
}
}
}
+27 -61
View File
@@ -2,12 +2,6 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]] [[package]]
name = "aes" name = "aes"
version = "0.9.3" version = "0.9.3"
@@ -168,8 +162,6 @@ version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [ dependencies = [
"crc32fast",
"miniz_oxide",
"zlib-rs", "zlib-rs",
] ]
@@ -316,16 +308,6 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@@ -429,33 +411,29 @@ dependencies = [
] ]
[[package]] [[package]]
name = "senbei-android-crypto" name = "senbei-crypto"
version = "1.2.0" version = "1.3.1"
dependencies = [ dependencies = [
"aes", "aes",
"thiserror", "thiserror",
] ]
[[package]] [[package]]
name = "senbei-android-elf" name = "senbei-elf"
version = "1.2.0" version = "1.3.1"
dependencies = [
"memmap2",
"senbei-android-crypto",
"serde",
"serde_json",
"sha2",
"tempfile",
"thiserror",
]
[[package]]
name = "senbei-android-engine"
version = "1.2.0"
dependencies = [ dependencies = [
"goblin", "goblin",
"thiserror",
]
[[package]]
name = "senbei-engine"
version = "1.3.1"
dependencies = [
"memmap2", "memmap2",
"senbei-android-crypto", "senbei-crypto",
"senbei-elf",
"senbei-pe",
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",
@@ -463,33 +441,18 @@ dependencies = [
"thiserror", "thiserror",
] ]
[[package]]
name = "senbei-android-metadata"
version = "1.2.0"
dependencies = [
"serde",
"thiserror",
]
[[package]]
name = "senbei-crypto"
version = "1.2.0"
dependencies = [
"thiserror",
]
[[package]] [[package]]
name = "senbei-io" name = "senbei-io"
version = "1.2.0" version = "1.3.1"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"flate2",
"indicatif", "indicatif",
"libc", "libc",
"memmap2",
"owo-colors", "owo-colors",
"senbei-android-elf", "senbei-crypto",
"senbei-android-engine", "senbei-elf",
"senbei-android-metadata", "senbei-engine",
"senbei-metadata", "senbei-metadata",
"senbei-pe", "senbei-pe",
"sha2", "sha2",
@@ -501,24 +464,27 @@ dependencies = [
[[package]] [[package]]
name = "senbei-metadata" name = "senbei-metadata"
version = "1.2.0" version = "1.3.1"
dependencies = [
"serde",
"thiserror",
]
[[package]] [[package]]
name = "senbei-pe" name = "senbei-pe"
version = "1.2.0" version = "1.3.1"
dependencies = [ dependencies = [
"senbei-crypto",
"thiserror", "thiserror",
] ]
[[package]] [[package]]
name = "senbei-wasm" name = "senbei-wasm"
version = "1.2.0" version = "1.3.1"
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",
] ]
+3 -2
View File
@@ -1,7 +1,8 @@
[package] [package]
name = "senbei-wasm" name = "senbei-wasm"
version = "1.2.0" version = "1.3.1"
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/)
```
+31 -3
View File
@@ -50,6 +50,22 @@ const KIND_LABEL = {
'native-dll': 'protected native DLL', 'native-dll': 'protected native DLL',
'managed-dll': 'protected managed DLL', 'managed-dll': 'protected managed DLL',
metadata: 'il2cpp metadata', metadata: 'il2cpp metadata',
'android-package':
'Android app package — the web build cannot unpack these yet; use the senbei CLI',
'android-so':
'Android AArch64 library — the web build cannot unpack these yet; use the senbei CLI',
};
// Android targets are recognized by extension so the row can explain the
// situation instead of reporting a protected file as unrecognized: the
// Android pipeline is filesystem orchestration (senbei-io) with no wasm
// build, so these files need the CLI. The pseudo-kinds are labels only —
// they never reach the worker.
const ANDROID_KIND = {
apk: 'android-package',
apks: 'android-package',
xapk: 'android-package',
so: 'android-so',
}; };
const COMPANION_SVG = const COMPANION_SVG =
@@ -91,8 +107,13 @@ async function stageFiles(list) {
// the PE header fields); read a small slice, not the whole file. // the PE header fields); read a small slice, not the whole file.
const head = new Uint8Array(await file.slice(0, 65536).arrayBuffer()); const head = new Uint8Array(await file.slice(0, 65536).arrayBuffer());
// Companions are ciphertext fragments; detect() only makes sense on the // Companions are ciphertext fragments; detect() only makes sense on the
// base module, so skip it for `._` files. // base module, so skip it for `._` files. Android targets short-circuit
const kind = file.name.endsWith('._') ? undefined : detect(head); // detect() as well: an ELF/zip never classifies as a protected PE, and
// the row must carry the android pseudo-kind for its status line.
const ext = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
const kind = file.name.endsWith('._')
? undefined
: (ANDROID_KIND[ext] ?? detect(head));
const old = files.get(file.name); const old = files.get(file.name);
files.set(file.name, { files.set(file.name, {
file, file,
@@ -284,7 +305,10 @@ function render() {
const unpackable = [...files].some( const unpackable = [...files].some(
([name, e]) => ([name, e]) =>
!name.endsWith('._') && e.kind !== undefined && e.state === 'staged', !name.endsWith('._') &&
e.kind !== undefined &&
!e.kind.startsWith('android-') &&
e.state === 'staged',
); );
unpackBtn.disabled = !unpackable; unpackBtn.disabled = !unpackable;
actions.hidden = files.size === 0; actions.hidden = files.size === 0;
@@ -364,6 +388,10 @@ unpackBtn.addEventListener('click', async () => {
continue; continue;
} }
// Android rows are informational only (no wasm pipeline); their staged
// status line already says to use the CLI.
if (entry.kind.startsWith('android-')) continue;
entry.state = 'working'; entry.state = 'working';
render(); render();
try { try {
+3 -1
View File
@@ -56,7 +56,9 @@
<p class="hint"> <p class="hint">
Protected <code>.exe</code> / <code>.dll</code> modules, optional Protected <code>.exe</code> / <code>.dll</code> modules, optional
<code>._</code> companions, or an il2cpp <code>._</code> companions, or an il2cpp
<code>global-metadata.dat</code>. <code>global-metadata.dat</code>. Android packages
(<code>.apk</code> / <code>.apks</code> / <code>.xapk</code>) and
<code>.so</code> libraries are recognized but need the CLI.
</p> </p>
<input type="file" id="picker" multiple hidden> <input type="file" id="picker" multiple hidden>
</div> </div>
+20
View File
@@ -333,6 +333,26 @@ footer {
} }
footer a { color: var(--dim); } footer a { color: var(--dim); }
/* --- narrow screens --- */
/* On a narrow viewport the status column (flex: 1, right-aligned) is
squeezed by a long file name into a one-word-per-line vertical strip.
Stack the row instead: name + icons on the first line, the status on its
own full-width line below, left-aligned. */
@media (max-width: 560px) {
main { padding: 1.5rem 0.9rem 2.5rem; }
#dropzone { padding: 1.75rem 1rem; }
.file .row { flex-wrap: wrap; }
.file .name { flex: 1; min-width: 0; }
.file .status {
order: 6; /* after the download/remove icons */
flex-basis: 100%;
text-align: left;
}
}
/* --- animations --- */ /* --- animations --- */
@keyframes fadeIn { @keyframes fadeIn {