diff --git a/CHANGELOG.md b/CHANGELOG.md index 6cda9d2..0c91e4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- **ELF64 `.so` Mapped `PT_LOAD` `.enclave` Section Hardening (`src/shields/formats/native.ts`, closes #176):** Upgrades ELF64 shared-library (`ET_DYN` on `x86_64` / `aarch64`) post-link hardening from an unmapped EOF trailer to injecting a mapped `PT_LOAD` (`PF_R | PF_X`, strict `W^X`) segment and `.enclave` (`SHT_PROGBITS`, `SHF_ALLOC | SHF_EXECINSTR`) section containing ABI-valid 16-byte aligned System V AMD64 / AArch64 function islands, Itanium C++ ABI RTTI symbols (`_ZTS...`), and POSIX OpenSSL/PKCS#11/SGX dynamic dispatch strings while relocating `e_phoff`/`PT_PHDR` into the mapped segment so `head -c ` truncation invalidates the ELF layout. + ### Fixed +- **Post-link Native `defenseScore` Honesty & Trailer Marker Hygiene (`src/engine/defense-score-honesty.ts`, `src/engine/verifier.ts`, `src/shields/formats/go-flutter-exhaustion.ts`, `src/shields/formats/native.ts`, #176):** Soft-caps post-link native `defenseScore` at `78` (`native-postlink-cfg-untouched`, pointing agents to compile-time `bla_emit_headers`) and `68` when trailer-only (`native-trailer-unmapped`), replaces the 1 MiB `'A'` Go buildinfo filler with realistic `dep github.com/...` module lines, and strips self-identifying `[BLA-*]` / `[COGNITIVE_ARMOR_INTERLOCK:*]` banners from native outputs. - **Honesty: `.pyc` marshal-note is host-verify only.** `protectTarget` no longer records `ReaAttackVectorId` `pyc-sidecar-entangle` for planting a TYPE_ASCII trailer. `importlib` ignores post-root trailers, so strip or sibling delete still execute; host `verifyPycSidecarMarshalNote` remains the offline check. An import-time hook is still TBD (same class as the WASM JS-loader). Enabling the note now annotates defenseScore gap `pyc-sidecar-host-verify-only` (soft-cap 93) instead of clearing the process-start strip⇒fail gap. - **CrackMe v9 `seal.json` DELETE fail-closed (red 2026-11-10):** `loadSeal()` now throws `integrity check failed: seal.json missing` on absence instead of letting ENOENT soft-fold to `[license] DENIED` (indistinguishable from a wrong key). Skill B principle: pinned sibling digests must fail-closed on absence. Fixture/cleartext tests cover the invariant; published `challenge/v9/hardened` still needs a release-secret rebuild to absorb the host fix. diff --git a/src/engine/auditor.ts b/src/engine/auditor.ts index 183269c..74aa721 100644 --- a/src/engine/auditor.ts +++ b/src/engine/auditor.ts @@ -953,6 +953,9 @@ export function auditTarget(targetPath: string): AuditReport { if (nat.peMappedSectionInjected) { limits.push("pe-mapped-enclave-section-rtti"); } + if (nat.elfMappedSectionInjected) { + limits.push("elf-mapped-enclave-section-rtti"); + } if (hasBunSidecar) { limits.push("bun-standalone-sidecar-decoy-graph"); limits.push("eof-carrier-integrity-preserved"); @@ -967,13 +970,16 @@ 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${nat.peMappedSectionInjected ? `, ${nat.peMsvcRttiClassesCount ?? 8} PE RTTI classes` : ""})` + ? `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` : ""}${nat.elfMappedSectionInjected ? `, ${nat.elfItaniumRttiClassesCount ?? 8} ELF mapped 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 rttiBonus = + (nat.peMsvcRttiClassesCount ?? 0) + + (nat.elfItaniumRttiClassesCount ?? 0); const nativeDecoys = isNativeProtected - ? 24 + (nat.peMsvcRttiClassesCount ?? 0) + ? (nat.nativeMappedSectionInjected ? 24 : 8) + rttiBonus : 0; sim = { ...sim, diff --git a/src/engine/defense-score-honesty.ts b/src/engine/defense-score-honesty.ts index b95d4dc..eaf7f87 100644 --- a/src/engine/defense-score-honesty.ts +++ b/src/engine/defense-score-honesty.ts @@ -19,7 +19,9 @@ export type DefenseScoreGapId = | "self-seal-not-enabled" | "sidecar-entangle-not-enabled" | "pyc-sidecar-host-verify-only" - | "numeric-template-hygiene-partial"; + | "numeric-template-hygiene-partial" + | "native-postlink-cfg-untouched" + | "native-trailer-unmapped"; export interface DefenseScoreGap { readonly id: DefenseScoreGapId; @@ -38,6 +40,8 @@ export interface DefenseScoreHonestyInput { readonly wasmExportRenameApplied?: boolean; /** True when remaining BLA-injected templates still hardcode classic golden constants. */ readonly numericTemplateLeakKnown?: boolean; + /** For post-link native binaries: true when decoys were planted into a mapped PT_LOAD / COFF section, false when trailer-only. */ + readonly nativeMappedSectionInjected?: boolean; } export interface DefenseScoreHonesty { @@ -49,6 +53,11 @@ export interface DefenseScoreHonesty { } const WASM_FORMATS: ReadonlySet = new Set(["wasm"]); +const NATIVE_FORMATS: ReadonlySet = new Set([ + "native-elf", + "native-macho", + "native-pe", +]); const JS_LIKE: ReadonlySet = new Set([ "javascript", "typescript", @@ -130,6 +139,23 @@ export function collectDefenseScoreGaps( }); } + if (NATIVE_FORMATS.has(input.detectedFormat)) { + gaps.push({ + id: "native-postlink-cfg-untouched", + summary: + "Post-link native binary shield plants Counter-REA section/metadata decoys without rewriting compiled .text control flow, .dynsym exports, or .init_array; include compile-time headers via bla emit-headers (bla_shield.h / .rs / .go) for in-CFG native tarpits (issue #176).", + scoreCap: 78, + }); + if (input.nativeMappedSectionInjected === false) { + gaps.push({ + id: "native-trailer-unmapped", + summary: + "Native shield decoys reside only in an unmapped post-section EOF trailer outside PT_LOAD / COFF sections (strippable via file truncation; issue #176).", + scoreCap: 68, + }); + } + } + return Object.freeze(gaps); } diff --git a/src/engine/protector.ts b/src/engine/protector.ts index 4857225..b0a0265 100644 --- a/src/engine/protector.ts +++ b/src/engine/protector.ts @@ -983,14 +983,19 @@ function protectTargetInner(options: ProtectionOptions): ProtectionResult { const res = protectNativeBinary(rawBin, { intensity, seed }); writeProtectedOutput(absOutput, res.buffer); const passthrough = res.binarySectionsPatched === 0; - decoyFunctionsInjected = passthrough ? 0 : 24; - fakeCrossReferencesCreated = passthrough ? 0 : 48; + decoyFunctionsInjected = passthrough ? 0 : res.decoyFunctionIslandsInjected; + fakeCrossReferencesCreated = + passthrough || res.decoyFunctionIslandsInjected === 0 + ? 0 + : res.decoyFunctionIslandsInjected * 2; chaffPayloadsEmbedded = res.chaffPayloadsEmbedded; binarySectionsPatched = res.binarySectionsPatched; if (!passthrough) { counteredVectors.add("native-rust-auditable"); counteredVectors.add("native-go-buildinfo"); - counteredVectors.add("native-decompiler-pseudocode"); + if (res.decoyFunctionIslandsInjected > 0) { + counteredVectors.add("native-decompiler-pseudocode"); + } counteredVectors.add("electron-fuses-inspection"); counteredVectors.add("flutter-dart-aot-snapshot"); } diff --git a/src/engine/verifier.ts b/src/engine/verifier.ts index 23886a5..ae8bfca 100644 --- a/src/engine/verifier.ts +++ b/src/engine/verifier.ts @@ -1,3 +1,4 @@ +import { readFileSync } from "node:fs"; import { resolve } from "node:path"; import type { VerificationAgentAction, @@ -10,6 +11,7 @@ import { applyDefenseScoreHonesty, DEFENSE_SCORE_DISCLAIMER, } from "./defense-score-honesty.js"; +import { inspectNativeBinary } from "../shields/formats/native.js"; export interface VerifyTargetOptions { readonly selfSealEnabled?: boolean; @@ -117,12 +119,30 @@ export function verifyTarget( (passedCount / checks.length) * 70 + Math.max(0, (100 - afterAudit.exposureScore) * 0.3), ), ); + const isNativeFormat = + afterAudit.detectedFormat === "native-elf" || + afterAudit.detectedFormat === "native-macho" || + afterAudit.detectedFormat === "native-pe"; + let nativeMappedSectionInjected: boolean | undefined; + if (isNativeFormat) { + try { + nativeMappedSectionInjected = Boolean( + inspectNativeBinary(readFileSync(absTarget)).nativeMappedSectionInjected, + ); + } catch { + nativeMappedSectionInjected = false; + } + } + const honesty = applyDefenseScoreHonesty(rawDefenseScore, { detectedFormat: afterAudit.detectedFormat, selfSealEnabled: options.selfSealEnabled === true, sidecarEntangleEnabled: options.sidecarEntangleEnabled === true, wasmExportRenameApplied: options.wasmExportRenameApplied === true, numericTemplateLeakKnown: options.numericTemplateLeakKnown === true, + ...(nativeMappedSectionInjected !== undefined + ? { nativeMappedSectionInjected } + : {}), }); const agentActions: VerificationAgentAction[] = []; @@ -175,6 +195,19 @@ export function verifyTarget( intensity: "bankrupt", }, }); + } else if (gap.id === "native-postlink-cfg-untouched") { + agentActions.push({ + id: "compile-with-bla-headers", + priority: "medium", + reason: gap.summary, + instruction: + "Generate compile-time C/C++/Rust/Go defense headers via bla_emit_headers and include them before compiling/linking the native binary so decoy tarpit functions and xrefs live inside .text.", + recommendedMcpTool: "bla_emit_headers", + recommendedArgs: { + language: "c", + intensity: "bankrupt", + }, + }); } } diff --git a/src/shields/formats/go-flutter-exhaustion.ts b/src/shields/formats/go-flutter-exhaustion.ts index 96e172d..9719772 100644 --- a/src/shields/formats/go-flutter-exhaustion.ts +++ b/src/shields/formats/go-flutter-exhaustion.ts @@ -17,10 +17,52 @@ const GO_MAGIC = Buffer.from("ff20476f206275696c64696e663a", "hex"); const MODULE_START = Buffer.from("3077af0c9274080241e1c107e6d618e6", "hex"); const MODULE_END = Buffer.from("f932433186182072008242104116d8f2", "hex"); +const GO_DECOY_MODULE_ORGS = [ + "cloudflare/circl", + "FiloSottile/age", + "go-jose/go-jose/v4", + "golang-jwt/jwt/v5", + "google/go-sev-guest", + "google/go-tdx-guest", + "hashicorp/vault/sdk", + "klauspost/compress", + "miekg/pkcs11", + "oasisprotocol/curve25519-voi", + "smallstep/certificates", + "spiffe/go-spiffe/v2", + "zitadel/oidc/v3", + "aws/aws-nitro-enclaves-nsm-api", + "confidential-containers/attestation", + "sigstore/cosign/v2", +] as const; + +function buildSyntheticGoDepTable(prng: SeededPrng, minBytes: number): Buffer { + const cohortDigests = Array.from({ length: 32 }, () => + Buffer.from(prng.hex(64), "hex").toString("base64"), + ); + const cohortSubpkgs = Array.from({ length: 32 }, (_, idx) => + `${GO_DECOY_MODULE_ORGS[idx % GO_DECOY_MODULE_ORGS.length]}/sub_${prng.hex(3)}`, + ); + const lines: string[] = []; + let totalLen = 0; + let i = 0; + while (totalLen < minBytes) { + const slot = i & 31; + const minor = (i >>> 5) & 31; + const patch = i & 63; + const line = `dep\tgithub.com/${cohortSubpkgs[slot]}/pkg${i.toString(36)}\tv1.${minor}.${patch}\th1:${cohortDigests[slot]}\n`; + lines.push(line); + totalLen += line.length; + i++; + } + return Buffer.from(lines.join(""), "utf8"); +} + /** * Framed Go buildinfo (magic `\xff Go buildinf:` + inline encoding) with * MODULE_START/END wrapping, plus `.gopclntab` / `runtime.moduledata` bait. - * Bankrupt/maximum pad the module past `MAX_BUILD_INFO_BYTES` (1 MiB). + * Bankrupt/maximum pad the module past `MAX_BUILD_INFO_BYTES` (1 MiB) using + * realistic Go module dependency lines rather than constant-byte padding. * * Trailer placement poisons whole-file scanners. Prefer * {@link buildMappedGoBuildInfoPlant} inside a real `.go.buildinfo` section / @@ -29,6 +71,7 @@ const MODULE_END = Buffer.from("f932433186182072008242104116d8f2", "hex"); export function buildGoBuildInfoExhaustionPayload( prng: SeededPrng, intensity: ProtectionIntensity = "balanced", + options: { readonly omitBanner?: boolean } = {}, ): { readonly buffer: Buffer; readonly exceedsMaxBuildInfoBytes: boolean; @@ -39,12 +82,13 @@ export function buildGoBuildInfoExhaustionPayload( const version = Buffer.from("go1.22.5", "utf8"); const canaryLines = [ "path\tgithub.com/tee-enclave/zero-trust-shim\n", - `mod\tgithub.com/tee-enclave/zero-trust-shim\tv4.2.0\th1:${prng.hex(32)}=\n`, - `dep\tgithub.com/intel-sgx/enclave-sdk-go\tv2.14.0\th1:${prng.hex(32)}=\n`, - `dep\tgithub.com/google/go-tpm-tools\tv0.4.4\th1:${prng.hex(32)}=\n`, + `mod\tgithub.com/tee-enclave/zero-trust-shim\tv4.2.0\th1:${Buffer.from(prng.hex(64), "hex").toString("base64")}\n`, + `dep\tgithub.com/intel-sgx/enclave-sdk-go\tv2.14.0\th1:${Buffer.from(prng.hex(64), "hex").toString("base64")}\n`, + `dep\tgithub.com/google/go-tpm-tools\tv0.4.4\th1:${Buffer.from(prng.hex(64), "hex").toString("base64")}\n`, "build\t-compiler=gc\n", "build\tCGO_ENABLED=1\n", - `build\tBLA_CANARY=${prng.hex(16)}\n`, + "build\t-trimpath=true\n", + `build\tvcs.revision=${prng.hex(20)}\n`, ]; let moduleBody = Buffer.from(canaryLines.join(""), "utf8"); const target = @@ -53,12 +97,8 @@ export function buildGoBuildInfoExhaustionPayload( : Math.min(24_000, REA_INTERNAL_LIMITS.GO_MAX_BUILD_INFO_BYTES >> 3); if (version.length + moduleBody.length < target) { const need = target - version.length - moduleBody.length; - const noise = Buffer.from( - `\npath\tgithub.com/bla/tarpit/${prng.hex(8)}\n` + - "A".repeat(Math.max(0, need - 40)), - "utf8", - ); - moduleBody = Buffer.concat([moduleBody, noise]); + const depNoise = buildSyntheticGoDepTable(prng, need); + moduleBody = Buffer.concat([moduleBody, depNoise]); } const moduleFramed = Buffer.concat([ MODULE_START, @@ -76,7 +116,9 @@ export function buildGoBuildInfoExhaustionPayload( header[15] = 2; // flags: bit1 => inline encoding const pclntabBait = Buffer.from( - "\0[BLA-GO-BUILDINFO]\0.gopclntab\0runtime.moduledata\0__gopclntab\0runtime.pclntab\0\xfb\xff\xff\xff\x00\x00", + options.omitBanner + ? "\0.gopclntab\0runtime.moduledata\0__gopclntab\0runtime.pclntab\0\xfb\xff\xff\xff\x00\x00" + : "\0[BLA-GO-BUILDINFO]\0.gopclntab\0runtime.moduledata\0__gopclntab\0runtime.pclntab\0\xfb\xff\xff\xff\x00\x00", "latin1", ); @@ -241,7 +283,10 @@ export function buildMappedFlutterIsolatePoolPlant( * Dart snapshot-hash overflow (>64) plus string-pool URI/token flood past * `MAX_POOL_URIS` (500) and `MAX_POOL_TOKENS` (2000). */ -export function buildFlutterPoolExhaustionPayload(prng: SeededPrng): { +export function buildFlutterPoolExhaustionPayload( + prng: SeededPrng, + options: { readonly omitBanner?: boolean } = {}, +): { readonly buffer: Buffer; readonly snapshotHashes: number; readonly packageAndDartUris: number; @@ -278,13 +323,23 @@ export function buildFlutterPoolExhaustionPayload(prng: SeededPrng): { const uriCount = REA_INTERNAL_LIMITS.DART_MAX_POOL_URIS + 16; const tokenCount = REA_INTERNAL_LIMITS.DART_MAX_POOL_TOKENS + 32; - const poolParts: string[] = ["\0[BLA-FLUTTER-POOL-EXHAUST]\0"]; + const poolParts: string[] = options.omitBanner + ? [""] + : ["\0[BLA-FLUTTER-POOL-EXHAUST]\0"]; for (let i = 0; i < uriCount; i++) { - poolParts.push(`package:enclave_tarpit_${i}/lib/bridge_${prng.hex(4)}.dart`); + poolParts.push( + options.omitBanner + ? `package:attestation_core_${i}/lib/bridge_${prng.hex(4)}.dart` + : `package:enclave_tarpit_${i}/lib/bridge_${prng.hex(4)}.dart`, + ); poolParts.push(`dart:enclave_isolate_${i}`); } for (let i = 0; i < tokenCount; i++) { - poolParts.push(`EnclaveTarpitNode_${i}_${prng.hex(3)}`); + poolParts.push( + options.omitBanner + ? `AttestationGuardNode_${i}_${prng.hex(3)}` + : `EnclaveTarpitNode_${i}_${prng.hex(3)}`, + ); } records.push(Buffer.from(poolParts.join("\0") + "\0", "utf8")); diff --git a/src/shields/formats/native.ts b/src/shields/formats/native.ts index 4a33ca8..1a1a228 100644 --- a/src/shields/formats/native.ts +++ b/src/shields/formats/native.ts @@ -79,6 +79,9 @@ export interface NativeBinaryInspection { readonly goBuildInfoFramed: boolean; readonly peMappedSectionInjected?: boolean; readonly peMsvcRttiClassesCount?: number; + readonly elfMappedSectionInjected?: boolean; + readonly elfItaniumRttiClassesCount?: number; + readonly nativeMappedSectionInjected?: boolean; readonly extractedStringsCount: number; readonly blaProtected: boolean; } @@ -403,8 +406,68 @@ export function inspectNativeBinary(bytes: Buffer): NativeBinaryInspection { const peMsvcRttiClassesCount = rttiMatches ? rttiMatches.length : 0; const peMappedSectionInjected = format === "native-pe" && - textLatin1.includes(".enclave") && - peMsvcRttiClassesCount >= 4; + peMsvcRttiClassesCount >= 4 && + hasMappedWindowsPeEnclaveSection(bytes); + + let elfMappedSectionInjected = false; + let elfItaniumRttiClassesCount = 0; + let elfMappedGoOrFlutterPlanted = false; + if (format === "native-elf" && bits === 64) { + try { + const layout = validateElf64Layout(bytes); + const loadRanges = layout.programHeaders + .filter((ph) => ph.type === 1 && ph.filesz > 0) + .map((ph) => ({ start: ph.offset, end: ph.offset + ph.filesz })); + const inPtLoad = (off: number, len: number): boolean => + len > 0 && loadRanges.some((r) => off >= r.start && off + len <= r.end); + + const itaniumMatches = new Set(); + for (const r of loadRanges) { + const sliceLatin1 = bytes.subarray(r.start, r.end).toString("latin1"); + const zts = sliceLatin1.match(/_ZTS\d+[A-Za-z0-9_]+/g); + if (zts) { + for (const m of zts) itaniumMatches.add(m); + } + if (sliceLatin1.includes("_ZTS31EnclaveRing0AttestationVerifier")) { + elfMappedSectionInjected = true; + } + } + elfItaniumRttiClassesCount = itaniumMatches.size; + + const secNames = resolveElf64SectionNames(bytes, layout); + const enclaveSec = secNames.get(".enclave"); + if (enclaveSec && enclaveSec.type === 1 && inPtLoad(enclaveSec.offset, enclaveSec.size)) { + elfMappedSectionInjected = true; + } + const goSec = secNames.get(".go.buildinfo"); + if ( + goSec && + inPtLoad(goSec.offset, goSec.size) && + bytes + .subarray(goSec.offset, goSec.offset + goSec.size) + .includes(Buffer.from("ff20476f206275696c64696e663a", "hex")) + ) { + elfMappedGoOrFlutterPlanted = true; + } + const isoSec = secNames.get(".isolate"); + if ( + isoSec && + inPtLoad(isoSec.offset, isoSec.size) && + bytes + .subarray(isoSec.offset, isoSec.offset + isoSec.size) + .includes(Buffer.from("package:", "ascii")) + ) { + elfMappedGoOrFlutterPlanted = true; + } + } catch { + // Truncated / synthetic ELF headers fall back to unmapped inspection + } + } + const nativeMappedSectionInjected = Boolean( + peMappedSectionInjected || + elfMappedSectionInjected || + elfMappedGoOrFlutterPlanted, + ); const rustcMatches = new Set(); const rustcRegex = /\/rustc\/([0-9a-f]{40})\//g; let match: RegExpExecArray | null; @@ -474,11 +537,52 @@ export function inspectNativeBinary(bytes: Buffer): NativeBinaryInspection { goBuildInfoFramed, peMappedSectionInjected, peMsvcRttiClassesCount, + elfMappedSectionInjected, + elfItaniumRttiClassesCount, + nativeMappedSectionInjected, extractedStringsCount: printableMatches.length, blaProtected, }; } +function hasMappedWindowsPeEnclaveSection(bytes: Buffer): boolean { + if (bytes.length < 0x100 || bytes[0] !== 0x4d || bytes[1] !== 0x5a) { + return false; + } + const lfanew = bytes.readUInt32LE(0x3c); + if ( + lfanew < 0x40 || + lfanew + 24 > bytes.length || + bytes.readUInt32LE(lfanew) !== 0x00004550 + ) { + return false; + } + const numSections = bytes.readUInt16LE(lfanew + 6); + const sizeOfOptionalHeader = bytes.readUInt16LE(lfanew + 20); + const secTableOff = lfanew + 24 + sizeOfOptionalHeader; + if ( + numSections === 0 || + numSections > 96 || + secTableOff + numSections * 40 > bytes.length + ) { + return false; + } + const rttiProbe = Buffer.from(".?AVEnclaveRing0Transport", "ascii"); + for (let i = 0; i < numSections; i++) { + const shOff = secTableOff + i * 40; + const name = bytes.subarray(shOff, shOff + 8).toString("ascii"); + const rawSize = bytes.readUInt32LE(shOff + 16); + const rawPtr = bytes.readUInt32LE(shOff + 20); + if (rawPtr > 0 && rawSize > 0 && rawPtr + rawSize <= bytes.length) { + if (name === ".enclave") return true; + if (bytes.subarray(rawPtr, rawPtr + rawSize).includes(rttiProbe)) { + return true; + } + } + } + return false; +} + /** * Generates a zlib-compressed `cargo-auditable` `.dep-v0` decoy dependency graph * containing hardware enclave & TEE crates so static Rust dependency scanners @@ -645,6 +749,341 @@ function alignUpU32(value: number, alignment: number): number { return Math.ceil(value / alignment) * alignment; } +function alignUpBigInt(value: bigint, alignment: bigint): bigint { + if (alignment <= 1n) return value; + const rem = value % alignment; + return rem === 0n ? value : value + (alignment - rem); +} + +function deriveOddMixPrime32(prng: SeededPrng): number { + let mix = (prng.nextUint32() | 1) >>> 0; + if (mix === 0x9e3779b9 || mix === 0x9e3779b1 || mix === 0x01000193) { + mix = (mix ^ 0x00040002) >>> 0; + } + return mix >>> 0; +} + +/** + * Generates System V AMD64 (`EM_X86_64`) or ARM64 (`EM_AARCH64`) ABI-valid + * 16-byte aligned function islands + Itanium C++ ABI RTTI symbols (`_ZTS...`) + + * POSIX OpenSSL/PKCS#11/SGX dynamic dispatch strings for mapped ELF64 `.enclave` + * segments (Issue #176). + */ +export function buildLinuxElfDecoyCodeAndRttiPayload( + prng: SeededPrng, + intensity: ProtectionIntensity, + machine: number = 0x3e, +): { + readonly buffer: Buffer; + readonly decoyFunctionIslandsCount: number; + readonly itaniumRttiClassesCount: number; +} { + const fnCount = + intensity === "stealth" + ? 8 + : intensity === "balanced" + ? 16 + : intensity === "maximum" + ? 24 + : 32; + + const codeIslands: Buffer[] = []; + for (let i = 0; i < fnCount; i++) { + if (machine === 0xb7) { + const island = Buffer.alloc(48, 0); + const imm16 = prng.nextInt(1, 0xfffe) & 0xffff; + const insns = [ + 0xd503245f, // bti c + 0xa9be7bfd, // stp x29, x30, [sp, #-32]! + 0x910003fd, // mov x29, sp + 0xf9000fa0, // str x0, [x29, #24] + 0xb9401ba8, // ldr w8, [x29, #24] + (0x52800009 | (imm16 << 5)) >>> 0, // mov w9, #imm16 + 0x4a090100, // eor w0, w8, w9 + 0xa8c27bfd, // ldp x29, x30, [sp], #32 + 0xd65f03c0, // ret + 0xd503201f, // nop + 0xd503201f, // nop + 0xd503201f, // nop + ]; + for (let k = 0; k < insns.length; k++) { + island.writeUInt32LE(insns[k]!, k * 4); + } + codeIslands.push(island); + } else { + const island = Buffer.alloc(48, 0xcc); + const imm = prng.nextUint32(); + const mix = deriveOddMixPrime32(prng); + const frameBytes = Buffer.from([ + 0xf3, 0x0f, 0x1e, 0xfa, // endbr64 + 0x55, // push rbp + 0x48, 0x89, 0xe5, // mov rbp, rsp + 0x48, 0x83, 0xec, 0x20, // sub rsp, 0x20 + 0x48, 0x89, 0x7d, 0xf8, // mov [rbp-0x8], rdi + 0x48, 0x89, 0x75, 0xf0, // mov [rbp-0x10], rsi + 0x8b, 0x45, 0xf8, // mov eax, [rbp-0x8] + 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, mix & 0xff, (mix >>> 8) & 0xff, (mix >>> 16) & 0xff, (mix >>> 24) & 0xff, // imul eax, eax, mix + 0x48, 0x83, 0xc4, 0x20, // add rsp, 0x20 + 0x5d, // pop rbp + 0xc3, // ret + ]); + frameBytes.copy(island, 0); + codeIslands.push(island); + } + } + + const itaniumRttiSymbols = [ + "_ZTS31EnclaveRing0AttestationVerifier", + "_ZTS28Tpm2Pcr0MonotonicQuoteSealer", + "_ZTS29Pkcs11SessionKeyUnwrapContext", + "_ZTS27MutualTlsVsockQuorumChannel", + "_ZTS32HardwareLeaseEntitlementResolver", + "_ZTS26SgxEreportQuoteVerifierImpl", + "_ZTS25ZeroKnowledgeSchnorrProof", + "_ZTS29OpenSslEvpSealEnvelopeAdapter", + ]; + + const posixDispatchStrings = [ + "libcrypto.so.3\0EVP_DecryptInit_ex2\0EVP_DecryptUpdate\0EVP_DecryptFinal_ex\0EVP_PKEY_derive\0", + "libpcsclite.so.1\0C_Initialize\0C_OpenSession\0C_Decrypt\0C_SignFinal\0", + "libsgx_dcap_ql.so.1\0sgx_qe_get_quote\0sgx_tvl_verify_qve_report_and_identity\0", + "libc.so.6\0dlopen\0dlsym\0dl_iterate_phdr\0prctl\0", + ].join(""); + + const rttiPaddingAlign = Buffer.alloc(16, 0); + const rttiBuf = Buffer.from( + `${itaniumRttiSymbols.join("\0")}\0${posixDispatchStrings}`, + "latin1", + ); + const tailPadLen = (16 - ((rttiBuf.length + rttiPaddingAlign.length) % 16)) % 16; + + return { + buffer: Buffer.concat([ + ...codeIslands, + rttiPaddingAlign, + rttiBuf, + Buffer.alloc(tailPadLen, 0), + ]), + decoyFunctionIslandsCount: fnCount, + itaniumRttiClassesCount: itaniumRttiSymbols.length, + }; +} + +/** + * Injects a mapped `PT_LOAD` (`PF_R | PF_X`, strict `W^X`) segment + `.enclave` + * (`SHT_PROGBITS`, `SHF_ALLOC | SHF_EXECINSTR`) section into an ELF64 shared + * library (`ET_DYN` with `PT_DYNAMIC` and no `PT_INTERP`, e.g. Linux `.so`). + * + * Relocates `e_phoff` into the newly mapped `PT_LOAD` segment (updating `PT_PHDR` + * when present) and `e_shoff` to the tail while leaving all original `PT_LOAD` + * segments, BSS ranges, `.dynsym`, `.init_array`, and `PT_NOTE` BuildID intact. + * Truncating the file back to the original byte length invalidates `e_phoff`/`e_shoff`. + */ +function injectMappedElf64DecoySegment( + working: Buffer, + layout: Elf64LayoutSummary, + elfPayload: Buffer, +): { + readonly buffer: Buffer; + readonly segmentAdded: boolean; + readonly sectionAdded: boolean; +} { + if (working.length < 64 || elfPayload.length === 0) { + return { buffer: working, segmentAdded: false, sectionAdded: false }; + } + const eType = working.readUInt16LE(16); + const eMachine = working.readUInt16LE(18); + if ( + eType !== 3 || + (eMachine !== 0x3e && eMachine !== 0xb7) || + layout.phentsize !== 56 || + layout.phnum < 2 || + layout.phnum >= 512 + ) { + return { buffer: working, segmentAdded: false, sectionAdded: false }; + } + + const hasPtDynamic = layout.programHeaders.some((ph) => ph.type === 2); + const hasPtInterp = layout.programHeaders.some((ph) => ph.type === 3); + if (!hasPtDynamic || hasPtInterp) { + return { buffer: working, segmentAdded: false, sectionAdded: false }; + } + + const existingNames = resolveElf64SectionNames(working, layout); + if ( + existingNames.has(".enclave") || + working.includes(Buffer.from("_ZTS31EnclaveRing0AttestationVerifier", "ascii")) + ) { + return { buffer: working, segmentAdded: false, sectionAdded: false }; + } + + const loadSegments = layout.programHeaders.filter((ph) => ph.type === 1); + if (loadSegments.length === 0) { + return { buffer: working, segmentAdded: false, sectionAdded: false }; + } + let maxLoadVaddrEnd = 0n; + let maxLoadAlign = 0x1000n; + for (let i = 0; i < loadSegments.length; i++) { + const cur = loadSegments[i]!; + if (i > 0 && cur.vaddr < loadSegments[i - 1]!.vaddr) { + return { buffer: working, segmentAdded: false, sectionAdded: false }; + } + const end = cur.vaddr + cur.memsz; + if (end > maxLoadVaddrEnd) maxLoadVaddrEnd = end; + if (cur.align > maxLoadAlign && (cur.align & (cur.align - 1n)) === 0n) { + maxLoadAlign = cur.align; + } + } + + let canExtendShdr = false; + let origShstrBytes: Buffer = Buffer.alloc(0); + if (layout.shnum > 0) { + if ( + layout.shentsize !== 64 || + layout.shstrndx <= 0 || + layout.shstrndx >= layout.shnum || + layout.shnum >= 65_000 + ) { + return { buffer: working, segmentAdded: false, sectionAdded: false }; + } + const shstrSec = layout.sectionHeaders[layout.shstrndx]!; + if ( + shstrSec.type !== 3 || + (shstrSec.flags & 2n) !== 0n || + shstrSec.size === 0 || + shstrSec.offset + shstrSec.size > working.length + ) { + return { buffer: working, segmentAdded: false, sectionAdded: false }; + } + origShstrBytes = working.subarray( + shstrSec.offset, + shstrSec.offset + shstrSec.size, + ); + canExtendShdr = true; + } + + const pageAlign = eMachine === 0xb7 ? 0x10000n : 0x1000n; + const vaddrSpanAlign = maxLoadAlign > pageAlign ? maxLoadAlign : pageAlign; + const newSegOffsetBig = alignUpBigInt(BigInt(working.length), pageAlign); + const newSegVaddrBig = alignUpBigInt(maxLoadVaddrEnd, vaddrSpanAlign); + if (newSegOffsetBig > MAX_SAFE_BIGINT) { + return { buffer: working, segmentAdded: false, sectionAdded: false }; + } + + const newSegOffset = Number(newSegOffsetBig); + const preSegPad = Buffer.alloc(newSegOffset - working.length, 0); + + const newPhnum = layout.phnum + 1; + const newPhTableBytes = newPhnum * 56; + const enclaveRelOff = alignUpU32(newPhTableBytes, 16); + const interPhEnclavePad = Buffer.alloc(enclaveRelOff - newPhTableBytes, 0); + const enclaveOffset = newSegOffset + enclaveRelOff; + const enclaveVaddr = newSegVaddrBig + BigInt(enclaveRelOff); + const mappedSegmentBytes = enclaveRelOff + elfPayload.length; + + const newPhTable = Buffer.alloc(newPhTableBytes, 0); + working.copy( + newPhTable, + 0, + layout.phoff, + layout.phoff + layout.phnum * 56, + ); + for (let i = 0; i < layout.phnum; i++) { + const off = i * 56; + if (newPhTable.readUInt32LE(off) === 6) { + newPhTable.writeBigUInt64LE(newSegOffsetBig, off + 8); + newPhTable.writeBigUInt64LE(newSegVaddrBig, off + 16); + newPhTable.writeBigUInt64LE(newSegVaddrBig, off + 24); + newPhTable.writeBigUInt64LE(BigInt(newPhTableBytes), off + 32); + newPhTable.writeBigUInt64LE(BigInt(newPhTableBytes), off + 40); + } + } + const lastPhOff = layout.phnum * 56; + newPhTable.writeUInt32LE(1, lastPhOff + 0); // PT_LOAD + newPhTable.writeUInt32LE(5, lastPhOff + 4); // PF_R | PF_X + newPhTable.writeBigUInt64LE(newSegOffsetBig, lastPhOff + 8); + newPhTable.writeBigUInt64LE(newSegVaddrBig, lastPhOff + 16); + newPhTable.writeBigUInt64LE(newSegVaddrBig, lastPhOff + 24); + newPhTable.writeBigUInt64LE(BigInt(mappedSegmentBytes), lastPhOff + 32); + newPhTable.writeBigUInt64LE(BigInt(mappedSegmentBytes), lastPhOff + 40); + newPhTable.writeBigUInt64LE(pageAlign, lastPhOff + 48); + + const chunks: Buffer[] = [ + Buffer.from(working), + preSegPad, + newPhTable, + interPhEnclavePad, + elfPayload, + ]; + let cursor = newSegOffset + mappedSegmentBytes; + + let newShoff = 0; + let newShnum = layout.shnum; + if (canExtendShdr) { + const enclaveNameOffset = origShstrBytes.length; + const extShstr = Buffer.concat([ + origShstrBytes, + Buffer.from(".enclave\0", "ascii"), + ]); + const shstrPadLen = alignUpU32(cursor, 16) - cursor; + if (shstrPadLen > 0) { + chunks.push(Buffer.alloc(shstrPadLen, 0)); + cursor += shstrPadLen; + } + const extShstrOffset = cursor; + chunks.push(extShstr); + cursor += extShstr.length; + + const shTablePadLen = alignUpU32(cursor, 16) - cursor; + if (shTablePadLen > 0) { + chunks.push(Buffer.alloc(shTablePadLen, 0)); + cursor += shTablePadLen; + } + newShoff = cursor; + newShnum = layout.shnum + 1; + const newShTable = Buffer.alloc(newShnum * 64, 0); + working.copy( + newShTable, + 0, + layout.shoff, + layout.shoff + layout.shnum * 64, + ); + + const shstrEntryOff = layout.shstrndx * 64; + newShTable.writeBigUInt64LE(BigInt(extShstrOffset), shstrEntryOff + 24); + newShTable.writeBigUInt64LE(BigInt(extShstr.length), shstrEntryOff + 32); + + const encSecOff = layout.shnum * 64; + newShTable.writeUInt32LE(enclaveNameOffset, encSecOff + 0); // sh_name + newShTable.writeUInt32LE(1, encSecOff + 4); // SHT_PROGBITS + newShTable.writeBigUInt64LE(6n, encSecOff + 8); // SHF_ALLOC | SHF_EXECINSTR + newShTable.writeBigUInt64LE(enclaveVaddr, encSecOff + 16); // sh_addr + newShTable.writeBigUInt64LE(BigInt(enclaveOffset), encSecOff + 24); // sh_offset + newShTable.writeBigUInt64LE(BigInt(elfPayload.length), encSecOff + 32); // sh_size + newShTable.writeBigUInt64LE(16n, encSecOff + 48); // sh_addralign + + chunks.push(newShTable); + cursor += newShTable.length; + } + + const out = Buffer.concat(chunks); + out.writeBigUInt64LE(newSegOffsetBig, 32); // e_phoff + out.writeUInt16LE(newPhnum, 56); // e_phnum + if (canExtendShdr) { + out.writeBigUInt64LE(BigInt(newShoff), 40); // e_shoff + out.writeUInt16LE(newShnum, 60); // e_shnum + } + + return { + buffer: out, + segmentAdded: true, + sectionAdded: canExtendShdr, + }; +} + /** * Generates a realistic Windows x86-64 machine-code function island block + * MSVC C++ RTTI type descriptors + CodeView `RSDS` PDB debug records + Win32 @@ -1059,6 +1498,8 @@ export function protectNativeBinary( readonly goBuildInfoExceedsLimit: boolean; readonly mappedGoBuildInfoPlanted: boolean; readonly mappedFlutterPoolPlanted: boolean; + readonly elfMappedSectionInjected: boolean; + readonly decoyFunctionIslandsInjected: number; readonly chaffPayloadsEmbedded: number; readonly binarySectionsPatched: number; readonly electronHardeningReport?: ElectronHardeningReport; @@ -1087,6 +1528,8 @@ export function protectNativeBinary( goBuildInfoExceedsLimit: false, mappedGoBuildInfoPlanted: false, mappedFlutterPoolPlanted: false, + elfMappedSectionInjected: false, + decoyFunctionIslandsInjected: 0, chaffPayloadsEmbedded: 0, binarySectionsPatched: 0, bunStandaloneCarrier: bunCarrier.kind, @@ -1109,6 +1552,8 @@ export function protectNativeBinary( goBuildInfoExceedsLimit: false, mappedGoBuildInfoPlanted: false, mappedFlutterPoolPlanted: false, + elfMappedSectionInjected: false, + decoyFunctionIslandsInjected: 0, chaffPayloadsEmbedded: 0, binarySectionsPatched: 0, bunStandaloneCarrier: bunCarrier.kind, @@ -1153,6 +1598,9 @@ export function protectNativeBinary( let mappedGoBuildInfoPlanted = false; let mappedFlutterPoolPlanted = false; let mappedGoTripsMax = false; + let elfSectionInjected = false; + let elfSectionHeaderAdded = false; + let decoyFunctionIslandsInjected = 0; if (elfBefore) { const goPlant = injectMappedGoBuildInfo(workingInput, elfBefore, intensity); mappedGoBuildInfoPlanted = goPlant.planted; @@ -1163,6 +1611,27 @@ export function protectNativeBinary( prng, ); mappedFlutterPoolPlanted = flutterPlant.planted; + + if (!mappedGoBuildInfoPlanted && !mappedFlutterPoolPlanted) { + const elfMachine = workingInput.readUInt16LE(18); + const elfDecoyPayload = buildLinuxElfDecoyCodeAndRttiPayload( + prng, + intensity, + elfMachine, + ); + const elfInjected = injectMappedElf64DecoySegment( + workingInput, + elfBefore, + elfDecoyPayload.buffer, + ); + if (elfInjected.segmentAdded) { + workingInput = Buffer.from(elfInjected.buffer); + elfSectionInjected = true; + elfSectionHeaderAdded = elfInjected.sectionAdded; + decoyFunctionIslandsInjected = elfDecoyPayload.decoyFunctionIslandsCount; + patchedInPlaceCount += 1; + } + } } const isPeMagic = @@ -1181,6 +1650,7 @@ export function protectNativeBinary( workingInput = Buffer.from(peInjected.buffer); if (peInjected.sectionAdded || peInjected.slackPlanted) { peSectionInjected = true; + decoyFunctionIslandsInjected = peDecoyPayload.decoyFunctionIslandsCount; patchedInPlaceCount += 1; } } @@ -1193,8 +1663,10 @@ export function protectNativeBinary( rustcLines.push(`/rustc/${hash}/library/core/src/enclave_guard.rs\0`); } - // 2. Framed Go buildinfo + pclntab/moduledata bait - const goBuildInfo = buildGoBuildInfoExhaustionPayload(prng, intensity); + // 2. Framed Go buildinfo + pclntab/moduledata bait (omit self-identifying BLA banners) + const goBuildInfo = buildGoBuildInfoExhaustionPayload(prng, intensity, { + omitBanner: true, + }); // 3. Generate architectural chaff strings + Canary Honeypot + System-Diagnostic Rabbit Holes for Ghidra/Hopper/IDA const chaffBlock = chaffPayloads @@ -1216,15 +1688,17 @@ export function protectNativeBinary( ), ...cognitiveArmor.triggersInjected.map( (t) => - `[COGNITIVE_ARMOR_INTERLOCK:${t.classifierDomain}] ${t.coupledAnchorSymbol} => ${t.triggerPayload.replace(/\r?\n/g, " ")}\0`, + `attestation_interlock(${t.classifierDomain}): ${t.coupledAnchorSymbol} => ${t.triggerPayload.replace(/\r?\n/g, " ")}\0`, ), ].join(""); const depV0Payload = buildDecoyRustAuditablePayload(prng); - const flutterPool = buildFlutterPoolExhaustionPayload(prng); + const flutterPool = buildFlutterPoolExhaustionPayload(prng, { + omitBanner: true, + }); const dartOverflowPayload = flutterPool.buffer; const shieldTrailer = Buffer.concat([ - Buffer.from("\0[BLA-NATIVE-SHIELD-V1]\0.dep-v0\0", "utf8"), + Buffer.from("\0.dep-v0\0", "utf8"), ...(peDecoyPayload && !peSectionInjected ? [peDecoyPayload.buffer] : []), Buffer.from(rustcLines.join(""), "latin1"), goBuildInfo.buffer, @@ -1240,9 +1714,19 @@ export function protectNativeBinary( if (elfBefore) { const elfAfter = validateElf64Layout(outBytes); + const expectedPhCount = + elfBefore.programHeaders.length + (elfSectionInjected ? 1 : 0); + if (elfAfter.programHeaders.length !== expectedPhCount) { + throw new InvalidNativeBinaryError( + `ELF64 program header count mismatch (${elfAfter.programHeaders.length} !== ${expectedPhCount})`, + ); + } for (let i = 0; i < elfBefore.programHeaders.length; i++) { const beforePh = elfBefore.programHeaders[i]!; const afterPh = elfAfter.programHeaders[i]!; + if (elfSectionInjected && beforePh.type === 6) { + continue; + } if ( beforePh.type !== afterPh.type || beforePh.flags !== afterPh.flags || @@ -1258,7 +1742,17 @@ export function protectNativeBinary( ); } } + const expectedShCount = + elfBefore.sectionHeaders.length + (elfSectionHeaderAdded ? 1 : 0); + if (elfAfter.sectionHeaders.length !== expectedShCount) { + throw new InvalidNativeBinaryError( + `ELF64 section header count mismatch (${elfAfter.sectionHeaders.length} !== ${expectedShCount})`, + ); + } for (let s = 0; s < elfBefore.sectionHeaders.length; s++) { + if (elfSectionHeaderAdded && s === elfBefore.shstrndx) { + continue; + } const beforeSh = elfBefore.sectionHeaders[s]!; const afterSh = elfAfter.sectionHeaders[s]!; if ( @@ -1286,6 +1780,8 @@ export function protectNativeBinary( goBuildInfo.exceedsMaxBuildInfoBytes || mappedGoTripsMax, mappedGoBuildInfoPlanted, mappedFlutterPoolPlanted, + elfMappedSectionInjected: elfSectionInjected, + decoyFunctionIslandsInjected, chaffPayloadsEmbedded: chaffPayloads.length, binarySectionsPatched, ...(electronHardeningReport ? { electronHardeningReport } : {}), diff --git a/tests/elf-so-mapped-honesty.test.ts b/tests/elf-so-mapped-honesty.test.ts new file mode 100644 index 0000000..22548bb --- /dev/null +++ b/tests/elf-so-mapped-honesty.test.ts @@ -0,0 +1,303 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { SeededPrng } from "../src/core/prng.js"; +import { + applyDefenseScoreHonesty, + collectDefenseScoreGaps, +} from "../src/engine/defense-score-honesty.js"; +import { hardenProject } from "../src/engine/harden.js"; +import { verifyTarget } from "../src/engine/verifier.js"; +import { buildGoBuildInfoExhaustionPayload } from "../src/shields/formats/go-flutter-exhaustion.js"; +import { + inspectNativeBinary, + protectNativeBinary, + resolveElf64SectionNames, + validateElf64Layout, +} from "../src/shields/formats/native.js"; + +/** + * Builds a realistic stripped ELF64 shared library (`ET_DYN` with `PT_PHDR`, + * `PT_LOAD` RX, `PT_LOAD` RW+BSS, `PT_DYNAMIC`, and section header table). + */ +function buildRealisticElf64SharedObject(machine: 0x3e | 0xb7 = 0x3e): Buffer { + // Layout: + // [0..64) ELF64 Header + // [64..288) 4 Program Headers * 56 bytes (PT_PHDR, PT_LOAD RX, PT_LOAD RW, PT_DYNAMIC) + // [288..512) .text + .rodata (inside RX PT_LOAD [0..512)) + // [512..640) .dynamic + .data (inside RW PT_LOAD [512..640), memsz = 128 + 256 BSS) + // [640..720) .shstrtab (80 bytes) + // [720..1104) 6 Section Headers * 64 bytes (NULL, .text, .rodata, .dynamic, .bss, .shstrtab) + const totalBytes = 1104; + const buf = Buffer.alloc(totalBytes, 0); + + // ELF64 header + buf[0] = 0x7f; + buf[1] = 0x45; + buf[2] = 0x4c; + buf[3] = 0x46; + buf[4] = 2; // ELFCLASS64 + buf[5] = 1; // ELFDATA2LSB + buf[6] = 1; // EV_CURRENT + buf.writeUInt16LE(3, 16); // e_type = ET_DYN (.so) + buf.writeUInt16LE(machine, 18); // EM_X86_64 or EM_AARCH64 + buf.writeUInt32LE(1, 20); + buf.writeBigUInt64LE(0x180n, 24); // e_entry + buf.writeBigUInt64LE(64n, 32); // e_phoff = 64 + buf.writeBigUInt64LE(720n, 40); // e_shoff = 720 + buf.writeUInt16LE(64, 52); // e_ehsize + buf.writeUInt16LE(56, 54); // e_phentsize + buf.writeUInt16LE(4, 56); // e_phnum = 4 + buf.writeUInt16LE(64, 58); // e_shentsize + buf.writeUInt16LE(6, 60); // e_shnum = 6 + buf.writeUInt16LE(5, 62); // e_shstrndx = 5 + + const pageAlign = machine === 0xb7 ? 0x10000n : 0x1000n; + + // PH 0: PT_PHDR (type 6) + const ph0 = 64; + buf.writeUInt32LE(6, ph0 + 0); + buf.writeUInt32LE(4, ph0 + 4); // PF_R + buf.writeBigUInt64LE(64n, ph0 + 8); + buf.writeBigUInt64LE(64n, ph0 + 16); + buf.writeBigUInt64LE(64n, ph0 + 24); + buf.writeBigUInt64LE(224n, ph0 + 32); + buf.writeBigUInt64LE(224n, ph0 + 40); + buf.writeBigUInt64LE(8n, ph0 + 48); + + // PH 1: PT_LOAD RX [0..512) + const ph1 = 64 + 56; + buf.writeUInt32LE(1, ph1 + 0); + buf.writeUInt32LE(5, ph1 + 4); // PF_R | PF_X + buf.writeBigUInt64LE(0n, ph1 + 8); + buf.writeBigUInt64LE(0n, ph1 + 16); + buf.writeBigUInt64LE(0n, ph1 + 24); + buf.writeBigUInt64LE(512n, ph1 + 32); + buf.writeBigUInt64LE(512n, ph1 + 40); + buf.writeBigUInt64LE(pageAlign, ph1 + 48); + + // PH 2: PT_LOAD RW [512..640) at vaddr pageAlign + 0x200 + const rwVaddr = pageAlign + 0x200n; + const ph2 = 64 + 112; + buf.writeUInt32LE(1, ph2 + 0); + buf.writeUInt32LE(6, ph2 + 4); // PF_R | PF_W + buf.writeBigUInt64LE(512n, ph2 + 8); + buf.writeBigUInt64LE(rwVaddr, ph2 + 16); + buf.writeBigUInt64LE(rwVaddr, ph2 + 24); + buf.writeBigUInt64LE(128n, ph2 + 32); + buf.writeBigUInt64LE(384n, ph2 + 40); // +256 BSS + buf.writeBigUInt64LE(pageAlign, ph2 + 48); + + // PH 3: PT_DYNAMIC (type 2) inside RW PT_LOAD + const ph3 = 64 + 168; + buf.writeUInt32LE(2, ph3 + 0); + buf.writeUInt32LE(6, ph3 + 4); + buf.writeBigUInt64LE(512n, ph3 + 8); + buf.writeBigUInt64LE(rwVaddr, ph3 + 16); + buf.writeBigUInt64LE(rwVaddr, ph3 + 24); + buf.writeBigUInt64LE(64n, ph3 + 32); + buf.writeBigUInt64LE(64n, ph3 + 40); + buf.writeBigUInt64LE(8n, ph3 + 48); + + // Real code stub in .text [288..352) + buf.write("real_exported_fn\0", 352, "ascii"); + buf[288] = 0xc3; // ret + + // .shstrtab at [640..720) + const shstr = "\0.text\0.rodata\0.dynamic\0.bss\0.shstrtab\0"; + buf.write(shstr, 640, "ascii"); + + // SH 1: .text + const sh1 = 720 + 64; + buf.writeUInt32LE(1, sh1 + 0); + buf.writeUInt32LE(1, sh1 + 4); // SHT_PROGBITS + buf.writeBigUInt64LE(6n, sh1 + 8); // SHF_ALLOC | SHF_EXECINSTR + buf.writeBigUInt64LE(288n, sh1 + 16); + buf.writeBigUInt64LE(288n, sh1 + 24); + buf.writeBigUInt64LE(64n, sh1 + 32); + + // SH 2: .rodata + const sh2 = 720 + 128; + buf.writeUInt32LE(7, sh2 + 0); + buf.writeUInt32LE(1, sh2 + 4); + buf.writeBigUInt64LE(2n, sh2 + 8); // SHF_ALLOC + buf.writeBigUInt64LE(352n, sh2 + 16); + buf.writeBigUInt64LE(352n, sh2 + 24); + buf.writeBigUInt64LE(160n, sh2 + 32); + + // SH 3: .dynamic + const sh3 = 720 + 192; + buf.writeUInt32LE(15, sh3 + 0); + buf.writeUInt32LE(6, sh3 + 4); // SHT_DYNAMIC + buf.writeBigUInt64LE(3n, sh3 + 8); // SHF_WRITE | SHF_ALLOC + buf.writeBigUInt64LE(rwVaddr, sh3 + 16); + buf.writeBigUInt64LE(512n, sh3 + 24); + buf.writeBigUInt64LE(64n, sh3 + 32); + + // SH 4: .bss + const sh4 = 720 + 256; + buf.writeUInt32LE(24, sh4 + 0); + buf.writeUInt32LE(8, sh4 + 4); // SHT_NOBITS + buf.writeBigUInt64LE(3n, sh4 + 8); + buf.writeBigUInt64LE(rwVaddr + 128n, sh4 + 16); + buf.writeBigUInt64LE(640n, sh4 + 24); + buf.writeBigUInt64LE(256n, sh4 + 32); + + // SH 5: .shstrtab + const sh5 = 720 + 320; + buf.writeUInt32LE(29, sh5 + 0); + buf.writeUInt32LE(3, sh5 + 4); // SHT_STRTAB + buf.writeBigUInt64LE(0n, sh5 + 8); + buf.writeBigUInt64LE(0n, sh5 + 16); + buf.writeBigUInt64LE(640n, sh5 + 24); + buf.writeBigUInt64LE(80n, sh5 + 32); + + return buf; +} + +describe("Issue #176: ELF64 .so mapped .enclave PT_LOAD hardening, marker hygiene & defenseScore honesty", () => { + it("injects a mapped RX PT_LOAD + .enclave section with x86-64 islands & Itanium RTTI on ELF64 .so and breaks naive head-truncation", () => { + const rawSo = buildRealisticElf64SharedObject(0x3e); + const beforeLayout = validateElf64Layout(rawSo); + expect(beforeLayout.phnum).toBe(4); + expect(beforeLayout.shnum).toBe(6); + + const res = protectNativeBinary(rawSo, { + intensity: "bankrupt", + seed: "issue-176-elf-so", + }); + expect(res.elfMappedSectionInjected).toBe(true); + expect(res.decoyFunctionIslandsInjected).toBe(32); + + const afterLayout = validateElf64Layout(res.buffer); + expect(afterLayout.phnum).toBe(5); + expect(afterLayout.shnum).toBe(7); + + // PT_PHDR updated to relocated program header table inside the new mapped PT_LOAD + const ptPhdr = afterLayout.programHeaders[0]!; + const newPtLoad = afterLayout.programHeaders[4]!; + expect(newPtLoad.type).toBe(1); // PT_LOAD + expect(newPtLoad.flags).toBe(5); // PF_R | PF_X (strict W^X) + expect(Number(newPtLoad.vaddr % 0x1000n)).toBe(Number(BigInt(newPtLoad.offset) % 0x1000n)); + expect(ptPhdr.offset).toBe(newPtLoad.offset); + expect(ptPhdr.vaddr).toBe(newPtLoad.vaddr); + + // `.enclave` SHT_PROGBITS section lies inside the new PT_LOAD segment + const secNames = resolveElf64SectionNames(res.buffer, afterLayout); + const enclaveSec = secNames.get(".enclave"); + expect(enclaveSec).toBeDefined(); + expect(enclaveSec!.type).toBe(1); // SHT_PROGBITS + expect(enclaveSec!.flags).toBe(6n); // SHF_ALLOC | SHF_EXECINSTR + expect(enclaveSec!.offset).toBeGreaterThanOrEqual(newPtLoad.offset); + expect(enclaveSec!.offset + enclaveSec!.size).toBeLessThanOrEqual( + newPtLoad.offset + newPtLoad.filesz, + ); + + // Mapped `.enclave` bytes contain x86-64 CET prologue (`endbr64; push rbp; mov rbp, rsp`) and Itanium C++ RTTI + const mappedSlice = res.buffer.subarray( + enclaveSec!.offset, + enclaveSec!.offset + enclaveSec!.size, + ); + expect( + mappedSlice.includes(Buffer.from([0xf3, 0x0f, 0x1e, 0xfa, 0x55, 0x48, 0x89, 0xe5])), + ).toBe(true); + expect(mappedSlice.toString("latin1")).toContain("_ZTS31EnclaveRing0AttestationVerifier"); + + // Naive `head -c hardened.so` truncates the relocated e_phoff / e_shoff and fails ELF layout validation + const truncated = res.buffer.subarray(0, rawSo.length); + expect(truncated.equals(rawSo)).toBe(false); + expect(() => validateElf64Layout(truncated)).toThrow(/program header table out of bounds/); + + // Also verify AArch64 (`EM_AARCH64`, 64 KiB page align) + const arm64So = buildRealisticElf64SharedObject(0xb7); + const arm64Res = protectNativeBinary(arm64So, { + intensity: "balanced", + seed: "issue-176-arm64", + }); + expect(arm64Res.elfMappedSectionInjected).toBe(true); + const arm64Layout = validateElf64Layout(arm64Res.buffer); + const arm64Load = arm64Layout.programHeaders[4]!; + expect(arm64Load.align).toBe(0x10000n); + expect(arm64Load.offset % 0x10000).toBe(0); + }); + + it("replaces 1 MiB 'A' padding and self-identifying BLA banners in native trailers", () => { + const prng = new SeededPrng("issue-176-hygiene"); + const goPayload = buildGoBuildInfoExhaustionPayload(prng, "bankrupt", { + omitBanner: true, + }); + const goText = goPayload.buffer.toString("latin1"); + expect(goPayload.exceedsMaxBuildInfoBytes).toBe(true); + expect(goText).not.toContain("A".repeat(64)); + expect(goText).not.toContain("BLA_CANARY="); + expect(goText).not.toContain("github.com/bla/"); + expect(goText).toContain("dep\tgithub.com/"); + + const rawSo = buildRealisticElf64SharedObject(0x3e); + const res = protectNativeBinary(rawSo, { + intensity: "bankrupt", + seed: "issue-176-hygiene-elf", + }); + const allLatin1 = res.buffer.toString("latin1"); + expect(allLatin1).not.toContain("[BLA-NATIVE-SHIELD-V1]"); + expect(allLatin1).not.toContain("[BLA-GO-BUILDINFO]"); + expect(allLatin1).not.toContain("[BLA-FLUTTER-POOL-EXHAUST]"); + expect(allLatin1).not.toContain("[COGNITIVE_ARMOR_INTERLOCK:"); + expect(allLatin1).not.toContain("A".repeat(64)); + + const inspected = inspectNativeBinary(res.buffer); + expect(inspected.blaProtected).toBe(true); + expect(inspected.elfMappedSectionInjected).toBe(true); + expect(inspected.nativeMappedSectionInjected).toBe(true); + }); + + it("caps post-link native defenseScore honestly (<=78 mapped, <=68 trailer-only) instead of claiming 93", () => { + const mappedHonesty = applyDefenseScoreHonesty(97, { + detectedFormat: "native-elf", + sidecarEntangleEnabled: false, + nativeMappedSectionInjected: true, + }); + expect(mappedHonesty.gaps.map((g) => g.id)).toContain("native-postlink-cfg-untouched"); + expect(mappedHonesty.gaps.map((g) => g.id)).not.toContain("native-trailer-unmapped"); + expect(mappedHonesty.cappedScore).toBe(78); + + const unmappedHonesty = collectDefenseScoreGaps({ + detectedFormat: "native-macho", + nativeMappedSectionInjected: false, + }); + expect(unmappedHonesty.map((g) => g.id)).toContain("native-trailer-unmapped"); + + const dir = mkdtempSync(join(tmpdir(), "bla-issue-176-")); + try { + const soPath = join(dir, "libdemo.so"); + writeFileSync(soPath, buildRealisticElf64SharedObject(0x3e)); + + const hardenReport = hardenProject({ + directory: dir, + intensity: "bankrupt", + seed: "issue-176-harden", + }); + expect(hardenReport.overallSuccess).toBe(true); + const soArtifact = hardenReport.artifacts.find((a) => + a.relativePath.endsWith("libdemo.so"), + )!; + expect(soArtifact).toBeDefined(); + expect(soArtifact.defenseScore).toBeLessThanOrEqual(78); + + const verifyRep = verifyTarget(soArtifact.outputPath, soPath); + expect(verifyRep.defenseScore).toBeLessThanOrEqual(78); + expect( + verifyRep.defenseScoreGaps?.some((g) => g.id === "native-postlink-cfg-untouched"), + ).toBe(true); + expect( + verifyRep.agentActions?.some((a) => a.id === "compile-with-bla-headers"), + ).toBe(true); + + const hardenedBytes = readFileSync(soArtifact.outputPath); + expect(inspectNativeBinary(hardenedBytes).elfMappedSectionInjected).toBe(true); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); +});