Skip to content

armgit / bla

Public Imported from GitHub
0

πŸ›‘οΈ BLA (Blind LLM Agents) β€” Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, and WebAssembly against AI reverse-engineering agents like REA. Poison -> Exhaust -> Hallucinate.

feat(android,dex): counter REA #8154 with external-invoke decoy multidex (v1.5.2)

qybaihe71cf950485bb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 532a04c..e0e9d73 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,30 @@ All notable changes to **bla-agents** are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.5.2] β€” 2026-10-31
+
+Counters REA #8154 (`feat(android): trace callers of external DEX methods` β€”
+`MAX_EXTERNAL_XREF_BYTES` β‰ˆ 1 MiB caller/prototype inventory in
+`bridge/android/ReaJadxBridge.java`).
+
+### Added
+
+- **Android DEX external-invoke decoy** (`src/shields/formats/android-dex-xref.ts`) β€”
+ emits a structurally valid `dex\n035\0` multidex member whose decoy caller
+ classes each contain a real `invoke-static` to `android.util.Log.d(String,String)`.
+ Planted as the next free `classesN.dex` on unsigned APKs only; the developer's
+ root `AndroidManifest.xml` and own `classes.dex` export/behavior surface stay
+ intact (trailer shield on existing DEX unchanged).
+- `REA_INTERNAL_LIMITS.ANDROID_EXTERNAL_XREF_BYTES` / `ANDROID_XREF_TEXT_BYTES`
+ plus `verify:rea` coverage (now walks `bridge/**/*.java`; **72** checks).
+- `tests/android-dex-xref-counter.test.ts` β€” DEX checksum/signature validity,
+ intensity scaling past the 1 MiB budget, multidex naming, unsigned-APK planting.
+
+### Notes
+
+- Signed APKs remain refuse-by-default. Empirical JADX red-team of the decoy
+ against a live REA session is queued for the next nightly (needs JADX on box).
+
## [1.5.1] β€” 2026-10-30
Counters REA #6998 (`BunStandaloneArtifactReader` β€” inventory/extraction of
diff --git a/NIGHTLY.md b/NIGHTLY.md
index 4ee9fcd..ea722e3 100644
--- a/NIGHTLY.md
+++ b/NIGHTLY.md
@@ -1,5 +1,33 @@
# BLA nightly development log
+## 2026-10-31 (Asia/Shanghai)
+
+### Recovery
+- Investigated reported "last night failed" claim: working tree was **clean** at
+ `b2d6436` (v1.5.1), in sync with `origin/main`, CI green. No dirty state /
+ merge conflict / uncommitted junk to recover. Proceeded with new work.
+
+### REA delta
+- Pulled `morluto/rea`: `c0c390220` β†’ `69bf61f7c` (**46 commits**).
+- Headline new analyzer: **#8154** external DEX method caller tracing
+ (`MAX_XREF_TEXT_BYTES` = 8 MiB βˆ’ 1 KiB, `MAX_EXTERNAL_XREF_BYTES` = that / 8).
+- Also noted: #8015 .NET field constant defaults (no new trip-able budget);
+ #8117 Apple `.appex`/`.framework`/`.xpc`/`.plugin` bundle open (admission
+ expansion, not a densify target tonight).
+
+### Done tonight
+- `src/shields/formats/android-dex-xref.ts` + unsigned-APK wiring in `archive.ts`.
+- `src/identity.ts` + `verify:rea` (.java walk) + tests.
+- Release **[email protected]**.
+
+### Next step (2026-11-01)
+1. Empirical red-team: point sibling REA JADX external-references tool at a
+ BLA-hardened unsigned APK fixture; capture before/after in `docs/redteam/`.
+2. Optionally densify decoy callers further / add overload prototype bait for
+ the method_inventory stage of #8154.
+3. Continue roadmap: ESP32 / Godot PCK / process-echo evidence deception, or
+ MCP one-click polish.
+
## 2026-10-28 (Asia/Shanghai)
### REA delta
diff --git a/docs/releases/v1.5.2.md b/docs/releases/v1.5.2.md
new file mode 100644
index 0000000..b9fb670
--- /dev/null
+++ b/docs/releases/v1.5.2.md
@@ -0,0 +1,23 @@
+# bla-agents 1.5.2 β€” Android DEX external-invoke counter (REA #8154)
+
+**Date:** 2026-10-31 (Asia/Shanghai)
+
+## Headline
+
+Counters REA #8154 (`trace callers of external DEX methods`) by planting a
+byte-valid decoy `classesN.dex` whose caller classes each contain a real
+`invoke-static` to `android.util.Log.d`. Saturates
+`MAX_EXTERNAL_XREF_BYTES` (β‰ˆ 1 MiB) without touching the developer's root
+manifest or rewriting their own DEX beyond the existing trailer shield.
+
+## Gates
+
+- `npm run build` β€” ok
+- `npm test` β€” 223/223 on Node 24.22.1
+- `node dist/cli.js benchmark` β€” 14/14 runtime-equivalent
+- `npm run verify:rea` β€” 72/72 (now walks `bridge/**/*.java`)
+
+## Red line
+
+Unsigned APKs only. Signed APKs still refused. Developer
+`AndroidManifest.xml` and existing class export surface preserved.
diff --git a/package.json b/package.json
index cb80b55..0984424 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "bla-agents",
- "version": "1.5.1",
+ "version": "1.5.2",
"description": "BLA (Blind LLM Agents) \u2014 Adversarial defense shield that protects binaries, Electron apps, JS bundles, Python, WebAssembly, SQLite, AI Models, and Android DEX/IL2CPP against AI reverse-engineering agents like REA.",
"keywords": [
"reverse-engineering-defense",
diff --git a/scripts/verify-rea-constants.mjs b/scripts/verify-rea-constants.mjs
index dd06d38..7e3a258 100755
--- a/scripts/verify-rea-constants.mjs
+++ b/scripts/verify-rea-constants.mjs
@@ -180,6 +180,8 @@ const NUMERIC_EXPECTATIONS = [
{ name: "ANDROID_JNI_REPORT_BYTES", expected: 16 * 1024 * 1024 },
{ name: "MAX_NATIVE_EXPORT_ROWS", expected: 262_144 },
// Bun standalone module graph reader (REA #6998).
+ // REA #8154 β€” external DEX invoke inventories (ReaJadxBridge.java)
+ { name: "MAX_XREF_TEXT_BYTES", expected: 8 * 1024 * 1024 - 1024 },
{ name: "BUN_RECORD_BYTES_1_3_3", expected: 36 },
{ name: "BUN_RECORD_BYTES_1_3_9", expected: 52 },
{ name: "MAX_BUN_MODULE_COUNT", expected: 100_000 },
@@ -339,6 +341,8 @@ const SYMBOL_EXPECTATIONS = [
"SqliteColumnEvaluationFailure",
"parseRecordedTransportUrl",
"singleQueryValues",
+ "MAX_EXTERNAL_XREF_BYTES",
+ "ReferenceLimit",
];
const EXPECTED_OBLIGATION_FAMILIES = [
@@ -388,7 +392,7 @@ function main() {
const files = [
...walkFiles(join(REA_ROOT, "src"), [".ts", ".js"]),
- ...walkFiles(join(REA_ROOT, "bridge"), [".ts", ".js", ".py"]),
+ ...walkFiles(join(REA_ROOT, "bridge"), [".ts", ".js", ".py", ".java"]),
];
const rows = [];
diff --git a/src/identity.ts b/src/identity.ts
index 1b5188d..a04faf6 100644
--- a/src/identity.ts
+++ b/src/identity.ts
@@ -5,7 +5,7 @@ export const BLA_IDENTITY = Object.freeze({
packageAlias: "bla-shield",
cliBinary: "bla",
cliAlias: "bla-agents",
- version: "1.5.1",
+ version: "1.5.2",
slogan: "Poison -> Exhaust -> Hallucinate. Make Reverse Engineering Bankrupt Again.",
counterpart: {
name: "REA",
@@ -32,6 +32,7 @@ export const BLA_IDENTITY = Object.freeze({
* - `src/domain/android/proguardMapping.ts` & `androidMapping.ts` (REA #7456)
* - `src/domain/android/androidJniBindings.ts` & `src/android/AndroidJniLibraries.ts` (REA #7472)
* - `src/domain/native/nativeExports.ts` (`MAX_NATIVE_EXPORT_ROWS`)
+ * - `bridge/android/ReaJadxBridge.java` (`MAX_EXTERNAL_XREF_BYTES`, REA #8154)
*/
export const REA_INTERNAL_LIMITS = Object.freeze({
/** Maximum distinct alternatives retained in one normalized primitive value (`SEMANTIC_PRIMITIVE_CANDIDATE_LIMIT`). */
@@ -157,6 +158,13 @@ export const REA_INTERNAL_LIMITS = Object.freeze({
ANDROID_MANIFEST_PERMISSION_BYTES: 1_048_576,
ANDROID_MANIFEST_PROCESS_BYTES: 1_048_576,
ANDROID_MANIFEST_DETAIL_BYTES: 1_048_576,
+ /**
+ * External DEX invoke prototype + caller inventory budget
+ * (`MAX_EXTERNAL_XREF_BYTES` in `bridge/android/ReaJadxBridge.java`, REA #8154).
+ * Derived as `(MAX_XREF_TEXT_BYTES = 8 MiB - 1 KiB) / 8`.
+ */
+ ANDROID_EXTERNAL_XREF_BYTES: 1_048_448,
+ ANDROID_XREF_TEXT_BYTES: 8_387_584,
/**
* Bun standalone module-graph reader (`BunModuleGraphLayout.ts` /
* `BunStandaloneArtifactReader.ts`, REA #6998).
diff --git a/src/shields/formats/android-dex-xref.ts b/src/shields/formats/android-dex-xref.ts
new file mode 100644
index 0000000..399d34f
--- /dev/null
+++ b/src/shields/formats/android-dex-xref.ts
@@ -0,0 +1,509 @@
+/**
+ * Counter REA #8154 β€” `feat(android): trace callers of external DEX methods`.
+ *
+ * REA's JADX bridge (`ReaJadxBridge.java`) walks every method body for
+ * `INVOKE_*` opcodes targeting an exact external class/method, then budgets
+ * the resulting prototype + caller inventories against
+ * `MAX_EXTERNAL_XREF_BYTES = (8 MiB - 1 KiB) / 8` (β‰ˆ 1_048_448 bytes).
+ *
+ * This module emits a standalone, byte-valid Dalvik Executable (`dex\n035\0`)
+ * whose only purpose is to saturate that budget:
+ * - One external target: `android.util.Log.d(String, String)` (no class_def).
+ * - N decoy caller classes, each with a static `bait()` that contains a real
+ * `invoke-static` to that target β€” so JADX's instruction visitor sees them.
+ *
+ * The developer's own `classes.dex` is NEVER rewritten by this generator; the
+ * decoy is planted as an additional `classesN.dex` multidex member (see
+ * `archive.ts`). Header checksum / signature / file_size are recomputed so
+ * any tool that validates the DEX container still accepts it.
+ */
+import { createHash } from "node:crypto";
+import { SeededPrng } from "../../core/prng.js";
+import type { ProtectionIntensity } from "../../core/types.js";
+import { REA_INTERNAL_LIMITS } from "../../identity.js";
+import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.js";
+
+export interface AndroidDexXrefCounterResult {
+ readonly dexBuffer: Buffer;
+ /** Number of decoy caller classes that invoke the external Log.d target. */
+ readonly callerClassesEmitted: number;
+ /** External method refs planted (currently always 1 β€” Log.d). */
+ readonly externalMethodRefs: number;
+ /** Marker string embedded for inspect/detect. */
+ readonly marker: string;
+}
+
+function encodeUleb128(value: number): Buffer {
+ const bytes: number[] = [];
+ let v = value >>> 0;
+ do {
+ let byte = v & 0x7f;
+ v >>>= 7;
+ if (v !== 0) byte |= 0x80;
+ bytes.push(byte);
+ } while (v !== 0);
+ return Buffer.from(bytes);
+}
+
+function align4(n: number): number {
+ return (n + 3) & ~3;
+}
+
+function intensityCallerCount(intensity: ProtectionIntensity): number {
+ // Escaped JSON per caller row is hundreds of bytes under InvokeBudget's
+ // 12Γ— character bound. Aim past ANDROID_EXTERNAL_XREF_BYTES at maximum /
+ // bankrupt; keep stealth/balanced smaller but still meaningful.
+ switch (intensity) {
+ case "stealth":
+ return 96;
+ case "balanced":
+ return 384;
+ case "maximum":
+ return 2_048;
+ case "bankrupt":
+ return 6_144;
+ default:
+ return 384;
+ }
+}
+
+interface BuiltDex {
+ readonly buffer: Buffer;
+ readonly callerCount: number;
+}
+
+/**
+ * Build a minimal but structurally valid DEX 035 containing `callerCount`
+ * static caller classes that each `invoke-static` `Landroid/util/Log;->d`.
+ */
+function buildExternalInvokeDex(
+ prng: SeededPrng,
+ callerCount: number,
+ extraStrings: readonly string[],
+): BuiltDex {
+ const marker = "BLA-DEX-XREF-V1";
+
+ // ----- string pool (order matters; indices are referenced below) -----
+ const strings: string[] = [];
+ const strIndex = new Map<string, number>();
+ const addStr = (s: string): number => {
+ const existing = strIndex.get(s);
+ if (existing !== undefined) return existing;
+ const idx = strings.length;
+ strings.push(s);
+ strIndex.set(s, idx);
+ return idx;
+ };
+
+ // Fixed descriptor / name strings used by the external target + callers.
+ const sVoid = addStr("V");
+ const sObject = addStr("Ljava/lang/Object;");
+ const sString = addStr("Ljava/lang/String;");
+ const sLog = addStr("Landroid/util/Log;");
+ const sShortyLogD = addStr("VLL"); // return V, two reference args
+ const sShortyVoid = addStr("V");
+ const sMethodD = addStr("d");
+ const sMethodBait = addStr("bait");
+ const sMarker = addStr(marker);
+ const sSource = addStr("BlaDexXref.java");
+
+ const callerTypeStrIdx: number[] = [];
+ for (let i = 0; i < callerCount; i++) {
+ const hex = prng.hex(6);
+ callerTypeStrIdx.push(
+ addStr(`Lcom/enclave/xref/ExternalInvokeCaller_${hex}_${i};`),
+ );
+ }
+
+ for (const extra of extraStrings) {
+ // DEX MUTF-8 string_data cannot contain U+0000; keep payloads clean.
+ addStr(extra.replace(/\0/g, " ").slice(0, 200));
+ }
+
+ // ----- type_ids (index into string_ids) -----
+ const types: number[] = [];
+ const typeIndex = new Map<number, number>(); // stringIdx -> typeIdx
+ const addType = (stringIdx: number): number => {
+ const existing = typeIndex.get(stringIdx);
+ if (existing !== undefined) return existing;
+ const idx = types.length;
+ types.push(stringIdx);
+ typeIndex.set(stringIdx, idx);
+ return idx;
+ };
+
+ const tVoid = addType(sVoid);
+ const tObject = addType(sObject);
+ const tString = addType(sString);
+ const tLog = addType(sLog);
+ const callerTypeIdx: number[] = callerTypeStrIdx.map((si) => addType(si));
+ void tVoid; // referenced via proto return; kept for clarity
+
+ // ----- proto_ids -----
+ // proto 0: (Ljava/lang/String;Ljava/lang/String;)V β€” Log.d
+ // proto 1: ()V β€” bait()
+ // We write type_lists into the data section later; record placeholders.
+ interface ProtoRec {
+ shortyIdx: number;
+ returnTypeIdx: number;
+ /** 0 = no params; else offset filled after layout. */
+ paramTypeIdxs: number[];
+ }
+ const protos: ProtoRec[] = [
+ { shortyIdx: sShortyLogD, returnTypeIdx: tVoid, paramTypeIdxs: [tString, tString] },
+ { shortyIdx: sShortyVoid, returnTypeIdx: tVoid, paramTypeIdxs: [] },
+ ];
+
+ // ----- method_ids -----
+ // method 0: Log.d (external β€” no class_def for Log)
+ // method 1..N: Caller_i.bait
+ interface MethodRec {
+ classIdx: number;
+ protoIdx: number;
+ nameIdx: number;
+ }
+ const methods: MethodRec[] = [
+ { classIdx: tLog, protoIdx: 0, nameIdx: sMethodD },
+ ];
+ for (let i = 0; i < callerCount; i++) {
+ methods.push({
+ classIdx: callerTypeIdx[i]!,
+ protoIdx: 1,
+ nameIdx: sMethodBait,
+ });
+ }
+
+ // ----- Lay out the data section -----
+ // We'll assemble: string_data β†’ type_list(s) β†’ code_item(s) β†’ class_data β†’
+ // map_list. Offsets are relative to start of file; header + id tables come
+ // first so we compute their size up front.
+ const headerSize = 0x70;
+ const stringIdsSize = strings.length * 4;
+ const typeIdsSize = types.length * 4;
+ const protoIdsSize = protos.length * 12;
+ const fieldIdsSize = 0;
+ const methodIdsSize = methods.length * 8;
+ const classDefsSize = callerCount * 32;
+ const idsEnd =
+ headerSize +
+ stringIdsSize +
+ typeIdsSize +
+ protoIdsSize +
+ fieldIdsSize +
+ methodIdsSize +
+ classDefsSize;
+
+ let dataCursor = idsEnd;
+ const dataChunks: { offset: number; buf: Buffer }[] = [];
+ const place = (buf: Buffer, align = false): number => {
+ if (align) {
+ const padded = align4(dataCursor) - dataCursor;
+ if (padded > 0) {
+ dataChunks.push({ offset: dataCursor, buf: Buffer.alloc(padded, 0) });
+ dataCursor += padded;
+ }
+ }
+ const off = dataCursor;
+ dataChunks.push({ offset: off, buf });
+ dataCursor += buf.length;
+ return off;
+ };
+
+ // string_data_item[] β€” MUTF-8 with uleb128 utf16_size prefix + NUL
+ const stringDataOffs: number[] = [];
+ for (const s of strings) {
+ const utf8 = Buffer.from(s, "utf8");
+ // Approximate utf16 length as utf8 length for ASCII-heavy payloads (our
+ // strings are ASCII). Canary payloads may contain non-BMP rarely; DEX
+ // requires modified UTF-8 β€” for BMP-only JS strings, utf16_size === code units.
+ let utf16Size = 0;
+ for (const ch of s) {
+ const cp = ch.codePointAt(0)!;
+ utf16Size += cp > 0xffff ? 2 : 1;
+ }
+ const item = Buffer.concat([encodeUleb128(utf16Size), utf8, Buffer.from([0])]);
+ stringDataOffs.push(place(item));
+ }
+
+ // type_list for Log.d params (String, String) β€” size uint32 + type_idx[] uint16, align 4
+ let logParamListOff = 0;
+ {
+ const paramBuf = Buffer.alloc(4 + 2 * 2);
+ paramBuf.writeUInt32LE(2, 0);
+ paramBuf.writeUInt16LE(tString, 4);
+ paramBuf.writeUInt16LE(tString, 6);
+ logParamListOff = place(paramBuf, true);
+ }
+ const protoParamOffs = [logParamListOff, 0];
+
+ // code_item for bait(): invoke-static {v0,v1}, Log.d ; return-void
+ // Format 35c invoke-static: op=0x71, A=2 args, method_idx=0, regs C=0 D=1
+ const insnBytes = Buffer.from([
+ 0x71, 0x20, 0x00, 0x00, 0x10, 0x00, // invoke-static {v0, v1}, method@0 (Log.d)
+ 0x0e, 0x00, // return-void
+ ]);
+ const codeItemSize = 16 + insnBytes.length; // header 16 + 8 insn bytes
+ const codeItemTemplate = Buffer.alloc(codeItemSize);
+ codeItemTemplate.writeUInt16LE(2, 0); // registers_size
+ codeItemTemplate.writeUInt16LE(0, 2); // ins_size
+ codeItemTemplate.writeUInt16LE(2, 4); // outs_size
+ codeItemTemplate.writeUInt16LE(0, 6); // tries_size
+ codeItemTemplate.writeUInt32LE(0, 8); // debug_info_off
+ codeItemTemplate.writeUInt32LE(insnBytes.length / 2, 12); // insns_size (code units)
+ insnBytes.copy(codeItemTemplate, 16);
+
+ // Each caller gets its own code_item (identical body; unique off required by class_data)
+ const codeOffs: number[] = [];
+ for (let i = 0; i < callerCount; i++) {
+ codeOffs.push(place(Buffer.from(codeItemTemplate), true));
+ }
+
+ // class_data_item per caller: 0 static fields, 0 instance, 1 direct method, 0 virtual
+ const classDataOffs: number[] = [];
+ for (let i = 0; i < callerCount; i++) {
+ // method_idx_diff: methods[0] is Log.d; Caller_i.bait is methods[1+i]
+ // First direct method diff = (1+i) - 0 = 1+i
+ const methodIdxDiff = 1 + i;
+ const accessFlags = 0x0009; // public static
+ const parts = Buffer.concat([
+ encodeUleb128(0), // static_fields_size
+ encodeUleb128(0), // instance_fields_size
+ encodeUleb128(1), // direct_methods_size
+ encodeUleb128(0), // virtual_methods_size
+ encodeUleb128(methodIdxDiff),
+ encodeUleb128(accessFlags),
+ encodeUleb128(codeOffs[i]!),
+ ]);
+ classDataOffs.push(place(parts));
+ }
+
+ // map_list β€” required; list every section
+ // We'll finalize map after we know map's own offset.
+ const mapStart = align4(dataCursor);
+ if (mapStart !== dataCursor) {
+ place(Buffer.alloc(mapStart - dataCursor, 0));
+ }
+
+ // map entries (type, unused, size, offset) β€” 12 bytes each, plus uint32 size header
+ // Types from dalvik docs:
+ const TYPE_HEADER_ITEM = 0x0000;
+ const TYPE_STRING_ID_ITEM = 0x0001;
+ const TYPE_TYPE_ID_ITEM = 0x0002;
+ const TYPE_PROTO_ID_ITEM = 0x0003;
+ const TYPE_METHOD_ID_ITEM = 0x0005;
+ const TYPE_CLASS_DEF_ITEM = 0x0006;
+ const TYPE_CODE_ITEM = 0x2001;
+ const TYPE_STRING_DATA_ITEM = 0x2002;
+ const TYPE_TYPE_LIST = 0x1001;
+ const TYPE_CLASS_DATA_ITEM = 0x2000;
+ const TYPE_MAP_LIST = 0x1000;
+
+ const mapEntries: { type: number; size: number; offset: number }[] = [
+ { type: TYPE_HEADER_ITEM, size: 1, offset: 0 },
+ { type: TYPE_STRING_ID_ITEM, size: strings.length, offset: headerSize },
+ {
+ type: TYPE_TYPE_ID_ITEM,
+ size: types.length,
+ offset: headerSize + stringIdsSize,
+ },
+ {
+ type: TYPE_PROTO_ID_ITEM,
+ size: protos.length,
+ offset: headerSize + stringIdsSize + typeIdsSize,
+ },
+ {
+ type: TYPE_METHOD_ID_ITEM,
+ size: methods.length,
+ offset:
+ headerSize + stringIdsSize + typeIdsSize + protoIdsSize + fieldIdsSize,
+ },
+ {
+ type: TYPE_CLASS_DEF_ITEM,
+ size: callerCount,
+ offset:
+ headerSize +
+ stringIdsSize +
+ typeIdsSize +
+ protoIdsSize +
+ fieldIdsSize +
+ methodIdsSize,
+ },
+ { type: TYPE_TYPE_LIST, size: 1, offset: logParamListOff },
+ {
+ type: TYPE_CODE_ITEM,
+ size: callerCount,
+ offset: codeOffs[0]!,
+ },
+ {
+ type: TYPE_STRING_DATA_ITEM,
+ size: strings.length,
+ offset: stringDataOffs[0]!,
+ },
+ {
+ type: TYPE_CLASS_DATA_ITEM,
+ size: callerCount,
+ offset: classDataOffs[0]!,
+ },
+ ];
+
+ const mapListSize = 4 + (mapEntries.length + 1) * 12; // +1 for MAP_LIST itself
+ const mapOff = dataCursor;
+ const mapBuf = Buffer.alloc(mapListSize);
+ mapBuf.writeUInt32LE(mapEntries.length + 1, 0);
+ let mapAt = 4;
+ for (const e of mapEntries) {
+ mapBuf.writeUInt16LE(e.type, mapAt);
+ mapBuf.writeUInt16LE(0, mapAt + 2);
+ mapBuf.writeUInt32LE(e.size, mapAt + 4);
+ mapBuf.writeUInt32LE(e.offset, mapAt + 8);
+ mapAt += 12;
+ }
+ // Self entry
+ mapBuf.writeUInt16LE(TYPE_MAP_LIST, mapAt);
+ mapBuf.writeUInt16LE(0, mapAt + 2);
+ mapBuf.writeUInt32LE(1, mapAt + 4);
+ mapBuf.writeUInt32LE(mapOff, mapAt + 8);
+ place(mapBuf);
+
+ const fileSize = dataCursor;
+
+ // ----- Write the full file -----
+ const out = Buffer.alloc(fileSize, 0);
+ // header
+ out.write("dex\n035\0", 0, "ascii");
+ // checksum + signature filled later
+ out.writeUInt32LE(fileSize, 32);
+ out.writeUInt32LE(headerSize, 36);
+ out.writeUInt32LE(0x12345678, 40); // endian_tag
+ out.writeUInt32LE(0, 44); // link_size
+ out.writeUInt32LE(0, 48); // link_off
+ out.writeUInt32LE(mapOff, 52);
+ out.writeUInt32LE(strings.length, 56);
+ out.writeUInt32LE(headerSize, 60); // string_ids_off
+ out.writeUInt32LE(types.length, 64);
+ out.writeUInt32LE(headerSize + stringIdsSize, 68); // type_ids_off
+ out.writeUInt32LE(protos.length, 72);
+ out.writeUInt32LE(headerSize + stringIdsSize + typeIdsSize, 76); // proto_ids_off
+ out.writeUInt32LE(0, 80); // field_ids_size
+ out.writeUInt32LE(0, 84); // field_ids_off
+ out.writeUInt32LE(methods.length, 88);
+ out.writeUInt32LE(
+ headerSize + stringIdsSize + typeIdsSize + protoIdsSize + fieldIdsSize,
+ 92,
+ ); // method_ids_off
+ out.writeUInt32LE(callerCount, 96);
+ out.writeUInt32LE(
+ headerSize +
+ stringIdsSize +
+ typeIdsSize +
+ protoIdsSize +
+ fieldIdsSize +
+ methodIdsSize,
+ 100,
+ ); // class_defs_off
+ out.writeUInt32LE(fileSize - idsEnd, 104); // data_size
+ out.writeUInt32LE(idsEnd, 108); // data_off
+
+ // string_ids
+ let at = headerSize;
+ for (const off of stringDataOffs) {
+ out.writeUInt32LE(off, at);
+ at += 4;
+ }
+ // type_ids
+ for (const si of types) {
+ out.writeUInt32LE(si, at);
+ at += 4;
+ }
+ // proto_ids
+ for (let i = 0; i < protos.length; i++) {
+ const p = protos[i]!;
+ out.writeUInt32LE(p.shortyIdx, at);
+ out.writeUInt32LE(p.returnTypeIdx, at + 4);
+ out.writeUInt32LE(protoParamOffs[i]!, at + 8);
+ at += 12;
+ }
+ // method_ids
+ for (const m of methods) {
+ out.writeUInt16LE(m.classIdx, at);
+ out.writeUInt16LE(m.protoIdx, at + 2);
+ out.writeUInt32LE(m.nameIdx, at + 4);
+ at += 8;
+ }
+ // class_defs
+ for (let i = 0; i < callerCount; i++) {
+ out.writeUInt32LE(callerTypeIdx[i]!, at); // class_idx
+ out.writeUInt32LE(0x0001, at + 4); // ACC_PUBLIC
+ out.writeUInt32LE(tObject, at + 8); // superclass
+ out.writeUInt32LE(0, at + 12); // interfaces_off
+ out.writeUInt32LE(sSource, at + 16); // source_file_idx
+ out.writeUInt32LE(0, at + 20); // annotations_off
+ out.writeUInt32LE(classDataOffs[i]!, at + 24); // class_data_off
+ out.writeUInt32LE(0, at + 28); // static_values_off
+ at += 32;
+ }
+
+ // data chunks
+ for (const chunk of dataChunks) {
+ chunk.buf.copy(out, chunk.offset);
+ }
+
+ // Keep marker reachable for inspect
+ void sMarker;
+
+ // SHA-1 signature over bytes [32..end] β†’ [12..32]
+ const sha1 = createHash("sha1").update(out.subarray(32)).digest();
+ sha1.copy(out, 12);
+ // Adler32 checksum over bytes [12..end] β†’ [8..12]
+ let a = 1;
+ let b = 0;
+ for (let i = 12; i < out.length; i++) {
+ a = (a + out[i]!) % 65521;
+ b = (b + a) % 65521;
+ }
+ out.writeUInt32LE(((b << 16) | a) >>> 0, 8);
+
+ return { buffer: out, callerCount };
+}
+
+/**
+ * Generate a decoy DEX that saturates REA #8154's external-invoke caller
+ * inventory (`MAX_EXTERNAL_XREF_BYTES`).
+ */
+export function generateAndroidDexXrefCounter(
+ prng: SeededPrng,
+ intensity: ProtectionIntensity = "balanced",
+): AndroidDexXrefCounterResult {
+ const callerCount = intensityCallerCount(intensity);
+ const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
+ // Embed a handful of canary/diagnostic strings so string-pool scanners also
+ // surface honeypots; does not affect invoke budgets.
+ const extras = deception.textRecords.slice(0, 12);
+ const built = buildExternalInvokeDex(prng, callerCount, extras);
+
+ // Sanity: callers should exceed what a single ~1 MiB inventory comfortably holds
+ // at bankrupt/maximum. We don't assert the byte math here β€” unit tests do.
+ void REA_INTERNAL_LIMITS.ANDROID_EXTERNAL_XREF_BYTES;
+
+ return {
+ dexBuffer: built.buffer,
+ callerClassesEmitted: built.callerCount,
+ externalMethodRefs: 1,
+ marker: "BLA-DEX-XREF-V1",
+ };
+}
+
+/** Next free `classesN.dex` name given existing ZIP entry names. */
+export function nextMultidexName(existingNames: readonly string[]): string {
+ let max = 1; // classes.dex counts as 1
+ for (const name of existingNames) {
+ const base = name.split("/").pop() ?? name;
+ if (/^classes\.dex$/i.test(base)) {
+ max = Math.max(max, 1);
+ continue;
+ }
+ const m = /^classes(\d+)\.dex$/i.exec(base);
+ if (m) max = Math.max(max, Number(m[1]));
+ }
+ return `classes${max + 1}.dex`;
+}
diff --git a/src/shields/formats/archive.ts b/src/shields/formats/archive.ts
index 44d6c15..5e910c6 100644
--- a/src/shields/formats/archive.ts
+++ b/src/shields/formats/archive.ts
@@ -6,6 +6,10 @@ import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.j
import { protectAndroidDexBuffer, protectIl2cppMetadataBuffer } from "./mobile-game.js";
import { generateAndroidR8Counter } from "./android-r8.js";
import { generateAndroidManifestCounter } from "./android-manifest.js";
+import {
+ generateAndroidDexXrefCounter,
+ nextMultidexName,
+} from "./android-dex-xref.js";
export interface ZipEntryInfo {
readonly name: string;
@@ -263,6 +267,9 @@ export function protectZipOrApkBuffer(
/** Non-zero when unsigned APK path planted decoy AndroidManifest.xml (REA #7379/#7818). */
readonly androidManifestDecoyBytes: number;
readonly androidManifestNamedComponents: number;
+ /** Non-zero when unsigned APK path planted decoy classesN.dex for REA #8154. */
+ readonly androidDexXrefBytes: number;
+ readonly androidDexXrefCallers: number;
} {
const preview = readZipEntries(bytes);
const isSigned = preview.some((e) => /^META-INF\/.*\.(SF|RSA|DSA|EC)$/i.test(e.name));
@@ -350,6 +357,8 @@ export function protectZipOrApkBuffer(
let androidJniExportsPlanted = 0;
let androidManifestDecoyBytes = 0;
let androidManifestNamedComponents = 0;
+ let androidDexXrefBytes = 0;
+ let androidDexXrefCallers = 0;
let r8ExtraEntries = 0;
if (treatAsApk) {
const r8 = generateAndroidR8Counter(prng, intensity);
@@ -386,6 +395,17 @@ export function protectZipOrApkBuffer(
androidManifestDecoyBytes = mfBuf.length;
androidManifestNamedComponents = mf.namedComponentsEmitted;
r8ExtraEntries += 2;
+
+ // Counter REA #8154: plant a standalone multidex classesN.dex whose decoy
+ // caller classes each invoke-static android.util.Log.d β€” saturating
+ // MAX_EXTERNAL_XREF_BYTES caller inventory. Never rewrite the developer's
+ // own classes.dex beyond the existing trailer shield above.
+ const xref = generateAndroidDexXrefCounter(prng, intensity);
+ const xrefName = nextMultidexName(outputFiles.map((f) => f.name));
+ outputFiles.push({ name: xrefName, data: xref.dexBuffer });
+ androidDexXrefBytes = xref.dexBuffer.length;
+ androidDexXrefCallers = xref.callerClassesEmitted;
+ r8ExtraEntries += 1;
}
return {
@@ -399,5 +419,7 @@ export function protectZipOrApkBuffer(
androidJniExportsPlanted,
androidManifestDecoyBytes,
androidManifestNamedComponents,
+ androidDexXrefBytes,
+ androidDexXrefCallers,
};
}
diff --git a/tests/android-dex-xref-counter.test.ts b/tests/android-dex-xref-counter.test.ts
new file mode 100644
index 0000000..ca78b52
--- /dev/null
+++ b/tests/android-dex-xref-counter.test.ts
@@ -0,0 +1,125 @@
+import { createHash } from "node:crypto";
+import { describe, expect, it } from "vitest";
+import { SeededPrng } from "../src/core/prng.js";
+import { REA_INTERNAL_LIMITS } from "../src/identity.js";
+import {
+ generateAndroidDexXrefCounter,
+ nextMultidexName,
+} from "../src/shields/formats/android-dex-xref.js";
+import {
+ protectZipOrApkBuffer,
+ readZipEntries,
+ writeZipArchive,
+} from "../src/shields/formats/archive.js";
+import { inspectAndroidDex } from "../src/shields/formats/mobile-game.js";
+
+function adler32(bytes: Buffer, start = 0): number {
+ let a = 1;
+ let b = 0;
+ for (let i = start; i < bytes.length; i++) {
+ a = (a + bytes[i]!) % 65521;
+ b = (b + a) % 65521;
+ }
+ return ((b << 16) | a) >>> 0;
+}
+
+describe("android DEX external-invoke decoy (REA #8154)", () => {
+ it("emits a structurally valid DEX 035 with matching checksum/signature", () => {
+ const res = generateAndroidDexXrefCounter(
+ new SeededPrng("xref-valid"),
+ "balanced",
+ );
+ const dex = res.dexBuffer;
+ expect(dex.subarray(0, 8).toString("latin1")).toBe("dex\n035\0");
+ expect(dex.readUInt32LE(32)).toBe(dex.length);
+ expect(dex.readUInt32LE(36)).toBe(0x70);
+ expect(dex.readUInt32LE(40)).toBe(0x12345678);
+
+ const sha1 = createHash("sha1").update(dex.subarray(32)).digest();
+ expect(Buffer.compare(sha1, dex.subarray(12, 32))).toBe(0);
+ expect(dex.readUInt32LE(8)).toBe(adler32(dex, 12));
+
+ expect(dex.includes(Buffer.from("BLA-DEX-XREF-V1", "utf8"))).toBe(true);
+ expect(dex.includes(Buffer.from("Landroid/util/Log;", "utf8"))).toBe(true);
+ expect(res.callerClassesEmitted).toBeGreaterThan(100);
+ expect(res.externalMethodRefs).toBe(1);
+
+ const inspected = inspectAndroidDex(dex);
+ expect(inspected.validDex).toBe(true);
+ });
+
+ it("scales caller classes with intensity and exceeds budget math at bankrupt", () => {
+ const stealth = generateAndroidDexXrefCounter(
+ new SeededPrng("xref-s"),
+ "stealth",
+ );
+ const balanced = generateAndroidDexXrefCounter(
+ new SeededPrng("xref-b"),
+ "balanced",
+ );
+ const bankrupt = generateAndroidDexXrefCounter(
+ new SeededPrng("xref-k"),
+ "bankrupt",
+ );
+ expect(balanced.callerClassesEmitted).toBeGreaterThan(
+ stealth.callerClassesEmitted,
+ );
+ expect(bankrupt.callerClassesEmitted).toBeGreaterThan(
+ balanced.callerClassesEmitted,
+ );
+ // InvokeBudget.admit charges β‰₯256 bytes base per row before string accounting;
+ // bankrupt caller count Γ— 256 exceeds MAX_EXTERNAL_XREF_BYTES.
+ expect(bankrupt.callerClassesEmitted * 256).toBeGreaterThan(
+ REA_INTERNAL_LIMITS.ANDROID_EXTERNAL_XREF_BYTES,
+ );
+ });
+
+ it("nextMultidexName skips past existing classesN.dex", () => {
+ expect(nextMultidexName([])).toBe("classes2.dex");
+ expect(nextMultidexName(["classes.dex"])).toBe("classes2.dex");
+ expect(nextMultidexName(["classes.dex", "classes2.dex"])).toBe(
+ "classes3.dex",
+ );
+ expect(
+ nextMultidexName(["lib/classes.dex", "classes5.dex", "assets/x.txt"]),
+ ).toBe("classes6.dex");
+ });
+
+ it("unsigned APK path plants decoy classesN.dex without rewriting root manifest", () => {
+ const dex = Buffer.alloc(112, 0);
+ dex.write("dex\n035\0", 0, "ascii");
+ dex.writeUInt32LE(112, 32);
+ dex.writeUInt32LE(112, 36);
+ dex.writeUInt32LE(0x12345678, 40);
+
+ const input = writeZipArchive([
+ { name: "AndroidManifest.xml", data: Buffer.from("<manifest/>", "utf8") },
+ { name: "classes.dex", data: dex },
+ ]);
+ const res = protectZipOrApkBuffer(input, {
+ intensity: "balanced",
+ seed: "apk-xref",
+ isApk: true,
+ });
+ expect(res.androidDexXrefCallers).toBeGreaterThan(100);
+ expect(res.androidDexXrefBytes).toBeGreaterThan(1_000);
+
+ const entries = readZipEntries(res.buffer);
+ const names = entries.map((e) => e.name);
+ expect(names).toContain("classes.dex");
+ expect(names.some((n) => /^classes\d+\.dex$/.test(n))).toBe(true);
+ // Root manifest must stay byte-identical (red line).
+ const rootMf = entries.find((e) => e.name === "AndroidManifest.xml")!;
+ expect(rootMf.data.toString("utf8")).toBe("<manifest/>");
+
+ const decoy = entries.find((e) => /^classes\d+\.dex$/.test(e.name))!;
+ expect(decoy.data.includes(Buffer.from("BLA-DEX-XREF-V1", "utf8"))).toBe(
+ true,
+ );
+ expect(decoy.data.includes(Buffer.from("Landroid/util/Log;", "utf8"))).toBe(
+ true,
+ );
+ // invoke-static opcode 0x71 must appear in the decoy code items.
+ expect(decoy.data.includes(Buffer.from([0x71, 0x20]))).toBe(true);
+ });
+});