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,r8): counter REA #7456/#7472 with mapping poison + JNI decoy .so (v1.4.6)

qybaihec77c468f7375
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6a6394d..58c3a4c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,33 @@ 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.4.6] β€” 2026-10-28
+
+Counter for REA's new Android R8/ProGuard mapping ingestion (#7456) and JNI
+native-declaration ↔ `.so` export linking (#7472). Unsigned APK hardening now
+plants a caller-tempting `mapping.txt` (residual conflicts past `candidates: 8`,
+malformed samples past `malformedSamples: 16`) plus a decoy
+`lib/arm64-v8a/libbla_enclave_jni.so` with real `Java_*` dynsym exports. DEX
+trailers also receive matching JNI-mangled names. Existing developer `.so`
+members are never rewritten (red line).
+
+### Added
+
+- **`src/shields/formats/android-r8.ts`** β€” ProGuard/R8 mapping generator +
+ minimal ELF64 AArch64 ET_DYN builder for JNI decoy exports.
+- **`REA_INTERNAL_LIMITS` Android constants** β€” `PROGUARD_MAPPING_*`,
+ `ANDROID_MAPPING_FILE_BYTES`, `ANDROID_JNI_*`, `MAX_NATIVE_EXPORT_ROWS`.
+- **`verify:rea` drift checks** for the new Android mapping / JNI limits
+ (including `Object.freeze({...})` object forms).
+
+### Changed
+
+- **Unsigned APK path** (`protectZipOrApkBuffer`) injects
+ `assets/bla-shield/mapping.txt`, `proguard-mapping.txt`, and
+ `lib/arm64-v8a/libbla_enclave_jni.so`.
+- **DEX shield** plants JNI-mangled `Java_*` names alongside enclave class decoys.
+- Classic ZIP entry-count reservation widened (9 β†’ 16) for the new decoys.
+
## [1.4.2] β€” 2026-10-27
Patch: stop CI from treating an absent sibling REA checkout as "REA = this
diff --git a/NIGHTLY.md b/NIGHTLY.md
new file mode 100644
index 0000000..4ee9fcd
--- /dev/null
+++ b/NIGHTLY.md
@@ -0,0 +1,30 @@
+# BLA nightly development log
+
+## 2026-10-28 (Asia/Shanghai)
+
+### REA delta
+- Pulled `morluto/rea`: `dd7a2da5b` β†’ `0cd7ef456` (**325 commits**).
+- New analyzers / budgets worth countering:
+ - **#7456** caller-selected R8/ProGuard mapping (`PROGUARD_MAPPING_LIMITS`:
+ candidates=8, malformedSamples=16, projectionBytes=8MiB, indexBytes=128MiB;
+ `ANDROID_MAPPING_LIMITS.fileBytes`=64MiB).
+ - **#7472** JNI native-declaration ↔ `.so` export linking
+ (`ANDROID_JNI_REPORT_BYTES`=16MiB, `ANDROID_JNI_LIBRARY_LIMITS`).
+ - **#7379** selected AndroidManifest component declarations (queued for next night).
+- Remainder of delta: evidence/contract refactors, browser/cli fixes β€” no new
+ BLA-relevant budget constants beyond the Android set above.
+
+### Done tonight
+- `src/identity.ts`: registered Android mapping + JNI + `MAX_NATIVE_EXPORT_ROWS` limits.
+- `src/shields/formats/android-r8.ts`: mapping generator (residual conflicts +
+ malformed bait) + ELF64 AArch64 ET_DYN decoy with real `Java_*` dynsym exports.
+- Wired into unsigned APK path + DEX trailer JNI names.
+- `verify:rea` catalog extended (Object.freeze-aware).
+- Release **[email protected]**.
+
+### Next step (2026-10-29)
+1. Empirical red-team: point sibling REA Android mapping + JNI tools at a
+ BLA-hardened unsigned APK fixture; capture before/after in `docs/redteam/`.
+2. Counter REA #7379 with binary/XML AndroidManifest component decoys (unsigned only).
+3. Optionally densify decoy JNI `.so` past `ANDROID_JNI_REPORT_BYTES` projection
+ when intensity β‰₯ maximum (keep red-line: never rewrite developer libs).
diff --git a/STATE.md b/STATE.md
index 6704af9..fb061dc 100644
--- a/STATE.md
+++ b/STATE.md
@@ -1,6 +1,6 @@
# BLA state of the project
-**Version:** 1.4.0 (`package.json` ↔ `src/identity.ts`, verified by build)
+**Version:** 1.4.6 (`package.json` ↔ `src/identity.ts`, verified by build)
**Status:** Launch-ready locally. Gates green on Node 22.23.4 and Node 24.22.1.
**Blocker to publish:** GitHub token (no push / tag / npm publish / GitHub Release yet).
@@ -29,7 +29,7 @@ Also: `bla_harden` MCP tool with `{ "directory": "." }`.
| EVM bytecode | βœ“ | **verified** β€” `EVM_INTERFACE_LIMITS.inputBytes` | |
| PCAP | βœ“ | **verified** β€” `TSHARK_JSON_MAX_BYTES` (needs tshark) | |
| GPU PTX | βœ“ canary/exhaustion | soft β€” REA still `after=ok` | densifies but no hard budget trip |
-| DEX / IL2CPP / bplist / .NET / JVM / ZIP | βœ“ | designed-for | signed APK refused (by design) |
+| DEX / IL2CPP / bplist / .NET / JVM / ZIP / **Android R8+JNI** | βœ“ | designed-for (R8/JNI new in 1.4.6) | signed APK refused (by design); unsigned APK gets mapping.txt + decoy JNI .so |
| Firmware / SPIR-V / CUDA / AMD GPU objects | β€” | **skipped** | no stable REA analyzer / not in scope yet |
**Designed-for but not empirically verified here** (need native tooling on the REA side): Ghidra, Frida, LLDB, Rizin, JADX.
@@ -77,13 +77,25 @@ Outside the repo, `npm pack` β†’ install tarball β†’ isolated `HOME`:
- `redteam:rea` as sole authoritative evidence; `verify:rea` demoted
- Honest docs separation verified / designed-for / skipped
+## Nightly progress (2026-10-28 Asia/Shanghai)
+
+- Pulled both repos. REA delta since last local tip: **325 commits** on `main`
+ (dd7a2da5b β†’ 0cd7ef456). Headline new analyzers: Android R8/ProGuard mapping
+ (#7456), JNI native-declaration ↔ `.so` export linking (#7472), manifest
+ component declarations (#7379). Most other delta is evidence/contract refactors.
+- Shipped **v1.4.6** counter: `android-r8.ts` + unsigned-APK wiring + identity
+ constants + `verify:rea` drift entries.
+
## Nightly roadmap remaining
-1. **GPU objects** β€” make PTX (and later CUDA/SPIR-V/AMD) trip a real REA budget without breaking validity
-2. **Firmware** β€” decide scope or keep skipped
-3. **Native-tool REA verification** β€” Ghidra / Frida / LLDB / Rizin / JADX empirical probes
-4. **Signed APK** β€” keep refuse-by-default; optional resign workflow documentation
-5. Polish doctor subsystem list (SQLite / models / BEAM / EVM) for parity with shields
+1. **Empirical JADX / Android red-team** β€” run real REA Android mapping + JNI
+ tools against a BLA-hardened unsigned APK fixture; record before/after.
+2. **Manifest-component decoys** β€” counter REA #7379 selected manifest component
+ declarations (binary AndroidManifest.xml decoys for unsigned APKs).
+3. **GPU objects** β€” make PTX (and later CUDA/SPIR-V/AMD) trip a real REA budget without breaking validity
+4. **Firmware** β€” decide scope or keep skipped
+5. **Signed APK** β€” keep refuse-by-default; optional resign workflow documentation
+6. Polish doctor subsystem list (SQLite / models / BEAM / EVM / Android R8) for parity with shields
## Publish checklist (once a GitHub token exists)
diff --git a/package.json b/package.json
index 018fed0..2e91a95 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "bla-agents",
- "version": "1.4.5",
+ "version": "1.4.6",
"description": "BLA (Blind LLM Agents) β€” 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 8fab1c3..b04ae63 100755
--- a/scripts/verify-rea-constants.mjs
+++ b/scripts/verify-rea-constants.mjs
@@ -92,8 +92,9 @@ function findAssignments(files, name) {
function findObjectProperty(files, objectName, propName) {
const hits = [];
+ // Accept both `{ ... } as const` and `Object.freeze({ ... })` forms.
const objRe = new RegExp(
- String.raw`(?:export\s+)?const\s+${objectName}\s*=\s*\{([\s\S]*?)\n\}\s*(?:as\s+const)?\s*;`,
+ String.raw`(?:export\s+)?const\s+${objectName}\s*=\s*(?:Object\.freeze\s*\()?\{([\s\S]*?)\n\}\s*\)?\s*(?:as\s+const)?\s*;`,
"g",
);
for (const file of files) {
@@ -176,6 +177,8 @@ const NUMERIC_EXPECTATIONS = [
{ name: "GPU_OBJECT_BYTES", expected: 128 * 1024 * 1024 },
{ name: "MAX_FIRMWARE_STAGING_BYTES", expected: 512 * 1024 * 1024 },
{ name: "MAX_FIRMWARE_EXTRACTION_DEPTH", expected: 10 },
+ { name: "ANDROID_JNI_REPORT_BYTES", expected: 16 * 1024 * 1024 },
+ { name: "MAX_NATIVE_EXPORT_ROWS", expected: 262_144 },
];
const OBJECT_PROP_EXPECTATIONS = [
@@ -209,6 +212,66 @@ const OBJECT_PROP_EXPECTATIONS = [
expected: 1 * 1024 * 1024,
label: "EVM_INTERFACE_LIMITS.diagnosticBytes",
},
+ {
+ objectName: "PROGUARD_MAPPING_LIMITS",
+ propName: "indexBytes",
+ expected: 128 * 1024 * 1024,
+ label: "PROGUARD_MAPPING_LIMITS.indexBytes",
+ },
+ {
+ objectName: "PROGUARD_MAPPING_LIMITS",
+ propName: "projectionBytes",
+ expected: 8 * 1024 * 1024,
+ label: "PROGUARD_MAPPING_LIMITS.projectionBytes",
+ },
+ {
+ objectName: "PROGUARD_MAPPING_LIMITS",
+ propName: "malformedSamples",
+ expected: 16,
+ label: "PROGUARD_MAPPING_LIMITS.malformedSamples",
+ },
+ {
+ objectName: "PROGUARD_MAPPING_LIMITS",
+ propName: "candidates",
+ expected: 8,
+ label: "PROGUARD_MAPPING_LIMITS.candidates",
+ },
+ {
+ objectName: "ANDROID_MAPPING_LIMITS",
+ propName: "fileBytes",
+ expected: 64 * 1024 * 1024,
+ label: "ANDROID_MAPPING_LIMITS.fileBytes",
+ },
+ {
+ objectName: "ANDROID_JNI_LIBRARY_LIMITS",
+ propName: "libraryBytes",
+ expected: 64 * 1024 * 1024,
+ label: "ANDROID_JNI_LIBRARY_LIMITS.libraryBytes",
+ },
+ {
+ objectName: "ANDROID_JNI_LIBRARY_LIMITS",
+ propName: "totalBytes",
+ expected: 256 * 1024 * 1024,
+ label: "ANDROID_JNI_LIBRARY_LIMITS.totalBytes",
+ },
+ {
+ objectName: "ANDROID_JNI_LIBRARY_LIMITS",
+ propName: "factsBytes",
+ expected: 16 * 1024 * 1024,
+ label: "ANDROID_JNI_LIBRARY_LIMITS.factsBytes",
+ },
+ {
+ objectName: "ANDROID_JNI_LIBRARY_LIMITS",
+ propName: "entries",
+ expected: 100_000,
+ label: "ANDROID_JNI_LIBRARY_LIMITS.entries",
+ },
+ {
+ objectName: "ANDROID_JNI_LIBRARY_LIMITS",
+ propName: "libraries",
+ expected: 2048,
+ label: "ANDROID_JNI_LIBRARY_LIMITS.libraries",
+ },
];
const SYMBOL_EXPECTATIONS = [
diff --git a/src/identity.ts b/src/identity.ts
index 9aed48c..72903aa 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.4.5",
+ version: "1.4.6",
slogan: "Poison -> Exhaust -> Hallucinate. Make Reverse Engineering Bankrupt Again.",
counterpart: {
name: "REA",
@@ -29,6 +29,9 @@ export const BLA_IDENTITY = Object.freeze({
* - `src/model/ModelFormat.ts` (`SafetensorsHeader.ts` & `GgufHeader.ts`)
* - `src/domain/wasm/wasmInterface.ts`
* - `src/dotnet/ManagedDecodeBudget.ts`
+ * - `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`)
*/
export const REA_INTERNAL_LIMITS = Object.freeze({
/** Maximum distinct alternatives retained in one normalized primitive value (`SEMANTIC_PRIMITIVE_CANDIDATE_LIMIT`). */
@@ -119,4 +122,24 @@ export const REA_INTERNAL_LIMITS = Object.freeze({
FIRMWARE_MAX_STAGING_BYTES: 536_870_912,
/** Firmware extraction depth ceiling (`MAX_FIRMWARE_EXTRACTION_DEPTH` = 10). */
FIRMWARE_MAX_EXTRACTION_DEPTH: 10,
+ /**
+ * Caller-selected ProGuard / R8 mapping admission (`ANDROID_MAPPING_LIMITS` /
+ * `PROGUARD_MAPPING_LIMITS` in `src/domain/android/androidMapping.ts` +
+ * `proguardMapping.ts`, added by REA #7456).
+ */
+ ANDROID_MAPPING_FILE_BYTES: 67_108_864,
+ PROGUARD_MAPPING_INDEX_BYTES: 134_217_728,
+ PROGUARD_MAPPING_PROJECTION_BYTES: 8_388_608,
+ PROGUARD_MAPPING_MALFORMED_SAMPLES: 16,
+ PROGUARD_MAPPING_CANDIDATES: 8,
+ /** JNI native-declaration ↔ .so export report budget (`ANDROID_JNI_REPORT_BYTES` in `androidJniBindings.ts`, REA #7472). */
+ ANDROID_JNI_REPORT_BYTES: 16_777_216,
+ /** Per-library / aggregate JNI .so inventory caps (`ANDROID_JNI_LIBRARY_LIMITS` in `AndroidJniLibraries.ts`). */
+ ANDROID_JNI_LIBRARY_BYTES: 67_108_864,
+ ANDROID_JNI_TOTAL_BYTES: 268_435_456,
+ ANDROID_JNI_FACTS_BYTES: 16_777_216,
+ ANDROID_JNI_LIBRARY_ENTRIES: 100_000,
+ ANDROID_JNI_LIBRARIES: 2_048,
+ /** Native export inventory row ceiling (`MAX_NATIVE_EXPORT_ROWS` in `nativeExports.ts`). */
+ MAX_NATIVE_EXPORT_ROWS: 262_144,
});
diff --git a/src/index.ts b/src/index.ts
index b06a0f8..19fcf31 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -105,6 +105,13 @@ export {
protectAndroidDexBuffer,
protectIl2cppMetadataBuffer,
} from "./shields/formats/mobile-game.js";
+export {
+ generateAndroidR8Counter,
+ buildJniDecoyElf64,
+ buildJniExportNames,
+ mangleJniIdentifier,
+ type AndroidR8CounterResult,
+} from "./shields/formats/android-r8.js";
export {
UnsupportedArchiveError,
UnsupportedApkProtectionError,
diff --git a/src/shields/formats/android-r8.ts b/src/shields/formats/android-r8.ts
new file mode 100644
index 0000000..83be424
--- /dev/null
+++ b/src/shields/formats/android-r8.ts
@@ -0,0 +1,306 @@
+import { SeededPrng } from "../../core/prng.js";
+import type { ProtectionIntensity } from "../../core/types.js";
+import { REA_INTERNAL_LIMITS } from "../../identity.js";
+import { generateChaffPayloads } from "../chaff/chaff-generator.js";
+import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.js";
+
+export interface AndroidR8CounterResult {
+ /** Valid ProGuard / R8 mapping.txt with residual conflicts + malformed bait. */
+ readonly mappingText: string;
+ /** Distinct original classes that collide on one residual (past REA candidates: 8). */
+ readonly residualConflictCount: number;
+ /** Malformed mapping lines retained past REA malformedSamples: 16. */
+ readonly malformedSampleCount: number;
+ /** Total class records emitted (unique + conflicting). */
+ readonly classRecordsEmitted: number;
+ /** JNI-mangled `Java_*` export names planted in the decoy .so. */
+ readonly jniExportNames: readonly string[];
+ /** Minimal ELF64 AArch64 ET_DYN with those `Java_*` dynsym exports. */
+ readonly jniElfBuffer: Buffer;
+ readonly chaffPayloadsEmbedded: number;
+ readonly canaryTokensEmbedded: number;
+ readonly diagnosticsEmbedded: number;
+}
+
+/**
+ * JNI short-name mangling (mirrors REA `androidJniBindings.ts` escape rules):
+ * `/` β†’ `_`, `_` β†’ `_1`, `;` β†’ `_2`, `[` β†’ `_3`, else `_0XXXX` for non-alnum.
+ */
+export function mangleJniIdentifier(value: string): string {
+ let result = "";
+ for (let i = 0; i < value.length; i++) {
+ const code = value.charCodeAt(i);
+ const ch = value[i]!;
+ if (code === 47) result += "_";
+ else if (code === 95) result += "_1";
+ else if (code === 59) result += "_2";
+ else if (code === 91) result += "_3";
+ else if (
+ (code >= 48 && code <= 57) ||
+ (code >= 65 && code <= 90) ||
+ (code >= 97 && code <= 122)
+ ) {
+ result += ch;
+ } else {
+ result += `_0${code.toString(16).padStart(4, "0")}`;
+ }
+ }
+ return result;
+}
+
+/** Build `Java_<pkg>_<Class>_<method>` short names matching decoy DEX enclave classes. */
+export function buildJniExportNames(
+ prng: SeededPrng,
+ count: number,
+): string[] {
+ const names: string[] = [
+ "Java_com_enclave_sgx_TeeAttestationBridge_verifyShamirEd25519QuorumRing",
+ "Java_com_enclave_tpm2_KeyUnsealerStub_unsealVsockCid16Frame",
+ "Java_com_enclave_nitro_VsockRing0Transport_openAttestedChannel",
+ ];
+ for (let i = 0; i < count; i++) {
+ const hex = prng.hex(6);
+ const cls = mangleJniIdentifier(`com/enclave/tarpit/EnclaveStateNode_${hex}_${i}`);
+ const method = mangleJniIdentifier(`nativeUnseal_${hex}`);
+ names.push(`Java_${cls}_${method}`);
+ }
+ return names;
+}
+
+/**
+ * Minimal ELF64 little-endian AArch64 shared object (`ET_DYN`) with a real
+ * `.dynsym` / `.dynstr` / `.shstrtab` so REA's `parseNativeExports` admits the
+ * planted `Java_*` JNI export names (basis `jni-export` in #7472).
+ *
+ * Red-line safe: this is a NEW decoy `.so` injected under `lib/arm64-v8a/`,
+ * never a rewrite of the developer's existing native libraries.
+ */
+export function buildJniDecoyElf64(exportNames: readonly string[]): Buffer {
+ const SHT_NULL = 0;
+ const SHT_STRTAB = 3;
+ const SHT_DYNSYM = 11;
+ const SHN_UNDEF = 0;
+ const STB_GLOBAL = 1;
+ const STT_FUNC = 2;
+ const ST_INFO_GLOBAL_FUNC = (STB_GLOBAL << 4) | STT_FUNC;
+ const EM_AARCH64 = 183;
+ const ET_DYN = 3;
+ const EI_CLASS_64 = 2;
+ const EI_DATA_LE = 1;
+ const symbolWidth = 24;
+ const sectionWidth = 64;
+
+ // dynstr: leading NUL + each export name + NUL
+ const dynstrParts: Buffer[] = [Buffer.from([0])];
+ const nameOffsets: number[] = [0]; // null symbol
+ let dynstrBytes = 1;
+ for (const name of exportNames) {
+ nameOffsets.push(dynstrBytes);
+ const encoded = Buffer.from(`${name}\0`, "utf8");
+ dynstrParts.push(encoded);
+ dynstrBytes += encoded.length;
+ }
+ const dynstr = Buffer.concat(dynstrParts);
+
+ // symbols: null entry + one STT_FUNC GLOBAL per export
+ const symbolCount = 1 + exportNames.length;
+ const dynsym = Buffer.alloc(symbolCount * symbolWidth, 0);
+ for (let i = 1; i < symbolCount; i++) {
+ const at = i * symbolWidth;
+ dynsym.writeUInt32LE(nameOffsets[i]!, at); // st_name
+ dynsym[at + 4] = ST_INFO_GLOBAL_FUNC; // st_info
+ dynsym[at + 5] = 0; // st_other
+ dynsym.writeUInt16LE(SHN_UNDEF, at + 6); // st_shndx (undefined β€” name-only decoy)
+ // st_value / st_size remain 0
+ }
+
+ const shstrtab = Buffer.from("\0.dynsym\0.dynstr\0.shstrtab\0", "latin1");
+ // name offsets inside shstrtab
+ const SH_NAME_DYNSYM = 1;
+ const SH_NAME_DYNSTR = 9;
+ const SH_NAME_SHSTRTAB = 17;
+
+ let cursor = 0x100;
+ const align = (n: number) => Math.ceil(n / 16) * 16;
+ const place = (size: number): number => {
+ const offset = cursor;
+ cursor = align(cursor + size);
+ return offset;
+ };
+
+ const dynsymAt = place(dynsym.length);
+ const dynstrAt = place(dynstr.length);
+ const shstrtabAt = place(shstrtab.length);
+ const sectionAt = place(4 * sectionWidth); // NULL + 3 sections
+ const bytes = Buffer.alloc(cursor, 0);
+
+ // ELF64 header
+ bytes[0] = 0x7f;
+ bytes[1] = 0x45;
+ bytes[2] = 0x4c;
+ bytes[3] = 0x46;
+ bytes[4] = EI_CLASS_64;
+ bytes[5] = EI_DATA_LE;
+ bytes[6] = 1; // EV_CURRENT
+ bytes.writeUInt16LE(ET_DYN, 16);
+ bytes.writeUInt16LE(EM_AARCH64, 18);
+ bytes.writeUInt32LE(1, 20); // e_version
+ // e_entry = 0
+ // e_phoff = 0
+ bytes.writeBigUInt64LE(BigInt(sectionAt), 40); // e_shoff
+ bytes.writeUInt16LE(64, 52); // e_ehsize
+ bytes.writeUInt16LE(56, 54); // e_phentsize
+ // e_phnum = 0
+ bytes.writeUInt16LE(sectionWidth, 58); // e_shentsize
+ bytes.writeUInt16LE(4, 60); // e_shnum
+ bytes.writeUInt16LE(3, 62); // e_shstrndx = .shstrtab
+
+ dynsym.copy(bytes, dynsymAt);
+ dynstr.copy(bytes, dynstrAt);
+ shstrtab.copy(bytes, shstrtabAt);
+
+ const writeSection = (
+ index: number,
+ nameOff: number,
+ type: number,
+ offset: number,
+ size: number,
+ link: number,
+ info: number,
+ entsize: number,
+ ) => {
+ const at = sectionAt + index * sectionWidth;
+ bytes.writeUInt32LE(nameOff, at);
+ bytes.writeUInt32LE(type, at + 4);
+ // sh_flags = 0
+ bytes.writeBigUInt64LE(BigInt(offset), at + 24); // sh_offset
+ bytes.writeBigUInt64LE(BigInt(size), at + 32); // sh_size
+ bytes.writeUInt32LE(link, at + 40);
+ bytes.writeUInt32LE(info, at + 44);
+ bytes.writeBigUInt64LE(BigInt(entsize), at + 56);
+ };
+
+ writeSection(0, 0, SHT_NULL, 0, 0, 0, 0, 0);
+ // .dynsym links to .dynstr (section index 2); info = first non-local symbol (=1)
+ writeSection(1, SH_NAME_DYNSYM, SHT_DYNSYM, dynsymAt, dynsym.length, 2, 1, symbolWidth);
+ writeSection(2, SH_NAME_DYNSTR, SHT_STRTAB, dynstrAt, dynstr.length, 0, 0, 0);
+ writeSection(3, SH_NAME_SHSTRTAB, SHT_STRTAB, shstrtabAt, shstrtab.length, 0, 0, 0);
+
+ return bytes;
+}
+
+function intensityScale(intensity: ProtectionIntensity): {
+ conflicts: number;
+ uniqueClasses: number;
+ jniExports: number;
+ malformed: number;
+} {
+ // Always exceed PROGUARD_MAPPING_CANDIDATES (8) and malformedSamples (16).
+ const candidates = REA_INTERNAL_LIMITS.PROGUARD_MAPPING_CANDIDATES;
+ const malformedFloor = REA_INTERNAL_LIMITS.PROGUARD_MAPPING_MALFORMED_SAMPLES;
+ switch (intensity) {
+ case "stealth":
+ return {
+ conflicts: candidates + 4,
+ uniqueClasses: 16,
+ jniExports: 16,
+ malformed: malformedFloor + 4,
+ };
+ case "maximum":
+ case "bankrupt":
+ return {
+ conflicts: candidates * 8,
+ uniqueClasses: 96,
+ jniExports: 96,
+ malformed: malformedFloor * 3,
+ };
+ case "balanced":
+ default:
+ return {
+ conflicts: candidates * 3,
+ uniqueClasses: 32,
+ jniExports: 32,
+ malformed: malformedFloor + 8,
+ };
+ }
+}
+
+/**
+ * Generates a caller-tempting ProGuard / R8 `mapping.txt` plus a decoy
+ * `libbla_enclave_jni.so` that counter REA's new Android analyzers:
+ * - #7456 `AndroidMappingFile` / `parseProguardMapping` (residual conflicts past
+ * `candidates: 8`, malformed samples past `malformedSamples: 16`)
+ * - #7472 `projectAndroidJniBindings` (static `Java_*` export ↔ declaration linking)
+ */
+export function generateAndroidR8Counter(
+ prng: SeededPrng,
+ intensity: ProtectionIntensity = "balanced",
+): AndroidR8CounterResult {
+ const scale = intensityScale(intensity);
+ const chaff = generateChaffPayloads(prng, intensity);
+ const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
+
+ const lines: string[] = [
+ "# compiler: R8",
+ "# compiler_version: 8.7.18-bla-enclave",
+ "# min_api: 24",
+ `# pg_map_id: ${prng.hex(8)}`,
+ `# pg_map_hash: sha-256 ${prng.hex(32)}`,
+ "# bla-shield: decoy mapping β€” applying this file poisons REA residual resolution",
+ "",
+ ];
+
+ // Residual collision cluster: many originals β†’ same obfuscated residual `a.a.a`
+ // so resolveProguardClass truncates at candidates: 8 and surfaces conflict.
+ const residual = "a.a.a";
+ for (let i = 0; i < scale.conflicts; i++) {
+ const original = `com.enclave.sgx.TeeAttestationBridge$${prng.hex(4)}$${i}`;
+ lines.push(`${original} -> ${residual}:`);
+ lines.push(` int sealedCid -> a`);
+ lines.push(
+ ` 1:10:boolean verifyShamirEd25519QuorumRing(java.nio.ByteBuffer,byte[]) -> a`,
+ );
+ }
+
+ // Unique decoy class records (enclave / tarpit naming consistent with DEX shield)
+ for (let i = 0; i < scale.uniqueClasses; i++) {
+ const hex = prng.hex(6);
+ const original = `com.enclave.tarpit.EnclaveStateNode_${hex}_${i}`;
+ const mapped = `b.${String.fromCharCode(97 + (i % 26))}.${prng.hex(2)}`;
+ lines.push(`${original} -> ${mapped}:`);
+ lines.push(` long vsockHandle -> a`);
+ lines.push(` 1:5:void nativeUnseal_${hex}() -> a`);
+ }
+
+ // Malformed bait β€” lines that fail CLASS/FIELD/METHOD regexes so REA retains
+ // them under malformedSamples (cap 16) then drops the rest.
+ for (let i = 0; i < scale.malformed; i++) {
+ lines.push(`<<<MALFORMED_MAPPING_BAIT_${i}_${prng.hex(4)} not a class line`);
+ lines.push(` !!broken field ${i}`);
+ lines.push(` 1:2:notAType brokenMethod( -> xx`);
+ }
+
+ // Canary / diagnostic text as mapping comments (harmless to the grammar)
+ for (const rec of deception.textRecords.slice(0, 8)) {
+ lines.push(`# ${rec}`);
+ }
+ for (const c of chaff.slice(0, 4)) {
+ lines.push(`# chaff:${c.id}:${c.rawText.slice(0, 120)}`);
+ }
+
+ const mappingText = lines.join("\n") + "\n";
+ const jniExportNames = buildJniExportNames(prng, scale.jniExports);
+ const jniElfBuffer = buildJniDecoyElf64(jniExportNames);
+
+ return {
+ mappingText,
+ residualConflictCount: scale.conflicts,
+ malformedSampleCount: scale.malformed,
+ classRecordsEmitted: scale.conflicts + scale.uniqueClasses,
+ jniExportNames,
+ jniElfBuffer,
+ chaffPayloadsEmbedded: chaff.length,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
+ };
+}
diff --git a/src/shields/formats/archive.ts b/src/shields/formats/archive.ts
index 11bc081..43cc6de 100644
--- a/src/shields/formats/archive.ts
+++ b/src/shields/formats/archive.ts
@@ -4,6 +4,7 @@ import type { ProtectionIntensity } from "../../core/types.js";
import { generateChaffPayloads } from "../chaff/chaff-generator.js";
import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.js";
import { protectAndroidDexBuffer, protectIl2cppMetadataBuffer } from "./mobile-game.js";
+import { generateAndroidR8Counter } from "./android-r8.js";
export interface ZipEntryInfo {
readonly name: string;
@@ -200,9 +201,9 @@ export function validateZipProtectionInput(
options: { readonly allowUnsignedApk?: boolean } = {},
): readonly ZipEntryInfo[] {
const existingEntries = readZipEntries(bytes);
- // Reserve the largest existing transformation (eight entries plus its manifest).
+ // Reserve room for decoy property stubs + canary/manifest + R8 mapping pair + JNI .so.
// 0xffff is a ZIP64 sentinel, not a usable classic-ZIP entry count.
- if (existingEntries.length > 0xfffe - 9) {
+ if (existingEntries.length > 0xfffe - 16) {
throw new UnsupportedArchiveError("insufficient classic ZIP entry-count capacity for output");
}
const isSigned = existingEntries.some((e) =>
@@ -218,10 +219,14 @@ export function validateZipProtectionInput(
const reservedPrefixes = options.allowUnsignedApk
? ["assets/bla-shield", "assets/bla-shield/"]
: ["assets", "assets/enclave", "enclave", "assets/enclave/", "enclave/"];
+ const reservedExact = options.allowUnsignedApk
+ ? ["lib/arm64-v8a/libbla_enclave_jni.so"]
+ : [];
if (
existingEntries.some(
(e) =>
reservedPrefixes.includes(e.name) ||
+ reservedExact.includes(e.name) ||
e.name.startsWith("assets/bla-shield/") ||
(!options.allowUnsignedApk &&
(e.name.startsWith("assets/enclave/") || e.name.startsWith("enclave/"))),
@@ -251,6 +256,9 @@ export function protectZipOrApkBuffer(
readonly canaryTokensEmbedded: number;
readonly diagnosticsEmbedded: number;
readonly membersHardened: number;
+ /** Non-zero when unsigned APK path planted R8 mapping + JNI decoy .so (REA #7456/#7472). */
+ readonly androidR8MappingBytes: number;
+ readonly androidJniExportsPlanted: number;
} {
const preview = readZipEntries(bytes);
const isSigned = preview.some((e) => /^META-INF\/.*\.(SF|RSA|DSA|EC)$/i.test(e.name));
@@ -331,12 +339,40 @@ export function protectZipOrApkBuffer(
});
}
+ // Counter REA #7456 (caller-selected R8/ProGuard mapping) + #7472 (JNI export linking):
+ // plant a tempting mapping.txt and a decoy libbla_enclave_jni.so with real Java_* dynsym
+ // exports. Only on unsigned APK-shaped archives; never rewrite the developer's own .so.
+ let androidR8MappingBytes = 0;
+ let androidJniExportsPlanted = 0;
+ let r8ExtraEntries = 0;
+ if (treatAsApk) {
+ const r8 = generateAndroidR8Counter(prng, intensity);
+ const mappingBuf = Buffer.from(r8.mappingText, "utf8");
+ outputFiles.push({
+ name: `${decoyRoot}/mapping.txt`,
+ data: mappingBuf,
+ });
+ outputFiles.push({
+ name: `${decoyRoot}/proguard-mapping.txt`,
+ data: Buffer.from(r8.mappingText, "utf8"),
+ });
+ outputFiles.push({
+ name: "lib/arm64-v8a/libbla_enclave_jni.so",
+ data: r8.jniElfBuffer,
+ });
+ androidR8MappingBytes = mappingBuf.length;
+ androidJniExportsPlanted = r8.jniExportNames.length;
+ r8ExtraEntries = 3;
+ }
+
return {
buffer: writeZipArchive(outputFiles),
- decoyEntriesInjected: decoyCount + 2,
+ decoyEntriesInjected: decoyCount + 2 + r8ExtraEntries,
chaffPayloadsEmbedded: chaffPayloads.length,
canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
membersHardened,
+ androidR8MappingBytes,
+ androidJniExportsPlanted,
};
}
diff --git a/src/shields/formats/mobile-game.ts b/src/shields/formats/mobile-game.ts
index 535b71f..8b6d3b9 100644
--- a/src/shields/formats/mobile-game.ts
+++ b/src/shields/formats/mobile-game.ts
@@ -3,6 +3,7 @@ import { SeededPrng } from "../../core/prng.js";
import type { ProtectionIntensity } from "../../core/types.js";
import { generateChaffPayloads } from "../chaff/chaff-generator.js";
import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.js";
+import { buildJniExportNames } from "./android-r8.js";
function computeAdler32(bytes: Buffer): number {
let a = 1;
@@ -90,10 +91,13 @@ export function protectAndroidDexBuffer(
baseDex.writeUInt32LE(0x12345678, 40); // endian_tag
}
- // Trailer doubles as a string-pool pollution region for JADX/JEB string scanners.
+ // Trailer doubles as a string-pool pollution region for JADX/JEB string scanners
+ // and plants JNI-mangled Java_* names that match the decoy .so exports (REA #7472).
+ const jniNames = buildJniExportNames(prng, intensity === "stealth" ? 8 : intensity === "balanced" ? 16 : 48);
const trailerText = [
"\0[BLA-DEX-SHIELD-V1]",
...decoyClasses,
+ ...jniNames,
...chaffPayloads.map((p) => p.rawText),
...deception.textRecords,
].join("\0") + "\0";
diff --git a/tests/android-r8-counter.test.ts b/tests/android-r8-counter.test.ts
new file mode 100644
index 0000000..d4ec7a4
--- /dev/null
+++ b/tests/android-r8-counter.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+import { SeededPrng } from "../src/core/prng.js";
+import { REA_INTERNAL_LIMITS } from "../src/identity.js";
+import {
+ buildJniDecoyElf64,
+ buildJniExportNames,
+ generateAndroidR8Counter,
+ mangleJniIdentifier,
+} from "../src/shields/formats/android-r8.js";
+
+describe("android R8 / JNI counter (REA #7456 / #7472)", () => {
+ it("mangles JNI identifiers the same way REA escape() does", () => {
+ expect(mangleJniIdentifier("com/enclave/sgx/Tee")).toBe("com_enclave_sgx_Tee");
+ expect(mangleJniIdentifier("a_b")).toBe("a_1b");
+ expect(mangleJniIdentifier("x;")).toBe("x_2");
+ expect(mangleJniIdentifier("y[")).toBe("y_3");
+ });
+
+ it("builds an ELF64 ET_DYN with Java_* dynsym export names", () => {
+ const names = buildJniExportNames(new SeededPrng("elf"), 4);
+ const elf = buildJniDecoyElf64(names);
+ expect(elf[0]).toBe(0x7f);
+ expect(elf.subarray(1, 4).toString("latin1")).toBe("ELF");
+ expect(elf.readUInt16LE(16)).toBe(3); // ET_DYN
+ expect(elf.readUInt16LE(18)).toBe(183); // EM_AARCH64
+ for (const n of names) {
+ expect(elf.includes(Buffer.from(n + "\0", "utf8"))).toBe(true);
+ }
+ });
+
+ it("emits residual conflicts past PROGUARD_MAPPING_CANDIDATES and malformed past MALFORMED_SAMPLES", () => {
+ const res = generateAndroidR8Counter(new SeededPrng("r8-balanced"), "balanced");
+ expect(res.residualConflictCount).toBeGreaterThan(
+ REA_INTERNAL_LIMITS.PROGUARD_MAPPING_CANDIDATES,
+ );
+ expect(res.malformedSampleCount).toBeGreaterThan(
+ REA_INTERNAL_LIMITS.PROGUARD_MAPPING_MALFORMED_SAMPLES,
+ );
+ expect(res.classRecordsEmitted).toBeGreaterThan(res.residualConflictCount);
+ expect(res.jniExportNames.length).toBeGreaterThan(8);
+ expect(res.jniElfBuffer.length).toBeGreaterThan(256);
+ expect(res.mappingText).toMatch(/^# compiler: R8/m);
+ // Count residual collision lines
+ const residualLines = res.mappingText
+ .split("\n")
+ .filter((l) => l.endsWith(" -> a.a.a:"));
+ expect(residualLines.length).toBe(res.residualConflictCount);
+ const malformed = res.mappingText
+ .split("\n")
+ .filter((l) => l.includes("MALFORMED_MAPPING_BAIT_"));
+ expect(malformed.length).toBe(res.malformedSampleCount);
+ });
+
+ it("scales past candidates at every intensity", () => {
+ for (const intensity of ["stealth", "balanced", "maximum", "bankrupt"] as const) {
+ const res = generateAndroidR8Counter(new SeededPrng(`r8-${intensity}`), intensity);
+ expect(res.residualConflictCount).toBeGreaterThan(
+ REA_INTERNAL_LIMITS.PROGUARD_MAPPING_CANDIDATES,
+ );
+ expect(res.mappingText.length).toBeGreaterThan(100);
+ }
+ });
+});
diff --git a/tests/archive-integrity.test.ts b/tests/archive-integrity.test.ts
index fe8709f..185f9e2 100644
--- a/tests/archive-integrity.test.ts
+++ b/tests/archive-integrity.test.ts
@@ -86,6 +86,20 @@ describe("archive admission preserves bytes or fails closed", () => {
expect(outDex.toString("latin1")).toContain("BLA-DEX-SHIELD");
expect(outDex.toString("latin1")).toContain("PROTECTED_CANARY_CREDENTIAL=");
expect(entries.some((e) => e.name.startsWith("assets/bla-shield/"))).toBe(true);
+ // REA #7456 / #7472 counters: R8 mapping bait + JNI decoy .so with real Java_* dynsym.
+ expect(res.androidR8MappingBytes).toBeGreaterThan(200);
+ expect(res.androidJniExportsPlanted).toBeGreaterThan(8);
+ expect(entries.some((e) => e.name === "assets/bla-shield/mapping.txt")).toBe(true);
+ expect(entries.some((e) => e.name === "assets/bla-shield/proguard-mapping.txt")).toBe(true);
+ expect(entries.some((e) => e.name === "lib/arm64-v8a/libbla_enclave_jni.so")).toBe(true);
+ const elf = entries.find((e) => e.name === "lib/arm64-v8a/libbla_enclave_jni.so")!.data;
+ expect(elf[0]).toBe(0x7f);
+ expect(elf.subarray(1, 4).toString("latin1")).toBe("ELF");
+ expect(elf.includes(Buffer.from("Java_com_enclave_sgx_TeeAttestationBridge_verifyShamirEd25519QuorumRing"))).toBe(true);
+ const mapping = entries.find((e) => e.name === "assets/bla-shield/mapping.txt")!.data.toString("utf8");
+ expect(mapping).toMatch(/# compiler: R8/);
+ expect(mapping).toMatch(/-> a\.a\.a:/);
+ expect(outDex.toString("latin1")).toContain("Java_com_enclave_sgx_TeeAttestationBridge");
// Signed APK still fails closed.
const signed = writeZipArchive([
@@ -104,11 +118,12 @@ describe("archive admission preserves bytes or fails closed", () => {
expect(() => readZipEntries(writeZipArchive([{ name: "a", data: Buffer.from("1") }, { name: "a", data: Buffer.from("2") }]))).toThrow(/duplicate/);
});
it("reserves output entries below the classic ZIP sentinel before filesystem changes", () => {
- const files = Array.from({ length: 65_526 }, (_, i) => ({ name: `f${i}`, data: Buffer.alloc(0) }));
+ // 0xfffe - 16 = 65_518 usable input entries after decoy/R8/JNI reservation.
+ const files = Array.from({ length: 65_519 }, (_, i) => ({ name: `f${i}`, data: Buffer.alloc(0) }));
const accepted = writeZipArchive(files.slice(0, -1));
- expect(validateZipProtectionInput(accepted)).toHaveLength(65_525);
+ expect(validateZipProtectionInput(accepted)).toHaveLength(65_518);
const rejected = writeZipArchive(files); const original = Buffer.from(rejected);
- expect(readZipEntries(rejected)).toHaveLength(65_526);
+ expect(readZipEntries(rejected)).toHaveLength(65_519);
expect(() => protectZipOrApkBuffer(rejected, { intensity: "stealth" })).toThrow(/entry-count capacity/);
expect(rejected.equals(original)).toBe(true);
const dir = mkdtempSync(join(tmpdir(), "bla-archive-count-")); dirs.push(dir);