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(deception): wire canary+diagnostic into DEX/IL2CPP/bplist/.NET/JVM/ZIP-APK

qybaihe3129dbd9833b
diff --git a/src/engine/protector.ts b/src/engine/protector.ts
index 3fc9ed1..242902b 100644
--- a/src/engine/protector.ts
+++ b/src/engine/protector.ts
@@ -53,13 +53,16 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {
throw new Error(`Unsupported or missing target path: ${absInput}`);
}
- // Reject before auditing, generating payloads, or creating any output paths.
- if (format === "android-apk") throw new UnsupportedApkProtectionError();
+ // Signed APKs still fail closed inside protectZipOrApkBuffer; unsigned APKs
+ // get member-level DEX/IL2CPP hardening. Do not early-throw here.
const absOutput = resolve(
options.outputPath ?? deriveDefaultOutputPath(absInput, options.inPlace),
);
assertSafeOutputPath(absInput, absOutput, format === "directory", options.inPlace);
if (format === "archive-zip") validateZipProtectionInput(readFileSync(absInput));
+ if (format === "android-apk") {
+ validateZipProtectionInput(readFileSync(absInput), { allowUnsignedApk: true });
+ }
if (format === "electron-asar") validateAsarProtectionInput(readFileSync(absInput));
if (format === "sqlite") validateSqliteFileInput(absInput);
if (format === "python-source") findPythonPrologueInsertionOffset(readFileSync(absInput, "utf8"));
@@ -318,18 +321,21 @@ export function protectTarget(options: ProtectionOptions): ProtectionResult {
chaffPayloadsEmbedded = res.chaffPayloadsEmbedded;
binarySectionsPatched = 1;
counteredVectors.add("android-dex-il2cpp-inspection");
- } else if (format === "archive-zip") {
+ } else if (format === "archive-zip" || format === "android-apk") {
const rawZip = readFileSync(absInput);
const res = protectZipOrApkBuffer(rawZip, {
intensity,
seed,
- isApk: false,
+ isApk: format === "android-apk",
});
writeFileSync(absOutput, res.buffer);
- decoyFunctionsInjected = 12;
+ decoyFunctionsInjected = 12 + res.membersHardened;
chaffPayloadsEmbedded = res.chaffPayloadsEmbedded;
binarySectionsPatched = res.decoyEntriesInjected;
counteredVectors.add("archive-inventory");
+ if (res.membersHardened > 0) {
+ counteredVectors.add("android-dex-il2cpp-inspection");
+ }
} else if (format === "apple-plist") {
const rawPlist = readFileSync(absInput);
const res = protectApplePlistBuffer(rawPlist, { intensity, seed });
diff --git a/src/shields/formats/apple-plist.ts b/src/shields/formats/apple-plist.ts
index 1ca7028..20946bf 100644
--- a/src/shields/formats/apple-plist.ts
+++ b/src/shields/formats/apple-plist.ts
@@ -1,5 +1,6 @@
import { SeededPrng } from "../../core/prng.js";
import type { ProtectionIntensity } from "../../core/types.js";
+import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.js";
/**
* Exact constant from `morluto/rea/src/artifacts/apple/PropertyListDecodeBudget.ts:135`.
@@ -10,6 +11,10 @@ export interface ApplePlistShieldResult {
readonly xmlPlist: string;
readonly triggersInternalSubsetBudgetAbort: boolean;
readonly decoyEnclaveEntitlementsAdded: number;
+ readonly canaryTokensEmbedded: number;
+ readonly diagnosticsEmbedded: number;
+ /** True when bplist trailer claims nesting deeper than REA_MAX_BINARY_PLIST_NESTING_DEPTH. */
+ readonly exceedsBinaryPlistNestingDepth: boolean;
}
/**
@@ -68,11 +73,35 @@ export function protectAppleXmlPlist(
}
}
+ const intensity = options.intensity ?? "balanced";
+ const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
+
+ const canaryEntries: string[] = [];
+ deception.canary.syntheticCanaryTokens.forEach((tok, i) => {
+ canaryEntries.push(` <key>BLACanaryCredential_${i}</key>`);
+ canaryEntries.push(` <string>${tok.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</string>`);
+ });
+ deception.canary.ambiguousCredentialUrls.slice(0, 4).forEach((url, i) => {
+ canaryEntries.push(` <key>BLATransportEndpoint_${i}</key>`);
+ canaryEntries.push(` <string>${url.replace(/&/g, "&amp;").replace(/</g, "&lt;")}</string>`);
+ });
+ deception.diagnostics.diagnosticsInjected.slice(0, 4).forEach((d, i) => {
+ canaryEntries.push(` <key>BLASystemDiagnostic_${i}</key>`);
+ const msg = `[${d.errorClass}] (${d.systemCode}) ${d.diagnosticMessage}`.replace(/&/g, "&amp;").replace(/</g, "&lt;");
+ canaryEntries.push(` <string>${msg}</string>`);
+ });
+
+ // Deep nesting bait: claim depth REA_MAX_BINARY_PLIST_NESTING_DEPTH + 4 under a decoy key.
+ const depth = REA_MAX_BINARY_PLIST_NESTING_DEPTH + 4;
+ canaryEntries.push(` <key>BLABinaryPlistNestingDepthClaim</key>`);
+ canaryEntries.push(` <integer>${depth}</integer>`);
+
const enclaveDictEntries = [
` <key>BLAEnclaveAttestationAuthority</key>`,
` <string>com.apple.security.secure-enclave.ring0.${tag}</string>`,
` <key>BLAEnclaveVsockDelegationCID</key>`,
` <integer>16</integer>`,
+ ...canaryEntries,
].join("\n");
normalized = normalized.replace(
@@ -83,7 +112,10 @@ export function protectAppleXmlPlist(
return {
xmlPlist: normalized,
triggersInternalSubsetBudgetAbort: normalized.includes("[]>"),
- decoyEnclaveEntitlementsAdded: 2,
+ decoyEnclaveEntitlementsAdded: 2 + canaryEntries.length / 2,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
+ exceedsBinaryPlistNestingDepth: true,
};
}
@@ -97,18 +129,33 @@ export function protectApplePlistBuffer(
readonly buffer: Buffer;
readonly triggersBudgetAbort: boolean;
readonly decoyEnclaveEntitlementsAdded: number;
+ readonly canaryTokensEmbedded: number;
+ readonly diagnosticsEmbedded: number;
+ readonly exceedsBinaryPlistNestingDepth: boolean;
} {
- // If binary plist (`bplist00`), convert/wrap or append deep-nesting marker (>128 depth sentinel)
+ // If binary plist (`bplist00`), append a depth-claim trailer past REA_MAX_BINARY_PLIST_NESTING_DEPTH (128)
+ // plus canary/diagnostic UTF-8 records. Trailer is ignored by Apple's parser (stops at trailer offset).
if (rawBuffer.length >= 8 && rawBuffer.subarray(0, 6).toString("latin1") === "bplist") {
+ const intensity = options.intensity ?? "balanced";
const prng = new SeededPrng(options.seed ?? "bla-apple-plist-v1");
+ const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
+ const depth = REA_MAX_BINARY_PLIST_NESTING_DEPTH + 4;
const trailer = Buffer.from(
- `\0BLA_BPLIST_DEPTH_GUARD_132:${prng.hex(6)}:com.apple.security.secure-enclave.ring0\0`,
+ [
+ "",
+ `BLA_BPLIST_DEPTH_GUARD_${depth}:${prng.hex(6)}:com.apple.security.secure-enclave.ring0`,
+ ...deception.textRecords,
+ "",
+ ].join("\0"),
"utf8",
);
return {
buffer: Buffer.concat([rawBuffer, trailer]),
triggersBudgetAbort: true,
- decoyEnclaveEntitlementsAdded: 4,
+ decoyEnclaveEntitlementsAdded: 4 + deception.textRecords.length,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
+ exceedsBinaryPlistNestingDepth: true,
};
}
const xmlRes = protectAppleXmlPlist(rawBuffer.toString("utf8"), options);
@@ -116,5 +163,8 @@ export function protectApplePlistBuffer(
buffer: Buffer.from(xmlRes.xmlPlist, "utf8"),
triggersBudgetAbort: xmlRes.triggersInternalSubsetBudgetAbort,
decoyEnclaveEntitlementsAdded: xmlRes.decoyEnclaveEntitlementsAdded,
+ canaryTokensEmbedded: xmlRes.canaryTokensEmbedded,
+ diagnosticsEmbedded: xmlRes.diagnosticsEmbedded,
+ exceedsBinaryPlistNestingDepth: xmlRes.exceedsBinaryPlistNestingDepth,
};
}
diff --git a/src/shields/formats/archive.ts b/src/shields/formats/archive.ts
index 2107437..11bc081 100644
--- a/src/shields/formats/archive.ts
+++ b/src/shields/formats/archive.ts
@@ -2,6 +2,8 @@ import { deflateRawSync, inflateRawSync } from "node:zlib";
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 { protectAndroidDexBuffer, protectIl2cppMetadataBuffer } from "./mobile-game.js";
export interface ZipEntryInfo {
readonly name: string;
@@ -193,25 +195,47 @@ export function writeZipArchive(
}
/** Admission shared with the file engine, before any output paths are created. */
-export function validateZipProtectionInput(bytes: Buffer): readonly ZipEntryInfo[] {
+export function validateZipProtectionInput(
+ bytes: Buffer,
+ options: { readonly allowUnsignedApk?: boolean } = {},
+): readonly ZipEntryInfo[] {
const existingEntries = readZipEntries(bytes);
// Reserve the largest existing transformation (eight entries plus its manifest).
// 0xffff is a ZIP64 sentinel, not a usable classic-ZIP entry count.
if (existingEntries.length > 0xfffe - 9) {
throw new UnsupportedArchiveError("insufficient classic ZIP entry-count capacity for output");
}
- if (existingEntries.some((e) => e.name === "AndroidManifest.xml" || /^META-INF\/.*\.(SF|RSA|DSA|EC)$/i.test(e.name))) {
+ const isSigned = existingEntries.some((e) =>
+ /^META-INF\/.*\.(SF|RSA|DSA|EC)$/i.test(e.name),
+ );
+ const hasManifest = existingEntries.some((e) => e.name === "AndroidManifest.xml");
+ if (isSigned) {
+ throw new UnsupportedArchiveError("APK or signed archive requires a signing-aware pipeline");
+ }
+ if (hasManifest && !options.allowUnsignedApk) {
throw new UnsupportedArchiveError("APK or signed archive requires a signing-aware pipeline");
}
- if (existingEntries.some((e) => ["assets", "assets/enclave", "enclave"].includes(e.name) || e.name.startsWith("assets/enclave/") || e.name.startsWith("enclave/"))) {
+ const reservedPrefixes = options.allowUnsignedApk
+ ? ["assets/bla-shield", "assets/bla-shield/"]
+ : ["assets", "assets/enclave", "enclave", "assets/enclave/", "enclave/"];
+ if (
+ existingEntries.some(
+ (e) =>
+ reservedPrefixes.includes(e.name) ||
+ e.name.startsWith("assets/bla-shield/") ||
+ (!options.allowUnsignedApk &&
+ (e.name.startsWith("assets/enclave/") || e.name.startsWith("enclave/"))),
+ )
+ ) {
throw new UnsupportedArchiveError("existing entries overlap the reserved output namespace");
}
return existingEntries;
}
/**
- * Rewrites the admitted ZIP subset. APK rewriting is explicitly unsupported.
- * Embedded executable assets are copied, not recursively transformed.
+ * Rewrites the admitted ZIP subset. Unsigned APKs get member-level DEX/IL2CPP
+ * protection (classes.dex, *.dex, global-metadata.dat) plus canary decoys under
+ * `assets/bla-shield/`. Signed APKs still throw UnsupportedApkProtectionError.
*/
export function protectZipOrApkBuffer(
bytes: Buffer,
@@ -224,49 +248,95 @@ export function protectZipOrApkBuffer(
readonly buffer: Buffer;
readonly decoyEntriesInjected: number;
readonly chaffPayloadsEmbedded: number;
+ readonly canaryTokensEmbedded: number;
+ readonly diagnosticsEmbedded: number;
+ readonly membersHardened: number;
} {
- if (options.isApk) throw new UnsupportedApkProtectionError();
- const existingEntries = validateZipProtectionInput(bytes);
+ const preview = readZipEntries(bytes);
+ const isSigned = preview.some((e) => /^META-INF\/.*\.(SF|RSA|DSA|EC)$/i.test(e.name));
+ const hasManifest = preview.some((e) => e.name === "AndroidManifest.xml");
+ const treatAsApk = Boolean(options.isApk) || hasManifest;
+
+ if (treatAsApk && isSigned) {
+ throw new UnsupportedApkProtectionError();
+ }
+
+ const existingEntries = validateZipProtectionInput(bytes, {
+ allowUnsignedApk: treatAsApk,
+ });
const intensity = options.intensity ?? "balanced";
const prng = new SeededPrng(options.seed ?? "bla-archive-shield-v1");
const chaffPayloads = generateChaffPayloads(prng, intensity);
- const outputFiles: { name: string; data: Buffer; storeOnly?: boolean }[] = existingEntries.map((e) => ({
- name: e.name,
- data: e.data,
- }));
+ const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
+
+ let membersHardened = 0;
+ const outputFiles: { name: string; data: Buffer; storeOnly?: boolean }[] = existingEntries.map((e) => {
+ const lower = e.name.toLowerCase();
+ if (lower.endsWith(".dex") || lower === "classes.dex" || /(?:^|\/)classes\d*\.dex$/.test(lower)) {
+ const protectedDex = protectAndroidDexBuffer(e.data, { intensity, seed: options.seed });
+ membersHardened += 1;
+ return { name: e.name, data: protectedDex.buffer };
+ }
+ if (lower.endsWith("global-metadata.dat") || lower === "global-metadata.dat") {
+ const protectedMeta = protectIl2cppMetadataBuffer(e.data, { intensity, seed: options.seed });
+ membersHardened += 1;
+ return { name: e.name, data: protectedMeta.buffer };
+ }
+ return { name: e.name, data: e.data };
+ });
+
+ const decoyRoot = treatAsApk ? "assets/bla-shield" : "assets/enclave";
+ const shadowRoot = treatAsApk ? "assets/bla-shield" : "enclave";
- // Inject decoy enclave asset manifests & shadow class descriptors
const manifestContent = JSON.stringify(
{
schema: "bla-archive-enclave-shield/v1",
protected: true,
enclave_delegation: "hardware_tee_ring0",
+ apkMemberHardening: treatAsApk,
+ membersHardened,
manifests: chaffPayloads.map((p) => p.rawText),
+ canaryTokens: deception.canary.syntheticCanaryTokens,
+ diagnostics: deception.diagnostics.diagnosticsInjected.map((d) => ({
+ subsystem: d.subsystem,
+ errorClass: d.errorClass,
+ systemCode: d.systemCode,
+ diagnosticMessage: d.diagnosticMessage,
+ })),
},
null,
2,
);
outputFiles.push({
- name: "assets/enclave/bla-attestation-manifest.json",
+ name: `${decoyRoot}/bla-attestation-manifest.json`,
data: Buffer.from(manifestContent, "utf8"),
});
+ // Explicit canary / diagnostic bait files for archive inventory scanners.
+ outputFiles.push({
+ name: `${decoyRoot}/bla-canary-tokens.txt`,
+ data: Buffer.from(deception.textRecords.join("\n") + "\n", "utf8"),
+ });
+
const decoyCount = intensity === "stealth" ? 2 : intensity === "balanced" ? 4 : 8;
for (let i = 0; i < decoyCount; i++) {
const hex = prng.hex(6);
const payload = chaffPayloads[i % chaffPayloads.length]!;
outputFiles.push({
- name: options.isApk
- ? `assets/enclave/tee_bridge_stub_${hex}.properties`
- : `enclave/shadow_module_${hex}.json`,
+ name: treatAsApk
+ ? `${shadowRoot}/tee_bridge_stub_${hex}.properties`
+ : `${shadowRoot}/shadow_module_${hex}.json`,
data: Buffer.from(`# ${payload.rawText}\nenclave.cid=${16 + i}\nenclave.sealed=true\n`, "utf8"),
});
}
return {
buffer: writeZipArchive(outputFiles),
- decoyEntriesInjected: decoyCount + 1,
+ decoyEntriesInjected: decoyCount + 2,
chaffPayloadsEmbedded: chaffPayloads.length,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
+ membersHardened,
};
}
diff --git a/src/shields/formats/dotnet-managed.ts b/src/shields/formats/dotnet-managed.ts
index 576a74d..3882fc7 100644
--- a/src/shields/formats/dotnet-managed.ts
+++ b/src/shields/formats/dotnet-managed.ts
@@ -1,5 +1,6 @@
import { SeededPrng } from "../../core/prng.js";
import type { ProtectionIntensity } from "../../core/types.js";
+import { buildCanaryAndDiagnosticPayloads } from "../deception/format-payloads.js";
/**
* Exact constant from `morluto/rea/src/dotnet/ManagedDecodeBudget.ts:9`.
@@ -69,15 +70,31 @@ export function protectDotnetManagedBuffer(
): {
readonly buffer: Buffer;
readonly plan: DotnetManagedExhaustionPlan;
+ readonly canaryTokensEmbedded: number;
+ readonly diagnosticsEmbedded: number;
} {
+ const intensity = options.intensity ?? "balanced";
const prng = new SeededPrng(options.seed ?? "bla-dotnet-v1");
- const plan = planDotnetManagedBudgetExhaustion(prng, options.intensity ?? "balanced");
+ const plan = planDotnetManagedBudgetExhaustion(prng, intensity);
+ const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
+ // Stay under REA_MAX_MANAGED_METADATA_REPRESENTATION_BYTES (64 MiB) while
+ // still flooding ManagedDecodeBudget string/row charges with canary bait.
const metadataSection = Buffer.from(
- `\0BLA_DOTNET_CLR_SHIELD_V1\0${plan.decoyPInvokeImports.join("\0")}\0charge:${plan.totalReaRepresentationChargeBytes}\0`,
+ [
+ "",
+ "BLA_DOTNET_CLR_SHIELD_V1",
+ ...plan.decoyPInvokeImports,
+ `charge:${plan.totalReaRepresentationChargeBytes}`,
+ `maxRepresentationBytes:${REA_MAX_MANAGED_METADATA_REPRESENTATION_BYTES}`,
+ ...deception.textRecords,
+ "",
+ ].join("\0"),
"utf8",
);
return {
buffer: Buffer.concat([rawBuffer, metadataSection]),
plan,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
};
}
diff --git a/src/shields/formats/jvm-bytecode.ts b/src/shields/formats/jvm-bytecode.ts
index f8499f1..a65f314 100644
--- a/src/shields/formats/jvm-bytecode.ts
+++ b/src/shields/formats/jvm-bytecode.ts
@@ -1,12 +1,15 @@
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";
export interface JvmClassProtectionResult {
readonly buffer: Buffer;
readonly constantPoolEntriesAdded: number;
readonly customAttributesAdded: number;
readonly chaffPayloadsEmbedded: number;
+ readonly canaryTokensEmbedded: number;
+ readonly diagnosticsEmbedded: number;
}
/**
@@ -64,6 +67,7 @@ export function protectJvmClassBuffer(
): JvmClassProtectionResult {
const prng = new SeededPrng(options.seed);
const chaff = generateChaffPayloads(prng, options.intensity);
+ const deception = buildCanaryAndDiagnosticPayloads(prng, options.intensity);
const decoyCount =
options.intensity === "bankrupt"
@@ -80,6 +84,7 @@ export function protectJvmClassBuffer(
"verifyShamirEd25519QuorumRing:(Ljava/nio/ByteBuffer;[B)Z",
"unsealVsockCid16Frame:(J[B)[B",
...chaff.map((c) => `[BLA-JVM-ENCLAVE:${c.id}] ${c.rawText}`),
+ ...deception.textRecords,
];
for (let i = 0; i < decoyCount; i++) {
@@ -138,6 +143,8 @@ export function protectJvmClassBuffer(
constantPoolEntriesAdded: newCpBuffers.length,
customAttributesAdded: 1,
chaffPayloadsEmbedded: chaff.length,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
};
}
}
@@ -153,5 +160,7 @@ export function protectJvmClassBuffer(
constantPoolEntriesAdded: utf8Strings.length,
customAttributesAdded: 1,
chaffPayloadsEmbedded: chaff.length,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
};
}
diff --git a/src/shields/formats/mobile-game.ts b/src/shields/formats/mobile-game.ts
index 19040d6..535b71f 100644
--- a/src/shields/formats/mobile-game.ts
+++ b/src/shields/formats/mobile-game.ts
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
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";
function computeAdler32(bytes: Buffer): number {
let a = 1;
@@ -61,10 +62,13 @@ export function protectAndroidDexBuffer(
readonly buffer: Buffer;
readonly decoyClassesInjected: number;
readonly chaffPayloadsEmbedded: number;
+ readonly canaryTokensEmbedded: number;
+ readonly diagnosticsEmbedded: number;
} {
const intensity = options.intensity ?? "balanced";
const prng = new SeededPrng(options.seed ?? "bla-dex-shield-v1");
const chaffPayloads = generateChaffPayloads(prng, intensity);
+ const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
const decoyClassCount = intensity === "stealth" ? 12 : intensity === "balanced" ? 28 : 64;
const decoyClasses: string[] = [
@@ -86,10 +90,12 @@ export function protectAndroidDexBuffer(
baseDex.writeUInt32LE(0x12345678, 40); // endian_tag
}
+ // Trailer doubles as a string-pool pollution region for JADX/JEB string scanners.
const trailerText = [
"\0[BLA-DEX-SHIELD-V1]",
...decoyClasses,
...chaffPayloads.map((p) => p.rawText),
+ ...deception.textRecords,
].join("\0") + "\0";
const outDex = Buffer.concat([baseDex, Buffer.from(trailerText, "utf8")]);
@@ -106,6 +112,8 @@ export function protectAndroidDexBuffer(
buffer: outDex,
decoyClassesInjected: decoyClasses.length,
chaffPayloadsEmbedded: chaffPayloads.length,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
};
}
@@ -123,10 +131,13 @@ export function protectIl2cppMetadataBuffer(
readonly buffer: Buffer;
readonly decoyLiteralsInjected: number;
readonly chaffPayloadsEmbedded: number;
+ readonly canaryTokensEmbedded: number;
+ readonly diagnosticsEmbedded: number;
} {
const intensity = options.intensity ?? "balanced";
const prng = new SeededPrng(options.seed ?? "bla-il2cpp-shield-v1");
const chaffPayloads = generateChaffPayloads(prng, intensity);
+ const deception = buildCanaryAndDiagnosticPayloads(prng, intensity);
let header: Buffer;
if (bytes.length >= 256 && bytes.readUInt32LE(0) === 0xfab11baf) {
@@ -143,6 +154,9 @@ export function protectIl2cppMetadataBuffer(
const chaff = chaffPayloads[i % chaffPayloads.length]!;
literals.push(`Enclave.Ring0.Tarpit_${i}_${prng.hex(8)}:${chaff.rawText}`);
}
+ for (const rec of deception.textRecords) {
+ literals.push(rec);
+ }
const trailer = Buffer.from(
`\0[BLA-IL2CPP-SHIELD]\0${literals.join("\0")}\0`,
@@ -153,5 +167,7 @@ export function protectIl2cppMetadataBuffer(
buffer: Buffer.concat([header, trailer]),
decoyLiteralsInjected: decoyLiteralsCount,
chaffPayloadsEmbedded: chaffPayloads.length,
+ canaryTokensEmbedded: deception.canary.syntheticCanaryTokens.length,
+ diagnosticsEmbedded: deception.diagnostics.diagnosticsInjected.length,
};
}
diff --git a/tests/archive-integrity.test.ts b/tests/archive-integrity.test.ts
index 161e5fd..fe8709f 100644
--- a/tests/archive-integrity.test.ts
+++ b/tests/archive-integrity.test.ts
@@ -66,12 +66,40 @@ describe("archive admission preserves bytes or fails closed", () => {
expect(() => protectZipOrApkBuffer(input)).toThrow(UnsupportedArchiveError);
expect(input).toEqual(before);
});
- it("refuses unsigned APKs and APK contents renamed as ZIP", () => {
- expect(() => protectZipOrApkBuffer(fixture(), { isApk: true })).toThrow(UnsupportedApkProtectionError);
- const renamed = writeZipArchive([{ name: "AndroidManifest.xml", data: Buffer.from("fixture") }]);
- expect(() => protectZipOrApkBuffer(renamed)).toThrow(/signing-aware/);
+ it("hardens unsigned APK member DEX while refusing signed APKs", () => {
+ // Minimal DEX header (112 bytes) embedded as classes.dex inside an unsigned APK-shaped ZIP.
+ 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 unsignedApk = writeZipArchive([
+ { name: "AndroidManifest.xml", data: Buffer.from("<manifest/>") },
+ { name: "classes.dex", data: dex },
+ ]);
+ const res = protectZipOrApkBuffer(unsignedApk, { isApk: true, intensity: "stealth", seed: "apk-member" });
+ expect(res.membersHardened).toBe(1);
+ expect(res.canaryTokensEmbedded).toBeGreaterThan(0);
+ expect(res.diagnosticsEmbedded).toBeGreaterThan(0);
+ const entries = readZipEntries(res.buffer);
+ const outDex = entries.find((e) => e.name === "classes.dex")!.data;
+ 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);
+
+ // Signed APK still fails closed.
+ const signed = writeZipArchive([
+ { name: "AndroidManifest.xml", data: Buffer.from("<manifest/>") },
+ { name: "META-INF/CERT.RSA", data: Buffer.from("not a real signature") },
+ { name: "classes.dex", data: dex },
+ ]);
+ expect(() => protectZipOrApkBuffer(signed, { isApk: true })).toThrow(UnsupportedApkProtectionError);
});
- it("refuses signed archives and duplicate names", () => {
+ it("auto-detects AndroidManifest ZIPs as unsigned APK-shaped archives and refuses signed ones", () => {
+ const renamed = writeZipArchive([{ name: "AndroidManifest.xml", data: Buffer.from("fixture") }]);
+ const res = protectZipOrApkBuffer(renamed, { intensity: "stealth", seed: "manifest-zip" });
+ expect(res.canaryTokensEmbedded).toBeGreaterThan(0);
+ expect(readZipEntries(res.buffer).some((e) => e.name.startsWith("assets/bla-shield/"))).toBe(true);
expect(() => protectZipOrApkBuffer(writeZipArchive([{ name: "META-INF/TEST.RSA", data: Buffer.from("not a real signature") }]))).toThrow(/signing-aware/);
expect(() => readZipEntries(writeZipArchive([{ name: "a", data: Buffer.from("1") }, { name: "a", data: Buffer.from("2") }]))).toThrow(/duplicate/);
});
@@ -104,10 +132,10 @@ describe("archive admission preserves bytes or fails closed", () => {
expect(() => protectTarget({ inputPath: file, outputPath: join(dir, "new", "output.zip") })).toThrow(/reserved output namespace/);
expect(existsSync(join(dir, "new"))).toBe(false);
});
- it.each(["bad.zip", "unsigned.apk", "renamed.zip"])("retains input/output and creates no directory for %s", (name) => {
+ it("retains input/output and creates no directory for malformed ZIP", () => {
const dir = mkdtempSync(join(tmpdir(), "bla-archive-")); dirs.push(dir);
- const input = join(dir, name); const output = join(dir, "existing.zip");
- const bytes = name === "bad.zip" ? bad[0]![1]() : name === "renamed.zip" ? writeZipArchive([{ name: "AndroidManifest.xml", data: Buffer.from("fixture") }]) : fixture();
+ const input = join(dir, "bad.zip"); const output = join(dir, "existing.zip");
+ const bytes = bad[0]![1]();
writeFileSync(input, bytes); writeFileSync(output, "existing output");
expect(() => protectTarget({ inputPath: input, outputPath: output })).toThrow();
expect(readFileSync(output, "utf8")).toBe("existing output");
@@ -116,4 +144,24 @@ describe("archive admission preserves bytes or fails closed", () => {
expect(() => protectTarget({ inputPath: input, outputPath: join(dir, "new", "out.zip") })).toThrow();
expect(existsSync(join(dir, "new"))).toBe(false);
});
+ it("protects unsigned.apk in-place without touching unrelated outputs", () => {
+ const dir = mkdtempSync(join(tmpdir(), "bla-archive-apk-")); dirs.push(dir);
+ const input = join(dir, "unsigned.apk");
+ const unrelated = join(dir, "existing.zip");
+ 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 bytes = writeZipArchive([
+ { name: "AndroidManifest.xml", data: Buffer.from("<manifest/>") },
+ { name: "classes.dex", data: dex },
+ ]);
+ writeFileSync(input, bytes);
+ writeFileSync(unrelated, "existing output");
+ const res = protectTarget({ inputPath: input, outputPath: join(dir, "out.apk") });
+ expect(res.outputPath).toContain("out.apk");
+ expect(readFileSync(unrelated, "utf8")).toBe("existing output");
+ expect(readFileSync(input)).toEqual(bytes);
+ });
});
diff --git a/tests/format-canary-coverage.test.ts b/tests/format-canary-coverage.test.ts
new file mode 100644
index 0000000..b469731
--- /dev/null
+++ b/tests/format-canary-coverage.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from "vitest";
+import { protectAndroidDexBuffer, protectIl2cppMetadataBuffer } from "../src/shields/formats/mobile-game.js";
+import { protectApplePlistBuffer, REA_MAX_BINARY_PLIST_NESTING_DEPTH } from "../src/shields/formats/apple-plist.js";
+import {
+ protectDotnetManagedBuffer,
+ REA_MAX_MANAGED_METADATA_REPRESENTATION_BYTES,
+} from "../src/shields/formats/dotnet-managed.js";
+import { protectJvmClassBuffer } from "../src/shields/formats/jvm-bytecode.js";
+import { protectZipOrApkBuffer, readZipEntries, writeZipArchive } from "../src/shields/formats/archive.js";
+
+describe("Canary + system-diagnostic coverage on remaining formats", () => {
+ it("embeds canary/diagnostic text in Android DEX string-pool trailer and keeps checksums valid", () => {
+ 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 res = protectAndroidDexBuffer(dex, { intensity: "balanced", seed: "dex-canary" });
+ expect(res.canaryTokensEmbedded).toBeGreaterThan(0);
+ expect(res.diagnosticsEmbedded).toBeGreaterThan(0);
+ expect(res.buffer.readUInt32LE(32)).toBe(res.buffer.length);
+ expect(res.buffer.toString("latin1")).toContain("PROTECTED_CANARY_CREDENTIAL=");
+ expect(res.buffer.toString("latin1")).toMatch(/\[.*ERROR|FAULT|DIAG|SYSTEM/i);
+ });
+
+ it("embeds canary/diagnostic literals in IL2CPP global-metadata.dat trailer", () => {
+ const meta = Buffer.alloc(256, 0);
+ meta.writeUInt32LE(0xfab11baf, 0);
+ meta.writeInt32LE(29, 4);
+ const res = protectIl2cppMetadataBuffer(meta, { intensity: "balanced", seed: "il2-canary" });
+ expect(res.canaryTokensEmbedded).toBeGreaterThan(0);
+ expect(res.diagnosticsEmbedded).toBeGreaterThan(0);
+ expect(res.buffer.readUInt32LE(0)).toBe(0xfab11baf);
+ expect(res.buffer.toString("latin1")).toContain("PROTECTED_CANARY_CREDENTIAL=");
+ });
+
+ it(`claims bplist nesting past REA_MAX_BINARY_PLIST_NESTING_DEPTH (${REA_MAX_BINARY_PLIST_NESTING_DEPTH}) with canaries`, () => {
+ const bplist = Buffer.concat([
+ Buffer.from("bplist00", "latin1"),
+ Buffer.alloc(32, 0),
+ ]);
+ const res = protectApplePlistBuffer(bplist, { intensity: "balanced", seed: "bplist-canary" });
+ expect(res.exceedsBinaryPlistNestingDepth).toBe(true);
+ expect(res.canaryTokensEmbedded).toBeGreaterThan(0);
+ expect(res.diagnosticsEmbedded).toBeGreaterThan(0);
+ expect(res.buffer.subarray(0, 6).toString("latin1")).toBe("bplist");
+ expect(res.buffer.toString("latin1")).toContain(`BLA_BPLIST_DEPTH_GUARD_${REA_MAX_BINARY_PLIST_NESTING_DEPTH + 4}`);
+ });
+
+ it(`embeds canary/diagnostic into .NET managed assemblies under ${REA_MAX_MANAGED_METADATA_REPRESENTATION_BYTES} cap`, () => {
+ const pe = Buffer.concat([
+ Buffer.from("MZ", "ascii"),
+ Buffer.alloc(64, 0),
+ Buffer.from("BSJB", "ascii"),
+ Buffer.alloc(32, 0),
+ ]);
+ const res = protectDotnetManagedBuffer(pe, { intensity: "balanced", seed: "dotnet-canary" });
+ expect(res.canaryTokensEmbedded).toBeGreaterThan(0);
+ expect(res.diagnosticsEmbedded).toBeGreaterThan(0);
+ expect(res.plan.totalReaRepresentationChargeBytes).toBeLessThan(
+ REA_MAX_MANAGED_METADATA_REPRESENTATION_BYTES,
+ );
+ expect(res.buffer.toString("latin1")).toContain("PROTECTED_CANARY_CREDENTIAL=");
+ expect(res.buffer.toString("latin1")).toContain(`maxRepresentationBytes:${REA_MAX_MANAGED_METADATA_REPRESENTATION_BYTES}`);
+ });
+
+ it("embeds canary/diagnostic UTF-8 into JVM .class constant-pool / trailer", () => {
+ // Minimal CAFEBABE header (not a full valid class — falls back to trailer path)
+ const cls = Buffer.alloc(24, 0);
+ cls.writeUInt32BE(0xcafebabe, 0);
+ cls.writeUInt16BE(0, 4); // minor
+ cls.writeUInt16BE(55, 6); // major
+ cls.writeUInt16BE(1, 8); // cp count
+ const res = protectJvmClassBuffer(cls, { intensity: "balanced", seed: "jvm-canary" });
+ expect(res.canaryTokensEmbedded).toBeGreaterThan(0);
+ expect(res.diagnosticsEmbedded).toBeGreaterThan(0);
+ expect(res.buffer.toString("latin1")).toContain("PROTECTED_CANARY_CREDENTIAL=");
+ });
+
+ it("embeds canary decoys into ZIP members and recursively hardens nested DEX", () => {
+ 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 zip = writeZipArchive([
+ { name: "readme.txt", data: Buffer.from("hello archive") },
+ { name: "lib/classes.dex", data: dex },
+ ]);
+ const res = protectZipOrApkBuffer(zip, { intensity: "balanced", seed: "zip-canary" });
+ expect(res.membersHardened).toBe(1);
+ expect(res.canaryTokensEmbedded).toBeGreaterThan(0);
+ expect(res.diagnosticsEmbedded).toBeGreaterThan(0);
+ const entries = readZipEntries(res.buffer);
+ expect(entries.find((e) => e.name === "readme.txt")?.data.toString()).toBe("hello archive");
+ const outDex = entries.find((e) => e.name === "lib/classes.dex")!.data;
+ expect(outDex.toString("latin1")).toContain("BLA-DEX-SHIELD");
+ expect(outDex.toString("latin1")).toContain("PROTECTED_CANARY_CREDENTIAL=");
+ expect(entries.some((e) => e.name.includes("bla-canary-tokens"))).toBe(true);
+ });
+});
diff --git a/tests/multi-format-shields.test.ts b/tests/multi-format-shields.test.ts
index 26a2da2..b2d3d2b 100644
--- a/tests/multi-format-shields.test.ts
+++ b/tests/multi-format-shields.test.ts
@@ -220,13 +220,17 @@ describe("Multi-Format Shields (WASM, Python, Native ELF/Mach-O/PE, C/Rust/Go He
isApk: false,
});
- expect(protectedZip.decoyEntriesInjected).toBe(5);
+ expect(protectedZip.decoyEntriesInjected).toBe(6); // manifest + canary file + 4 shadow decoys
expect(protectedZip.chaffPayloadsEmbedded).toBeGreaterThanOrEqual(4);
const entriesAfter = readZipEntries(protectedZip.buffer);
- expect(entriesAfter.length).toBe(7);
+ expect(entriesAfter.length).toBe(8); // 2 originals + manifest + canary + 4 decoys
expect(
entriesAfter.some((e) => e.name === "assets/enclave/bla-attestation-manifest.json"),
).toBe(true);
+ expect(
+ entriesAfter.some((e) => e.name === "assets/enclave/bla-canary-tokens.txt"),
+ ).toBe(true);
+ expect(protectedZip.canaryTokensEmbedded).toBeGreaterThan(0);
});
});