From 45768a2e818b25a73996521733c6b78126dbcce5 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:20:45 -0500 Subject: [PATCH] fix(elf): reject invalid section table and zlib declarations (#12193) * fix(elf): reject invalid section table and zlib declarations Refs #10149, #10148, #9330. Co-authored-by: Nianze Wu * fix(elf): share section count admission with carrier readers (#12196) fix(elf): admit section tables before carrier recognition --------- Co-authored-by: Nianze Wu --- docs/architecture/architecture.mermaid | 4 +- docs/deno-standalone.md | 5 ++ docs/elf-notes.md | 4 +- docs/node-sea.md | 5 +- src/artifacts/NodeSeaArtifactReader.test.ts | 27 +++++++- .../deno/DenoStandaloneArtifactReader.test.ts | 29 +++++++- src/artifacts/deno/DenoStandaloneLocation.ts | 21 +++--- src/artifacts/nodeSea/NodeSeaLocation.ts | 3 + src/domain/elfDeclaredRanges.ts | 33 ++++++---- .../native/elfCompressedSection.test.ts | 66 +++++++++++++++++-- src/domain/native/elfCompressedSection.ts | 40 +++++++---- src/flutter/DartElf.test.ts | 11 ++++ src/flutter/DartElf.ts | 3 + src/gpu/GpuPayloadCodec.ts | 2 +- .../nodeCodecResult.ts} | 0 src/native/elf/ElfDependencyParser.ts | 8 +-- src/native/elf/ElfNoteParser.test.ts | 16 +++++ src/native/elf/ElfNoteParser.ts | 13 ++-- src/native/elf/ElfNotes.fixture.ts | 17 +++++ .../NativeInitializersParsers.test.ts | 10 ++- src/rust/RustAuditableReader.ts | 2 +- 21 files changed, 258 insertions(+), 61 deletions(-) rename src/{compression/NodeCodecResult.ts => kernel/nodeCodecResult.ts} (100%) diff --git a/docs/architecture/architecture.mermaid b/docs/architecture/architecture.mermaid index 16e055573f..4c4f2f39eb 100644 --- a/docs/architecture/architecture.mermaid +++ b/docs/architecture/architecture.mermaid @@ -2,7 +2,7 @@ graph TD %% Selected layer owners and dependency/wiring paths, not a directory or import inventory. %% Current deep-provider candidates are wired in src/composition/binary.ts. %% Layers, innermost first: kernel (src/kernel/: dependency-free helpers such as - %% errorMessage), domain, contracts, foundation, ports (src/ports/: + %% errorMessage and Node codec-result decoding), domain, contracts, foundation, ports (src/ports/: %% interfaces providers implement), providerCore (src/providers/: the shared %% provider core), providers, application, composition, adapters. An import may point to the same or an %% inner layer. scripts/lib/module-layers.mjs declares the layer of every @@ -77,7 +77,7 @@ graph TD ANDROID_TOOLS["src/adb/ + src/apktool/ + src/jeb/
BYO device, resource-decoding and JEB adapters
owned adb and Apktool processes; JEB engine client over MCP"] CAPTURE_TOOLS["src/captures/ + src/pcap/ + src/signals/ + src/sqlite/
BYO tshark, pcap, sigrok and SQLite child inspection
selected captures, recordings and databases; owned processes"] - NATIVE_READERS["src/go/ + src/rust/ + src/il2cpp/ + src/flutter/ + src/gpu/
Bundled in-process binary metadata readers
Go build info, Rust dependencies, IL2CPP, Dart build ID, GPU code objects
src/compression/: shared codec-result helper for rust and gpu"] + NATIVE_READERS["src/go/ + src/rust/ + src/il2cpp/ + src/flutter/ + src/gpu/
Bundled in-process binary metadata readers
Go build info, Rust dependencies, IL2CPP, Dart build ID, GPU code objects"] FORMAT_READERS["src/model/ + src/python/ + src/erlang/ + src/electron/
Bundled in-process format readers
GGUF and safetensors headers, Python .pyc, Erlang BEAM, Electron fuses"] RUNTIME["src/frida/ + src/cutter/
Frida instrumentation sessions and live Cutter bridge client"] end diff --git a/docs/deno-standalone.md b/docs/deno-standalone.md index 9b2b076592..eefd934916 100644 --- a/docs/deno-standalone.md +++ b/docs/deno-standalone.md @@ -14,6 +14,11 @@ The recognized carriers are a Mach-O `__SUI` section named `d3n0l4nd`, an Intel The PE probe follows the DOS header's PE offset and reads the declared header records and matching resource directories by file position. +The ELF probe skips malformed section tables, including tables with a reserved +direct `e_shnum` count, and still checks independently readable program +headers. A program note that confirms the Deno carrier alongside such damage +produces a format error. + Root metadata reports the carrier, entry point, argv, V8 flags, permission options, unstable configuration, application name, self-extracting marker, virtual-filesystem case sensitivity, and the npm snapshot byte length. The npm snapshot is not decoded. Each virtual file is one occurrence with its logical path, size, and SHA-256. Transpiled output, CJS export analysis, and source maps are separate occurrences beside that file. Each has the same `index` as the file and its own `role`. A region normally has the logical path of the file plus a `.deno-*` suffix. When that path belongs to another stored file, the region moves to an indexed path such as `deno-vfs/0.vfs-transpiled`, so read the reported `logical_path` instead of building it from the file name. They are not linked by `parent_occurrence_id`, which follows directories and expanded containers. Symlink targets stay recorded path parts and are never followed. `Metadata.env_vars_from_env_file` holds values from a compile-time `--env-file`, and `ca_data` holds certificate bytes. Inventory retains the variable names and values, certificate bytes, counts, and byte lengths in local Evidence, so sharing that Evidence shares them. Extraction does not write them as files. diff --git a/docs/elf-notes.md b/docs/elf-notes.md index 4e12308352..c09593af47 100644 --- a/docs/elf-notes.md +++ b/docs/elf-notes.md @@ -87,7 +87,9 @@ tables, declared note tables that extend past the file, and truncated note entries fail without partial success. ELF extended numbering (`PN_XNUM`, including a section count stored when `e_shnum` is 0) is unsupported and returns an unsupported-target outcome rather than invalid-input -recovery. +recovery. A direct section count of `0xff00` or greater in `e_shnum` is +malformed. Compressed section-name tables require zero or a power of two for +the decoded alignment. A zlib stream must consume its full declared payload. Zstandard section-name tables also use a 128 MiB decoder window limit. diff --git a/docs/node-sea.md b/docs/node-sea.md index e09a12e2e3..f0fce3a6a6 100644 --- a/docs/node-sea.md +++ b/docs/node-sea.md @@ -28,8 +28,9 @@ The container format is `node-sea`. REA locates Mach-O sections named locations come from the shared PE resource parser. ELF program-header `PT_NOTE` segments are authoritative, as at runtime; `SHT_NOTE` sections are read only when no program-header table is readable, because injectors can -leave stale section entries. A compressed section does not establish a raw -blob offset. A short remainder after the last ELF note must be zero padding. +leave stale section entries. The section fallback requires a valid direct +`e_shnum` count and an uncompressed note section to establish a raw blob +offset. A short remainder after the last ELF note must be zero padding. A PE without a `NODE_SEA_BLOB` resource name is left to native classification. Universal Mach-O carriers with different slice blobs are rejected as ambiguous; identical blobs are diff --git a/src/artifacts/NodeSeaArtifactReader.test.ts b/src/artifacts/NodeSeaArtifactReader.test.ts index 3bad8d770f..3812867afb 100644 --- a/src/artifacts/NodeSeaArtifactReader.test.ts +++ b/src/artifacts/NodeSeaArtifactReader.test.ts @@ -31,7 +31,11 @@ import { nodeSeaPe, nodeSeaUniversal, } from "./nodeSea/NodeSea.fixture.js"; -import { elfNote, elfNoteFixture } from "../native/elf/ElfNotes.fixture.js"; +import { + elfNote, + elfNoteFixture, + withElf64DirectSectionCount, +} from "../native/elf/ElfNotes.fixture.js"; import { peResourceFixture } from "../domain/pe/peResources.fixture.js"; import { locateNodeSea } from "./nodeSea/NodeSeaLocation.js"; import { MAX_INSPECT_PE_FILE_BYTES } from "../domain/native/peResources.js"; @@ -518,6 +522,27 @@ it("trusts the PT_NOTE blob over a stale SHT_NOTE entry", async () => { expect(inventory.manifest.root_format).toBe("node-sea"); }); +it.each(["section", "both"] as const)( + "only trusts an independently readable SEA program note beside a reserved section count (%s)", + async (ownership) => { + const bytes = withElf64DirectSectionCount( + nodeSeaElf({ ...populated, ownership }), + 0xff00, + ); + const handle = await open( + await writeCarrier("reserved-sections", bytes), + "r", + ); + try { + const location = await locateNodeSea(handle, bytes.length); + if (ownership === "section") expect(location).toBeUndefined(); + else expect(location).toMatchObject({ carrier: "elf" }); + } finally { + await handle.close(); + } + }, +); + it.each([ ["section", "elf"], ["both", "node-sea"], diff --git a/src/artifacts/deno/DenoStandaloneArtifactReader.test.ts b/src/artifacts/deno/DenoStandaloneArtifactReader.test.ts index 166721d3f8..e0605031e3 100644 --- a/src/artifacts/deno/DenoStandaloneArtifactReader.test.ts +++ b/src/artifacts/deno/DenoStandaloneArtifactReader.test.ts @@ -7,7 +7,11 @@ import { join } from "node:path"; import { expect, it, vi } from "vitest"; import { phaseGate } from "../../../tests/support/lifecycleHarness.js"; -import { elfNote, elfNoteFixture } from "../../native/elf/ElfNotes.fixture.js"; +import { + elfNote, + elfNoteFixture, + withElf64DirectSectionCount, +} from "../../native/elf/ElfNotes.fixture.js"; import { MAX_INSPECT_ELF_NOTE_ENTRIES, MAX_INSPECT_ELF_NOTE_FILE_BYTES, @@ -945,6 +949,29 @@ it("fails closed when a SUI note sits beside extended section numbering", async }); }); +it("records a reserved direct section count beside an independently confirmed program note", async () => { + const bytes = withElf64DirectSectionCount(denoElf(), 0xff00); + await expect( + locateDenoStandalone(bytesHandle(bytes), bytes.length), + ).resolves.toMatchObject({ + status: "present", + failure: { + reason: "format", + message: expect.stringContaining("reserved direct section count"), + }, + }); +}); + +it("does not confirm a Deno carrier from a section note in a malformed table", async () => { + const bytes = withElf64DirectSectionCount( + gnuElf("section", suiNote()), + 0xff00, + ); + await expect( + locateDenoStandalone(bytesHandle(bytes), bytes.length), + ).resolves.toEqual({ status: "absent" }); +}); + it("reaches a SUI section note past an unreadable program table", async () => { const bytes = patched(gnuElf("both", suiNote()), (image) => { image.writeBigUInt64LE(BigInt(image.length + 8), ELF64_PHOFF); diff --git a/src/artifacts/deno/DenoStandaloneLocation.ts b/src/artifacts/deno/DenoStandaloneLocation.ts index ec02613973..1f6ce3f7de 100644 --- a/src/artifacts/deno/DenoStandaloneLocation.ts +++ b/src/artifacts/deno/DenoStandaloneLocation.ts @@ -23,6 +23,7 @@ import { import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; +import { validateElfSectionTableFields } from "../../domain/elfDeclaredRanges.js"; import { readElfFixedHeader } from "../../domain/elfFixedHeader.js"; import { MAX_INSPECT_ELF_NOTE_ENTRIES } from "../../domain/native/elfNotes.js"; import { @@ -553,8 +554,10 @@ const locateElfNotes = async (carrier: Carrier): Promise => { const { programs, sections } = raw.value; if (programs.count === PN_XNUM) damaged("ELF extended program numbering is unsupported"); + const sectionTable = validateElfSectionTableFields(raw.value); + if (!sectionTable.ok) damaged(sectionTable.error); // A zero e_shnum with a section table moves the count into section zero. - if (sections.count === 0 && sections.offset !== 0n) + else if (sections.count === 0 && sections.offset !== 0n) damaged("ELF extended section numbering is unsupported"); const programHeaders = programs.count === PN_XNUM @@ -566,13 +569,15 @@ const locateElfNotes = async (carrier: Carrier): Promise => { wide ? ELF64_PROGRAM_HEADER_BYTES : ELF32_PROGRAM_HEADER_BYTES, "program header table", ); - const sectionHeaders = await readElfHeaderTable( - carrier, - walk, - sections, - wide ? ELF64_SECTION_HEADER_BYTES : ELF32_SECTION_HEADER_BYTES, - "section header table", - ); + const sectionHeaders = sectionTable.ok + ? await readElfHeaderTable( + carrier, + walk, + sections, + wide ? ELF64_SECTION_HEADER_BYTES : ELF32_SECTION_HEADER_BYTES, + "section header table", + ) + : undefined; const tables = new Map(); const addTable = (offset: bigint, length: bigint, align: bigint): void => { if ( diff --git a/src/artifacts/nodeSea/NodeSeaLocation.ts b/src/artifacts/nodeSea/NodeSeaLocation.ts index 194b34069c..6353d8869a 100644 --- a/src/artifacts/nodeSea/NodeSeaLocation.ts +++ b/src/artifacts/nodeSea/NodeSeaLocation.ts @@ -11,6 +11,7 @@ import { import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; +import { validateElfSectionTableFields } from "../../domain/elfDeclaredRanges.js"; import { constants as bufferConstants } from "node:buffer"; import { parsePeResources, @@ -470,6 +471,8 @@ const locateElfNotes = async ( if (found.length > 0 && opaque !== undefined) throw formatFailure(opaque); return found; } + // A malformed section declaration cannot supply a fallback note location. + if (!validateElfSectionTableFields(raw.value).ok) return []; const sections = await readElfTables(carrier, { offset: shoff, count: shnum, diff --git a/src/domain/elfDeclaredRanges.ts b/src/domain/elfDeclaredRanges.ts index 88be098f29..8a288eaf73 100644 --- a/src/domain/elfDeclaredRanges.ts +++ b/src/domain/elfDeclaredRanges.ts @@ -4,6 +4,8 @@ import { readElfRawTableDeclarations } from "./elfRawTableDeclarations.js"; import { readElfFixedHeader, type ElfFixedHeader } from "./elfFixedHeader.js"; import { err, ok, type Result } from "./result.js"; +const SHN_LORESERVE = 0xff00; + export interface ElfDeclaredRangeFacts { readonly hasInterpreter: boolean; } @@ -93,12 +95,12 @@ const extendedCounts = ( const counts = { ...initial }; if (counts.sectionCount === 0n) { counts.sectionCount = zero.size; - if (counts.sectionCount < 0xff00n) + if (counts.sectionCount < BigInt(SHN_LORESERVE)) return err("invalid ELF extended section count"); } if (counts.namesIndex === 0xffff) { counts.namesIndex = zero.link; - if (counts.namesIndex < 0xff00) + if (counts.namesIndex < SHN_LORESERVE) return err("invalid ELF extended section-name index"); } if (counts.programCount === 0xffffn) { @@ -109,21 +111,26 @@ const extendedCounts = ( return ok(counts); }; -/** A name index or extended count cannot refer to an absent section table. */ -export const validateElfSectionTablePresence = (tables: { +/** Admit the fixed section table declarations before inspecting any rows. */ +export const validateElfSectionTableFields = (tables: { readonly programs: { readonly count: number }; readonly sections: { readonly offset: bigint; readonly count: number; readonly namesIndex: number; }; -}): Result => - tables.sections.offset === 0n && - (tables.sections.count !== 0 || - tables.sections.namesIndex !== 0 || - tables.programs.count === 0xffff) - ? err("ELF section table is missing") - : ok(null); +}): Result => { + if (tables.sections.count >= SHN_LORESERVE) + return err("ELF e_shnum uses a reserved direct section count"); + if ( + tables.sections.offset === 0n && + (tables.sections.count !== 0 || + tables.sections.namesIndex !== 0 || + tables.programs.count === 0xffff) + ) + return err("ELF section table is missing"); + return ok(null); +}; /** Canonical table declarations, including extended counts in inactive section zero. */ export function* readElfTableDeclarations( @@ -143,8 +150,8 @@ export function* readElfTableDeclarations( let programCount = BigInt(programs.count); let sectionCount = BigInt(sections.count); let namesIndex = sections.namesIndex; - const presence = validateElfSectionTablePresence(raw.value); - if (!presence.ok) return presence; + const sectionTable = validateElfSectionTableFields(raw.value); + if (!sectionTable.ok) return sectionTable; if ( sectionOffset !== 0n && (sectionCount === 0n || namesIndex === 0xffff || programCount === 0xffffn) diff --git a/src/domain/native/elfCompressedSection.test.ts b/src/domain/native/elfCompressedSection.test.ts index a5a94b94d0..b8924411e3 100644 --- a/src/domain/native/elfCompressedSection.test.ts +++ b/src/domain/native/elfCompressedSection.test.ts @@ -13,6 +13,7 @@ const chdr = ( little: boolean, type: number, size: number, + alignment = 1n, ): Buffer => { const header = Buffer.alloc(bits === 64 ? 24 : 12); if (little) header.writeUInt32LE(type, 0); @@ -20,17 +21,17 @@ const chdr = ( if (bits === 64) { if (little) { header.writeBigUInt64LE(BigInt(size), 8); - header.writeBigUInt64LE(1n, 16); + header.writeBigUInt64LE(alignment, 16); } else { header.writeBigUInt64BE(BigInt(size), 8); - header.writeBigUInt64BE(1n, 16); + header.writeBigUInt64BE(alignment, 16); } } else if (little) { header.writeUInt32LE(size, 4); - header.writeUInt32LE(1, 8); + header.writeUInt32LE(Number(alignment), 8); } else { header.writeUInt32BE(size, 4); - header.writeUInt32BE(1, 8); + header.writeUInt32BE(Number(alignment), 8); } return header; }; @@ -188,3 +189,60 @@ describe("ELF compressed section payloads", () => { }); }); }); + +describe("ELF compressed section declaration admission", () => { + it.each([ + [32, false, 0x8000_0000n], + [64, true, 0x8000_0000_0000_0000n], + ] as const)( + "admits zero and the largest power-of-two alignment in an ELF%s header", + (bits, little, alignment) => { + for (const value of [0n, alignment]) { + const bytes = Buffer.concat([ + chdr(bits, little, 1, plain.length, value), + deflateSync(plain), + ]); + expect( + decodeElfSectionNameTable(bytes, 0x800n, bits, little, 1024), + ).toMatchObject({ state: "available", bytes: plain }); + } + }, + ); + + it.each([ + [32, false, 3n], + [64, true, 0x8000_0000_0000_0001n], + ] as const)( + "rejects a non-power-of-two alignment in an ELF%s header before inflation", + (bits, little, alignment) => { + const bytes = Buffer.concat([ + chdr(bits, little, 1, plain.length, alignment), + deflateSync(plain), + ]); + expect( + decodeElfSectionNameTable(bytes, 0x800n, bits, little, 1024), + ).toMatchObject({ + state: "malformed", + message: + "ELF compressed section-name table has an invalid decoded alignment", + inflatedBytes: 0, + }); + }, + ); + + it.each([Buffer.from([0]), deflateSync("another stream")])( + "rejects bytes beyond the single zlib stream in a section-name table", + (suffix) => { + const payload = Buffer.concat([deflateSync(plain), suffix]); + const bytes = Buffer.concat([chdr(64, true, 1, plain.length), payload]); + expect( + decodeElfSectionNameTable(bytes, 0x800n, 64, true, 1024), + ).toMatchObject({ + state: "malformed", + message: + "ELF compressed section-name table has bytes after its zlib stream", + inflatedBytes: payload.length, + }); + }, + ); +}); diff --git a/src/domain/native/elfCompressedSection.ts b/src/domain/native/elfCompressedSection.ts index 5f9c67a130..aacc943f0a 100644 --- a/src/domain/native/elfCompressedSection.ts +++ b/src/domain/native/elfCompressedSection.ts @@ -1,5 +1,6 @@ import { BinaryReader } from "../binaryContainer.js"; import { constants, inflateSync, zstdDecompressSync } from "node:zlib"; +import { nodeCodecResult } from "../../kernel/nodeCodecResult.js"; const SHF_COMPRESSED = 0x800n; const ELFCOMPRESS_ZLIB = 1; @@ -61,6 +62,12 @@ export const readElfCompressedSectionHeader = ( ) return { state: "unsupported", compressionType }; const declaredSize = reader.word(bits === 64 ? 8 : 4, bits); + const alignment = reader.word(bits === 64 ? 16 : 8, bits); + if ((alignment & (alignment - 1n)) !== 0n) + return { + state: "malformed", + message: `${subject} has an invalid decoded alignment`, + }; return { state: "compressed", compressionType, declaredSize, headerBytes }; }; @@ -141,21 +148,32 @@ const inflateDeclared = ( subject: string, ): ElfCompressedSectionResult => { const expected = Number(declaredSize); + const inflatedBytes = Math.max(expected, payload.length); let decoded: Buffer; try { const maxOutputLength = Math.max(1, expected); - decoded = - compression === "zstd" - ? zstdDecompressSync(payload, { - maxOutputLength, - // Retain Zstandard's default maximum decoder window of 128 MiB. - params: { [constants.ZSTD_d_windowLogMax]: 27 }, - }) - : inflateSync(payload, { maxOutputLength }); + if (compression === "zstd") { + decoded = zstdDecompressSync(payload, { + maxOutputLength, + // Retain Zstandard's default maximum decoder window of 128 MiB. + params: { [constants.ZSTD_d_windowLogMax]: 27 }, + }); + } else { + const result = nodeCodecResult( + inflateSync(payload, { info: true, maxOutputLength }), + ); + if (result.consumedBytes !== payload.length) + return { + state: "malformed", + message: `${subject} has bytes after its zlib stream`, + inflatedBytes, + }; + decoded = result.buffer; + } } catch (cause: unknown) { return { state: "malformed", - inflatedBytes: Math.max(expected, payload.length), + inflatedBytes, message: `${subject} could not be decompressed: ${cause instanceof Error ? cause.message : "invalid compressed data"}`, }; } @@ -163,13 +181,13 @@ const inflateDeclared = ( return { state: "malformed", message: `${subject} size is inconsistent`, - inflatedBytes: Math.max(expected, payload.length), + inflatedBytes, }; return { state: "available", bytes: decoded, compressed: true, compression, - inflatedBytes: Math.max(decoded.length, payload.length), + inflatedBytes, }; }; diff --git a/src/flutter/DartElf.test.ts b/src/flutter/DartElf.test.ts index 82c0af451e..d07b124f0c 100644 --- a/src/flutter/DartElf.test.ts +++ b/src/flutter/DartElf.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; +import { withElf64DirectSectionCount } from "../native/elf/ElfNotes.fixture.js"; import { readElfSymbols, readSnapshotHeader } from "./DartElf.js"; import { REFERENCE_HASH, @@ -72,6 +73,16 @@ describe("readElfSymbol", () => { expect(header.kind).toBe(3); }); + it("refuses to read snapshot symbols through a reserved direct section count", async () => { + const image = withElf64DirectSectionCount(imageWithSections(), 0xff00); + expect(await readElfSymbols(image, ["_kDartIsolateSnapshotData"])).toEqual({ + symbols: [], + failures: [ + { reason: "ELF e_shnum uses a reserved direct section count" }, + ], + }); + }); + it("refuses a non-ELF image instead of guessing", async () => { const result = await readElfSymbol(Buffer.from("not an elf at all"), "x"); expect("failure" in result && result.failure.reason).toBe( diff --git a/src/flutter/DartElf.ts b/src/flutter/DartElf.ts index 6d629fa805..ffe7560652 100644 --- a/src/flutter/DartElf.ts +++ b/src/flutter/DartElf.ts @@ -15,6 +15,7 @@ import { readElfSectionHeader } from "../domain/elfSectionHeader.js"; import { readElfProgramHeader } from "../domain/elfProgramHeader.js"; import { readElfSymbol } from "../domain/elfSymbol.js"; import { readElfRawTableDeclarations } from "../domain/elfRawTableDeclarations.js"; +import { validateElfSectionTableFields } from "../domain/elfDeclaredRanges.js"; import { Buffer } from "node:buffer"; import { setImmediate as yieldToEventLoop } from "node:timers/promises"; import { createElfLoadMap } from "./ElfLoadMap.js"; @@ -116,6 +117,8 @@ export const readElfHeader = ( return { failure: { reason: "unsupported ELF type" } }; const raw = readElfRawTableDeclarations(bytes, fixedHeader.value); if (!raw.ok) return { failure: { reason: raw.error.message } }; + const sectionTable = validateElfSectionTableFields(raw.value); + if (!sectionTable.ok) return { failure: { reason: sectionTable.error } }; const { programs, sections } = raw.value; const e_shoff = sections.offset <= BigInt(Number.MAX_SAFE_INTEGER) diff --git a/src/gpu/GpuPayloadCodec.ts b/src/gpu/GpuPayloadCodec.ts index 0552275673..fc7b9417eb 100644 --- a/src/gpu/GpuPayloadCodec.ts +++ b/src/gpu/GpuPayloadCodec.ts @@ -1,4 +1,4 @@ -import { nodeCodecResult } from "../compression/NodeCodecResult.js"; +import { nodeCodecResult } from "../kernel/nodeCodecResult.js"; import { constants, inflate, zstdDecompress } from "node:zlib"; import { promisify } from "node:util"; import { assertArtifactReadActive } from "../resources/index.js"; diff --git a/src/compression/NodeCodecResult.ts b/src/kernel/nodeCodecResult.ts similarity index 100% rename from src/compression/NodeCodecResult.ts rename to src/kernel/nodeCodecResult.ts diff --git a/src/native/elf/ElfDependencyParser.ts b/src/native/elf/ElfDependencyParser.ts index 58accc7764..947f473908 100644 --- a/src/native/elf/ElfDependencyParser.ts +++ b/src/native/elf/ElfDependencyParser.ts @@ -15,7 +15,7 @@ import { DT_SYMTAB, walkElfDynamicTable, } from "../../domain/elfDynamicEntry.js"; -import { validateElfSectionTablePresence } from "../../domain/elfDeclaredRanges.js"; +import { validateElfSectionTableFields } from "../../domain/elfDeclaredRanges.js"; import { readElfFixedHeader } from "../../domain/elfFixedHeader.js"; import { admitElfLoadSegment, @@ -670,8 +670,8 @@ export const readElfDependenciesSteps = function* ( fail(`ELF type ${String(type)} is not a loadable ET_EXEC or ET_DYN image.`); const raw = readElfRawTableDeclarations(bytes, header); if (!raw.ok) return fail(raw.error.message); - const presence = validateElfSectionTablePresence(raw.value); - if (!presence.ok) return fail(presence.error); + const sectionTable = validateElfSectionTableFields(raw.value); + if (!sectionTable.ok) return fail(sectionTable.error); const { programs, sections } = raw.value; if ( programs.offset > BigInt(Number.MAX_SAFE_INTEGER) || @@ -685,7 +685,7 @@ export const readElfDependenciesSteps = function* ( const shentsize = sections.width; const shnum = sections.count; const shstrndx = sections.namesIndex; - if (phnum === 0xffff || shnum === 0xffff || shstrndx === 0xffff) + if (phnum === 0xffff || shstrndx === 0xffff) throw new BinaryFormatFailure( "unsupported", "ELF extended numbering is unsupported.", diff --git a/src/native/elf/ElfNoteParser.test.ts b/src/native/elf/ElfNoteParser.test.ts index 3eb62e83ba..3419a8a2d2 100644 --- a/src/native/elf/ElfNoteParser.test.ts +++ b/src/native/elf/ElfNoteParser.test.ts @@ -573,6 +573,22 @@ it("rejects an extended section count stored in section zero", () => { ); }); +it("checks direct section count encoding in notes and the native directory", () => { + const bytes = elfExtendedSectionCountFixture(); + const sectionZero = Number(bytes.readBigUInt64LE(40)); + bytes.writeBigUInt64LE(0n, sectionZero + 32); + bytes.writeUInt16LE(0xfeff, 60); + expect(parse(bytes).tables[0]?.name).toBe(".note.gnu.build-id"); + expect(readElfDirectoryFromBuffer(bytes).sections[1]?.name).toBe( + ".note.gnu.build-id", + ); + + bytes.writeUInt16LE(0xff00, 60); + const reason = /e_shnum uses a reserved direct section count/u; + expect(() => parse(bytes)).toThrow(reason); + expect(() => readElfDirectoryFromBuffer(bytes)).toThrow(reason); +}); + const repeatedNotes = (count: number, notes: Buffer): Buffer => { const headers = Buffer.alloc(56 * count); const offset = 64 + headers.length; diff --git a/src/native/elf/ElfNoteParser.ts b/src/native/elf/ElfNoteParser.ts index 108553e223..7a5b37cd1a 100644 --- a/src/native/elf/ElfNoteParser.ts +++ b/src/native/elf/ElfNoteParser.ts @@ -4,7 +4,7 @@ import { } from "../../domain/elfStringTable.js"; import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; -import { validateElfSectionTablePresence } from "../../domain/elfDeclaredRanges.js"; +import { validateElfSectionTableFields } from "../../domain/elfDeclaredRanges.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; import { ArtifactReaderFailure, @@ -810,8 +810,8 @@ export const parseElfNotes = ( sections.offset > BigInt(Number.MAX_SAFE_INTEGER) ) return fail("ELF offset or size exceeds a safe integer."); - const presence = validateElfSectionTablePresence(raw.value); - if (!presence.ok) return fail(presence.error); + const sectionTable = validateElfSectionTableFields(raw.value); + if (!sectionTable.ok) return fail(sectionTable.error); const phoff = Number(programs.offset); const shoff = Number(sections.offset); const phentsize = programs.width; @@ -819,12 +819,7 @@ export const parseElfNotes = ( const shentsize = sections.width; const shnum = sections.count; const shstrndx = sections.namesIndex; - if ( - phnum === 0xffff || - shnum === 0xffff || - shstrndx === 0xffff || - (shoff !== 0 && shnum === 0) - ) + if (phnum === 0xffff || shstrndx === 0xffff || (shoff !== 0 && shnum === 0)) throw new BinaryFormatFailure( "unsupported", "ELF extended numbering is unsupported.", diff --git a/src/native/elf/ElfNotes.fixture.ts b/src/native/elf/ElfNotes.fixture.ts index f767724e1e..aa696b5bef 100644 --- a/src/native/elf/ElfNotes.fixture.ts +++ b/src/native/elf/ElfNotes.fixture.ts @@ -253,6 +253,23 @@ export const compressedElfNoteSectionFixture = ( return bytes; }; +/** Move an ELF64 little-endian fixture's existing section rows to a backed direct-count table. */ +export const withElf64DirectSectionCount = ( + image: Buffer, + count: number, +): Buffer => { + const offset = Number(image.readBigUInt64LE(40)); + const priorCount = image.readUInt16LE(60); + const table = Math.ceil(image.length / 8) * 8; + const result = Buffer.alloc(table + count * 64); + image.copy(result); + image.copy(result, table, offset, offset + priorCount * 64); + result.writeBigUInt64LE(BigInt(table), 40); + result.writeUInt16LE(64, 58); + result.writeUInt16LE(count, 60); + return result; +}; + /** Valid ELF64 section count stored in section header zero per the gABI. */ export const elfExtendedSectionCountFixture = (): Buffer => { const count = 0xff00; diff --git a/src/native/initializers/NativeInitializersParsers.test.ts b/src/native/initializers/NativeInitializersParsers.test.ts index 0b147d1a27..29f18fe577 100644 --- a/src/native/initializers/NativeInitializersParsers.test.ts +++ b/src/native/initializers/NativeInitializersParsers.test.ts @@ -976,11 +976,12 @@ describe("ELF section lookups", () => { async () => { const base = elf64PieInitializers(); const slots = MAX_NATIVE_INITIALIZER_ENTRIES; + const sectionCount = 0xffff; const payload = Buffer.alloc(slots * 8); for (let slot = 0; slot < slots; slot += 1) payload.writeBigUInt64LE(0x100n, slot * 8); // Allocated, unnamed sections that cover every slot and target address. - const extra = Buffer.alloc((0xffff - 12) * 64); + const extra = Buffer.alloc((sectionCount - 12) * 64); for (let at = 0; at < extra.length; at += 64) { extra.writeUInt32LE(1, at + 4); extra.writeBigUInt64LE(2n, at + 8); @@ -992,8 +993,11 @@ describe("ELF section lookups", () => { base.subarray(0x800, 0x800 + 12 * 64), extra, ]); - bytes.writeBigUInt64LE(BigInt(base.length + payload.length), 40); - bytes.writeUInt16LE(0xffff, 60); + const sectionTable = base.length + payload.length; + bytes.writeBigUInt64LE(BigInt(sectionTable), 40); + // Extended section numbering stores the count in section zero's sh_size. + bytes.writeUInt16LE(0, 60); + bytes.writeBigUInt64LE(BigInt(sectionCount), sectionTable + 32); // The single PT_LOAD maps the whole file; DT_INIT_ARRAY moves to the payload. bytes.writeBigUInt64LE(BigInt(bytes.length), 64 + 32); bytes.writeBigUInt64LE(BigInt(bytes.length), 64 + 40); diff --git a/src/rust/RustAuditableReader.ts b/src/rust/RustAuditableReader.ts index ea5dd134bd..bbed2e9e69 100644 --- a/src/rust/RustAuditableReader.ts +++ b/src/rust/RustAuditableReader.ts @@ -1,4 +1,4 @@ -import { nodeCodecResult } from "../compression/NodeCodecResult.js"; +import { nodeCodecResult } from "../kernel/nodeCodecResult.js"; import { inflateSync } from "node:zlib"; import { z } from "zod"; import { RUST_PRODUCER_DEFAULTS } from "../domain/rust/rustResourceLimits.js";