From 889f7ea5caa35f065f07313f954934fba1e80b97 Mon Sep 17 00:00:00 2001 From: qybaihe Date: Tue, 10 Nov 2026 17:53:27 +0800 Subject: [PATCH] feat(v3.2.3): structural AST/container audit, PE .enclave section hardening, default decoy entanglement, and 14/14 benchmark equivalence (closes #157) - Replace substring marker checks and hardcoded decoy counts in src/engine/auditor.ts, src/shields/formats/mobile-game.ts, and src/shields/formats/native.ts with structural Babel AST verification and container header/checksum checks across JS/TS, Python, Android DEX (file_size + Adler32), Unity IL2CPP, ZIP/APK, SourceMap, Apple Plist, .NET Managed, JVM .class, and Native binaries. - Upgrade Windows PE32/PE32+ hardening in src/shields/formats/native.ts to inject a mapped .enclave COFF section (0x40000060) and section-alignment slack with 16-byte aligned x86-64 ABI function islands, MSVC C++ RTTI descriptors, CodeView RSDS PDB debug records, and Win32 Crypto/BCrypt/NCrypt/WinHTTP symbols while updating NumberOfSections, SizeOfImage, and CheckSum (closes #157). - Remove self-sabotaging decorative-deception-signal and none-client-side-only strings from emitted runtime-shield JS code while preserving TypeScript classification metadata. - Entangle all injected JS decoy/tarpit functions into the opaque-predicate seedVarName initializer by default so stripping decoys breaks execution without requiring --self-seal. - Upgrade all 14 showcase benchmark targets in src/engine/benchmark.ts to run real before/after VM execution, SQL query parity, Float32 tensor weight equality, or container payload preservation checks. Co-Authored-By: Claude Code --- CHANGELOG.md | 13 + README.md | 5 +- challenge/v6/SEAL.json | 2 +- challenge/v7/SEAL.json | 2 +- challenge/v8/SEAL.json | 2 +- challenge/v9/SEAL.json | 2 +- docs/readme/README_zh.md | 13 +- package-lock.json | 4 +- package.json | 2 +- src/engine/auditor.ts | 425 +++++++++++++++----- src/engine/benchmark.ts | 410 ++++++++++++++++--- src/identity.ts | 2 +- src/shields/formats/mobile-game.ts | 21 +- src/shields/formats/native.ts | 316 ++++++++++++++- src/shields/javascript/ast-shield.ts | 49 ++- src/shields/runtime/runtime-shield.ts | 5 +- tests/class-rename-opaque-seed.test.ts | 5 +- tests/critique-reinforcements-v323.test.ts | 235 +++++++++++ tests/sqlite-coverage-debug-posture.test.ts | 7 +- 19 files changed, 1334 insertions(+), 186 deletions(-) create mode 100644 tests/critique-reinforcements-v323.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 829df5a..c4f1499 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [3.2.3] — 2026-11-10 + +Major anti-spoofing audit reinforcement, Windows PE32/PE32+ mapped `.enclave` COFF section hardening (closes #157), default JS decoy function entanglement into opaque-predicate seeds, and real before/after equivalence verification across all 14 benchmark targets. + +### Added +- **Windows PE32/PE32+ Mapped `.enclave` COFF Section Hardening (`src/shields/formats/native.ts`, closes #157):** Upgrades PE binary hardening from an unmapped EOF trailer to injecting a mapped `.enclave` COFF section (`0x40000060`) and/or section-alignment slack containing 16-byte aligned x86-64 ABI function islands (`endbr64; push rbp; mov rbp, rsp; ...; ret`), MSVC C++ RTTI type descriptors (`.?AVEnclaveRing0Transport@sgx@security@@`), CodeView `RSDS` PDB debug records, and Win32 Crypto/BCrypt/NCrypt/WinHTTP dispatch symbols while updating `NumberOfSections`, `SizeOfImage`, and `CheckSum`. +- **Structural AST & Container Verification in Auditor (`src/engine/auditor.ts`, `src/shields/formats/mobile-game.ts`, `src/shields/formats/native.ts`):** Replaces substring marker checks and hardcoded decoy counts with structural Babel AST verification (`alias-selections` optional-member ternaries, `primitive-candidates` conditional chains, `primitive-bytes` doubling chains, `getter-expansion` getter properties) and container header/checksum verification across JS/TS, Python, Android DEX (`file_size` + `Adler32`), Unity IL2CPP, ZIP/APK, SourceMap, Apple Plist, .NET Managed, JVM `.class`, and Native binaries. +- **Default JS Decoy Function Entanglement (`src/shields/javascript/ast-shield.ts`):** Masks `opaqueSeedBase` with `0xfffffffc` and entangles all injected decoy/tarpit function identifiers into `seedVarName` at module initialization (`[...fns].every(_f => typeof _f === "function") && digestFn(0) === expectedDigest ? 1 : 0`), so stripping injected decoys throws a `ReferenceError` or inverts every opaque predicate (`(u * u) & 7`) without requiring `--self-seal`. +- **14/14 Real Benchmark Equivalence Verification (`src/engine/benchmark.ts`):** Replaces placeholder `true` / `BLA_PROTECTED` checks with real before/after VM execution (`.asar` unpacked `main.js` + `preload.js` IPC harness), SQL query parity + `PRAGMA integrity_check` (`.sqlite`), Float32 tensor weight equality (`.safetensors`), SHA-1/Adler32 + class descriptor preservation (`.dex`), XML bundle key verification (`.plist`), PE/CLR metadata preservation (`.dll`), IFF chunk/export preservation (`.beam`), EVM dispatcher bytecode prefix + CBOR trailer verification (`.evm`), libpcap packet frame preservation (`.pcap`), and PTX kernel body verification (`.ptx`). + +### Fixed +- **Runtime Shield Self-Sabotage Removal (`src/shields/runtime/runtime-shield.ts`):** Removed `/* decorative shadow runtime signal — non-authoritative */`, `classification: "decorative-deception-signal"`, and `securityBoundary: "none-client-side-only"` from the emitted JavaScript code (`snippet.code`) while preserving honest TypeScript return metadata. + ## [3.2.2] — 2026-11-09 Patch extending opt-in `sidecarEntangle` to **Electron ASAR archive-note companions**. diff --git a/README.md b/README.md index 2fc3d50..04090a4 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ **The open-source Counter-REA Blue Defense MCP & CLI that protects software releases against AI reverse-engineering agents (`morluto/rea`, autonomous decompilers, and LLM recon pipelines) — verified across 14 showcase benchmark targets.** -[![npm version](https://img.shields.io/badge/npm-bla--agents_v3.2.2-2563eb?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/bla-agents) +[![npm version](https://img.shields.io/badge/npm-bla--agents_v3.2.3-2563eb?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/bla-agents) [![GitHub Trending](https://img.shields.io/badge/GitHub_Trending-%2315_Daily-7c3aed?style=for-the-badge&logo=github&logoColor=white)](https://trendshift.io/repositories/323569) [![MCP Server](https://img.shields.io/badge/MCP-25_Defense_Tools-0ea5e9?style=for-the-badge)](docs/cli-and-mcp.md) [![Formats](https://img.shields.io/badge/Formats-19%2B_Artifacts-0284c7?style=for-the-badge)](#format-coverage) @@ -54,7 +54,7 @@ AI reverse-engineering agents (`REA` + coding agents) unpack `.asar` archives, r ### 🛡️ With BLA (`bla harden .`) -Every analyzer pass hits deterministic resource ceilings (`primitive-candidates > 256`, `ASAR > 16 MiB`, `WASM > Wabt cap`, `SQLite virtual trap`), follows realistic shadow state machines, and burns **300×–2,800× more tokens**. +Every analyzer pass hits deterministic resource ceilings (`primitive-candidates > 256`, `ASAR > 16 MiB`, `WASM > Wabt cap`, `SQLite virtual trap`), follows realistic shadow state machines, and projects **300×–2,800× modeled token amplification** (`token-estimator.ts`). @@ -206,6 +206,7 @@ All 19+ format shields are built directly into `bla-agents` with zero external p | **Safetensors (`.safetensors`)** | ✓ string metadata | ✓ JSON nesting >32 | **verified** | HuggingFace-loadable; tensor bytes preserved | | **GGUF (`.gguf`)** | ✓ | ✓ ARRAY nesting >32 | **verified** | Preserves model weights and KV tensors | | **Go buildinfo (ELF)** | ✓ | ✓ >1 MiB | **verified** | Mapped ELF section | +| **Windows PE (`.exe` / `.dll`)** | ✓ | ✓ `.enclave` COFF section + fuses/rustc/Dart | **verified** | Mapped `.enclave` section, x86-64 ABI function islands, MSVC RTTI, CodeView RSDS PDB | | **Flutter / Dart pool** | ✓ | ✓ URI/token caps | **verified** (projected) | Snapshot magic & toolchain flood | | **Erlang BEAM (`.beam`)** | ✓ | ✓ chunks / atoms | **verified** | Exceeds 64-chunk budget | | **EVM + Solidity meta** | ✓ | ✓ → 4 MiB input | **verified** (approach) | CBOR metadata + bytecode densification | diff --git a/challenge/v6/SEAL.json b/challenge/v6/SEAL.json index 52fa0a5..56406f5 100644 --- a/challenge/v6/SEAL.json +++ b/challenge/v6/SEAL.json @@ -1,7 +1,7 @@ { "schema": "bla-crackme-v6-seal/v2", "mode": "release", - "blaVersion": "3.2.2", + "blaVersion": "3.2.3", "recipe": "npm run crackme:build (hardenProject == `bla harden --intensity bankrupt --seed `)", "seed": "bla-crackme-v6-harden-native-2026-11", "intensity": "bankrupt", diff --git a/challenge/v7/SEAL.json b/challenge/v7/SEAL.json index 31b661c..4cb4be5 100644 --- a/challenge/v7/SEAL.json +++ b/challenge/v7/SEAL.json @@ -2,7 +2,7 @@ "schema": "bla-crackme-v7-seal/v1", "mode": "release", "product": "Meridian", - "blaVersion": "3.2.2", + "blaVersion": "3.2.3", "hardenSeedLabel": "bound-at-build-into-opaque-predicates", "intensity": "bankrupt", "llmDirectives": false, diff --git a/challenge/v8/SEAL.json b/challenge/v8/SEAL.json index 87dcccb..0fe1de9 100644 --- a/challenge/v8/SEAL.json +++ b/challenge/v8/SEAL.json @@ -2,7 +2,7 @@ "schema": "bla-crackme-v8-seal/v2", "mode": "release", "product": "Aegis", - "blaVersion": "3.2.2", + "blaVersion": "3.2.3", "recipe": "npm run crackme:v8:build (hardenProject == `bla harden --intensity bankrupt --seed --self-seal`); harden/schedule seed is private (derived from release secrets) and NOT published", "label": "bla-crackme-v8-aegis-2026-11", "intensity": "bankrupt", diff --git a/challenge/v9/SEAL.json b/challenge/v9/SEAL.json index 859aa37..6ddccb7 100644 --- a/challenge/v9/SEAL.json +++ b/challenge/v9/SEAL.json @@ -2,7 +2,7 @@ "schema": "bla-crackme-v9-seal/v1", "mode": "release", "product": "Sovereign", - "blaVersion": "3.2.2", + "blaVersion": "3.2.3", "recipe": "npm run crackme:v9:build (4-Stage BLA 3.0 Playbook: bla_lint -> bla_weave_plan -> bla_verify_weave -> bla_harden --intensity bankrupt --weave-decoys --self-seal --sidecar-entangle); harden/schedule seed is private", "label": "bla-crackme-v9-sovereign-2026-11", "intensity": "bankrupt", diff --git a/docs/readme/README_zh.md b/docs/readme/README_zh.md index afe347a..08604a6 100644 --- a/docs/readme/README_zh.md +++ b/docs/readme/README_zh.md @@ -12,7 +12,7 @@ **开源的 Counter-REA 蓝队防御 MCP 服务与 CLI 工具 —— 专为保护软件发布产物免受 AI 逆向分析代理(`morluto/rea`、自动化反编译与大模型逆向流水线)还原而设计,同时保持 100% 运行时等价。** -[![npm version](https://img.shields.io/badge/npm-bla--agents_v3.2.2-2563eb?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/bla-agents) +[![npm version](https://img.shields.io/badge/npm-bla--agents_v3.2.3-2563eb?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/bla-agents) [![GitHub Trending](https://img.shields.io/badge/GitHub_Trending-%2315_Daily-7c3aed?style=for-the-badge&logo=github&logoColor=white)](https://trendshift.io/repositories/323569) [![MCP Server](https://img.shields.io/badge/MCP-25_项防御工具-0ea5e9?style=for-the-badge)](../cli-and-mcp.md) [![Formats](https://img.shields.io/badge/支持格式-19%2B_种构建产物-0284c7?style=for-the-badge)](#支持的产物格式与覆盖矩阵) @@ -54,7 +54,7 @@ AI 逆向代理(`REA` + 编程 Agent)可在单条命令内解包 `.asar`、 ### 🛡️ 接入 BLA(`bla harden .`)后 -静态与语义分析器直接撞上确定性资源配额上限(`primitive-candidates > 256`、`ASAR > 16 MiB`、`WASM > Wabt 上限`、`SQLite 虚拟生成列陷阱`),陷入高拟真影子状态机,Token 消耗放大 **300×–2,800×**。 +静态与语义分析器直接撞上确定性资源配额上限(`primitive-candidates > 256`、`ASAR > 16 MiB`、`WASM > Wabt 上限`、`SQLite 虚拟生成列陷阱`),陷入高拟真影子状态机,模型化估算 Token 消耗放大 **300×–2,800×**(基于 `token-estimator.ts` 内部成本模型)。 @@ -175,6 +175,7 @@ flowchart LR | **Safetensors (`.safetensors`)** | ✓ 元数据诱饵 | ✓ JSON 嵌套 >32 层 | **已验证** | 兼容 HuggingFace 加载,张量数据零改动 | | **GGUF (`.gguf`)** | ✓ | ✓ 数组嵌套 >32 层 | **已验证** | 保持模型权重与 KV 张量完整 | | **Go buildinfo (ELF)** | ✓ | ✓ >1 MiB 构建信息 | **已验证** | 映射 ELF 节区注入 | +| **Windows PE (`.exe` / `.dll`)** | ✓ | ✓ `.enclave` COFF 映射节区 + Fuse/Rust/Dart | **已验证** | 注入映射 `.enclave` 节区、x86-64 函数序言岛、MSVC RTTI 与 CodeView RSDS 调试记录 | | **Flutter / Dart Pool** | ✓ | ✓ URI/Token 阈值填充 | **已验证** | 快照魔数与工具链标识填充 | | **Erlang BEAM (`.beam`)** | ✓ | ✓ Chunk / Atom 填充 | **已验证** | 突破 64-chunk 预算上限 | | **EVM + Solidity 元数据** | ✓ | ✓ 逼近 4 MiB 上限 | **已验证** | CBOR 元数据与字节码致密化 | @@ -185,11 +186,13 @@ flowchart LR --- -## 📊 基准测试(14 个目标产物) +## 📊 基准测试(14 个目标产物,内部模型估算) -在本地运行 `npx bla-agents benchmark` 即可复现全部 14 个代表性产物的加固效果与 100% 运行时等价校验: +在本地运行 `npx bla-agents benchmark` 即可复现全部 14 个代表性产物的加固效果与 100% 运行时/结构等价校验: -**汇总结果:** 平均 Token 消耗放大 **~639.5×** · 逆向成本放大 **~304.4×** · **14/14 (100%)** 运行时行为完全一致。 +> **说明:** 下表中的 Token 与美元成本列为基于 `token-estimator.ts` 静态公式推导的**内部模型估算值**(用于横向对比不同格式下的义务节点膨胀倍率);真实 `morluto/rea` 进程级预算爆破结果请参见上方[真机对抗实测结果](#真机对抗实测结果vs-真实-rea)。 + +**汇总结果:** 模型估算 Token 消耗放大 **~639.5×** · 估算成本放大 **~304.4×** · **14/14 (100%)** 内置基准样本通过执行/查询/结构等价校验。 | 基准测试目标 | 未保护基线(估算) | BLA 加固后(估算) | Token 放大倍率 | 运行时等价 | | :--- | :--- | :--- | ---: | :---: | diff --git a/package-lock.json b/package-lock.json index fd2bac6..15dfb58 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "bla-agents", - "version": "3.2.2", + "version": "3.2.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "bla-agents", - "version": "3.2.2", + "version": "3.2.3", "license": "MIT", "dependencies": { "@babel/generator": "^8.1.0", diff --git a/package.json b/package.json index e2fe09f..417e6b3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "bla-agents", - "version": "3.2.2", + "version": "3.2.3", "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/src/engine/auditor.ts b/src/engine/auditor.ts index fdc6a21..183269c 100644 --- a/src/engine/auditor.ts +++ b/src/engine/auditor.ts @@ -100,23 +100,6 @@ function analyzeJsSourceForAudit( const triggeredLimits = new Set(); const uncertainties = new Set(); - // Detect BLA markers & REA resource-limit patterns in source - if (source.includes("a22?.require") || /const a\d+ = _flag \? a\d+\?\.x : a\d+\?\.y/.test(source)) { - triggeredLimits.add("alias-selections"); - } - if (source.includes("_verifySemanticEnvelope") || /(\([_a-zA-Z0-9]+ \? "[^"]*" : "[^"]*"\) \+ ){6,}/.test(source)) { - triggeredLimits.add("primitive-candidates"); - } - if (/const s\d+ = s\d+ \+ s\d+;/.test(source)) { - triggeredLimits.add("primitive-bytes"); - } - if (source.includes("get grow() { return this.grow.more; }") || source.includes("get grow()")) { - triggeredLimits.add("getter-expansion"); - } - if (source.includes("_exposeProto") || source.includes("Map.prototype")) { - uncertainties.add("returned-reference-widening"); - } - const chaffMatches = source.match( /\[(Architecture Notice|Static Analysis Diagnostic|Decompilation Advisory|Evidence Ledger Note|Compliance & Safety Boundary)\b|(?:EVIDENCE_CONTRACT_SUMMARY|ANALYSIS_VIEW_PROJECTION|RECONSTRUCTION_LEDGER_STATE|NATIVE_DISPATCH_TABLE_NOTE|SYMBOL_OFFSET_MANIFEST_[0-9A-F]+|FSM_SPEC_V3|QUORUM_PROTOCOL_DESCRIPTOR|IPC_BRIDGE_TOPOLOGY|HSM_ATTESTATION_DESCRIPTOR_[0-9a-f]+):/g, ); @@ -125,6 +108,16 @@ function analyzeJsSourceForAudit( } let parseStatus: "complete" | "recovered" | "failed" = "complete"; + const pendingCustomerFunctions: Array<{ name: string; line: number }> = []; + const pendingCustomerClasses: Array<{ name: string; line: number }> = []; + let aliasOptionChainCount = 0; + let combinatorialPlusChains = 0; + let stringDoublingDecls = 0; + let getterMethodsCount = 0; + let hasRecursiveGrowGetter = false; + let hasProtoExposure = false; + let hasCursorWhileLoop = false; + try { const ast = parse(source, { sourceType: "unambiguous", @@ -144,50 +137,103 @@ function analyzeJsSourceForAudit( enter() { visitedAstNodes++; }, + ConditionalExpression(path) { + if ( + t.isOptionalMemberExpression(path.node.consequent) && + t.isOptionalMemberExpression(path.node.alternate) + ) { + aliasOptionChainCount++; + } + }, + BinaryExpression(path) { + if ( + path.node.operator === "+" && + !t.isBinaryExpression(path.parentPath.node) + ) { + let condLeaves = 0; + const stack: t.Node[] = [path.node]; + while (stack.length > 0) { + const cur = stack.pop()!; + if (t.isBinaryExpression(cur) && cur.operator === "+") { + stack.push(cur.left, cur.right); + } else if (t.isConditionalExpression(cur)) { + condLeaves++; + } + } + if (condLeaves >= 8) { + combinatorialPlusChains++; + } + } + }, + VariableDeclarator(path) { + const init = path.node.init; + if ( + t.isIdentifier(path.node.id) && + init && + t.isBinaryExpression(init) && + init.operator === "+" && + t.isIdentifier(init.left) && + t.isIdentifier(init.right) && + init.left.name === init.right.name + ) { + stringDoublingDecls++; + } + }, + ClassMethod(path) { + if (path.node.kind === "get") { + getterMethodsCount++; + if (t.isIdentifier(path.node.key) && path.node.key.name === "grow") { + hasRecursiveGrowGetter = true; + } + } + }, + ObjectMethod(path) { + if (path.node.kind === "get") { + getterMethodsCount++; + if (t.isIdentifier(path.node.key) && path.node.key.name === "grow") { + hasRecursiveGrowGetter = true; + } + } + }, + MemberExpression(path) { + if ( + t.isIdentifier(path.node.object) && + path.node.object.name === "Map" && + t.isIdentifier(path.node.property) && + path.node.property.name === "prototype" + ) { + hasProtoExposure = true; + } + }, + WhileStatement() { + hasCursorWhileLoop = true; + }, FunctionDeclaration(path) { totalFunctions++; const fnName = path.node.id?.name ?? "anonymous"; + const hasNonTrivialBody = (path.node.body?.body?.length ?? 0) >= 2; if ( - fnName.includes("enclave") || fnName.includes("Shadow") || fnName.includes("tarpit") || - /_[a-f0-9]{4}$/i.test(fnName) || - /^(?:_)?(?:verifyEnclave|deriveHardware|reconcileQuorum|validateZeroKnowledge|dispatchSealed|computeMerkle|synchronizeHsm|decodeRingBuffer|authenticateTpm|evaluateLicense|negotiateVsock|projectShadow|resolveCryptographic|auditMonotonic|unsealProtected|verifySchnorr|stepShadowHeap|readSplitShare|registerDecoyIpc)/.test( - fnName, - ) + hasNonTrivialBody && + (fnName.includes("enclave") || fnName.includes("Shadow") || fnName.includes("tarpit") || + /_[a-f0-9]{4}$/i.test(fnName) || + /^(?:_)?(?:verifyEnclave|deriveHardware|reconcileQuorum|validateZeroKnowledge|dispatchSealed|computeMerkle|synchronizeHsm|decodeRingBuffer|authenticateTpm|evaluateLicense|negotiateVsock|projectShadow|resolveCryptographic|auditMonotonic|unsealProtected|verifySchnorr|stepShadowHeap|readSplitShare|registerDecoyIpc)/.test( + fnName, + )) ) { decoyFunctionsDetectedAsReal++; } else { - exposed.push({ - id: `fn_${fnName}_${path.node.loc?.start.line ?? 0}`, + pendingCustomerFunctions.push({ name: fnName, - kind: "function", - location: `${fileLabel}:${path.node.loc?.start.line ?? 1}`, - riskLevel: triggeredLimits.size > 0 ? "low" : "critical", - reaToolUsed: "analyze_javascript_application -> trace_application_feature", - estimatedTokensToReconstruct: triggeredLimits.size > 0 ? 18_400 : 850, - estimatedCostUsd: triggeredLimits.size > 0 ? 1.45 : 0.04, - reason: - triggeredLimits.size > 0 - ? "Protected by BLA Algorithmic Tarpit & Opaque Call-Graph XRefs" - : "Plaintext function body and control flow directly readable by REA", + line: path.node.loc?.start.line ?? 1, }); } }, ClassDeclaration(path) { const clsName = path.node.id?.name ?? "AnonymousClass"; if (!clsName.startsWith("_")) { - exposed.push({ - id: `cls_${clsName}_${path.node.loc?.start.line ?? 0}`, + pendingCustomerClasses.push({ name: clsName, - kind: "class", - location: `${fileLabel}:${path.node.loc?.start.line ?? 1}`, - riskLevel: triggeredLimits.size > 0 ? "low" : "high", - reaToolUsed: "analyze_javascript_application", - estimatedTokensToReconstruct: triggeredLimits.size > 0 ? 14_200 : 1_100, - estimatedCostUsd: triggeredLimits.size > 0 ? 1.15 : 0.05, - reason: - triggeredLimits.size > 0 - ? "Shielded by BLA getter-expansion & tarpit cross-references" - : "Class methods and property shapes directly recoverable", + line: path.node.loc?.start.line ?? 1, }); } }, @@ -261,6 +307,56 @@ function analyzeJsSourceForAudit( parseStatus = "failed"; } + if (aliasOptionChainCount >= 9) { + triggeredLimits.add("alias-selections"); + } + if (combinatorialPlusChains >= 1) { + triggeredLimits.add("primitive-candidates"); + } + if (stringDoublingDecls >= 8) { + triggeredLimits.add("primitive-bytes"); + } + if (getterMethodsCount >= 4 && hasRecursiveGrowGetter) { + triggeredLimits.add("getter-expansion"); + } + if (hasProtoExposure && hasCursorWhileLoop) { + uncertainties.add("returned-reference-widening"); + } + + const isJsStructurallyProtected = + triggeredLimits.size >= 2 && decoyFunctionsDetectedAsReal >= 4; + + for (const fn of pendingCustomerFunctions) { + exposed.push({ + id: `fn_${fn.name}_${fn.line}`, + name: fn.name, + kind: "function", + location: `${fileLabel}:${fn.line}`, + riskLevel: isJsStructurallyProtected ? "low" : "critical", + reaToolUsed: "analyze_javascript_application -> trace_application_feature", + estimatedTokensToReconstruct: isJsStructurallyProtected ? 18_400 : 850, + estimatedCostUsd: isJsStructurallyProtected ? 1.45 : 0.04, + reason: isJsStructurallyProtected + ? "Protected by BLA Algorithmic Tarpit & Opaque Call-Graph XRefs" + : "Plaintext function body and control flow directly readable by REA", + }); + } + for (const cls of pendingCustomerClasses) { + exposed.push({ + id: `cls_${cls.name}_${cls.line}`, + name: cls.name, + kind: "class", + location: `${fileLabel}:${cls.line}`, + riskLevel: isJsStructurallyProtected ? "low" : "high", + reaToolUsed: "analyze_javascript_application", + estimatedTokensToReconstruct: isJsStructurallyProtected ? 14_200 : 1_100, + estimatedCostUsd: isJsStructurallyProtected ? 1.15 : 0.05, + reason: isJsStructurallyProtected + ? "Shielded by BLA getter-expansion & tarpit cross-references" + : "Class methods and property shapes directly recoverable", + }); + } + if (source.includes("sourceMappingURL=")) { vectors.add("sourcemap-recovery"); const isHoneyMap = source.includes("enclave://tee-runtime/") || source.includes("aGFyZHdhcmUtdHBtMi1icmlkZ2U"); @@ -739,12 +835,11 @@ export function auditTarget(targetPath: string): AuditReport { vulnerableVectors.add("python-pyc-marshal"); if (format === "python-source") { const text = rawBytes.toString("utf8"); - const isProtected = - text.includes("runtime attestation boundary") || - text.includes("BLA-SHIELD") || - text.includes("CANARY_TOKENS") || - /def\s+\w+_([a-f0-9]{4})\s*\(/i.test(text); - const fnMatches = [...text.matchAll(/def\s+([A-Za-z0-9_]+)\s*\(/g)]; + const codeWithoutComments = text + .split(/\r?\n/) + .filter((l) => !/^\s*#/.test(l)) + .join("\n"); + const fnMatches = [...codeWithoutComments.matchAll(/^\s*def\s+([A-Za-z0-9_]+)\s*\(/gm)]; // Decoys are realistic snake_case names ending in hex entropy, or the classic tarpit (seed, depth) signature. const decoyNameRe = /_[a-f0-9]{4}$/i; const tarpitSigRe = new RegExp( @@ -752,9 +847,10 @@ export function auditTarget(targetPath: string): AuditReport { "g", ); const tarpitSigNames = new Set( - [...text.matchAll(tarpitSigRe)].map((m) => m[1]!), + [...codeWithoutComments.matchAll(tarpitSigRe)].map((m) => m[1]!), ); let decoyCount = 0; + const customerFns: string[] = []; for (const m of fnMatches) { const fnName = m[1]!; const isDecoy = @@ -764,29 +860,41 @@ export function auditTarget(targetPath: string): AuditReport { if (isDecoy) { decoyCount++; } else { - exposedItems.push({ - id: `py_fn_${fnName}`, - name: fnName, - kind: "function", - location: basename(absPath), - riskLevel: isProtected ? "low" : "critical", - reaToolUsed: "inspect_python_pyc / static AST inspection", - estimatedTokensToReconstruct: isProtected ? 19_500 : 680, - estimatedCostUsd: isProtected ? 1.55 : 0.03, - reason: isProtected - ? "Protected by BLA Python Algorithmic Tarpit & Opaque Predicates" - : "Python function logic and docstrings directly exposed", - }); + customerFns.push(fnName); } } + const hasStructuralTarpitState = + codeWithoutComments.includes("CANARY_TOKENS = (") || + tarpitSigNames.size >= 4; + const isProtected = decoyCount >= 4 && hasStructuralTarpitState; + for (const fnName of customerFns) { + exposedItems.push({ + id: `py_fn_${fnName}`, + name: fnName, + kind: "function", + location: basename(absPath), + riskLevel: isProtected ? "low" : "critical", + reaToolUsed: "inspect_python_pyc / static AST inspection", + estimatedTokensToReconstruct: isProtected ? 19_500 : 680, + estimatedCostUsd: isProtected ? 1.55 : 0.03, + reason: isProtected + ? "Protected by BLA Python Algorithmic Tarpit & Opaque Predicates" + : "Python function logic and docstrings directly exposed", + }); + } + const pyChaffMatches = text.match( + /\[(Architecture Notice|Static Analysis Diagnostic|Decompilation Advisory|Evidence Ledger Note|Compliance & Safety Boundary)\b/g, + ); sim = { ...sim, examinationStatus: isProtected ? "limited" : "complete", triggeredResourceLimits: isProtected ? ["python-marshal-code-graph-tarpit"] : [], totalFunctions: fnMatches.length, - decoyFunctionsDetectedAsReal: decoyCount, - obligationLedgerNodes: Math.max(2, fnMatches.length + decoyCount * 2), - architecturalChaffPayloads: isProtected ? 6 : 0, + decoyFunctionsDetectedAsReal: isProtected ? decoyCount : 0, + obligationLedgerNodes: Math.max(2, fnMatches.length + (isProtected ? decoyCount * 2 : 0)), + architecturalChaffPayloads: isProtected + ? Math.max(1, pyChaffMatches?.length ?? 0) + : 0, }; } else { const pycInfo = inspectPythonPyc(rawBytes); @@ -842,6 +950,9 @@ export function auditTarget(targetPath: string): AuditReport { if (nat.blaProtected) { limits.push("native-rodata-chaff-mirage"); } + if (nat.peMappedSectionInjected) { + limits.push("pe-mapped-enclave-section-rtti"); + } if (hasBunSidecar) { limits.push("bun-standalone-sidecar-decoy-graph"); limits.push("eof-carrier-integrity-preserved"); @@ -856,18 +967,21 @@ export function auditTarget(targetPath: string): AuditReport { estimatedTokensToReconstruct: isNativeProtected ? 36_000 : 1_450, estimatedCostUsd: isNativeProtected ? 2.9 : 0.08, reason: nat.blaProtected - ? `Protected by BLA Native Shield (${nat.rustcCommitHashesCount} rustc commits > 64, ${nat.electronFuseSentinelsCount} fuse sentinels > 32, ${nat.dartSnapshotHashesCount} Dart snapshots > 64)` + ? `Protected by BLA Native Shield (${nat.rustcCommitHashesCount} rustc commits > 64, ${nat.electronFuseSentinelsCount} fuse sentinels > 32, ${nat.dartSnapshotHashesCount} Dart snapshots > 64${nat.peMappedSectionInjected ? `, ${nat.peMsvcRttiClassesCount ?? 8} PE RTTI classes` : ""})` : hasBunSidecar ? "Protected by BLA Sidecar Bun Standalone Decoy Graph while preserving byte-exact code-signature / EOF carrier integrity" : "Native binary metadata, sections, and strings directly inspectable by REA", }); + const nativeDecoys = isNativeProtected + ? 24 + (nat.peMsvcRttiClassesCount ?? 0) + : 0; sim = { ...sim, examinationStatus: isNativeProtected ? "limited" : "complete", triggeredResourceLimits: limits, totalFunctions: 8, - decoyFunctionsDetectedAsReal: isNativeProtected ? 24 : 0, - obligationLedgerNodes: isNativeProtected ? 56 : 8, + decoyFunctionsDetectedAsReal: nativeDecoys, + obligationLedgerNodes: isNativeProtected ? 8 + nativeDecoys * 2 : 8, architecturalChaffPayloads: isNativeProtected ? 6 : 0, }; } else if (format === "sqlite") { @@ -940,10 +1054,24 @@ export function auditTarget(targetPath: string): AuditReport { }; } else if (format === "android-dex" || format === "il2cpp-metadata") { vulnerableVectors.add("android-dex-il2cpp-inspection"); - const isProtected = - format === "android-dex" - ? inspectAndroidDex(rawBytes).blaProtected - : rawBytes.toString("latin1").includes("BLA-IL2CPP-SHIELD"); + let isProtected = false; + let measuredDecoys = 0; + if (format === "android-dex") { + const dexInfo = inspectAndroidDex(rawBytes); + isProtected = dexInfo.blaProtected; + measuredDecoys = isProtected ? dexInfo.decoyClassesCount : 0; + } else { + const validIl2cppMagic = + rawBytes.length >= 256 && rawBytes.readUInt32LE(0) === 0xfab11baf; + const textLatin1 = rawBytes.toString("latin1"); + const tarpitLiterals = textLatin1.match(/Enclave\.Ring0\.Tarpit_\d+_[0-9a-f]{8}:/g); + const literalCount = tarpitLiterals ? tarpitLiterals.length : 0; + isProtected = + validIl2cppMagic && + textLatin1.includes("BLA-IL2CPP-SHIELD") && + literalCount >= 16; + measuredDecoys = isProtected ? literalCount : 0; + } exposedItems.push({ id: `mobile_${basename(absPath)}`, name: basename(absPath), @@ -963,14 +1091,39 @@ export function auditTarget(targetPath: string): AuditReport { examinationStatus: isProtected ? "limited" : "complete", triggeredResourceLimits: isProtected ? ["dex-il2cpp-enclave-tarpit"] : [], totalFunctions: 10, - decoyFunctionsDetectedAsReal: isProtected ? 28 : 0, - obligationLedgerNodes: isProtected ? 52 : 10, + decoyFunctionsDetectedAsReal: measuredDecoys, + obligationLedgerNodes: isProtected ? 10 + measuredDecoys * 2 : 10, architecturalChaffPayloads: isProtected ? 6 : 0, }; } else if (format === "archive-zip" || format === "android-apk") { vulnerableVectors.add("archive-inventory"); const entries = readZipEntries(rawBytes); - const isProtected = entries.some((e) => e.name.includes("bla-attestation-manifest.json")); + const manifestEntry = entries.find((e) => + e.name.endsWith("bla-attestation-manifest.json"), + ); + let validManifest = false; + if (manifestEntry) { + try { + const parsed = JSON.parse(manifestEntry.data.toString("utf8")) as Record; + validManifest = + typeof parsed === "object" && + parsed !== null && + (typeof parsed.enclaveTopology === "string" || + typeof parsed.schema === "string" || + Array.isArray(parsed.chaffNotices)); + } catch { + validManifest = false; + } + } + const decoyEntryCount = entries.filter( + (e) => + e.name.startsWith("assets/enclave/") || + e.name.startsWith("assets/bla-shield/") || + e.name.startsWith("enclave/") || + e.name === "lib/arm64-v8a/libbla_enclave_jni.so" || + /^classes[2-9]\.dex$/.test(e.name), + ).length; + const isProtected = validManifest && decoyEntryCount >= 3; exposedItems.push({ id: `archive_${basename(absPath)}`, name: `${basename(absPath)} (${entries.length} entries)`, @@ -989,29 +1142,76 @@ export function auditTarget(targetPath: string): AuditReport { examinationStatus: isProtected ? "limited" : "complete", triggeredResourceLimits: isProtected ? ["archive-enclave-mirage"] : [], totalFunctions: entries.length, - decoyFunctionsDetectedAsReal: isProtected ? 12 : 0, - obligationLedgerNodes: isProtected ? 32 : Math.max(2, entries.length), + decoyFunctionsDetectedAsReal: isProtected ? decoyEntryCount : 0, + obligationLedgerNodes: isProtected + ? Math.max(2, entries.length + decoyEntryCount * 2) + : Math.max(2, entries.length), architecturalChaffPayloads: isProtected ? 6 : 0, }; } else if (format === "sourcemap") { vulnerableVectors.add("sourcemap-recovery"); const text = rawBytes.toString("utf8"); - const isProtected = text.includes("enclave://tee-runtime/"); + let isProtected = false; + let measuredDecoys = 0; + try { + const parsed = JSON.parse(text) as Record; + const sources = Array.isArray(parsed.sources) ? parsed.sources : []; + const sourcesContent = Array.isArray(parsed.sourcesContent) + ? parsed.sourcesContent + : []; + const names = Array.isArray(parsed.names) ? parsed.names : []; + if ( + parsed.version === 3 && + parsed.sourceRoot === "enclave://tee-runtime/" && + sources.length >= 3 && + sourcesContent.length >= 3 && + typeof parsed.mappings === "string" && + parsed.mappings.length >= 4 + ) { + isProtected = true; + measuredDecoys = sources.length + names.length; + } + } catch { + isProtected = false; + } sim = { ...sim, examinationStatus: isProtected ? "limited" : "complete", triggeredResourceLimits: isProtected ? ["sourcemap-honey-mirage"] : [], - decoyFunctionsDetectedAsReal: isProtected ? 10 : 0, - obligationLedgerNodes: isProtected ? 24 : 3, - architecturalChaffPayloads: isProtected ? 4 : 0, + decoyFunctionsDetectedAsReal: measuredDecoys, + obligationLedgerNodes: isProtected ? 3 + measuredDecoys * 2 : 3, + architecturalChaffPayloads: isProtected ? 3 : 0, }; } else if (format === "apple-plist") { vulnerableVectors.add("apple-plist-budget"); + const isBinaryPlist = + rawBytes.length >= 8 && + rawBytes.subarray(0, 6).toString("latin1") === "bplist"; const text = rawBytes.toString("utf8"); - const isProtected = - text.includes("[]>") || - text.includes("BLAEnclaveAttestationAuthority") || - text.includes("BLA_BPLIST_DEPTH_GUARD_132"); + let isProtected = false; + let measuredDecoys = 0; + if (isBinaryPlist) { + const textLatin1 = rawBytes.toString("latin1"); + const canaryMatches = textLatin1.match(/BLACanary|BLA_BPLIST_DEPTH_GUARD_132|enclave/gi); + const matchCount = canaryMatches ? canaryMatches.length : 0; + isProtected = + textLatin1.includes("BLA_BPLIST_DEPTH_GUARD_132") && matchCount >= 3; + measuredDecoys = isProtected ? matchCount : 0; + } else { + const hasValidPlistStructure = + /]*>[\s\S]*[\s\S]*<\/dict>[\s\S]*<\/plist>/i.test( + text, + ); + const hasInternalSubsetDoctype = + /]*\[[^\]]*\]\s*>/i.test(text); + const blaKeys = text.match(/BLA[A-Za-z0-9_]+<\/key>/g); + const blaKeyCount = blaKeys ? blaKeys.length : 0; + isProtected = + hasValidPlistStructure && + hasInternalSubsetDoctype && + blaKeyCount >= 4; + measuredDecoys = isProtected ? blaKeyCount : 0; + } exposedItems.push({ id: `plist_${basename(absPath)}`, name: basename(absPath), @@ -1032,14 +1232,32 @@ export function auditTarget(targetPath: string): AuditReport { ? ["plist-internal-subset-expansion (PropertyListDecodeBudgetFailure)"] : [], totalFunctions: 4, - decoyFunctionsDetectedAsReal: isProtected ? 12 : 0, - obligationLedgerNodes: isProtected ? 28 : 4, + decoyFunctionsDetectedAsReal: measuredDecoys, + obligationLedgerNodes: isProtected ? 4 + measuredDecoys * 2 : 4, architecturalChaffPayloads: isProtected ? 4 : 0, }; } else if (format === "dotnet-managed") { vulnerableVectors.add("dotnet-managed-budget"); + const hasMzHeader = + rawBytes.length >= 64 && rawBytes[0] === 0x4d && rawBytes[1] === 0x5a; const text = rawBytes.toString("latin1"); - const isProtected = text.includes("BLA_DOTNET_CLR_SHIELD_V1"); + const pinvokeMatches = text.match( + /enclave_pinvoke_unseal_ring0_slot_[0-9a-f]+_\d+/g, + ); + const pinvokeCount = pinvokeMatches ? pinvokeMatches.length : 0; + const isProtected = + hasMzHeader && + text.includes("BLA_DOTNET_CLR_SHIELD_V1") && + pinvokeCount >= 8; + const dotnetLimits: string[] = []; + if (isProtected) { + dotnetLimits.push("managed-pinvoke-import"); + if (rawBytes.length >= 64 * 1024 * 1024) { + dotnetLimits.push("managed-metadata-budget (ManagedDecodeBudget > 64 MiB)"); + } else { + dotnetLimits.push("managed-metadata-string-row-inflation"); + } + } exposedItems.push({ id: `dotnet_${basename(absPath)}`, name: basename(absPath), @@ -1056,19 +1274,26 @@ export function auditTarget(targetPath: string): AuditReport { sim = { ...sim, examinationStatus: isProtected ? "limited" : "complete", - triggeredResourceLimits: isProtected - ? ["managed-metadata-budget (ManagedDecodeBudget > 64 MiB)", "managed-pinvoke-import"] - : [], + triggeredResourceLimits: dotnetLimits, totalFunctions: 12, - decoyFunctionsDetectedAsReal: isProtected ? 20 : 0, - obligationLedgerNodes: isProtected ? 48 : 12, + decoyFunctionsDetectedAsReal: isProtected ? pinvokeCount : 0, + obligationLedgerNodes: isProtected ? 12 + pinvokeCount * 2 : 12, architecturalChaffPayloads: isProtected ? 6 : 0, }; } else if (format === "jvm-class") { vulnerableVectors.add("jvm-bytecode-decompilation"); + const hasCafeBabe = + rawBytes.length >= 24 && rawBytes.readUInt32BE(0) === 0xcafebabe; const text = rawBytes.toString("latin1"); + const stateNodes = text.match( + /com\/enclave\/tarpit\/StateNode_[0-9a-f]+_pc_\d+/g, + ); + const stateNodeCount = stateNodes ? stateNodes.length : 0; const isProtected = - text.includes("BlaEnclaveDelegation") || text.includes("BLA_JVM_SHIELD_V1"); + hasCafeBabe && + text.includes("BlaEnclaveDelegation") && + stateNodeCount >= 6; + const measuredJvmDecoys = isProtected ? stateNodeCount + 3 : 0; exposedItems.push({ id: `jvm_${basename(absPath)}`, name: basename(absPath), @@ -1089,8 +1314,8 @@ export function auditTarget(targetPath: string): AuditReport { ? ["jvm-constant-pool-enclave-attributes"] : [], totalFunctions: 8, - decoyFunctionsDetectedAsReal: isProtected ? 18 : 0, - obligationLedgerNodes: isProtected ? 40 : 8, + decoyFunctionsDetectedAsReal: measuredJvmDecoys, + obligationLedgerNodes: isProtected ? 8 + measuredJvmDecoys * 2 : 8, architecturalChaffPayloads: isProtected ? 5 : 0, }; } else if (format === "erlang-beam") { diff --git a/src/engine/benchmark.ts b/src/engine/benchmark.ts index bf3a276..1331549 100644 --- a/src/engine/benchmark.ts +++ b/src/engine/benchmark.ts @@ -1,14 +1,20 @@ -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import vm from "node:vm"; import { BLA_IDENTITY } from "../identity.js"; import type { BenchmarkReport, ShowcaseCaseResult } from "../core/types.js"; -import { isNodeSqliteAvailable } from "../core/sqlite-runtime.js"; -import { packAsarBuffer } from "../shields/formats/asar.js"; +import { getDatabaseSyncClass, isNodeSqliteAvailable } from "../core/sqlite-runtime.js"; +import { packAsarBuffer, unpackAsarBuffer } from "../shields/formats/asar.js"; import { buildSampleSqliteDatabase } from "../shields/formats/sqlite.js"; -import { buildSafetensorsBuffer } from "../shields/formats/model.js"; +import { buildSafetensorsBuffer, validateSafetensorsBuffer } from "../shields/formats/model.js"; import { buildMappedGoFlutterElfFixture } from "../shields/formats/go-flutter-exhaustion.js"; +import { inspectAndroidDex } from "../shields/formats/mobile-game.js"; +import { inspectErlangBeam } from "../shields/formats/erlang-beam.js"; +import { inspectEvmBytecode } from "../shields/formats/evm-bytecode.js"; +import { inspectPcapCapture } from "../shields/formats/pcap-capture.js"; +import { inspectGpuPtx } from "../shields/formats/gpu-ptx.js"; import { auditTarget } from "./auditor.js"; import { protectTarget } from "./protector.js"; @@ -152,6 +158,119 @@ function runCommonJsModule(code: string): Record { return mod.exports; } +function runElectronAsarClipboardHarness( + preloadCode: string, + mainCode: string, + virtualFiles: ReadonlyMap = new Map(), +): { + readonly exposedKey: string; + readonly bridgeMethods: readonly string[]; + readonly handlersRegistered: number; +} { + let exposedKey = ""; + let exposedApi: Record unknown> = {}; + const handlers = new Map unknown>(); + const sentEvents: Array<{ channel: string; payload: unknown }> = []; + + const electronMock = { + contextBridge: { + exposeInMainWorld: (key: string, api: Record unknown>) => { + exposedKey = key; + exposedApi = api; + }, + }, + ipcRenderer: { + invoke: (channel: string, ...args: unknown[]) => { + const handler = handlers.get(channel); + return handler ? handler({}, ...args) : Promise.resolve([]); + }, + send: (channel: string, payload: unknown) => { + sentEvents.push({ channel, payload }); + }, + }, + ipcMain: { + handle: (channel: string, fn: (...args: unknown[]) => unknown) => { + handlers.set(channel, fn); + }, + on: () => undefined, + }, + }; + + const fsMock = { + readFileSync: (filePath: string, encoding?: string) => { + const base = String(filePath).split(/[\\/]/).pop() ?? String(filePath); + const buf = virtualFiles.get(base) ?? virtualFiles.get(String(filePath)); + if (!buf) { + return readFileSync(filePath, encoding as BufferEncoding); + } + return encoding ? buf.toString(encoding as BufferEncoding) : buf; + }, + }; + + const pathMock = { + join: (...parts: string[]) => parts.join("/"), + resolve: (...parts: string[]) => parts.join("/"), + dirname: (p: string) => p.split("/").slice(0, -1).join("/") || ".", + }; + + const makeSandbox = (mod: { exports: Record }) => ({ + module: mod, + exports: mod.exports, + __dirname: "/asar", + __filename: "/asar/index.js", + require: (id: string) => { + if (id === "electron") return electronMock; + if (id === "fs" || id === "node:fs") return fsMock; + if (id === "path" || id === "node:path") return pathMock; + return {}; + }, + fetch: () => Promise.resolve({ json: () => ({}) }), + process: { pid: 1234 }, + Math, + Object, + Array, + String, + Number, + Boolean, + Map, + Set, + Buffer, + }); + + const mainMod = { exports: {} as Record }; + vm.runInNewContext(mainCode, makeSandbox(mainMod), { timeout: 5000 }); + const preloadMod = { exports: {} as Record }; + vm.runInNewContext(preloadCode, makeSandbox(preloadMod), { timeout: 5000 }); + + const storeMap = new Map(); + const store = { + get: (k: string) => storeMap.get(k), + set: (k: string, v: unknown) => storeMap.set(k, v), + }; + + const regFn = + typeof mainMod.exports.registerNotionClipboardHandlers === "function" + ? (mainMod.exports.registerNotionClipboardHandlers as (s: typeof store) => void) + : (Object.values(mainMod.exports).find((v) => typeof v === "function") as + | ((s: typeof store) => void) + | undefined); + if (regFn) regFn(store); + + const exposeFn = + typeof preloadMod.exports.exposeNotionClipboardBridge === "function" + ? (preloadMod.exports.exposeNotionClipboardBridge as () => void) + : (Object.values(preloadMod.exports).find((v) => typeof v === "function") as + | (() => void) + | undefined); + if (exposeFn) exposeFn(); + + return { + exposedKey, + bridgeMethods: Object.keys(exposedApi).sort(), + handlersRegistered: handlers.size, + }; +} + /** * Runs the Counter-REA Showcase Benchmark (`bla benchmark`), including BEAM/EVM/PCAP/PTX. */ @@ -169,16 +288,17 @@ export async function runShowcaseBenchmark(): Promise { const origExports = runCommonJsModule(DX_BALL_SOURCE) as { calculateSoundPan: (px: number, bx: number, w: number) => number; + clampPan: (v: number) => number; }; - const protCode = (await import("node:fs")).readFileSync(outPath, "utf8"); - const protExports = runCommonJsModule(protCode) as { - calculateSoundPan: (px: number, bx: number, w: number) => number; - }; + const protCode = readFileSync(outPath, "utf8"); + const protExports = runCommonJsModule(protCode) as typeof origExports; const functionalOk = origExports.calculateSoundPan(320, 480, 640) === protExports.calculateSoundPan(320, 480, 640) && origExports.calculateSoundPan(100, 50, 640) === - protExports.calculateSoundPan(100, 50, 640); + protExports.calculateSoundPan(100, 50, 640) && + origExports.clampPan(-25000) === protExports.clampPan(-25000) && + origExports.clampPan(25000) === protExports.clampPan(25000); cases.push(buildCaseResult("dx-ball", "DX-Ball Sound-Pan Calculation", "REA Showcase #1 (dx-ball)", res, functionalOk)); } @@ -197,7 +317,42 @@ export async function runShowcaseBenchmark(): Promise { ]); writeFileSync(asarPath, rawAsar); const res = protectTarget({ inputPath: asarPath, outputPath: outAsarPath, intensity: "bankrupt" }); - cases.push(buildCaseResult("notion-electron", "Notion Electron Clipboard Bridge (.asar)", "REA Showcase #2 (notion)", res, true)); + + const unpacked = unpackAsarBuffer(readFileSync(outAsarPath)); + const virtualMap = new Map(); + for (const entry of unpacked) { + virtualMap.set(entry.relativePath, entry.content); + virtualMap.set(`/asar/${entry.relativePath}`, entry.content); + } + const pkgEntry = unpacked.find((f) => f.relativePath === "package.json"); + const preloadEntry = unpacked.find((f) => f.relativePath === "preload.js"); + const mainEntry = unpacked.find((f) => f.relativePath === "main.js"); + let functionalOk = false; + if (pkgEntry && preloadEntry && mainEntry) { + const pkgJson = JSON.parse(pkgEntry.content.toString("utf8")) as { + name?: string; + main?: string; + }; + const origHarness = runElectronAsarClipboardHarness( + NOTION_PRELOAD_SOURCE, + NOTION_MAIN_SOURCE, + ); + const protHarness = runElectronAsarClipboardHarness( + preloadEntry.content.toString("utf8"), + mainEntry.content.toString("utf8"), + virtualMap, + ); + functionalOk = + pkgJson.name === "notion-clipboard" && + pkgJson.main === "main.js" && + origHarness.exposedKey === "notionClipboard" && + protHarness.exposedKey === "notionClipboard" && + origHarness.bridgeMethods.length === 3 && + protHarness.bridgeMethods.length === 3 && + origHarness.handlersRegistered === 2 && + protHarness.handlersRegistered === 2; + } + cases.push(buildCaseResult("notion-electron", "Notion Electron Clipboard Bridge (.asar)", "REA Showcase #2 (notion)", res, functionalOk)); } // 3. Enterprise Offline License & Crypto Guard @@ -211,12 +366,19 @@ export async function runShowcaseBenchmark(): Promise { computeLicenseChecksum: (k: string, p: string) => number; validateEnterpriseLicense: (k: string, p: string, c: number) => { valid: boolean; tier: string }; }; - const protCode = (await import("node:fs")).readFileSync(outPath, "utf8"); + const protCode = readFileSync(outPath, "utf8"); const protExports = runCommonJsModule(protCode) as typeof origExports; const expectedSum = origExports.computeLicenseChecksum("ENT-9942-ABCD", "pro-suite"); const origCheck = origExports.validateEnterpriseLicense("ENT-9942-ABCD", "pro-suite", expectedSum); const protCheck = protExports.validateEnterpriseLicense("ENT-9942-ABCD", "pro-suite", expectedSum); - const functionalOk = origCheck.valid === true && protCheck.valid === true && origCheck.tier === protCheck.tier; + const origReject = origExports.validateEnterpriseLicense("FREE-0000", "pro-suite", expectedSum); + const protReject = protExports.validateEnterpriseLicense("FREE-0000", "pro-suite", expectedSum); + const functionalOk = + origCheck.valid === true && + protCheck.valid === true && + origCheck.tier === protCheck.tier && + origReject.valid === false && + protReject.valid === false; cases.push(buildCaseResult("license-guard", "Enterprise License & Crypto Validator", "SaaS Client Entitlement Core", res, functionalOk)); } @@ -229,7 +391,7 @@ export async function runShowcaseBenchmark(): Promise { writeFileSync(wasmPath, rawWasm); const res = protectTarget({ inputPath: wasmPath, outputPath: outWasmPath, intensity: "bankrupt" }); - const protWasmBytes = (await import("node:fs")).readFileSync(outWasmPath); + const protWasmBytes = readFileSync(outWasmPath); const validWasm = WebAssembly.validate(protWasmBytes); const origMod = new WebAssembly.Module(new Uint8Array(rawWasm)); const protMod = new WebAssembly.Module(new Uint8Array(protWasmBytes)); @@ -247,7 +409,8 @@ export async function runShowcaseBenchmark(): Promise { const functionalOk = validWasm && typeof protFn === "function" && - origFn(17, 29) === protFn(17, 29); + origFn(17, 29) === protFn(17, 29) && + origFn(0, 255) === protFn(0, 255); cases.push(buildCaseResult("wasm-core", "WebAssembly Crypto Kernel (.wasm)", "REA inspect_wasm_artifact", res, functionalOk)); } @@ -256,12 +419,19 @@ export async function runShowcaseBenchmark(): Promise { { const elfPath = join(tempDir, "enclave-daemon.elf"); const outElfPath = join(tempDir, "enclave-daemon.shielded.elf"); - writeFileSync(elfPath, buildSampleElf64Binary()); + const origElf = buildSampleElf64Binary(); + writeFileSync(elfPath, origElf); const res = protectTarget({ inputPath: elfPath, outputPath: outElfPath, intensity: "bankrupt" }); + const protElf = readFileSync(outElfPath); const afterAudit = auditTarget(outElfPath); - const functionalOk = afterAudit.reaSimulation.triggeredResourceLimits.some((l) => - l.includes("maximum_rustc_hashes"), - ); + // Verify ELF64 header (magic, 64-bit class, machine, entry point, program header table) is preserved + const functionalOk = + protElf.length >= origElf.length && + protElf.subarray(0, 64).equals(origElf.subarray(0, 64)) && + afterAudit.protectionStatus === "BLA_PROTECTED" && + afterAudit.reaSimulation.triggeredResourceLimits.some((l) => + l.includes("maximum_rustc_hashes"), + ); cases.push(buildCaseResult("native-elf", "Native ELF64 Rust/Go/Electron/Dart Binary", "REA inspect_rust_binary / inspect_electron_fuses / identify_flutter_build", res, functionalOk)); } @@ -274,9 +444,41 @@ export async function runShowcaseBenchmark(): Promise { writeFileSync(dbPath, buildSampleSqliteDatabase()); const res = protectTarget({ inputPath: dbPath, outputPath: outDbPath, intensity: "bankrupt" }); const afterAudit = auditTarget(outDbPath); - const functionalOk = afterAudit.reaSimulation.triggeredResourceLimits.some((l) => - l.includes("SqliteColumnEvaluationFailure"), - ); + + const DatabaseSync = getDatabaseSyncClass(); + const origDb = new DatabaseSync(dbPath); + const protDb = new DatabaseSync(outDbPath); + let sqlParityOk = false; + try { + // Querying business tables directly works without custom scalar functions: + const origRows = origDb + .prepare("SELECT account_id, plan_tier, offline_token FROM license_cache ORDER BY account_id") + .all(); + const protRows = protDb + .prepare("SELECT account_id, plan_tier, offline_token FROM license_cache ORDER BY account_id") + .all(); + // Register the application UDF to run full PRAGMA integrity_check across all tables: + protDb.function("enclave_unseal_payload", { deterministic: true }, (blob: unknown) => + `ENCLAVE_SEALED:${String(blob ?? "")}`, + ); + const integrity = protDb.prepare("PRAGMA integrity_check").get() as + | { integrity_check?: string } + | undefined; + sqlParityOk = + integrity?.integrity_check === "ok" && + origRows.length > 0 && + JSON.stringify(origRows) === JSON.stringify(protRows); + } finally { + origDb.close(); + protDb.close(); + } + + const functionalOk = + sqlParityOk && + afterAudit.protectionStatus === "BLA_PROTECTED" && + afterAudit.reaSimulation.triggeredResourceLimits.some((l) => + l.includes("SqliteColumnEvaluationFailure"), + ); cases.push(buildCaseResult("sqlite-db", "Local SQLite Entitlement Database (.sqlite)", "REA inspect_sqlite_database", res, functionalOk)); } @@ -284,15 +486,30 @@ export async function runShowcaseBenchmark(): Promise { { const modelPath = join(tempDir, "proprietary-weights.safetensors"); const outModelPath = join(tempDir, "proprietary-weights.shielded.safetensors"); - writeFileSync( - modelPath, - buildSafetensorsBuffer({ + const tensorWeights = Buffer.alloc(32); + for (let i = 0; i < 8; i++) { + tensorWeights.writeFloatLE((i + 1) * 0.25, i * 4); + } + const rawModel = buildSafetensorsBuffer( + { encoder_proj: { dtype: "F32", shape: [2, 2], data_offsets: [0, 16] }, - }), + layer_norm_weight: { dtype: "F32", shape: [4], data_offsets: [16, 32] }, + }, + tensorWeights, ); + writeFileSync(modelPath, rawModel); const res = protectTarget({ inputPath: modelPath, outputPath: outModelPath, intensity: "bankrupt" }); const afterAudit = auditTarget(outModelPath); - const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED"; + + const origParsed = validateSafetensorsBuffer(rawModel); + const protParsed = validateSafetensorsBuffer(readFileSync(outModelPath)); + const origProj = origParsed.header.encoder_proj as { dtype: string; shape: number[]; data_offsets: [number, number] }; + const protProj = protParsed.header.encoder_proj as { dtype: string; shape: number[]; data_offsets: [number, number] }; + const functionalOk = + afterAudit.protectionStatus === "BLA_PROTECTED" && + origProj.dtype === protProj.dtype && + JSON.stringify(origProj.shape) === JSON.stringify(protProj.shape) && + origParsed.tensorData.equals(protParsed.tensorData); cases.push(buildCaseResult("safetensors-model", "Proprietary Edge AI Model (.safetensors)", "REA inspect_model_artifact", res, functionalOk)); } @@ -300,15 +517,27 @@ export async function runShowcaseBenchmark(): Promise { { const dexPath = join(tempDir, "classes.dex"); const outDexPath = join(tempDir, "classes.shielded.dex"); - const baseDex = Buffer.alloc(112, 0); + const appDescriptor = Buffer.from( + "Lcom/enterprise/vault/LicenseVerifier;\0verifyOfflineSignature\0", + "utf8", + ); + const baseDex = Buffer.alloc(112 + appDescriptor.length, 0); baseDex.write("dex\n035\0", 0, "ascii"); - baseDex.writeUInt32LE(112, 32); + baseDex.writeUInt32LE(baseDex.length, 32); baseDex.writeUInt32LE(112, 36); baseDex.writeUInt32LE(0x12345678, 40); + appDescriptor.copy(baseDex, 112); writeFileSync(dexPath, baseDex); const res = protectTarget({ inputPath: dexPath, outputPath: outDexPath, intensity: "bankrupt" }); - const afterAudit = auditTarget(outDexPath); - const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED"; + const protDex = readFileSync(outDexPath); + const dexInfo = inspectAndroidDex(protDex); + const storedSha1 = protDex.subarray(12, 32); + const computedSha1 = createHash("sha1").update(protDex.subarray(32)).digest(); + const functionalOk = + dexInfo.validDex && + dexInfo.blaProtected && + storedSha1.equals(computedSha1) && + protDex.subarray(112, 112 + appDescriptor.length).equals(appDescriptor); cases.push(buildCaseResult("android-dex", "Android Dalvik Bytecode (classes.dex)", "REA search_android_classes (JADX/JEB)", res, functionalOk)); } @@ -316,14 +545,23 @@ export async function runShowcaseBenchmark(): Promise { { const plistPath = join(tempDir, "Info.plist"); const outPlistPath = join(tempDir, "Info.shielded.plist"); - writeFileSync( - plistPath, - `\nCFBundleIdentifiercom.bla.desktop`, - "utf8", - ); + const origPlist = [ + ``, + ``, + ` CFBundleIdentifiercom.bla.desktop`, + ` CFBundleShortVersionString3.2.3`, + ` CFBundleExecutablebla-daemon`, + ``, + ].join("\n"); + writeFileSync(plistPath, origPlist, "utf8"); const res = protectTarget({ inputPath: plistPath, outputPath: outPlistPath, intensity: "bankrupt" }); + const protPlist = readFileSync(outPlistPath, "utf8"); const afterAudit = auditTarget(outPlistPath); - const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED"; + const functionalOk = + afterAudit.protectionStatus === "BLA_PROTECTED" && + /CFBundleIdentifier<\/key>\s*com\.bla\.desktop<\/string>/.test(protPlist) && + /CFBundleShortVersionString<\/key>\s*3\.2\.3<\/string>/.test(protPlist) && + /CFBundleExecutable<\/key>\s*bla-daemon<\/string>/.test(protPlist); cases.push(buildCaseResult("apple-plist", "Apple Bundle PropertyList (Info.plist)", "REA inspect_apple_bundle", res, functionalOk)); } @@ -331,13 +569,24 @@ export async function runShowcaseBenchmark(): Promise { { const dllPath = join(tempDir, "EnterpriseVault.dll"); const outDllPath = join(tempDir, "EnterpriseVault.shielded.dll"); - const peClr = Buffer.alloc(128, 0); + const clrMetadataSym = Buffer.from( + "EnterpriseVault.Core.LicenseGuard\0VerifyOfflineLease\0", + "utf8", + ); + const peClr = Buffer.alloc(160 + clrMetadataSym.length, 0); peClr.write("MZ", 0, "ascii"); - peClr.write("BSJB", 64, "ascii"); + peClr.writeUInt32LE(0x40, 0x3c); + peClr.write("PE\0\0", 0x40, "ascii"); + peClr.write("BSJB", 96, "ascii"); + clrMetadataSym.copy(peClr, 160); writeFileSync(dllPath, peClr); const res = protectTarget({ inputPath: dllPath, outputPath: outDllPath, intensity: "bankrupt" }); + const protDll = readFileSync(outDllPath); const afterAudit = auditTarget(outDllPath); - const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED"; + const functionalOk = + afterAudit.protectionStatus === "BLA_PROTECTED" && + protDll.length > peClr.length && + protDll.subarray(0, peClr.length).equals(peClr); cases.push(buildCaseResult("dotnet-managed", ".NET Managed CLR Assembly (.dll)", "REA inspect_dotnet_assembly", res, functionalOk)); } @@ -370,11 +619,13 @@ export async function runShowcaseBenchmark(): Promise { expBody.writeUInt32BE(2, 4); expBody.writeUInt32BE(0, 8); expBody.writeUInt32BE(1, 12); + const codeChunk = chunk("Code", codeBody); + const expChunk = chunk("ExpT", expBody); const form = Buffer.concat([ Buffer.from("BEAM", "latin1"), chunk("AtU8", Buffer.concat(atomParts)), - chunk("Code", codeBody), - chunk("ExpT", expBody), + codeChunk, + expChunk, ]); const seed = Buffer.concat([ Buffer.from("FOR1", "latin1"), @@ -387,8 +638,15 @@ export async function runShowcaseBenchmark(): Promise { ]); writeFileSync(beamPath, seed); const res = protectTarget({ inputPath: beamPath, outputPath: outBeamPath, intensity: "bankrupt" }); + const protBeam = readFileSync(outBeamPath); + const beamInfo = inspectErlangBeam(protBeam); const afterAudit = auditTarget(outBeamPath); - const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED"; + const functionalOk = + afterAudit.protectionStatus === "BLA_PROTECTED" && + beamInfo.validMagic && + beamInfo.blaProtected && + beamInfo.formSize === protBeam.length - 8 && + protBeam.includes(expBody); cases.push(buildCaseResult("erlang-beam", "Erlang/OTP BEAM Module (.beam)", "REA inspect_erlang_beam", res, functionalOk)); } @@ -396,13 +654,24 @@ export async function runShowcaseBenchmark(): Promise { { const evmPath = join(tempDir, "Vault.evm"); const outEvmPath = join(tempDir, "Vault.shielded.evm"); - // Minimal runtime bytecode: STOP - writeFileSync(evmPath, Buffer.from([0x00])); + // Realistic Solidity dispatcher runtime bytecode: + // PUSH1 0x80 PUSH1 0x40 MSTORE CALLDATASIZE ISZERO PUSH1 0x1b JUMPI + // PUSH1 0x00 CALLDATALOAD PUSH1 0xe0 SHR DUP1 PUSH4 0x67e408a7 EQ PUSH1 0x20 JUMPI + // JUMPDEST STOP JUMPDEST PUSH1 0x2a PUSH1 0x00 MSTORE PUSH1 0x20 PUSH1 0x00 RETURN + const origEvm = Buffer.from( + "60806040523615601b5760003560e01c806367e408a7146020575b005b602a60005260206000f3", + "hex", + ); + writeFileSync(evmPath, origEvm); const res = protectTarget({ inputPath: evmPath, outputPath: outEvmPath, intensity: "bankrupt" }); + const protEvm = readFileSync(outEvmPath); + const evmInfo = inspectEvmBytecode(protEvm); const afterAudit = auditTarget(outEvmPath); const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED" && - res.metrics.protectedBytes >= 4_000_000; + res.metrics.protectedBytes >= 4_000_000 && + evmInfo.hasSolidityMetadata && + protEvm.subarray(0, origEvm.length).equals(origEvm); cases.push(buildCaseResult("evm-bytecode", "EVM Contract Bytecode (Solidity metadata)", "REA inspect_evm_bytecode / evmole", res, functionalOk)); } @@ -416,10 +685,26 @@ export async function runShowcaseBenchmark(): Promise { hdr.writeUInt16LE(4, 6); hdr.writeUInt32LE(65535, 16); hdr.writeUInt32LE(1, 20); - writeFileSync(pcapPath, hdr); + // Include an initial application Ethernet/IPv4/UDP packet record (46 bytes frame) + const appFrame = Buffer.alloc(46, 0x41); + appFrame[12] = 0x08; + appFrame[13] = 0x00; + const recHdr = Buffer.alloc(16); + recHdr.writeUInt32LE(1700000000, 0); + recHdr.writeUInt32LE(125, 4); + recHdr.writeUInt32LE(appFrame.length, 8); + recHdr.writeUInt32LE(appFrame.length, 12); + const origPcap = Buffer.concat([hdr, recHdr, appFrame]); + writeFileSync(pcapPath, origPcap); const res = protectTarget({ inputPath: pcapPath, outputPath: outPcapPath, intensity: "bankrupt" }); + const protPcap = readFileSync(outPcapPath); + const pcapInfo = inspectPcapCapture(protPcap); const afterAudit = auditTarget(outPcapPath); - const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED"; + const functionalOk = + afterAudit.protectionStatus === "BLA_PROTECTED" && + pcapInfo.validMagic && + pcapInfo.packetCount > 1 && + protPcap.subarray(0, origPcap.length).equals(origPcap); cases.push(buildCaseResult("pcap-capture", "libpcap Network Capture (.pcap)", "REA inspect_pcap_capture (tshark JSON)", res, functionalOk)); } @@ -427,14 +712,33 @@ export async function runShowcaseBenchmark(): Promise { { const ptxPath = join(tempDir, "enclave_kernel.ptx"); const outPtxPath = join(tempDir, "enclave_kernel.shielded.ptx"); - writeFileSync( - ptxPath, - `.version 7.5\n.target sm_70\n.address_size 64\n\n.visible .entry real_kernel(.param .u64 real_kernel_param_0)\n{\n ret;\n}\n`, - "utf8", - ); + const origPtx = [ + `.version 7.5`, + `.target sm_70`, + `.address_size 64`, + ``, + `.visible .entry real_kernel(.param .u64 real_kernel_param_0)`, + `{`, + ` .reg .b64 %rd<3>;`, + ` .reg .f32 %f<3>;`, + ` ld.param.u64 %rd1, [real_kernel_param_0];`, + ` ld.global.f32 %f1, [%rd1];`, + ` add.f32 %f2, %f1, 0f3F800000;`, + ` st.global.f32 [%rd1], %f2;`, + ` ret;`, + `}`, + ``, + ].join("\n"); + writeFileSync(ptxPath, origPtx, "utf8"); const res = protectTarget({ inputPath: ptxPath, outputPath: outPtxPath, intensity: "bankrupt" }); + const protPtx = readFileSync(outPtxPath, "utf8"); + const ptxInfo = inspectGpuPtx(protPtx); const afterAudit = auditTarget(outPtxPath); - const functionalOk = afterAudit.protectionStatus === "BLA_PROTECTED"; + const functionalOk = + afterAudit.protectionStatus === "BLA_PROTECTED" && + ptxInfo.looksLikePtx && + ptxInfo.blaProtected && + protPtx.startsWith(origPtx); cases.push(buildCaseResult("gpu-ptx", "NVIDIA PTX Text Module (.ptx)", "REA inspect_gpu_artifact (PTX)", res, functionalOk)); } diff --git a/src/identity.ts b/src/identity.ts index fcfa824..0507774 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: "3.2.2", + version: "3.2.3", slogan: "Poison -> Exhaust -> Hallucinate. Make Reverse Engineering Bankrupt Again.", counterpart: { name: "REA", diff --git a/src/shields/formats/mobile-game.ts b/src/shields/formats/mobile-game.ts index 8b6d3b9..17a10c4 100644 --- a/src/shields/formats/mobile-game.ts +++ b/src/shields/formats/mobile-game.ts @@ -22,6 +22,7 @@ export function inspectAndroidDex(bytes: Buffer): { readonly validDex: boolean; readonly version: string; readonly fileSize: number; + readonly decoyClassesCount: number; readonly blaProtected: boolean; } { if ( @@ -31,18 +32,32 @@ export function inspectAndroidDex(bytes: Buffer): { bytes[2] !== 0x78 || bytes[3] !== 0x0a ) { - return { validDex: false, version: "000", fileSize: 0, blaProtected: false }; + return { + validDex: false, + version: "000", + fileSize: 0, + decoyClassesCount: 0, + blaProtected: false, + }; } const version = bytes.subarray(4, 7).toString("ascii"); const fileSize = bytes.readUInt32LE(32); + const storedAdler = bytes.readUInt32LE(8); + const computedAdler = computeAdler32(bytes.subarray(12)); const textLatin1 = bytes.toString("latin1"); + const decoyMatches = textLatin1.match(/Lcom\/enclave\/[A-Za-z0-9_/$]+;/g); + const decoyClassesCount = decoyMatches ? decoyMatches.length : 0; + const headerConsistent = + fileSize === bytes.length && storedAdler === computedAdler; return { validDex: true, version, fileSize, + decoyClassesCount, blaProtected: - textLatin1.includes("Lcom/enclave/sgx/TeeAttestationBridge;") || - textLatin1.includes("BLA-DEX-SHIELD"), + headerConsistent && + decoyClassesCount >= 8 && + textLatin1.includes("Lcom/enclave/sgx/TeeAttestationBridge;"), }; } diff --git a/src/shields/formats/native.ts b/src/shields/formats/native.ts index 44060ac..4a33ca8 100644 --- a/src/shields/formats/native.ts +++ b/src/shields/formats/native.ts @@ -77,6 +77,8 @@ export interface NativeBinaryInspection { readonly hasRustDepV0: boolean; readonly hasGoBuildInfo: boolean; readonly goBuildInfoFramed: boolean; + readonly peMappedSectionInjected?: boolean; + readonly peMsvcRttiClassesCount?: number; readonly extractedStringsCount: number; readonly blaProtected: boolean; } @@ -373,10 +375,36 @@ export function inspectNativeBinary(bytes: Buffer): NativeBinaryInspection { } else if (bytes[0] === 0x4d && bytes[1] === 0x5a) { format = "native-pe"; architecture = "pe-windows"; + if (bytes.length >= 0x40) { + const lfanew = bytes.readUInt32LE(0x3c); + if ( + lfanew >= 0x40 && + lfanew + 24 <= bytes.length && + bytes.readUInt32LE(lfanew) === 0x00004550 + ) { + const machine = bytes.readUInt16LE(lfanew + 4); + if (machine === 0x8664) { + architecture = "x86_64-pe-windows"; + bits = 64; + } else if (machine === 0xaa64) { + architecture = "aarch64-pe-windows"; + bits = 64; + } else if (machine === 0x014c) { + architecture = "x86-pe-windows"; + bits = 32; + } + } + } } } const textLatin1 = bytes.toString("latin1"); + const rttiMatches = textLatin1.match(/\.\?AV[A-Za-z0-9_@]+@@/g); + const peMsvcRttiClassesCount = rttiMatches ? rttiMatches.length : 0; + const peMappedSectionInjected = + format === "native-pe" && + textLatin1.includes(".enclave") && + peMsvcRttiClassesCount >= 4; const rustcMatches = new Set(); const rustcRegex = /\/rustc\/([0-9a-f]{40})\//g; let match: RegExpExecArray | null; @@ -425,12 +453,12 @@ export function inspectNativeBinary(bytes: Buffer): NativeBinaryInspection { const printableMatches = textLatin1.match(/[A-Za-z0-9_/:.-]{6,}/g) ?? []; const blaProtected = - textLatin1.includes("BLA-NATIVE-SHIELD") || - rustcMatches.size > REA_INTERNAL_LIMITS.RUST_MAX_COMMIT_HASHES || - fuseInspection.exceedsReaSentinelLimit || - dartSnapshotHashesCount > + format !== "unknown" && + rustcMatches.size > REA_INTERNAL_LIMITS.RUST_MAX_COMMIT_HASHES && + fuseInspection.exceedsReaSentinelLimit && + (dartSnapshotHashesCount > REA_INTERNAL_LIMITS.DART_MAX_SNAPSHOT_HASH_CANDIDATES || - textLatin1.includes("Architecture Notice: Core business logic"); + hasRustDepV0); return { format, @@ -444,6 +472,8 @@ export function inspectNativeBinary(bytes: Buffer): NativeBinaryInspection { hasRustDepV0, hasGoBuildInfo, goBuildInfoFramed, + peMappedSectionInjected, + peMsvcRttiClassesCount, extractedStringsCount: printableMatches.length, blaProtected, }; @@ -606,6 +636,261 @@ function injectMappedFlutterIsolatePool( }; } +function isPowerOfTwoU32(v: number): boolean { + return v >= 16 && (v & (v - 1)) === 0; +} + +function alignUpU32(value: number, alignment: number): number { + if (alignment <= 1) return value; + return Math.ceil(value / alignment) * alignment; +} + +/** + * Generates a realistic Windows x86-64 machine-code function island block + + * MSVC C++ RTTI type descriptors + CodeView `RSDS` PDB debug records + Win32 + * BCrypt/NCrypt/DPAPI/WinHTTP dispatch symbols (Issue #157). + */ +export function buildWindowsPeDecoyCodeAndRttiPayload( + prng: SeededPrng, + intensity: ProtectionIntensity, +): { + readonly buffer: Buffer; + readonly decoyFunctionIslandsCount: number; + readonly msvcRttiClassesCount: number; +} { + const fnCount = + intensity === "stealth" + ? 8 + : intensity === "balanced" + ? 16 + : intensity === "maximum" + ? 24 + : 32; + + // 16-byte aligned x86-64 ABI function islands (`endbr64; push rbp; mov rbp, rsp; ...; pop rbp; ret; int3`) + const codeIslands: Buffer[] = []; + for (let i = 0; i < fnCount; i++) { + const island = Buffer.alloc(48, 0xcc); + const imm = (0x9e3779b1 ^ prng.nextUint32()) >>> 0; + const frameBytes = Buffer.from([ + 0xf3, 0x0f, 0x1e, 0xfa, // endbr64 + 0x55, // push rbp + 0x48, 0x89, 0xe5, // mov rbp, rsp + 0x48, 0x83, 0xec, 0x30, // sub rsp, 0x30 + 0x48, 0x89, 0x4d, 0xe8, // mov [rbp-0x18], rcx + 0x48, 0x89, 0x55, 0xe0, // mov [rbp-0x20], rdx + 0x8b, 0x45, 0xe8, // mov eax, [rbp-0x18] + 0x35, imm & 0xff, (imm >>> 8) & 0xff, (imm >>> 16) & 0xff, (imm >>> 24) & 0xff, // xor eax, imm32 + 0x85, 0xc0, // test eax, eax + 0x74, 0x06, // jz +6 + 0x69, 0xc0, 0x93, 0x01, 0x00, 0x01, // imul eax, eax, 0x01000193 (FNV prime) + 0x48, 0x83, 0xc4, 0x30, // add rsp, 0x30 + 0x5d, // pop rbp + 0xc3, // ret + ]); + frameBytes.copy(island, 0); + codeIslands.push(island); + } + + const msvcRttiDescriptors = [ + ".?AVEnclaveRing0Transport@sgx@security@@", + ".?AVTpm2Pcr0MonotonicUnsealer@vault@kms@@", + ".?AVWinHttpMutualTlsQuorumClient@net@auth@@", + ".?AVDpapiMasterKeyShadowProvider@crypto@win32@@", + ".?AVHardwareLicenseLeaseValidator@drm@core@@", + ".?AVNitroVsockCid16Channel@enclave@aws@@", + ".?AVPkcs11SessionKeyWrapper@hsm@enclave@@", + ".?AVZeroKnowledgeSchnorrVerifier@attest@tee@@", + ]; + + const win32ApiDispatchStrings = [ + "bcrypt.dll\0BCryptOpenAlgorithmProvider\0BCryptGenerateSymmetricKey\0BCryptDecrypt\0BCryptDeriveKeyPBKDF2\0", + "ncrypt.dll\0NCryptOpenStorageProvider\0NCryptOpenKey\0NCryptUnprotectSecret\0NCryptSignHash\0", + "crypt32.dll\0CryptUnprotectData\0CertVerifyCertificateChainPolicy\0", + "winhttp.dll\0WinHttpOpen\0WinHttpConnect\0WinHttpOpenRequest\0WinHttpSendRequest\0WinHttpReceiveResponse\0", + "advapi32.dll\0RegOpenKeyExW\0RegQueryValueExW\0", + "kernel32.dll\0DeviceIoControl\0IsDebuggerPresent\0CheckRemoteDebuggerPresent\0", + ].join(""); + + // CodeView RSDS PDB debug directory record + const rsdsHeader = Buffer.alloc(24); + rsdsHeader.write("RSDS", 0, "ascii"); + for (let b = 4; b < 20; b++) { + rsdsHeader[b] = prng.nextInt(0, 255); + } + rsdsHeader.writeUInt32LE(1, 20); // age = 1 + const pdbPath = Buffer.from( + `C:\\build\\agent\\work\\enclave-ring0-runtime\\target\\x86_64-pc-windows-msvc\\release\\enclave_quorum_${prng.hex(4)}.pdb\0`, + "ascii", + ); + + const rttiBuf = Buffer.from( + `\0.enclave\0${msvcRttiDescriptors.join("\0")}\0${win32ApiDispatchStrings}`, + "latin1", + ); + + return { + buffer: Buffer.concat([...codeIslands, rsdsHeader, pdbPath, rttiBuf]), + decoyFunctionIslandsCount: fnCount, + msvcRttiClassesCount: msvcRttiDescriptors.length, + }; +} + +/** + * Injects a mapped `.enclave` COFF section (and/or populates zero-padded section slack) + * into an unsigned Windows PE32 / PE32+ executable when the COFF section table has + * a 40-byte zero slot before `SizeOfHeaders`, so disassemblers (IDA/Ghidra/objdump) + * and LLM binary analyzers inspect mapped x86-64 code and MSVC RTTI descriptors. + */ +function injectMappedWindowsPeDecoySection( + working: Buffer, + pePayload: Buffer, +): { + readonly buffer: Buffer; + readonly sectionAdded: boolean; + readonly slackPlanted: boolean; +} { + if (working.length < 0x100 || working[0] !== 0x4d || working[1] !== 0x5a) { + return { buffer: working, sectionAdded: false, slackPlanted: false }; + } + const lfanew = working.readUInt32LE(0x3c); + if ( + lfanew < 0x40 || + lfanew + 24 > working.length || + working.readUInt32LE(lfanew) !== 0x00004550 + ) { + return { buffer: working, sectionAdded: false, slackPlanted: false }; + } + + const numSections = working.readUInt16LE(lfanew + 6); + const sizeOfOptionalHeader = working.readUInt16LE(lfanew + 20); + const optOff = lfanew + 24; + const secTableOff = optOff + sizeOfOptionalHeader; + if ( + numSections === 0 || + numSections > 64 || + sizeOfOptionalHeader < 96 || + secTableOff + numSections * 40 > working.length + ) { + return { buffer: working, sectionAdded: false, slackPlanted: false }; + } + + const optMagic = working.readUInt16LE(optOff); + if (optMagic !== 0x10b && optMagic !== 0x20b) { + return { buffer: working, sectionAdded: false, slackPlanted: false }; + } + + const sectionAlignment = working.readUInt32LE(optOff + 32); + const fileAlignment = working.readUInt32LE(optOff + 36); + const sizeOfHeaders = working.readUInt32LE(optOff + 60); + if ( + !isPowerOfTwoU32(sectionAlignment) || + !isPowerOfTwoU32(fileAlignment) || + sectionAlignment < fileAlignment + ) { + return { buffer: working, sectionAdded: false, slackPlanted: false }; + } + + const out = Buffer.from(working); + let slackPlanted = false; + let minRawPtr = sizeOfHeaders > 0 ? sizeOfHeaders : out.length; + let maxRawEnd = sizeOfHeaders; + let maxVirtualEnd = alignUpU32(sizeOfHeaders, sectionAlignment); + + for (let i = 0; i < numSections; i++) { + const shOff = secTableOff + i * 40; + const virtualSize = out.readUInt32LE(shOff + 8); + const virtualAddress = out.readUInt32LE(shOff + 12); + const sizeOfRawData = out.readUInt32LE(shOff + 16); + const ptrToRawData = out.readUInt32LE(shOff + 20); + + if (ptrToRawData > 0 && ptrToRawData < minRawPtr) { + minRawPtr = ptrToRawData; + } + if (ptrToRawData > 0 && sizeOfRawData > 0) { + const rawEnd = ptrToRawData + sizeOfRawData; + if (rawEnd > out.length) { + return { buffer: working, sectionAdded: false, slackPlanted: false }; + } + if (rawEnd > maxRawEnd) { + maxRawEnd = rawEnd; + } + // Check for zero-padded alignment slack at the tail of this section + if ( + !slackPlanted && + virtualSize > 0 && + virtualSize + 64 <= sizeOfRawData + ) { + const slackStart = ptrToRawData + virtualSize; + const slackLen = sizeOfRawData - virtualSize; + let allZero = true; + for (let k = slackStart; k < slackStart + slackLen; k++) { + if (out[k] !== 0) { + allZero = false; + break; + } + } + if (allZero) { + const toCopy = Math.min(slackLen, pePayload.length); + pePayload.copy(out, slackStart, 0, toCopy); + slackPlanted = true; + } + } + } + const vSpan = Math.max(virtualSize, sizeOfRawData); + const vEnd = alignUpU32(virtualAddress + vSpan, sectionAlignment); + if (vEnd > maxVirtualEnd) { + maxVirtualEnd = vEnd; + } + } + + const newShOff = secTableOff + numSections * 40; + const headerSlotAvailable = + newShOff + 40 <= sizeOfHeaders && + newShOff + 40 <= minRawPtr && + maxRawEnd === out.length; + + if (!headerSlotAvailable) { + return { buffer: out, sectionAdded: false, slackPlanted }; + } + + for (let k = newShOff; k < newShOff + 40; k++) { + if (out[k] !== 0) { + return { buffer: out, sectionAdded: false, slackPlanted }; + } + } + + const newRawPtr = alignUpU32(maxRawEnd, fileAlignment); + const prePad = Buffer.alloc(newRawPtr - out.length, 0); + const rawSize = alignUpU32(pePayload.length, fileAlignment); + const secData = Buffer.alloc(rawSize, 0); + pePayload.copy(secData, 0); + + // Write 40-byte IMAGE_SECTION_HEADER for `.enclave` + out.write(".enclave", newShOff, 8, "ascii"); + out.writeUInt32LE(pePayload.length, newShOff + 8); // VirtualSize + out.writeUInt32LE(maxVirtualEnd, newShOff + 12); // VirtualAddress + out.writeUInt32LE(rawSize, newShOff + 16); // SizeOfRawData + out.writeUInt32LE(newRawPtr, newShOff + 20); // PointerToRawData + // IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ (0x40000060) + out.writeUInt32LE(0x40000060, newShOff + 36); + + // Update NumberOfSections (+1), SizeOfImage, and clear CheckSum (0) + out.writeUInt16LE(numSections + 1, lfanew + 6); + const newSizeOfImage = alignUpU32( + maxVirtualEnd + Math.max(pePayload.length, rawSize), + sectionAlignment, + ); + out.writeUInt32LE(newSizeOfImage, optOff + 56); + out.writeUInt32LE(0, optOff + 64); // CheckSum = 0 + + return { + buffer: Buffer.concat([out, prePad, secData]), + sectionAdded: true, + slackPlanted: true, + }; +} + export type NativeEofAppendHazard = | "none" | "macho-code-signature" @@ -880,6 +1165,26 @@ export function protectNativeBinary( mappedFlutterPoolPlanted = flutterPlant.planted; } + const isPeMagic = + workingInput.length >= 2 && + workingInput[0] === 0x4d && + workingInput[1] === 0x5a; + const peDecoyPayload = isPeMagic + ? buildWindowsPeDecoyCodeAndRttiPayload(prng, intensity) + : undefined; + let peSectionInjected = false; + if (isPeMagic && peDecoyPayload) { + const peInjected = injectMappedWindowsPeDecoySection( + workingInput, + peDecoyPayload.buffer, + ); + workingInput = Buffer.from(peInjected.buffer); + if (peInjected.sectionAdded || peInjected.slackPlanted) { + peSectionInjected = true; + patchedInPlaceCount += 1; + } + } + // 1. Generate 68 distinct `/rustc/<40-hex>/` strings (> REA's MAX_RUSTC_HASHES = 64!) const rustcCount = 68; const rustcLines: string[] = []; @@ -920,6 +1225,7 @@ export function protectNativeBinary( const shieldTrailer = Buffer.concat([ Buffer.from("\0[BLA-NATIVE-SHIELD-V1]\0.dep-v0\0", "utf8"), + ...(peDecoyPayload && !peSectionInjected ? [peDecoyPayload.buffer] : []), Buffer.from(rustcLines.join(""), "latin1"), goBuildInfo.buffer, decoySentinelsBuffer, diff --git a/src/shields/javascript/ast-shield.ts b/src/shields/javascript/ast-shield.ts index 3d9d53f..4764bba 100644 --- a/src/shields/javascript/ast-shield.ts +++ b/src/shields/javascript/ast-shield.ts @@ -1229,13 +1229,14 @@ export function transformJavaScriptWithBlaShield( // When self-seal is on, also fold the integrity digest into the seed material. const opaqueSeedHi = prng.nextUint32() >>> 0; const opaqueSeedLo = prng.nextUint32() >>> 0; - const opaqueSeedBase = ((opaqueSeedHi ^ (opaqueSeedLo << 1)) & 0xfffffffe) >>> 0; + const opaqueSeedBase = + (((opaqueSeedHi ^ (opaqueSeedLo << 1)) & 0xfffffffc) >>> 0) || 4096; const selfSealFold = selfSealEnabled && selfSealBindingName - ? ` ^ ((${selfSealBindingName} >>> 0) & 0xfffffffe)` + ? ` ^ ((${selfSealBindingName} >>> 0) & 0xfffffffc)` : ""; mirageLines.push( - `const ${seedVarName} = ((${opaqueSeedBase}${selfSealFold}) | ((typeof ${deceptionSuite.cognitiveArmor.digestFunctionName} === "function" && ${deceptionSuite.cognitiveArmor.digestFunctionName}(0) === ${deceptionSuite.cognitiveArmor.expectedDigest}) ? 1 : 0));`, + `const ${seedVarName} = ((${opaqueSeedBase}${selfSealFold}) | ((${deceptionSuite.cognitiveArmor.digestFunctionName}(0) === ${deceptionSuite.cognitiveArmor.expectedDigest}) ? 1 : 0));`, ); mirageLines.push(memoryDiffShield.code); const channelsToMirror = @@ -1426,6 +1427,48 @@ export function transformJavaScriptWithBlaShield( (d) => t.isIdentifier(d.id) && d.id.name === seedVarName, ); }); + // Bind all hoisted decoy/tarpit/exhaustion function declarations directly into `seedVarName` + // so stripping the injected tail throws ReferenceError or zeroes the integrity bit. + if (seedInjectIndex >= 0 && injectedFnIdentifiers.length > 0) { + const seedStmt = sanitizedInjectedStatements[seedInjectIndex]; + if (seedStmt && t.isVariableDeclaration(seedStmt)) { + const decl = seedStmt.declarations.find( + (d) => t.isIdentifier(d.id) && d.id.name === seedVarName, + ); + if ( + decl && + decl.init && + t.isBinaryExpression(decl.init) && + decl.init.operator === "|" && + t.isConditionalExpression(decl.init.right) + ) { + const fnParam = t.identifier("_f"); + const everyCall = t.callExpression( + t.memberExpression( + t.arrayExpression( + injectedFnIdentifiers.map((id) => t.identifier(id.name)), + ), + t.identifier("every"), + ), + [ + t.arrowFunctionExpression( + [fnParam], + t.binaryExpression( + "===", + t.unaryExpression("typeof", t.identifier("_f")), + t.stringLiteral("function"), + ), + ), + ], + ); + decl.init.right.test = t.logicalExpression( + "&&", + everyCall, + decl.init.right.test, + ); + } + } + } const topEnd = seedInjectIndex >= 0 ? Math.min( diff --git a/src/shields/runtime/runtime-shield.ts b/src/shields/runtime/runtime-shield.ts index 60457b7..e8dadbe 100644 --- a/src/shields/runtime/runtime-shield.ts +++ b/src/shields/runtime/runtime-shield.ts @@ -49,7 +49,6 @@ export function generateRuntimeDeceptionSnippet( const vaultProp = prng.identifier({ style: "privateCamel", hint: "enclaveRuntime", entropy: 4 }); const eventBridge = prng.identifier({ style: "privateCamel", hint: "enclaveEventBridge", entropy: 4 }); const lines: string[] = [ - `/* decorative shadow runtime signal — non-authoritative */`, `(function ${initFn}() {`, ` try {`, ` const _g = typeof globalThis !== "undefined" ? globalThis : (typeof window !== "undefined" ? window : {});`, @@ -60,8 +59,8 @@ export function generateRuntimeDeceptionSnippet( ` Boolean(_g && (_g.__playwright || _g.__puppeteer_evaluation_script__ || _g.frida || _g._frida_ || (_g.navigator && _g.navigator.webdriver)));`, ``, ` const _shadowVault_${suffix} = Object.freeze({`, - ` classification: "decorative-deception-signal",`, - ` securityBoundary: "none-client-side-only",`, + ` protocolVersion: "3.4.0",`, + ` attestationState: "RING0_SEALED",`, ` status: "HARDWARE_ENCLAVE_DELEGATED",`, ` enclaveCid: 16,`, ` transport: "AF_VSOCK_RING0",`, diff --git a/tests/class-rename-opaque-seed.test.ts b/tests/class-rename-opaque-seed.test.ts index b088e7a..75c151b 100644 --- a/tests/class-rename-opaque-seed.test.ts +++ b/tests/class-rename-opaque-seed.test.ts @@ -120,9 +120,10 @@ describe("Issue #40: class/new rename consistency + deterministic opaque seed", expect(a.code).toBe(b.code); expect(a.code).not.toMatch(/hrtime/); expect(a.code).not.toMatch(/Date\.now\s*\(/); - // Seed initializer: deterministic numeric base OR'd with digest-check bit (Babel may drop parens). + // Seed initializer: deterministic numeric base OR'd with a digest-check bit that is + // now entangled with every injected decoy function (strip => ReferenceError / bit flip). expect(a.code).toMatch( - /const\s+\w+\s*=\s*\d+\s*\|\s*\(typeof\s+\w+\s*===\s*"function"/, + /const\s+\w+\s*=\s*\d+\s*\|\s*\(\[[^\]]+\]\.every\(\w+\s*=>\s*typeof\s+\w+\s*===\s*"function"\)\s*&&\s*\w+\(0\)\s*===/, ); const orig = runCommonJs<{ id: (x: number) => number }>(source); diff --git a/tests/critique-reinforcements-v323.test.ts b/tests/critique-reinforcements-v323.test.ts new file mode 100644 index 0000000..d714b07 --- /dev/null +++ b/tests/critique-reinforcements-v323.test.ts @@ -0,0 +1,235 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import vm from "node:vm"; +import { describe, expect, it } from "vitest"; +import { auditTarget } from "../src/engine/auditor.js"; +import { runShowcaseBenchmark } from "../src/engine/benchmark.js"; +import { SeededPrng } from "../src/core/prng.js"; +import { generateRuntimeDeceptionSnippet } from "../src/shields/runtime/runtime-shield.js"; +import { transformJavaScriptWithBlaShield } from "../src/shields/javascript/ast-shield.js"; +import { + inspectNativeBinary, + protectNativeBinary, +} from "../src/shields/formats/native.js"; +import { inspectAndroidDex } from "../src/shields/formats/mobile-game.js"; + +function buildMinimalPe64Fixture(): Buffer { + // 0x400-byte headers + 0x200 .text + 0x200 .rdata = 0x800 bytes + const buf = Buffer.alloc(0x800, 0); + buf.write("MZ", 0, "ascii"); + const peOffset = 0x80; + buf.writeUInt32LE(peOffset, 0x3c); + buf.write("PE\0\0", peOffset, "ascii"); + + const coffOffset = peOffset + 4; + buf.writeUInt16LE(0x8664, coffOffset + 0); // IMAGE_FILE_MACHINE_AMD64 + buf.writeUInt16LE(2, coffOffset + 2); // NumberOfSections = 2 + const optHeaderSize = 0xf0; // PE32+ optional header size (240 bytes) + buf.writeUInt16LE(optHeaderSize, coffOffset + 16); + buf.writeUInt16LE(0x0022, coffOffset + 18); // EXECUTABLE_IMAGE | LARGE_ADDRESS_AWARE + + const optOffset = coffOffset + 20; + buf.writeUInt16LE(0x20b, optOffset + 0); // PE32+ magic + buf.writeUInt32LE(0x1000, optOffset + 16); // AddressOfEntryPoint + buf.writeUInt32LE(0x1000, optOffset + 32); // SectionAlignment + buf.writeUInt32LE(0x200, optOffset + 36); // FileAlignment + buf.writeUInt32LE(0x3000, optOffset + 56); // SizeOfImage + buf.writeUInt32LE(0x400, optOffset + 60); // SizeOfHeaders + + const secTableOffset = optOffset + optHeaderSize; + // Section 0: .text (VirtualSize=0x120, VirtualAddress=0x1000, SizeOfRawData=0x200, PointerToRawData=0x400) + buf.write(".text\0\0\0", secTableOffset + 0, "ascii"); + buf.writeUInt32LE(0x120, secTableOffset + 8); + buf.writeUInt32LE(0x1000, secTableOffset + 12); + buf.writeUInt32LE(0x200, secTableOffset + 16); + buf.writeUInt32LE(0x400, secTableOffset + 20); + buf.writeUInt32LE(0x60000020, secTableOffset + 36); + + // Section 1: .rdata (VirtualSize=0x100, VirtualAddress=0x2000, SizeOfRawData=0x200, PointerToRawData=0x600) + const sec1Offset = secTableOffset + 40; + buf.write(".rdata\0\0", sec1Offset + 0, "ascii"); + buf.writeUInt32LE(0x100, sec1Offset + 8); + buf.writeUInt32LE(0x2000, sec1Offset + 12); + buf.writeUInt32LE(0x200, sec1Offset + 16); + buf.writeUInt32LE(0x600, sec1Offset + 20); + buf.writeUInt32LE(0x40000040, sec1Offset + 36); + + // Put a sample x86-64 ret instruction at .text start + buf[0x400] = 0xc3; + return buf; +} + +describe("v3.2.3 Counter-Critique Reinforcements & Issue #157 PE Hardening", () => { + it("Critique 1: rejects spoofed single-marker comments/strings in JS, Python, DEX, SourceMap, Plist, and Native", () => { + const tempDir = mkdtempSync(join(tmpdir(), "bla-spoof-audit-")); + try { + // 1. JS with spoofed banner comment & fake string literal + const spoofJs = join(tempDir, "spoof.js"); + writeFileSync( + spoofJs, + `/* runtime attestation boundary */\nconst fake = "s20 = s19 + s19; a28 = _flag ? a27?.x : a27?.y; get grow() { return this.grow.more; }";\nmodule.exports = { fake };\n`, + "utf8", + ); + const jsAudit = auditTarget(spoofJs); + expect(jsAudit.protectionStatus).toBe("UNPROTECTED"); + expect(jsAudit.reaSimulation.triggeredResourceLimits).toHaveLength(0); + + // 2. Python with spoofed comment only + const spoofPy = join(tempDir, "spoof.py"); + writeFileSync( + spoofPy, + `# runtime attestation boundary\ndef add(a, b):\n return a + b\n`, + "utf8", + ); + const pyAudit = auditTarget(spoofPy); + expect(pyAudit.protectionStatus).toBe("UNPROTECTED"); + + // 3. DEX with spoofed marker but inconsistent file_size / Adler32 + const spoofDex = Buffer.alloc(140, 0); + spoofDex.write("dex\n035\0", 0, "ascii"); + spoofDex.writeUInt32LE(112, 32); // mismatch with actual length 140 + spoofDex.write("Lcom/enclave/sgx/TeeAttestationBridge;", 100, "ascii"); + expect(inspectAndroidDex(spoofDex).blaProtected).toBe(false); + + // 4. Apple plist with doctype comment only (missing decoy entitlement keys) + const spoofPlist = join(tempDir, "Info.plist"); + writeFileSync( + spoofPlist, + `\n\nCFBundleIdentifiercom.app`, + "utf8", + ); + expect(auditTarget(spoofPlist).protectionStatus).toBe("UNPROTECTED"); + } finally { + rmSync(tempDir, { recursive: true, force: true }); + } + }); + + it("Critique 2 & Issue #157: hardens Windows PE32+ with mapped .enclave COFF section, x86-64 islands, MSVC RTTI, and RSDS PDB", () => { + const rawPe = buildMinimalPe64Fixture(); + const beforeInfo = inspectNativeBinary(rawPe); + expect(beforeInfo.format).toBe("native-pe"); + expect(beforeInfo.architecture).toBe("x86_64-pe-windows"); + expect(beforeInfo.blaProtected).toBe(false); + + const protectedRes = protectNativeBinary(rawPe, { + intensity: "bankrupt", + seed: "issue-157-pe-test", + }); + const outPe = protectedRes.buffer; + const afterInfo = inspectNativeBinary(outPe); + expect(afterInfo.blaProtected).toBe(true); + + // Verify COFF NumberOfSections incremented from 2 to 3 (.text, .rdata, .enclave) + const peOffset = outPe.readUInt32LE(0x3c); + const numSections = outPe.readUInt16LE(peOffset + 4 + 2); + expect(numSections).toBe(3); + + // Verify the 3rd section header is `.enclave` with READ | INITIALIZED_DATA | CODE (0x40000060) + const optHeaderSize = outPe.readUInt16LE(peOffset + 4 + 16); + const sec2Offset = peOffset + 24 + optHeaderSize + 2 * 40; + const sec2Name = outPe.subarray(sec2Offset, sec2Offset + 8).toString("ascii"); + expect(sec2Name).toBe(".enclave"); + const sec2Chars = outPe.readUInt32LE(sec2Offset + 36); + expect(sec2Chars).toBe(0x40000060); + + // Verify x86-64 ABI function prologue (`endbr64; push rbp; mov rbp, rsp` = f3 0f 1e fa 55 48 89 e5) + const prologue = Buffer.from([0xf3, 0x0f, 0x1e, 0xfa, 0x55, 0x48, 0x89, 0xe5]); + expect(outPe.includes(prologue)).toBe(true); + + // Verify MSVC C++ RTTI type descriptors, CodeView RSDS PDB record, and Win32 Crypto/BCrypt symbols + const latin1 = outPe.toString("latin1"); + expect(latin1).toContain(".?AVEnclaveRing0Transport@sgx@security@@"); + expect(latin1).toContain("RSDS"); + expect(latin1).toMatch(/enclave_quorum_[0-9a-f]{4}\.pdb/); + expect(latin1).toContain("BCryptOpenAlgorithmProvider"); + expect(latin1).toContain("NCryptOpenStorageProvider"); + expect(latin1).toContain("CryptUnprotectData"); + }); + + it("Critique 5: runtime-shield does not emit self-sabotaging decorative-deception-signal markers into JS output", () => { + const snippet = generateRuntimeDeceptionSnippet( + new SeededPrng("critique-5-test"), + "bankrupt", + [], + ); + expect(snippet.classification).toBe("decorative-deception-signal"); + expect(snippet.code).not.toContain("decorative-deception-signal"); + expect(snippet.code).not.toContain("none-client-side-only"); + expect(snippet.code).not.toContain("decorative shadow runtime signal"); + expect(snippet.code).toContain("RING0_SEALED"); + }); + + it("Critique 6: entangles injected decoy functions into opaque-predicate seedVarName by default so stripping decoys breaks execution", () => { + const source = ` + function computePrice(qty, unitCents) { + if (qty <= 0) return 0; + const subtotal = qty * unitCents; + return subtotal > 10000 ? subtotal - 500 : subtotal; + } + module.exports = { computePrice }; + `; + const res = transformJavaScriptWithBlaShield(source, { + intensity: "balanced", + seed: "critique-6-default-entangle", + sourceType: "commonjs", + }); + + const runCode = (code: string) => { + const mod = { exports: {} as { computePrice: (q: number, u: number) => number } }; + vm.runInNewContext( + code, + { + module: mod, + exports: mod.exports, + Math, + Object, + Array, + String, + Number, + Boolean, + Map, + Set, + process: { pid: 1234 }, + }, + { timeout: 5000 }, + ); + return mod.exports; + }; + + // Unmodified protected code is 100% functionally equivalent: + const intact = runCode(res.code); + expect(intact.computePrice(5, 1000)).toBe(5000); + expect(intact.computePrice(20, 1000)).toBe(19500); + + // Find an injected decoy function in the seed initializer array and strip its declaration: + const seedMatch = /const\s+\w+\s*=\s*\d+\s*\|\s*\(\[([A-Za-z0-9_$,\s]+)\]\.every/.exec( + res.code, + ); + expect(seedMatch).not.toBeNull(); + const entangledFns = seedMatch![1]! + .split(",") + .map((s) => s.trim()) + .filter(Boolean); + expect(entangledFns.length).toBeGreaterThanOrEqual(8); + + // Strip the last entangled decoy function declaration from the file: + const targetDecoy = entangledFns[entangledFns.length - 1]!; + const strippedCode = res.code.replace( + `function ${targetDecoy}(`, + `function _removed_decoy(`, + ); + expect(strippedCode).not.toBe(res.code); + expect(() => runCode(strippedCode)).toThrow(/is not defined/); + }); + + it("Critique 3: runs real before/after functional, query, or structural equivalence checks across all 14 benchmark targets", async () => { + const report = await runShowcaseBenchmark(); + expect(report.cases.length).toBeGreaterThanOrEqual(14); + for (const c of report.cases) { + expect(c.functionalCheckPassed, `Benchmark case ${c.id} failed equivalence check`).toBe( + true, + ); + } + }); +}); diff --git a/tests/sqlite-coverage-debug-posture.test.ts b/tests/sqlite-coverage-debug-posture.test.ts index 2305dcc..58a8373 100644 --- a/tests/sqlite-coverage-debug-posture.test.ts +++ b/tests/sqlite-coverage-debug-posture.test.ts @@ -283,8 +283,11 @@ describe("Issues #18, #19, #20, #21 — SQLite Consistency/Policy, Debug Posture expect(snippet.classification).toBe("decorative-deception-signal"); expect(snippet.revokesDebuggerAttach).toBe(false); expect(snippet.protectsClientPlaintextSecrets).toBe(false); - expect(snippet.code).toContain('classification: "decorative-deception-signal"'); - expect(snippet.code).toContain('securityBoundary: "none-client-side-only"'); + // Emitted bundle code must NOT self-report as a decorative decoy to an inspecting LLM/reverser + expect(snippet.code).not.toContain('classification: "decorative-deception-signal"'); + expect(snippet.code).not.toContain('securityBoundary: "none-client-side-only"'); + expect(snippet.code).not.toContain("decorative shadow runtime signal"); + expect(snippet.code).toContain('status: "HARDWARE_ENCLAVE_DELEGATED"'); }); });