diff --git a/.agents/skills/blind-llm-agents/SKILL.md b/.agents/skills/blind-llm-agents/SKILL.md index 25c71ba..8f5ae62 100644 --- a/.agents/skills/blind-llm-agents/SKILL.md +++ b/.agents/skills/blind-llm-agents/SKILL.md @@ -7,7 +7,7 @@ description: > Agents). Prefer this skill as the guide; call existing MCP tools / CLI — do not invent new MCP tools. Default verb: bla_harden. Refuse crack/RE of third-party software. metadata: - version: "1.5.11" + version: "1.5.12" --- # BLA: Blind LLM Agents @@ -24,7 +24,7 @@ model misjudgment on proprietary logic, or **one-click / 一键加固** a build. Defensive only: protect **their own** artifacts. Refuse crack, RE, bypass PoCs, or attack playbooks against software they do not own. -**Principles (red-blue round-1+2+3+4+5+6+7):** do not ship a stable public WASM ABI without an explicit `wasm_preserve_exports` list; do not leave JS-side independent lane tables — prefer whole-key chained mixing (`bla_lint_lanes` / harden refuse). **Do not** place plaintext seal/catalog JSON (`revision`, salts, certificate ciphertext) beside hardened outputs. Public compare targets must be **one-way** (SHA-256/HMAC/etc.); reversible ARX/Feistel digests as public `revision` are a key-recovery footgun (round-2 break — **closed in round-3** when seal is digests-only). Enforce with `bla_lint_seal` / `bla lint-seal`; bankrupt harden **refuses** unless `allow_plaintext_seal` / `--allow-plaintext-seal`. Round-3 residual **gates**: `bla_lint_wasm_params` / `bla lint-wasm-params` — bankrupt refuses clear `R2SEAL`/`R3PARM`/`R3CIPH`-class carriers unless `allow_wasm_clear_params`; `bla_lint_panel_derive` — maximum/bankrupt **rewrites** `__vaultPanelDerive_*` to `_blaPd_*` unless `allow_stable_panel_derive`; bankrupt harden sets `selfSealRecommended` for multi-artifact trees (never auto for single-file) — prefer **`self_seal`**. Round-4 gates: `bla_lint_js_aes_unwrap` / `bla lint-js-aes-unwrap` — bankrupt **refuses** JS wrap-key + `create*iv` + fixed sealed hdr (e.g. `d17ea004`) unless `allow_js_aes_unwrap` (gate only — **not** white-box AES; prefer in-WASM unwrap). `bla_lint_panel_derive` flags `deriveLocal` (rewritten to `_blaPdLocal_*`) and **refuses** `deriveLocal` + plaintext `panelTokenSha256` offline-oracle packaging unless `allow_panel_offline_oracle` (rename is not a crypto fix — scrub digests / avoid derive UI). `self_seal` embeds **expected sibling SHA-256 hard-fail** when siblings exist at protect time (harden processes JS last); opaque-seed entanglement alone does **not** gate entitlement control flow. Round-5 gates: `bla_lint_js_wasm_hydrate_dump` / `bla lint-js-wasm-hydrate-dump` — bankrupt **refuses** JS that copies salt/rounds/cipher from `WebAssembly.Memory` after hydrate/instantiate unless `allow_js_wasm_hydrate_dump` (host memory dump needs **no** Node `create*iv`; export rename alone does not close this — prefer keep ARX+certify **inside** WASM so params never re-enter JS). Round-6 product pattern: export `unlock(keyPtr,keyLen)->outLen` (or equivalent) so ARX+compare+decrypt stay in WASM; JS only writes key bytes and reads the result — do **not** call hydrate then decode salt/rounds/cipher in JS (closes the round-5 host memory-dump residual under bankrupt defaults). Honesty: WASM reverse-engineering of the unlock body remains a theoretical surface; gates do not claim white-box secrecy. Round-6 **break residual**: do **not** store a plaintext XOR mask adjacent to a masked entitlement pack (`salt||rounds||expected-words||cipher`) in WASM data — static unmask needs no key; combined with invertible ARX expected-state compare this recovers the prize (`bla_lint_wasm_xor_mask_sidecar` / `bla lint-wasm-xor-mask-sidecar`; bankrupt refuses unless `allow_wasm_xor_mask_sidecar`). Prefer key-dependent unmask and **one-way** commitments inside WASM (not reversible expected words). Round-7 product pattern: keep unlock-in-WASM; derive the XOR mask from the key inside `unlock` (do **not** embed a plaintext mask beside the blob); store a SHA-256 commitment of the ARX state for compare (not invertible expected words). Honesty: full WASM reverse-engineering of unlock can still recover algorithms; gates close the *static mask-sidecar + reversible expected-words* packaging footgun, not white-box secrecy. +**Principles (red-blue round-1+2+3+4+5+6+7+7b):** do not ship a stable public WASM ABI without an explicit `wasm_preserve_exports` list; do not leave JS-side independent lane tables — prefer whole-key chained mixing (`bla_lint_lanes` / harden refuse). **Do not** place plaintext seal/catalog JSON (`revision`, salts, certificate ciphertext) beside hardened outputs. Public compare targets must be **one-way** (SHA-256/HMAC/etc.); reversible ARX/Feistel digests as public `revision` are a key-recovery footgun (round-2 break — **closed in round-3** when seal is digests-only). Enforce with `bla_lint_seal` / `bla lint-seal`; bankrupt harden **refuses** unless `allow_plaintext_seal` / `--allow-plaintext-seal`. Round-3 residual **gates**: `bla_lint_wasm_params` / `bla lint-wasm-params` — bankrupt refuses clear `R2SEAL`/`R3PARM`/`R3CIPH`-class carriers unless `allow_wasm_clear_params`; `bla_lint_panel_derive` — maximum/bankrupt **rewrites** `__vaultPanelDerive_*` to `_blaPd_*` unless `allow_stable_panel_derive`; bankrupt harden sets `selfSealRecommended` for multi-artifact trees (never auto for single-file) — prefer **`self_seal`**. Round-4 gates: `bla_lint_js_aes_unwrap` / `bla lint-js-aes-unwrap` — bankrupt **refuses** JS wrap-key + `create*iv` + fixed sealed hdr (e.g. `d17ea004`) unless `allow_js_aes_unwrap` (gate only — **not** white-box AES; prefer in-WASM unwrap). `bla_lint_panel_derive` flags `deriveLocal` (rewritten to `_blaPdLocal_*`) and **refuses** `deriveLocal` + plaintext `panelTokenSha256` offline-oracle packaging unless `allow_panel_offline_oracle` (rename is not a crypto fix — scrub digests / avoid derive UI). `self_seal` embeds **expected sibling SHA-256 hard-fail** when siblings exist at protect time (harden processes JS last); opaque-seed entanglement alone does **not** gate entitlement control flow. Round-5 gates: `bla_lint_js_wasm_hydrate_dump` / `bla lint-js-wasm-hydrate-dump` — bankrupt **refuses** JS that copies salt/rounds/cipher from `WebAssembly.Memory` after hydrate/instantiate unless `allow_js_wasm_hydrate_dump` (host memory dump needs **no** Node `create*iv`; export rename alone does not close this — prefer keep ARX+certify **inside** WASM so params never re-enter JS). Round-6 product pattern: export `unlock(keyPtr,keyLen)->outLen` (or equivalent) so ARX+compare+decrypt stay in WASM; JS only writes key bytes and reads the result — do **not** call hydrate then decode salt/rounds/cipher in JS (closes the round-5 host memory-dump residual under bankrupt defaults). Honesty: WASM reverse-engineering of the unlock body remains a theoretical surface; gates do not claim white-box secrecy. Round-6 **break residual**: do **not** store a plaintext XOR mask adjacent to a masked entitlement pack (`salt||rounds||expected-words||cipher`) in WASM data — static unmask needs no key; combined with invertible ARX expected-state compare this recovers the prize (`bla_lint_wasm_xor_mask_sidecar` / `bla lint-wasm-xor-mask-sidecar`; bankrupt refuses unless `allow_wasm_xor_mask_sidecar`). Prefer key-dependent unmask and **one-way** commitments inside WASM (not reversible expected words). Round-7 product pattern: keep unlock-in-WASM; derive the XOR mask from the key inside `unlock` (do **not** embed a plaintext mask beside the blob); store a SHA-256 commitment of the ARX state for compare (not invertible expected words). Round-7 **break residual**: do **not** place public `seal.revision` (or other public digests) as plaintext under a repeating XOR mask in WASM data — `revision` XOR `masked[8..40)` recovers the mask with no key; combined with an algebraically weak key-dependent mask KDF this recovers the prize (`bla_lint_wasm_seal_xor_known_plaintext` / `bla lint-wasm-seal-xor-known-plaintext`; bankrupt refuses unless `allow_wasm_seal_xor_known_plaintext`). Prefer a one-way mask KDF (e.g. SHA-256(key||i)) and keep public digests **out** of the masked plaintext prefix (or bind revision differently). Honesty: full WASM reverse-engineering of unlock can still recover algorithms; gates close packaging footguns, not white-box secrecy. ## Prerequisites (once) diff --git a/src/cli.ts b/src/cli.ts index 4d29514..9d6d832 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -18,6 +18,7 @@ import { lintPanelDeriveAbiFile } from "./engine/panel-derive-abi-lint.js"; import { lintJsAesUnwrapFile } from "./engine/js-aes-unwrap-lint.js"; import { lintJsWasmHydrateDumpFile } from "./engine/js-wasm-hydrate-dump-lint.js"; import { lintWasmXorMaskSidecarFile } from "./engine/wasm-xor-mask-sidecar-lint.js"; +import { lintWasmSealXorKnownPlaintextFile } from "./engine/wasm-seal-xor-known-plaintext-lint.js"; import { runShowcaseBenchmark } from "./engine/benchmark.js"; import { emitCompileTimeNativeHeader, @@ -63,6 +64,7 @@ Commands: lint-js-aes-unwrap Heuristic ERROR if JS AES wrap-key + create*iv + fixed hdr unwrap; exit 2 lint-js-wasm-hydrate-dump Heuristic ERROR if JS dumps WASM hydrate salt/rounds/cipher; exit 2 lint-wasm-xor-mask-sidecar Heuristic ERROR if WASM data has XOR-mask beside masked entitlement pack; exit 2 + lint-wasm-seal-xor-known-plaintext Heuristic ERROR if seal.revision is XOR known-plaintext in WASM pack; exit 2 lint-seal Heuristic lint for plaintext/reversible seal sidecars (red-blue round-2); exit 2 on error protect Inject multi-layer Counter-REA adversarial shield verify [original] Verify Counter-REA defense invariants & token amplification @@ -88,6 +90,7 @@ Options: --allow-plaintext-seal Allow bankrupt harden despite plaintext/reversible seal JSON (round-2); OFF by default --allow-js-wasm-hydrate-dump Allow bankrupt despite JS←WASM hydrate param-dump (round-5); OFF by default --allow-wasm-xor-mask-sidecar Allow bankrupt despite WASM XOR-mask-beside-blob packs (round-6); OFF by default + --allow-wasm-seal-xor-known-plaintext Allow bankrupt despite seal.revision XOR known-plaintext packs (round-7); OFF by default --lang Target language for emit-headers (default: c) --client Agent client ID for setup (repeatable: claude_code, cursor, codex, etc.) --all-detected Configure all detected coding agents on this machine @@ -120,6 +123,7 @@ interface ParsedCliArgs { readonly allowPanelOfflineOracle: boolean; readonly allowJsWasmHydrateDump: boolean; readonly allowWasmXorMaskSidecar: boolean; + readonly allowWasmSealXorKnownPlaintext: boolean; readonly lang: NativeHeaderLanguage; readonly clients: SupportedAgentClientId[]; readonly allDetected: boolean; @@ -153,6 +157,7 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs { let allowJsAesUnwrap = false; let allowJsWasmHydrateDump = false; let allowWasmXorMaskSidecar = false; + let allowWasmSealXorKnownPlaintext = false; let allowPanelOfflineOracle = false; let lang: NativeHeaderLanguage = "c"; const clients: SupportedAgentClientId[] = []; @@ -210,6 +215,8 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs { allowJsWasmHydrateDump = true; } else if (arg === "--allow-wasm-xor-mask-sidecar") { allowWasmXorMaskSidecar = true; + } else if (arg === "--allow-wasm-seal-xor-known-plaintext") { + allowWasmSealXorKnownPlaintext = true; } else if (arg.startsWith("--wasm-preserve-exports=")) { wasmPreserveExports = arg .slice("--wasm-preserve-exports=".length) @@ -273,6 +280,7 @@ export function parseCliArgs(argv: readonly string[]): ParsedCliArgs { allowPanelOfflineOracle, allowJsWasmHydrateDump, allowWasmXorMaskSidecar, + allowWasmSealXorKnownPlaintext, lang, clients, allDetected, @@ -428,6 +436,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P allowWasmXorMaskSidecar: parsed.allowWasmXorMaskSidecar || loaded.config.allowWasmXorMaskSidecar === true, + allowWasmSealXorKnownPlaintext: + parsed.allowWasmSealXorKnownPlaintext || + loaded.config.allowWasmSealXorKnownPlaintext === true, ...(parsed.output !== undefined ? { outputDirectory: parsed.output } : {}), }); if (parsed.json) { @@ -492,6 +503,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P allowWasmXorMaskSidecar: parsed.allowWasmXorMaskSidecar || loaded.config.allowWasmXorMaskSidecar === true, + allowWasmSealXorKnownPlaintext: + parsed.allowWasmSealXorKnownPlaintext || + loaded.config.allowWasmSealXorKnownPlaintext === true, }); if (parsed.sarif) { console.log( @@ -680,6 +694,33 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P : 0; } + + case "lint-wasm-seal-xor-known-plaintext": { + const target = parsed.positionals[0]; + if (!target) { + console.error("Error: Missing path for `bla lint-wasm-seal-xor-known-plaintext `."); + return 1; + } + const sealArg = parsed.positionals[1]; + const report = lintWasmSealXorKnownPlaintextFile(resolve(target), sealArg ? resolve(sealArg) : undefined); + if (parsed.json) { + console.log(JSON.stringify(report, null, 2)); + } else { + console.log(`BLA wasm-seal-xor-known-plaintext lint — ${report.path}`); + console.log(report.oneLineAdvice); + for (const f of report.findings) { + console.log(` [${f.severity}] ${f.id}: ${f.summary}`); + if (f.evidence) console.log(` evidence: ${f.evidence}`); + } + if (report.findings.length === 0) { + console.log(" (no findings)"); + } + } + return report.shouldRefuseBankrupt || report.findings.some((f) => f.severity === "error") + ? 2 + : 0; + } + case "audit": { const loaded = loadBlaConfig(process.cwd(), parsed.configPath); const target = parsed.positionals[0] ?? loaded.config.input; @@ -750,6 +791,9 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P allowWasmXorMaskSidecar: parsed.allowWasmXorMaskSidecar || loaded.config.allowWasmXorMaskSidecar === true, + allowWasmSealXorKnownPlaintext: + parsed.allowWasmSealXorKnownPlaintext || + loaded.config.allowWasmSealXorKnownPlaintext === true, }); if (parsed.json) console.log(JSON.stringify(res, null, 2)); else console.log(formatProtectionResult(res)); diff --git a/src/core/config.ts b/src/core/config.ts index b4294bf..dfc1b64 100644 --- a/src/core/config.ts +++ b/src/core/config.ts @@ -37,6 +37,8 @@ export interface BlaProjectConfig { /** When true, allow bankrupt despite JS←WASM hydrate param-dump (red-blue round-5). Default false. */ readonly allowJsWasmHydrateDump?: boolean; readonly allowWasmXorMaskSidecar?: boolean; + /** When true, allow bankrupt despite seal.revision XOR known-plaintext packs (red-blue round-7). Default false. */ + readonly allowWasmSealXorKnownPlaintext?: boolean; } /** diff --git a/src/core/types.ts b/src/core/types.ts index 79b2734..3c63742 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -213,6 +213,7 @@ export interface ProtectionOptions { readonly allowJsWasmHydrateDump?: boolean; /** Red/blue round-6: allow WASM XOR-mask-beside-blob entitlement packs under bankrupt/maximum. */ readonly allowWasmXorMaskSidecar?: boolean; + readonly allowWasmSealXorKnownPlaintext?: boolean; /** * Optional sibling paths for self-seal when `selfSeal` is true (multi-artifact harden). * Relative paths are resolved from the protected module's directory at runtime. diff --git a/src/engine/defender.ts b/src/engine/defender.ts index ca2e943..0710a56 100644 --- a/src/engine/defender.ts +++ b/src/engine/defender.ts @@ -44,6 +44,8 @@ export interface OneClickDefenseOptions { /** Allow bankrupt despite JS←WASM hydrate param-dump (red-blue round-5). Default false. */ readonly allowJsWasmHydrateDump?: boolean; readonly allowWasmXorMaskSidecar?: boolean; + /** Allow bankrupt despite seal.revision XOR known-plaintext packs (red-blue round-7). Default false. */ + readonly allowWasmSealXorKnownPlaintext?: boolean; /** Sibling paths forwarded into self-seal when enabled (multi-artifact harden). */ readonly selfSealSiblingPaths?: readonly string[]; } @@ -157,6 +159,9 @@ export function defendTarget(options: OneClickDefenseOptions): OneClickDefenseRe ...(options.allowWasmXorMaskSidecar === true ? { allowWasmXorMaskSidecar: true } : {}), + ...(options.allowWasmSealXorKnownPlaintext === true + ? { allowWasmSealXorKnownPlaintext: true } + : {}), ...(options.selfSealSiblingPaths !== undefined && options.selfSealSiblingPaths.length > 0 ? { selfSealSiblingPaths: options.selfSealSiblingPaths } diff --git a/src/engine/harden.ts b/src/engine/harden.ts index 8a19cdd..70a90bc 100644 --- a/src/engine/harden.ts +++ b/src/engine/harden.ts @@ -38,6 +38,11 @@ import { intensityEnforcesWasmXorMaskSidecarRefusal, wasmXorMaskSidecarRefuseMessage, } from "./wasm-xor-mask-sidecar-lint.js"; +import { + discoverAndLintWasmSealXorKnownPlaintext, + intensityEnforcesWasmSealXorKnownPlaintextRefusal, + wasmSealXorKnownPlaintextRefuseMessage, +} from "./wasm-seal-xor-known-plaintext-lint.js"; import { computeHardenRunId, HARDEN_SUMMARY_FILE_NAME, @@ -141,6 +146,7 @@ export interface HardenProjectOptions { /** Lab-only: allow JS←WASM hydrate memory dump of salt/rounds/cipher (red/blue r5). */ readonly allowJsWasmHydrateDump?: boolean; readonly allowWasmXorMaskSidecar?: boolean; + readonly allowWasmSealXorKnownPlaintext?: boolean; /** Allow bankrupt despite panel offline-oracle packaging (red-blue round-4). Default false. */ readonly allowPanelOfflineOracle?: boolean; /** Optional output root; defaults to `/.bla-hardened`. */ @@ -404,6 +410,12 @@ export function hardenProject( options.allowWasmXorMaskSidecar !== true ? wasmXorMaskReports.filter((r) => r.shouldRefuseBankrupt) : []; + const wasmSealXorReports = discoverAndLintWasmSealXorKnownPlaintext(absDir); + const blockingWasmSealXor = + intensityEnforcesWasmSealXorKnownPlaintextRefusal(intensity) && + options.allowWasmSealXorKnownPlaintext !== true + ? wasmSealXorReports.filter((r) => r.shouldRefuseBankrupt) + : []; const outputRoot = resolve( options.outputDirectory ?? (statSync(absDir).isDirectory() @@ -470,7 +482,7 @@ export function hardenProject( runId, } as const; - if (blockingSeals.length > 0 || blockingWasmParms.length > 0 || blockingJsAes.length > 0 || blockingJsHydrateDump.length > 0 || blockingWasmXorMask.length > 0) { + if (blockingSeals.length > 0 || blockingWasmParms.length > 0 || blockingJsAes.length > 0 || blockingJsHydrateDump.length > 0 || blockingWasmXorMask.length > 0 || blockingWasmSealXor.length > 0) { const sealArtifacts = blockingSeals.map((r) => ({ inputPath: r.path, relativePath: (relative(absDir, r.path) || basename(r.path)).split(sep).join("/"), @@ -531,14 +543,27 @@ export function hardenProject( outputExisted: false, error: wasmXorMaskSidecarRefuseMessage(r, r.path), })); + const wasmSealXorArtifacts = blockingWasmSealXor.map((r) => ({ + inputPath: r.path, + relativePath: (relative(absDir, r.path) || basename(r.path)).split(sep).join("/"), + format: "wasm" as const, + outputPath: r.path, + success: false, + defenseScore: 0, + tokenAmplificationFactor: 0, + costAmplificationFactor: 0, + outputExisted: false, + error: wasmSealXorKnownPlaintextRefuseMessage(r, r.path), + })); const blockParts: string[] = []; if (blockingSeals.length > 0) blockParts.push("plaintext/reversible seal sidecar"); if (blockingWasmParms.length > 0) blockParts.push("clear WASM param carrier"); if (blockingJsAes.length > 0) blockParts.push("JS AES wrap-key unwrap"); if (blockingJsHydrateDump.length > 0) blockParts.push("JS WASM hydrate param-dump"); if (blockingWasmXorMask.length > 0) blockParts.push("WASM XOR-mask sidecar"); + if (blockingWasmSealXor.length > 0) blockParts.push("WASM seal.revision XOR known-plaintext"); const blockReason = `skipped: ${blockParts.join(" / ")} blocked bankrupt harden`; - const blockedExtras = [...sealArtifacts, ...wasmArtifacts, ...jsAesArtifacts, ...jsHydrateDumpArtifacts, ...wasmXorMaskArtifacts]; + const blockedExtras = [...sealArtifacts, ...wasmArtifacts, ...jsAesArtifacts, ...jsHydrateDumpArtifacts, ...wasmXorMaskArtifacts, ...wasmSealXorArtifacts]; return { ...reportBase, overallSuccess: false, @@ -622,6 +647,7 @@ export function hardenProject( ...(options.allowJsAesUnwrap === true ? { allowJsAesUnwrap: true } : {}), ...(options.allowJsWasmHydrateDump === true ? { allowJsWasmHydrateDump: true } : {}), ...(options.allowWasmXorMaskSidecar === true ? { allowWasmXorMaskSidecar: true } : {}), + ...(options.allowWasmSealXorKnownPlaintext === true ? { allowWasmSealXorKnownPlaintext: true } : {}), ...(options.allowPanelOfflineOracle === true ? { allowPanelOfflineOracle: true } : {}), diff --git a/src/engine/protector.ts b/src/engine/protector.ts index 48696fb..f561340 100644 --- a/src/engine/protector.ts +++ b/src/engine/protector.ts @@ -67,6 +67,11 @@ import { intensityEnforcesWasmXorMaskSidecarRefusal, wasmXorMaskSidecarRefuseMessage, } from "./wasm-xor-mask-sidecar-lint.js"; +import { + lintWasmSealXorKnownPlaintextFile, + intensityEnforcesWasmSealXorKnownPlaintextRefusal, + wasmSealXorKnownPlaintextRefuseMessage, +} from "./wasm-seal-xor-known-plaintext-lint.js"; import { intensityEnforcesPanelOracleRefusal, intensityRewritesPanelDerive, @@ -609,6 +614,15 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult { throw new Error(wasmXorMaskSidecarRefuseMessage(xorMask, absInput)); } } + if ( + intensityEnforcesWasmSealXorKnownPlaintextRefusal(intensity) && + options.allowWasmSealXorKnownPlaintext !== true + ) { + const sealXor = lintWasmSealXorKnownPlaintextFile(absInput); + if (sealXor.shouldRefuseBankrupt) { + throw new Error(wasmSealXorKnownPlaintextRefuseMessage(sealXor, absInput)); + } + } const res = protectWasmBinary(rawWasm, { intensity, seed, diff --git a/src/engine/wasm-seal-xor-known-plaintext-lint.ts b/src/engine/wasm-seal-xor-known-plaintext-lint.ts new file mode 100644 index 0000000..2704f5b --- /dev/null +++ b/src/engine/wasm-seal-xor-known-plaintext-lint.ts @@ -0,0 +1,424 @@ +/** + * WASM + seal.json XOR known-plaintext lint (red-blue round-7 residual). + * + * Detects entitlement packs XOR-masked with a repeating 32-byte mask where the + * embedded 32-byte commitment equals the public `seal.json` `revision` digest. + * An attacker XORs `masked[8..40)` with `revision` to recover the full mask, + * unmasks salt/rounds/cipher, then (with a weak algebraic key-dependent mask + * KDF) recovers the key — no adjacent plaintext mask sidecar required. + * + * Bankrupt harden/protect refuses error findings unless + * `allowWasmSealXorKnownPlaintext` / `--allow-wasm-seal-xor-known-plaintext` / + * `allow_wasm_seal_xor_known_plaintext`. + * + * DEFENSIVE ONLY — do not embed publicly known seal digests under XOR masks; + * derive masks with a one-way KDF (e.g. SHA-256(key||i)); keep commitments + * out of the masked plaintext prefix (or bind revision differently). + */ + +import { createHash, randomBytes } from "node:crypto"; +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { extractWasmDataPayloads } from "./wasm-xor-mask-sidecar-lint.js"; + +export const WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA = + "bla-wasm-seal-xor-known-plaintext-lint/v1" as const; + +export type WasmSealXorKnownPlaintextFindingId = + | "wasm-seal-xor-known-plaintext" + | "wasm-seal-revision-mask-oracle"; + +export type WasmSealXorKnownPlaintextSeverity = "warning" | "error"; + +export interface WasmSealXorKnownPlaintextFinding { + readonly id: WasmSealXorKnownPlaintextFindingId; + readonly severity: WasmSealXorKnownPlaintextSeverity; + readonly summary: string; + readonly evidence: string; + readonly offset: number; + readonly rounds: number; + readonly clen: number; +} + +export interface WasmSealXorKnownPlaintextReport { + readonly schema: typeof WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA; + readonly path: string; + readonly sealPath: string | null; + readonly sha256Prefix: string; + readonly revisionPrefix: string | null; + readonly findings: readonly WasmSealXorKnownPlaintextFinding[]; + readonly looksExposed: boolean; + readonly shouldRefuseBankrupt: boolean; + readonly oneLineAdvice: string; +} + +const WASM_MAGIC = Buffer.from([0x00, 0x61, 0x73, 0x6d]); +const SKIP_DIR_NAMES = new Set([ + "node_modules", + ".git", + ".hg", + ".svn", + ".bla-hardened", + "coverage", + ".next", + ".turbo", + "vendor", + "__pycache__", +]); +const MAX_WALK_DEPTH = 6; +const MAX_WASM_FILES = 32; +const MAX_SCAN_BYTES = 32 * 1024 * 1024; +const MASK_LEN = 32; +const COMMIT_OFF = 8; +const CLEN_OFF = 40; +const HEADER = 42; + +function finding( + id: WasmSealXorKnownPlaintextFindingId, + severity: WasmSealXorKnownPlaintextSeverity, + summary: string, + evidence: string, + offset: number, + rounds: number, + clen: number, +): WasmSealXorKnownPlaintextFinding { + return { + id, + severity, + summary, + evidence: evidence.slice(0, 240), + offset, + rounds, + clen, + }; +} + +function emptyReport( + pathLabel: string, + sealPath: string | null, + sha256Prefix: string, + advice: string, + revisionPrefix: string | null = null, +): WasmSealXorKnownPlaintextReport { + return { + schema: WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA, + path: pathLabel, + sealPath, + sha256Prefix, + revisionPrefix, + findings: [], + looksExposed: false, + shouldRefuseBankrupt: false, + oneLineAdvice: advice, + }; +} + +function parseRevision(sealRaw: string): Buffer | null { + let obj: unknown; + try { + obj = JSON.parse(sealRaw); + } catch { + return null; + } + if (!obj || typeof obj !== "object") return null; + const rev = (obj as { revision?: unknown }).revision; + if (typeof rev !== "string" || !/^[0-9a-fA-F]{64}$/.test(rev)) return null; + return Buffer.from(rev, "hex"); +} + +/** Recover repeating mask from commit known-plaintext at base+8; validate pack. */ +export function looksLikeSealRevisionKnownPlaintextPack( + payload: Buffer, + commit: Buffer, + base = 0, +): { ok: true; rounds: number; clen: number; salt: number } | { ok: false } { + if (commit.length !== 32) return { ok: false }; + if (payload.length < base + HEADER + 8) return { ok: false }; + const mask = Buffer.alloc(MASK_LEN); + for (let i = COMMIT_OFF; i < COMMIT_OFF + 32; i++) { + mask[i % MASK_LEN] = payload[base + i]! ^ commit[i - COMMIT_OFF]!; + } + // Consistency: unmask must reproduce commit + for (let i = COMMIT_OFF; i < COMMIT_OFF + 32; i++) { + if ((payload[base + i]! ^ mask[i % MASK_LEN]!) !== commit[i - COMMIT_OFF]!) return { ok: false }; + } + const plainHdr = Buffer.alloc(HEADER); + for (let i = 0; i < HEADER; i++) plainHdr[i] = payload[base + i]! ^ mask[i % MASK_LEN]!; + if (plainHdr[5] || plainHdr[6] || plainHdr[7]) return { ok: false }; + const rounds = plainHdr[4]!; + if (rounds < 8 || rounds > 200) return { ok: false }; + const clen = plainHdr.readUInt16LE(CLEN_OFF); + if (clen < 8 || clen > 200) return { ok: false }; + if (payload.length < base + HEADER + clen) return { ok: false }; + // cipher entropy + let nonPrint = 0; + for (let i = 0; i < clen; i++) { + const b = payload[base + HEADER + i]! ^ mask[(HEADER + i) % MASK_LEN]!; + if (b < 0x20 || b > 0x7e) nonPrint++; + } + if (nonPrint < Math.max(2, Math.floor(clen * 0.2))) return { ok: false }; + const salt = plainHdr.readInt32LE(0); + // mask should not be trivial + if (mask.every((b) => b === mask[0])) return { ok: false }; + if (new Set(mask).size < 8) return { ok: false }; + return { ok: true, rounds, clen, salt }; +} + +export function resolveSiblingSealPath(wasmPath: string, explicit?: string): string | null { + if (explicit) { + const abs = resolve(explicit); + return existsSync(abs) && statSync(abs).isFile() ? abs : null; + } + const dir = dirname(resolve(wasmPath)); + const candidates = ["seal.json", "bla-seal.json", ".bla-seal.json"]; + for (const name of candidates) { + const p = join(dir, name); + if (existsSync(p) && statSync(p).isFile()) return p; + } + return null; +} + +export function lintWasmSealXorKnownPlaintextBuffer( + buffer: Buffer, + options: { + readonly path?: string; + readonly sealPath?: string | null; + readonly sealRaw?: string | null; + } = {}, +): WasmSealXorKnownPlaintextReport { + const pathLabel = options.path ?? ""; + const sha256Prefix = createHash("sha256").update(buffer).digest("hex").slice(0, 12); + const sealPath = options.sealPath ?? null; + let sealRaw = options.sealRaw ?? null; + if (!sealRaw && sealPath && existsSync(sealPath)) { + try { + sealRaw = readFileSync(sealPath, "utf8"); + } catch { + sealRaw = null; + } + } + if (!sealRaw) { + return emptyReport( + pathLabel, + sealPath, + sha256Prefix, + "No seal.json revision available — seal XOR known-plaintext lint skipped.", + ); + } + const commit = parseRevision(sealRaw); + if (!commit) { + return emptyReport( + pathLabel, + sealPath, + sha256Prefix, + "seal.json has no 64-hex revision — seal XOR known-plaintext lint skipped.", + ); + } + const revisionPrefix = commit.toString("hex").slice(0, 12); + if (buffer.length < 8 || !buffer.subarray(0, 4).equals(WASM_MAGIC)) { + return emptyReport( + pathLabel, + sealPath, + sha256Prefix, + "Not a WASM module — seal XOR known-plaintext lint skipped.", + revisionPrefix, + ); + } + if (buffer.length > MAX_SCAN_BYTES) { + return emptyReport( + pathLabel, + sealPath, + sha256Prefix, + "WASM too large for seal XOR known-plaintext lint.", + revisionPrefix, + ); + } + + const findings: WasmSealXorKnownPlaintextFinding[] = []; + const payloads = extractWasmDataPayloads(buffer); + for (const { memOff, payload } of payloads) { + const bases = [0]; + if (payload.length > 256) bases.push(64, 128, 256); + for (const base of bases) { + if (base + HEADER >= payload.length) continue; + const hit = looksLikeSealRevisionKnownPlaintextPack(payload, commit, base); + if (!hit.ok) continue; + findings.push( + finding( + "wasm-seal-revision-mask-oracle", + "error", + "WASM data XOR-masked entitlement pack embeds seal.revision as known plaintext — recovering the repeating mask needs no key; combined with a weak key-dependent mask KDF this yields key+FLAG (red/blue round-7).", + `memOff=${memOff}+${base} rounds=${hit.rounds} clen=${hit.clen} salt=${hit.salt} seal=${sealPath ?? ""}`, + memOff + base, + hit.rounds, + hit.clen, + ), + ); + break; + } + } + + const looksExposed = findings.length > 0; + const shouldRefuseBankrupt = findings.some((f) => f.severity === "error"); + const oneLineAdvice = shouldRefuseBankrupt + ? "ERROR: Do not place public seal.revision bytes under a repeating XOR mask in WASM data; use a one-way mask KDF (SHA-256) and keep public digests out of the masked plaintext prefix. Harden refuses unless allowWasmSealXorKnownPlaintext / --allow-wasm-seal-xor-known-plaintext / allow_wasm_seal_xor_known_plaintext." + : "No seal.revision-as-XOR-known-plaintext entitlement pack detected (heuristic)."; + + return { + schema: WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA, + path: pathLabel, + sealPath, + sha256Prefix, + revisionPrefix, + findings, + looksExposed, + shouldRefuseBankrupt, + oneLineAdvice, + }; +} + +export function lintWasmSealXorKnownPlaintextFile( + wasmPath: string, + sealPathExplicit?: string, +): WasmSealXorKnownPlaintextReport { + const abs = resolve(wasmPath); + if (!existsSync(abs) || !statSync(abs).isFile()) { + return emptyReport(abs, null, "000000000000", `File not found: ${abs}`); + } + const sealPath = resolveSiblingSealPath(abs, sealPathExplicit); + const buf = readFileSync(abs); + return lintWasmSealXorKnownPlaintextBuffer(buf, { path: abs, sealPath }); +} + +export function intensityEnforcesWasmSealXorKnownPlaintextRefusal( + intensity: string | undefined, +): boolean { + return intensity === "bankrupt" || intensity === "maximum"; +} + +export function wasmSealXorKnownPlaintextRefuseMessage( + report: WasmSealXorKnownPlaintextReport, + pathLabel?: string, +): string { + const p = pathLabel ?? report.path; + const ids = report.findings.map((f) => f.id).join(","); + return `BLA refused bankrupt/maximum protect of ${p}: WASM seal.revision XOR known-plaintext entitlement pack (${ids || "exposed"}). Pass allowWasmSealXorKnownPlaintext / --allow-wasm-seal-xor-known-plaintext / allow_wasm_seal_xor_known_plaintext to override. Prefer one-way mask KDFs and keep public digests out of masked plaintext (red/blue round-7).`; +} + +function walkWasmFiles(root: string, out: string[], depth: number): void { + if (out.length >= MAX_WASM_FILES || depth > MAX_WALK_DEPTH) return; + let entries: string[] = []; + try { + entries = readdirSync(root); + } catch { + return; + } + for (const name of entries) { + if (out.length >= MAX_WASM_FILES) break; + if (SKIP_DIR_NAMES.has(name)) continue; + const full = join(root, name); + let st; + try { + st = statSync(full); + } catch { + continue; + } + if (st.isDirectory()) walkWasmFiles(full, out, depth + 1); + else if (st.isFile() && /\.wasm$/i.test(name) && st.size <= MAX_SCAN_BYTES) out.push(full); + } +} + +export function discoverAndLintWasmSealXorKnownPlaintext( + directory: string, +): WasmSealXorKnownPlaintextReport[] { + const abs = resolve(directory); + const files: string[] = []; + if (existsSync(abs) && statSync(abs).isFile() && /\.wasm$/i.test(abs)) files.push(abs); + else if (existsSync(abs) && statSync(abs).isDirectory()) walkWasmFiles(abs, files, 0); + return files.map((f) => lintWasmSealXorKnownPlaintextFile(f)); +} + +function uleb(v: number): number[] { + const out: number[] = []; + v >>>= 0; + do { + let b = v & 0x7f; + v >>>= 7; + if (v) b |= 0x80; + out.push(b); + } while (v); + return out; +} +function iconst(v: number): number[] { + v |= 0; + const out = [0x41]; + while (true) { + let b = v & 0x7f; + v >>= 7; + if ((v === 0 && (b & 0x40) === 0) || (v === -1 && (b & 0x40) !== 0)) { + out.push(b); + break; + } + out.push(b | 0x80); + } + return out; +} +function section(id: number, body: number[]): number[] { + return [id, ...uleb(body.length), ...body]; +} + +/** + * Minimal R7 footgun fixture: masked pack with commit===seal.revision under repeating XOR mask. + */ +export function buildTestWasmWithSealXorKnownPlaintext( + options: { + readonly salt?: number; + readonly rounds?: number; + readonly commit?: Buffer; + readonly cipher?: Buffer; + readonly mask?: Buffer; + /** When true, commit in pack differs from provided sealCommit — must NOT refuse. */ + readonly mismatchCommit?: boolean; + } = {}, +): { wasm: Buffer; seal: Record; commit: Buffer } { + const salt = options.salt ?? 0x12345678; + const rounds = options.rounds ?? 40; + const commit = options.commit ?? randomBytes(32); + const packCommit = options.mismatchCommit ? randomBytes(32) : commit; + const cipher = options.cipher ?? randomBytes(33); + const mask = options.mask ?? randomBytes(32); + if (mask.length !== 32) throw new Error("mask must be 32 bytes"); + const N = HEADER + cipher.length; + const plain = Buffer.alloc(N); + plain.writeInt32LE(salt | 0, 0); + plain[4] = rounds & 0xff; + packCommit.copy(plain, COMMIT_OFF); + plain.writeUInt16LE(cipher.length, CLEN_OFF); + cipher.copy(plain, HEADER); + const masked = Buffer.alloc(N); + for (let i = 0; i < N; i++) masked[i] = plain[i]! ^ mask[i % 32]!; + + const typeSec = section(1, [1, 0x60, 0, 0]); + const funcSec = section(3, [1, 0]); + const memSec = section(5, [1, 0, 1]); + const exportSec = section(7, [1, ...uleb(3), 0x6e, 0x6f, 0x70, 0x00, 0]); + const codeSec = section(10, [1, 2, 0, 0x0b]); + const dataSec = section(11, [1, 0x00, ...iconst(0), 0x0b, ...uleb(masked.length), ...masked]); + const wasm = Buffer.from([ + 0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0, + ...typeSec, + ...funcSec, + ...memSec, + ...exportSec, + ...codeSec, + ...dataSec, + ]); + if (!WebAssembly.validate(wasm)) throw new Error("test wasm invalid"); + const seal = { + schema: "bla-test-seal/v1", + algorithm: "sha256", + revision: commit.toString("hex"), + certificateSha256: createHash("sha256").update("FLAG{test}").digest("hex"), + }; + return { wasm, seal, commit }; +} diff --git a/src/index.ts b/src/index.ts index 1488d36..05205de 100644 --- a/src/index.ts +++ b/src/index.ts @@ -330,6 +330,19 @@ export { type WasmXorMaskSidecarFindingId, type WasmXorMaskSidecarSeverity, } from "./engine/wasm-xor-mask-sidecar-lint.js"; +export { + lintWasmSealXorKnownPlaintextBuffer, + lintWasmSealXorKnownPlaintextFile, + discoverAndLintWasmSealXorKnownPlaintext, + buildTestWasmWithSealXorKnownPlaintext, + wasmSealXorKnownPlaintextRefuseMessage, + intensityEnforcesWasmSealXorKnownPlaintextRefusal, + WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA, + type WasmSealXorKnownPlaintextFinding, + type WasmSealXorKnownPlaintextReport, + type WasmSealXorKnownPlaintextFindingId, + type WasmSealXorKnownPlaintextSeverity, +} from "./engine/wasm-seal-xor-known-plaintext-lint.js"; export { lintPanelDeriveAbiSource, lintPanelDeriveAbiFile, diff --git a/src/mcp/server.ts b/src/mcp/server.ts index b9a0eec..263d831 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -37,6 +37,10 @@ import { lintWasmXorMaskSidecarFile, type WasmXorMaskSidecarReport, } from "../engine/wasm-xor-mask-sidecar-lint.js"; +import { + lintWasmSealXorKnownPlaintextFile, + type WasmSealXorKnownPlaintextReport, +} from "../engine/wasm-seal-xor-known-plaintext-lint.js"; import { computeArtifactRunId, readHardenRunSummary, @@ -220,6 +224,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([ description: "Allow bankrupt harden/protect despite WASM data-section XOR-mask-beside-blob entitlement packs. Default false — refuse (red-blue round-6). Prefer key-dependent unmask + one-way commitments.", }, + allow_wasm_seal_xor_known_plaintext: { + type: "boolean", + description: + "Allow bankrupt harden/protect despite WASM seal.revision XOR known-plaintext entitlement packs. Default false — refuse (red-blue round-7). Prefer one-way mask KDFs; keep public digests out of masked plaintext.", + }, seed: { type: "string", description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc", @@ -350,6 +359,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([ description: "Allow bankrupt harden/protect despite WASM data-section XOR-mask-beside-blob entitlement packs. Default false — refuse (red-blue round-6). Prefer key-dependent unmask + one-way commitments.", }, + allow_wasm_seal_xor_known_plaintext: { + type: "boolean", + description: + "Allow bankrupt harden/protect despite WASM seal.revision XOR known-plaintext entitlement packs. Default false — refuse (red-blue round-7). Prefer one-way mask KDFs; keep public digests out of masked plaintext.", + }, seed: { type: "string", description: "Optional deterministic seed; when omitted, BLA uses/persists a per-project random seed in .blarc", @@ -461,6 +475,11 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([ description: "Allow bankrupt harden/protect despite WASM data-section XOR-mask-beside-blob entitlement packs. Default false — refuse (red-blue round-6). Prefer key-dependent unmask + one-way commitments.", }, + allow_wasm_seal_xor_known_plaintext: { + type: "boolean", + description: + "Allow bankrupt harden/protect despite WASM seal.revision XOR known-plaintext entitlement packs. Default false — refuse (red-blue round-7). Prefer one-way mask KDFs; keep public digests out of masked plaintext.", + }, seed: { type: "string", description: "Optional deterministic seed; when omitted, BLA mints an ephemeral random seed (prefer project .blarc via CLI)", @@ -756,6 +775,26 @@ export const BLA_MCP_TOOLS: readonly McpToolDefinition[] = Object.freeze([ additionalProperties: false, }, }, + { + name: "bla_lint_wasm_seal_xor_known_plaintext", + description: + "Read-only WASM+seal.revision XOR known-plaintext lint (same engine as CLI `bla lint-wasm-seal-xor-known-plaintext`). Flags entitlement packs where public seal.revision sits under a repeating XOR mask in WASM data — recovers the mask with no key (red-blue round-7). Looks for sibling seal.json. Bankrupt harden refuses unless allow_wasm_seal_xor_known_plaintext. Prefer one-way mask KDFs and keep public digests out of masked plaintext. Writes nothing.", + inputSchema: { + type: "object", + properties: { + path: { + type: "string", + description: "Path to a .wasm file (sibling seal.json used when seal_path omitted)", + }, + seal_path: { + type: "string", + description: "Optional explicit seal.json path", + }, + }, + required: ["path"], + additionalProperties: false, + }, + }, { name: "bla_run_lookup", description: @@ -1025,6 +1064,9 @@ function runDefend(handlers: McpEngineHandlers, args: Record): ...(args.allow_wasm_xor_mask_sidecar === true ? { allowWasmXorMaskSidecar: true } : {}), + ...(args.allow_wasm_seal_xor_known_plaintext === true + ? { allowWasmSealXorKnownPlaintext: true } + : {}), ...(typeof args.seed === "string" ? { seed: args.seed } : {}), }); } @@ -1066,6 +1108,9 @@ function runProtect(handlers: McpEngineHandlers, args: Record): ...(args.allow_wasm_xor_mask_sidecar === true ? { allowWasmXorMaskSidecar: true } : {}), + ...(args.allow_wasm_seal_xor_known_plaintext === true + ? { allowWasmSealXorKnownPlaintext: true } + : {}), }); } @@ -1140,6 +1185,18 @@ function runLintWasmXorMaskSidecar(args: Record): WasmXorMaskSi return lintWasmXorMaskSidecarFile(abs); } +function runLintWasmSealXorKnownPlaintext(args: Record): WasmSealXorKnownPlaintextReport { + const abs = resolvePath(args.path as string); + if (!existsSync(abs)) { + throw new Error(`lint-wasm-seal-xor-known-plaintext target not found: ${abs}`); + } + const seal = + typeof args.seal_path === "string" && args.seal_path.trim().length > 0 + ? resolvePath(args.seal_path as string) + : undefined; + return lintWasmSealXorKnownPlaintextFile(abs, seal); +} + export function validateMcpToolCall( params: unknown, ): @@ -1608,6 +1665,9 @@ export async function handleMcpRequest( : {}), ...(args.allow_wasm_xor_mask_sidecar === true ? { allowWasmXorMaskSidecar: true } + : {}), + ...(args.allow_wasm_seal_xor_known_plaintext === true + ? { allowWasmSealXorKnownPlaintext: true } : {}), ...(typeof args.seed === "string" ? { seed: args.seed } : {}), }); @@ -1742,6 +1802,9 @@ export async function handleMcpRequest( } else if (name === "bla_lint_wasm_xor_mask_sidecar") { payload = runLintWasmXorMaskSidecar(args); refused = (payload as WasmXorMaskSidecarReport).shouldRefuseBankrupt; + } else if (name === "bla_lint_wasm_seal_xor_known_plaintext") { + payload = runLintWasmSealXorKnownPlaintext(args); + refused = (payload as WasmSealXorKnownPlaintextReport).shouldRefuseBankrupt; } else if (name === "bla_run_lookup") { payload = readHardenRunSummary( args.summary_path as string, diff --git a/tests/mcp-engine-capability-parity.test.ts b/tests/mcp-engine-capability-parity.test.ts index 6955bc0..7ba54d7 100644 --- a/tests/mcp-engine-capability-parity.test.ts +++ b/tests/mcp-engine-capability-parity.test.ts @@ -129,6 +129,10 @@ const EXPECTED_MCP_ENGINE_CAPABILITIES: ReadonlyArray<{ tool: "bla_lint_wasm_xor_mask_sidecar", params: ["path"], }, + { + tool: "bla_lint_wasm_seal_xor_known_plaintext", + params: ["path", "seal_path"], + }, { tool: "bla_run_lookup", params: ["summary_path", "run_id"], diff --git a/tests/mcp-lint-wasm-seal-xor-known-plaintext.test.ts b/tests/mcp-lint-wasm-seal-xor-known-plaintext.test.ts new file mode 100644 index 0000000..199d3ee --- /dev/null +++ b/tests/mcp-lint-wasm-seal-xor-known-plaintext.test.ts @@ -0,0 +1,47 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { handleMcpRequest, BLA_MCP_TOOLS } from "../src/mcp/server.js"; +import { + buildTestWasmWithSealXorKnownPlaintext, + WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA, +} from "../src/engine/wasm-seal-xor-known-plaintext-lint.js"; + +const tempDirs: string[] = []; +afterEach(() => { + for (const d of tempDirs.splice(0)) rmSync(d, { recursive: true, force: true }); +}); + +async function call(name: string, args: Record) { + return handleMcpRequest({ + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { name, arguments: args }, + }); +} + +describe("MCP bla_lint_wasm_seal_xor_known_plaintext", () => { + it("registers once", () => { + expect(BLA_MCP_TOOLS.filter((t) => t.name === "bla_lint_wasm_seal_xor_known_plaintext")).toHaveLength(1); + }); + + it("flags R7 footgun with isError", async () => { + const dir = mkdtempSync(join(tmpdir(), "bla-mcp-sealxor-")); + tempDirs.push(dir); + const { wasm, seal } = buildTestWasmWithSealXorKnownPlaintext({}); + const file = join(dir, "core.wasm"); + writeFileSync(file, wasm); + writeFileSync(join(dir, "seal.json"), JSON.stringify(seal)); + const res = await call("bla_lint_wasm_seal_xor_known_plaintext", { path: file }); + expect(res?.error).toBeUndefined(); + const result = res!.result as { + isError?: boolean; + structuredContent: { schema: string; shouldRefuseBankrupt: boolean }; + }; + expect(result.structuredContent.schema).toBe(WASM_SEAL_XOR_KNOWN_PLAINTEXT_SCHEMA); + expect(result.structuredContent.shouldRefuseBankrupt).toBe(true); + expect(result.isError).toBe(true); + }); +}); diff --git a/tests/wasm-seal-xor-known-plaintext-harden-gate.test.ts b/tests/wasm-seal-xor-known-plaintext-harden-gate.test.ts new file mode 100644 index 0000000..4f324fe --- /dev/null +++ b/tests/wasm-seal-xor-known-plaintext-harden-gate.test.ts @@ -0,0 +1,60 @@ +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { protectTarget } from "../src/engine/protector.js"; +import { hardenProject } from "../src/engine/harden.js"; +import { buildTestWasmWithSealXorKnownPlaintext } from "../src/engine/wasm-seal-xor-known-plaintext-lint.js"; + +const dirs: string[] = []; +afterEach(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); +}); + +describe("red-blue round-7 WASM seal.revision XOR known-plaintext gate", () => { + it("bankrupt protect refuses seal.revision known-plaintext unless allowed", () => { + const dir = mkdtempSync(join(tmpdir(), "bla-sealxor-gate-")); + dirs.push(dir); + const { wasm, seal } = buildTestWasmWithSealXorKnownPlaintext({}); + const input = join(dir, "core.wasm"); + const output = join(dir, "core.out.wasm"); + writeFileSync(input, wasm); + writeFileSync(join(dir, "seal.json"), JSON.stringify(seal, null, 2)); + expect(() => + protectTarget({ + inputPath: input, + outputPath: output, + intensity: "bankrupt", + seed: "r7-sealxor-gate", + }), + ).toThrow(/allowWasmSealXorKnownPlaintext|seal\.revision XOR known-plaintext/i); + const ok = protectTarget({ + inputPath: input, + outputPath: output, + intensity: "bankrupt", + seed: "r7-sealxor-gate", + allowWasmSealXorKnownPlaintext: true, + }); + expect(ok.detectedFormat).toBe("wasm"); + }); + + it("bankrupt harden refuses project trees with seal.revision known-plaintext WASM", () => { + const dir = mkdtempSync(join(tmpdir(), "bla-sealxor-harden-")); + dirs.push(dir); + mkdirSync(join(dir, "dist")); + const { wasm, seal } = buildTestWasmWithSealXorKnownPlaintext({}); + writeFileSync(join(dir, "dist", "core.wasm"), wasm); + writeFileSync(join(dir, "dist", "seal.json"), JSON.stringify(seal, null, 2)); + writeFileSync(join(dir, "dist", "app.js"), "export const ok = 1;\n", "utf8"); + const report = hardenProject({ + directory: dir, + intensity: "bankrupt", + seed: "r7-harden-sealxor", + dryRun: true, + }); + expect(report.overallSuccess).toBe(false); + expect( + report.artifacts.some((a) => /seal\.revision XOR known-plaintext|allowWasmSealXorKnownPlaintext/i.test(a.error ?? "")), + ).toBe(true); + }); +}); diff --git a/tests/wasm-seal-xor-known-plaintext-lint.test.ts b/tests/wasm-seal-xor-known-plaintext-lint.test.ts new file mode 100644 index 0000000..4d6ec6f --- /dev/null +++ b/tests/wasm-seal-xor-known-plaintext-lint.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vitest"; +import { + buildTestWasmWithSealXorKnownPlaintext, + lintWasmSealXorKnownPlaintextBuffer, + looksLikeSealRevisionKnownPlaintextPack, +} from "../src/engine/wasm-seal-xor-known-plaintext-lint.js"; + +describe("wasm-seal-xor-known-plaintext-lint", () => { + it("flags fixture where seal.revision is XOR known-plaintext in pack", () => { + const { wasm, seal, commit } = buildTestWasmWithSealXorKnownPlaintext({}); + const report = lintWasmSealXorKnownPlaintextBuffer(wasm, { + path: "fixture.wasm", + sealRaw: JSON.stringify(seal), + sealPath: "seal.json", + }); + expect(report.shouldRefuseBankrupt).toBe(true); + expect(report.looksExposed).toBe(true); + expect(report.findings.some((f) => f.id === "wasm-seal-revision-mask-oracle")).toBe(true); + expect(commit.length).toBe(32); + }); + + it("does not refuse when embedded commit mismatches seal.revision", () => { + const { wasm, seal } = buildTestWasmWithSealXorKnownPlaintext({ mismatchCommit: true }); + const report = lintWasmSealXorKnownPlaintextBuffer(wasm, { + path: "mismatch.wasm", + sealRaw: JSON.stringify(seal), + }); + expect(report.shouldRefuseBankrupt).toBe(false); + expect(report.findings).toHaveLength(0); + }); + + it("looksLike helper rejects empty buffer", () => { + expect(looksLikeSealRevisionKnownPlaintextPack(Buffer.alloc(10), Buffer.alloc(32)).ok).toBe(false); + }); +}); diff --git a/tests/wasm-xor-mask-sidecar-lint.test.ts b/tests/wasm-xor-mask-sidecar-lint.test.ts index 645a639..9950e6b 100644 --- a/tests/wasm-xor-mask-sidecar-lint.test.ts +++ b/tests/wasm-xor-mask-sidecar-lint.test.ts @@ -27,12 +27,10 @@ describe("wasm-xor-mask-sidecar-lint", () => { it("looksLikeXorMaskedEntitlementPack requires tight pack + entropy", () => { const wasm = buildTestWasmWithXorMaskSidecar({}); - // data payload starts after sections — use lint instead of raw guess const report = lintWasmXorMaskSidecarBuffer(wasm); expect(report.findings[0]?.blobLen).toBeGreaterThanOrEqual(40); expect(looksLikeXorMaskedEntitlementPack(Buffer.alloc(100)).ok).toBe(false); }); -}); it("does not refuse masked entitlement pack without adjacent plaintext mask (r7 key-dep style)", () => { const wasm = buildTestWasmWithXorMaskSidecar({ omitMaskSidecar: true }); @@ -40,4 +38,4 @@ describe("wasm-xor-mask-sidecar-lint", () => { expect(report.shouldRefuseBankrupt).toBe(false); expect(report.findings).toHaveLength(0); }); - +});