diff --git a/docs/bun-standalone.md b/docs/bun-standalone.md index bd9db5d422..069f32184a 100644 --- a/docs/bun-standalone.md +++ b/docs/bun-standalone.md @@ -33,8 +33,11 @@ Bun 1.3.9 layout. These labels identify structural layouts, not a detected compi version. Bun does not store an explicit revision identifier: unknown table sizes and ambiguous known layouts are unsupported. A future layout that is byte-for-byte compatible cannot be distinguished. Invalid pointers and truncated claimed sections -are malformed. An absent trailer without a named section does not establish a Bun -graph. Unknown enum values remain raw, with a null name. +are malformed. A named Mach-O section is also malformed when it declares zero-fill +or falls outside its containing segment's file or virtual address range. A confirmed +section graph requires a complete Mach-O load command table. An absent +trailer without a named section does not establish a Bun graph. Unknown enum values +remain raw, with a null name. Sourcemaps are stored Bun regions, not necessarily standalone JSON source maps. Extracted contents retain their original encoding. Use JavaScript analysis only on diff --git a/docs/deno-standalone.md b/docs/deno-standalone.md index dcd54ca84b..9b2b076592 100644 --- a/docs/deno-standalone.md +++ b/docs/deno-standalone.md @@ -11,6 +11,9 @@ In MCP, open the executable with `open_binary`, then call `inspect_artifact`. Us The recognized carriers are a Mach-O `__SUI` section named `d3n0l4nd`, an Intel Mach-O `<~sui-data~>` trailer, an ELF `PT_NOTE` or `SHT_NOTE` owned by `SUI` with type `0x53554901` and descriptor name `d3n0l4nd`, and a PE `RT_RCDATA` resource named `D3N0L4ND`. These are structural layouts. The metadata JSON has no Deno version field, so the compiler version stays unknown unless another record establishes it. Other layouts, including older eszip trailers, are unsupported. +The PE probe follows the DOS header's PE offset and reads the declared header +records and matching resource directories by file position. + 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-dependencies.md b/docs/elf-dependencies.md index ad611f2b52..182a9190c0 100644 --- a/docs/elf-dependencies.md +++ b/docs/elf-dependencies.md @@ -60,14 +60,16 @@ each import keeps its version index, hidden bit, and a resolved A missing `PT_DYNAMIC` is an observed empty load-time dependency inventory. It is not proof another overlay or container carried dynamic linking metadata. -`DT_*` entries are the load-time facts. A section header is used for a table -only when it names the same address, maps to the same file bytes, and agrees -on any declared size or entry width; a disagreeing section is reported as an -issue and the `DT_*` declaration is used. When section headers are stripped, -tables are located from `PT_DYNAMIC` and `DT_*` virtual addresses through -`PT_LOAD`. Coverage is `partial` when a table -cannot be located or a string cannot be read. Complete coverage never retains -issues. +`DT_*` entries are the load-time facts. A section header can locate a table +when its starting address, mapped file offset, and declared size or entry +width agree. A plain gap in load coverage can still allow recovery from the +section's file bytes. A different file translation or declared zero-fill in +the requested span prevents that recovery. A disagreeing section is reported +as an issue and the `DT_*` declaration is used. An admitted symbol-section +header can still name its string table when the symbol rows are unreadable. When section headers are +stripped, tables are located from `PT_DYNAMIC` and `DT_*` virtual addresses +through `PT_LOAD`. Coverage is `partial` when a table cannot be located or a +string cannot be read. Complete coverage never retains issues. ## Limits and failures diff --git a/docs/guides/managed/managed-code-analysis.md b/docs/guides/managed/managed-code-analysis.md index 35f883f59c..62fe4d518e 100644 --- a/docs/guides/managed/managed-code-analysis.md +++ b/docs/guides/managed/managed-code-analysis.md @@ -40,6 +40,11 @@ inspection is needed; see [selected member inspection](#selected-member-inspecti Compare separate builds with [member comparison](#member-comparison), preserving their paths, digests, and selection scope. +If the PE's `SizeOfHeaders` fails to cover its section table or exceeds the +file size, the artifact inspection retains PE identity and reports partial +coverage with the offset of that field. Managed metadata and CIL remain +unavailable because the section table cannot establish their file mappings. + ### Field constant defaults `inspect_managed_members` reads field-owned values from the ECMA-335 `Constant` diff --git a/docs/guides/native/binary-diagnostics.md b/docs/guides/native/binary-diagnostics.md index 9d6e566045..47fda8b7f3 100644 --- a/docs/guides/native/binary-diagnostics.md +++ b/docs/guides/native/binary-diagnostics.md @@ -249,7 +249,8 @@ count and SHA-256. Resources retain separate type, name and language identities: numeric IDs are distinct from UTF-16 names, whose original bytes are also reported. Directory headers, entries, data entries and payloads retain original file offsets and lengths. Each opaque payload has its own SHA-256; code page and -reserved data-entry fields are preserved. +reserved data-entry fields are preserved. The complete inventory requires +numeric IDs to appear in ascending order within each directory. Every `directories[]` row retains its identity `path` and the matching incoming `entry_locations`: both are empty for the root, then contain the type and diff --git a/docs/node-sea.md b/docs/node-sea.md index 89a2ee4022..e09a12e2e3 100644 --- a/docs/node-sea.md +++ b/docs/node-sea.md @@ -28,12 +28,19 @@ 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 PE without a `NODE_SEA_BLOB` resource name is +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. +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 inventoried once. Native carrier bytes keep their content hash and native classification while the root occurrence represents the SEA container. +REA reports a named Mach-O SEA section as malformed when it declares zero-fill +or falls outside its containing segment's file or virtual address range. +The load command containing the section must be aligned and within the declared +command table. A framing failure later in that table prevents blob recovery. + Root `format_metadata` preserves raw flags, decoded flags, code path, blob location, exec arguments and fuse observations. Main and asset children retain their role and exact declared name in `source_path`. Safe, noncolliding names @@ -124,12 +131,12 @@ and host memory remain independent of larger selected budgets. PE carriers additionally use the shared 512 MiB input, 65,536 directory-entry and 8 MiB resource-metadata ceilings; the Node SEA selections do not raise those -shared PE-parser boundaries. The PE name probe reads headers from the first -64 KiB of the carrier; a PE whose -headers extend beyond that is left to native classification. ELF note tables -are read for at most one note per 12 carrier bytes in total, the most that -disjoint tables can hold, so program headers that repeat the same notes do not -rescan them once per header. Past that count the remaining tables are +shared PE-parser boundaries. The PE name probe follows the DOS header's PE +offset and reads the declared header records and resource directories by file +position. The ELF scan +allows one framing read per 12 carrier bytes. Both a note header and a short +table tail consume a read from that allowance, so repeated declarations +cannot drive unbounded rescans. Past that count the remaining tables are unreadable: an ELF without a confirmed blob keeps its native classification, and one with a blob fails closed. Snapshot and code-cache bytes remain opaque. diff --git a/scripts/verify/baselines/raw-buffer-read.json b/scripts/verify/baselines/raw-buffer-read.json index 2c0060e39b..d354f286c2 100644 --- a/scripts/verify/baselines/raw-buffer-read.json +++ b/scripts/verify/baselines/raw-buffer-read.json @@ -10,7 +10,6 @@ "src/artifacts/bun/BunModuleGraphLayout.ts": 22, "src/artifacts/dotnet/DotnetBundle.ts": 5, "src/artifacts/nodeSea/NodeSeaBlob.ts": 4, - "src/artifacts/nodeSea/NodeSeaLocation.ts": 2, "src/artifacts/pyinstaller/CArchiveLayout.ts": 8, "src/domain/apkSignature/apkSignatureSchemes.ts": 1, "src/domain/apkSignature/apkSigningBlock.ts": 2, @@ -57,8 +56,7 @@ "src/domain/native/elfPointerRelocations.ts": 6, "src/domain/native/nativeAotPe.ts": 37, "src/domain/native/readBinaryContainer.ts": 1, - "src/domain/pe/peResourceInventory.ts": 11, - "src/domain/pe/peResourceLayout.ts": 3, + "src/domain/pe/peResourceInventory.ts": 7, "src/domain/pe/peResourceTreeFacts.ts": 9, "src/domain/peOptionalHeader.ts": 12, "src/domain/peSectionHeader.ts": 5, diff --git a/src/artifacts/NodeSeaArtifactReader.test.ts b/src/artifacts/NodeSeaArtifactReader.test.ts index 5096819173..3bad8d770f 100644 --- a/src/artifacts/NodeSeaArtifactReader.test.ts +++ b/src/artifacts/NodeSeaArtifactReader.test.ts @@ -303,6 +303,30 @@ it("reads a 32-bit and a big-endian Mach-O section", async () => { } }); +it.each([ + ["zero-fill", (bytes: Buffer) => bytes.writeUInt32LE(0x1, 32 + 72 + 64)], + ["file extent", (bytes: Buffer) => bytes.writeBigUInt64LE(1n, 32 + 48)], + [ + "virtual extent", + (bytes: Buffer) => bytes.writeBigUInt64LE(1n, 32 + 72 + 32), + ], +] as const)( + "refuses a named Mach-O SEA section with invalid %s backing", + async (reason, change) => { + const bytes = nodeSeaMachO(); + change(bytes); + const handle = await open(await writeCarrier("macho-backing", bytes), "r"); + try { + await expect(locateNodeSea(handle, bytes.length)).rejects.toMatchObject({ + reason: "format", + message: expect.stringContaining(reason), + }); + } finally { + await handle.close(); + } + }, +); + it("classifies a main script without a JavaScript suffix as javascript-bundle", async () => { const snapshot = await scanCanonicalArtifactInventory( await writeCarrier( @@ -417,6 +441,31 @@ it("leaves a Mach-O, ELF, or PE without a SEA slot in its native format", async expect(pe.manifest.root_format).toBe("pe"); }); +it("locates a SEA resource past a distant DOS stub", async () => { + const { bytes: image } = peResourceFixture( + true, + [ + { + type: 10, + name: "NODE_SEA_BLOB", + language: 0, + payload: buildNodeSeaBlob(populated), + }, + ], + 65536, + 4, + 0x20080, + ); + const path = await writeCarrier("distant-pe", image); + const reader = new NodeSeaArtifactReader(path); + try { + const entries = await seaEntries(reader); + expect(entries.map(({ path: member }) => member)).toContain("app/main.js"); + } finally { + await reader.close(); + } +}); + it.each([false, true])( "scopes the large PE admission limit to SEA resources (PE32+: %s)", async (plus) => { @@ -469,6 +518,48 @@ it("trusts the PT_NOTE blob over a stale SHT_NOTE entry", async () => { expect(inventory.manifest.root_format).toBe("node-sea"); }); +it.each([ + ["section", "elf"], + ["both", "node-sea"], +] as const)( + "does not locate raw SEA bytes in compressed note storage (%s)", + async (ownership, expected) => { + const bytes = nodeSeaElf({ ...populated, ownership }); + // Flag the note section as compressed, leaving its raw descriptor bytes intact. + const sectionOffset = Number(bytes.readBigUInt64LE(0x28)) + 64; + bytes.writeBigUInt64LE(0x800n, sectionOffset + 8); + const inventory = await scanCanonicalArtifactInventory( + await writeCarrier("compressed-note-section", bytes), + ); + expect(inventory.manifest.root_format).toBe(expected); + }, +); + +it.each([0, 1])( + "only accepts padding bytes after a SEA note (%i)", + async (tail) => { + const bytes = elfNoteFixture({ + notes: Buffer.concat([ + elfNote("NODE_SEA_BLOB", 0, buildNodeSeaBlob(populated)), + Buffer.from([tail]), + ]), + ownership: "section", + type: 2, + }); + const inventory = scanCanonicalArtifactInventory( + await writeCarrier("note-table-tail", bytes), + ); + if (tail === 0) + await expect(inventory).resolves.toMatchObject({ + manifest: { root_format: "node-sea" }, + }); + else + await expect(inventory).rejects.toMatchObject({ + message: expect.stringContaining("trailing non-zero bytes"), + }); + }, +); + it("leaves a non-SEA PE with a cyclic resource tree to native classification", async () => { const fixture = peResourceFixture(true); fixture.bytes.writeUInt32LE(0x80000000, (fixture.entryOffsets[0] ?? 0) + 4); @@ -1103,7 +1194,7 @@ it.each(["__TEXT", "NODE_SEA"])( }, ); -it("retains SEA admission for a complete segment with a nonaligned command size", async () => { +it("leaves a SEA section in a misaligned Mach-O command unrecognized", async () => { const original = nodeSeaMachO(); const commandSize = original.readUInt32LE(20); const payloadAt = 32 + commandSize; @@ -1121,11 +1212,7 @@ it("retains SEA admission for a complete segment with a nonaligned command size" "r", ); try { - expect(await locateNodeSea(handle, bytes.length)).toEqual({ - carrier: "mach-o", - blobOffset: payloadAt + 1, - blobLength: Number(original.readBigUInt64LE(32 + 72 + 40)), - }); + expect(await locateNodeSea(handle, bytes.length)).toBeUndefined(); } finally { await handle.close(); } diff --git a/src/artifacts/bun/BunModuleGraph.test.ts b/src/artifacts/bun/BunModuleGraph.test.ts index b28bb216d3..5055bd00b1 100644 --- a/src/artifacts/bun/BunModuleGraph.test.ts +++ b/src/artifacts/bun/BunModuleGraph.test.ts @@ -267,6 +267,28 @@ it("refuses multiple embedded graphs instead of selecting one", async () => { }); }); +it.each([ + ["zero-fill", (bytes: Buffer) => bytes.writeUInt32LE(0x12, 32 + 72 + 64)], + ["file extent", (bytes: Buffer) => bytes.writeBigUInt64LE(1n, 32 + 48)], + [ + "virtual extent", + (bytes: Buffer) => bytes.writeBigUInt64LE(1n, 32 + 72 + 32), + ], +] as const)( + "refuses a named Mach-O Bun section with invalid %s backing", + async (reason, change) => { + const section = bunPrefixedPayload( + bunModuleGraphPayload({ modules: [{}] }), + ); + const bytes = machoBunSection(section); + change(bytes); + expect(await locate(bytes)).toMatchObject({ + status: "present", + failure: { reason: "format", message: expect.stringContaining(reason) }, + }); + }, +); + it("probes a section graph without reading its payload data", async () => { const contents = Buffer.alloc(1024 * 1024, 0x61); const bytes = machoBunSection( @@ -435,3 +457,25 @@ it("recognizes an ELF Bun section name deep in the string table by reading only }); expect(observed.bytesRead).toBeLessThan(1024); }); + +it.each([ + ["missing command", (image: Buffer) => image.writeUInt32LE(2, 16)], + [ + "unused command bytes", + (image: Buffer) => image.writeUInt32LE(image.readUInt32LE(20) + 8, 20), + ], +] as const)("refuses a Mach-O Bun graph with %s", async (_label, damage) => { + const image = machoBunSection( + bunPrefixedPayload( + bunModuleGraphPayload({ + modules: [{ name: "main.js", contents: Buffer.from("hello") }], + }), + ), + ); + damage(image); + const { result } = await probe(image); + expect(result).toMatchObject({ + status: "present", + failure: { reason: "format" }, + }); +}); diff --git a/src/artifacts/bun/BunModuleGraphLayout.ts b/src/artifacts/bun/BunModuleGraphLayout.ts index abe61d221a..3b84b4dc32 100644 --- a/src/artifacts/bun/BunModuleGraphLayout.ts +++ b/src/artifacts/bun/BunModuleGraphLayout.ts @@ -8,6 +8,11 @@ import { readMachoLoadCommandTableHeader, MachoLoadCommandCursor, } from "../../domain/apple/machoLoadCommands.js"; +import { + machoSectionBacking, + readMachoSectionHeader, +} from "../../domain/apple/machoSectionHeader.js"; +import { readMachoSegmentHeader } from "../../domain/apple/machoSegmentHeader.js"; import type { FileHandle } from "node:fs/promises"; import { @@ -33,8 +38,6 @@ export const BUN_RECORD_BYTES_1_3_3 = 36; export const BUN_RECORD_BYTES_1_3_9 = 52; const MAX_PE_SECTIONS = 96; -const SEGMENT_64_HEADER_BYTES = 72; -const SEGMENT_32_HEADER_BYTES = 56; const SECTION_64_BYTES = 80; const SECTION_32_BYTES = 68; @@ -116,12 +119,15 @@ interface BunProbeSource { interface SectionWindow { readonly carrier: Exclude; readonly fileOffset: number; - readonly declaredSize: number; readonly available: number; /** The declared section extent ends past EOF. */ readonly truncated: boolean; + /** The Mach-O table could not be fully framed after this section was located. */ + readonly loadCommandsFailure?: string; } +type SectionClaim = SectionWindow | { readonly failure: ArtifactReaderFailure }; + /** * Locate at most one graph claim with bounded reads of headers, length * prefixes, and suffixes. Payload data is not read. Multiple real claims are @@ -135,7 +141,7 @@ export const probeBunStandaloneGraph = async ( ): Promise => { abortIfNeeded(signal); const source = { handle, fileSize, signal, limits }; - let claims: readonly SectionWindow[]; + let claims: readonly SectionClaim[]; try { claims = [ ...(await machOClaims(source, 0, fileSize)), @@ -150,7 +156,10 @@ export const probeBunStandaloneGraph = async ( const real: BunStandaloneProbe[] = []; for (const claim of claims) { abortIfNeeded(signal); - const evaluated = await evaluateSection(source, claim); + const evaluated = + "failure" in claim + ? presentFailure(claim.failure) + : await evaluateSection(source, claim); if (evaluated.status === "present") { if (real.length > 0) return presentFailure( @@ -380,6 +389,10 @@ const evaluateSection = async ( ); const failure = suffixFailure(suffix, length, limits); if (failure !== undefined) return presentFailure(failure); + if (claim.loadCommandsFailure !== undefined) + return presentFailure( + bunFormatFailure(`Mach-O load commands: ${claim.loadCommandsFailure}`), + ); return { status: "present", claim: { carrier: claim.carrier, payloadOffset, payloadLength: length }, @@ -473,7 +486,7 @@ const machOClaims = async ( source: BunProbeSource, imageOffset: number, imageLimit: number, -): Promise => { +): Promise => { const { handle, fileSize, signal, limits } = source; if (imageOffset < 0 || imageOffset >= fileSize) return []; const header = await tryRead(handle, imageOffset, 12, fileSize, signal); @@ -512,12 +525,16 @@ const machOClaims = async ( signal, ); if (commands === null || commands.length !== sizeofcmds) return []; - const claims: SectionWindow[] = []; + const claims: SectionClaim[] = []; const cursor = new MachoLoadCommandCursor(table); + let framingFailure: string | undefined; while (cursor.nextOffset !== null) { abortIfNeeded(signal); const read = cursor.read(commands.subarray(cursor.nextOffset)); - if (!read.ok) break; + if (!read.ok) { + framingFailure = read.error; + break; + } const { command: cmd, offset, size } = read.value; if (cmd === LC.SEGMENT_64 || cmd === LC.SEGMENT) for (const claim of segmentClaims( @@ -529,7 +546,15 @@ const machOClaims = async ( )) claims.push(claim); } - return claims; + const complete = cursor.finish(); + if (!complete.ok) framingFailure ??= complete.error; + return framingFailure === undefined + ? claims + : claims.map((claim) => + "failure" in claim + ? claim + : { ...claim, loadCommandsFailure: framingFailure }, + ); }; const segmentClaims = ( @@ -538,34 +563,44 @@ const segmentClaims = ( wide: boolean, imageOffset: number, fileSize: number, -): readonly SectionWindow[] => { - const headerBytes = wide ? SEGMENT_64_HEADER_BYTES : SEGMENT_32_HEADER_BYTES; +): readonly SectionClaim[] => { + const parsedSegment = readMachoSegmentHeader(command, wide, littleEndian); + if (!parsedSegment.ok) return []; + const segment = parsedSegment.value; + const { headerSize, sectionCount } = segment; const sectionBytes = wide ? SECTION_64_BYTES : SECTION_32_BYTES; - if (command.length < headerBytes) return []; - const nsects = readU32(command, wide ? 64 : 48, littleEndian); - if (headerBytes + nsects * sectionBytes > command.length) return []; - const claims: SectionWindow[] = []; - for (let index = 0; index < nsects; index += 1) { - const start = headerBytes + index * sectionBytes; - const section = command.subarray(start, start + sectionBytes); - if (!exactName(section.subarray(0, 16), "__bun")) continue; - if (!exactName(section.subarray(16, 32), "__BUN")) continue; - const size = wide - ? readBoundedU64(section, 40, littleEndian) - : readU32(section, 36, littleEndian); - const offset = readU32(section, wide ? 48 : 40, littleEndian); - if (size === undefined) { + if (headerSize + sectionCount * sectionBytes > command.length) return []; + const claims: SectionClaim[] = []; + for (let index = 0; index < sectionCount; index += 1) { + const start = headerSize + index * sectionBytes; + const bytes = command.subarray(start, start + sectionBytes); + if (!exactName(bytes.subarray(0, 16), "__bun")) continue; + if (!exactName(bytes.subarray(16, 32), "__BUN")) continue; + const parsedSection = readMachoSectionHeader(bytes, wide, littleEndian); + if (!parsedSection.ok) continue; + const section = parsedSection.value; + const { issue } = machoSectionBacking(section, segment); + if (issue !== null) { claims.push({ - carrier: "mach-o-section", - fileOffset: imageOffset + offset, - declaredSize: Number.MAX_SAFE_INTEGER, - available: 0, - truncated: false, + failure: bunFormatFailure(`Mach-O __bun section ${issue}`), + }); + continue; + } + if (section.size > BigInt(Number.MAX_SAFE_INTEGER)) { + claims.push({ + failure: bunFormatFailure( + "Mach-O __bun section size is not a safe integer", + ), }); continue; } claims.push( - windowFor("mach-o-section", imageOffset + offset, size, fileSize), + windowFor( + "mach-o-section", + imageOffset + section.offset, + Number(section.size), + fileSize, + ), ); } return claims; @@ -574,7 +609,7 @@ const segmentClaims = ( const fatClaims = async ( source: BunProbeSource, prefix: Buffer, -): Promise => { +): Promise => { const { handle, fileSize, signal } = source; let parsed = readFatContainerHeader(prefix, fileSize); if (parsed.state === "needs-data") { @@ -589,7 +624,7 @@ const fatClaims = async ( parsed = readFatContainerHeader(table, fileSize); } if (parsed.state !== "parsed") return []; - const claims: SectionWindow[] = []; + const claims: SectionClaim[] = []; for (const slice of parsed.slices) { abortIfNeeded(signal); if (parsed.rangeIssues[slice.index] !== null) continue; @@ -766,7 +801,6 @@ const windowFor = ( return { carrier, fileOffset, - declaredSize, available: 0, truncated: false, }; @@ -774,7 +808,6 @@ const windowFor = ( return { carrier, fileOffset, - declaredSize, available: Math.min(declaredSize, room), truncated: declaredSize > room, }; diff --git a/src/artifacts/bun/BunStandalone.fixture.ts b/src/artifacts/bun/BunStandalone.fixture.ts index ce433fbc22..3ca9f78dd9 100644 --- a/src/artifacts/bun/BunStandalone.fixture.ts +++ b/src/artifacts/bun/BunStandalone.fixture.ts @@ -121,45 +121,20 @@ export const bunPrefixedPayload = (payload: Buffer): Buffer => { return Buffer.concat([prefix, payload]); }; -export const machoBunSection = (section: Buffer): Buffer => { - const headerBytes = 32; - const commandBytes = 72 + 80; - const contentOffset = headerBytes + commandBytes; - const bytes = Buffer.alloc(contentOffset + section.length); - bytes.writeUInt32LE(0xfeedfacf, 0); - bytes.writeUInt32LE(0x0100000c, 4); - bytes.writeUInt32LE(2, 12); - bytes.writeUInt32LE(1, 16); - bytes.writeUInt32LE(commandBytes, 20); - bytes.writeUInt32LE(0x19, 32); - bytes.writeUInt32LE(commandBytes, 36); - bytes.write("__BUN", 40, "utf8"); - bytes.writeBigUInt64LE(BigInt(section.length), 64); - bytes.writeBigUInt64LE(BigInt(contentOffset), 72); - bytes.writeBigUInt64LE(BigInt(section.length), 80); - bytes.writeUInt32LE(1, 96); - bytes.write("__bun", 104, "utf8"); - bytes.write("__BUN", 120, "utf8"); - bytes.writeBigUInt64LE(BigInt(section.length), 144); - bytes.writeUInt32LE(contentOffset, 152); - section.copy(bytes, contentOffset); - return bytes; -}; +export const machoBunSection = (section: Buffer): Buffer => + machoBunSections([section]); /** Two real `__bun` sections. Inventory must not guess which graph to read. */ export const machoBunSections = (sections: readonly Buffer[]): Buffer => { const headerBytes = 32; const sectionCount = sections.length; const commandBytes = 72 + 80 * sectionCount; - let contentOffset = headerBytes + commandBytes; - const contents: Buffer[] = []; - const offsets: number[] = []; - for (const section of sections) { - offsets.push(contentOffset); - contents.push(section); - contentOffset += section.length; - } - const bytes = Buffer.alloc(contentOffset); + const payloadAt = headerBytes + commandBytes; + const payloadSize = sections.reduce( + (sum, section) => sum + section.length, + 0, + ); + const bytes = Buffer.alloc(payloadAt + payloadSize); bytes.writeUInt32LE(0xfeedfacf, 0); bytes.writeUInt32LE(0x0100000c, 4); bytes.writeUInt32LE(2, 12); @@ -168,15 +143,20 @@ export const machoBunSections = (sections: readonly Buffer[]): Buffer => { bytes.writeUInt32LE(0x19, 32); bytes.writeUInt32LE(commandBytes, 36); bytes.write("__BUN", 40, "utf8"); + bytes.writeBigUInt64LE(BigInt(payloadSize), 64); + bytes.writeBigUInt64LE(BigInt(payloadAt), 72); + bytes.writeBigUInt64LE(BigInt(payloadSize), 80); bytes.writeUInt32LE(sectionCount, 96); + let offset = payloadAt; sections.forEach((section, index) => { const sectionHeader = 32 + 72 + index * 80; - const offset = offsets[index] ?? 0; bytes.write("__bun", sectionHeader, "utf8"); bytes.write("__BUN", sectionHeader + 16, "utf8"); + bytes.writeBigUInt64LE(BigInt(offset - payloadAt), sectionHeader + 32); bytes.writeBigUInt64LE(BigInt(section.length), sectionHeader + 40); bytes.writeUInt32LE(offset, sectionHeader + 48); section.copy(bytes, offset); + offset += section.length; }); return bytes; }; diff --git a/src/artifacts/deno/DenoStandaloneArtifactReader.test.ts b/src/artifacts/deno/DenoStandaloneArtifactReader.test.ts index 4ea247b9e9..166721d3f8 100644 --- a/src/artifacts/deno/DenoStandaloneArtifactReader.test.ts +++ b/src/artifacts/deno/DenoStandaloneArtifactReader.test.ts @@ -1321,6 +1321,30 @@ it("refuses a confirmed Intel trailer when the allowance ends the outer search", }); }); +it("locates a PE resource past a distant DOS stub using positional reads", async () => { + const section = buildDenoSection(); + const { bytes: image } = peResourceFixture( + true, + [{ type: 10, name: "D3N0L4ND", language: 0, payload: section }], + 65536, + 4, + 0x20080, + ); + const handle = bytesHandle(image, (length) => { + if (length > 512) throw new Error("Read exceeded the header record bounds"); + }); + await expect( + locateDenoStandalone(handle, image.length), + ).resolves.toMatchObject({ + status: "present", + location: { + carrier: "pe", + embedding: "pe-resource", + length: section.length, + }, + }); +}); + it("locates a small D3N0L4ND resource in a PE larger than 512 MiB", async () => { const section = buildDenoSection(); const image = denoPe([section]); @@ -1342,6 +1366,23 @@ it("locates a small D3N0L4ND resource in a PE larger than 512 MiB", async () => }); }); +it("keeps a PE resource read failure when the caller aborts with that same error", async () => { + const image = denoPe([buildDenoSection()]); + const controller = new AbortController(); + const failure = Object.assign(new Error("PE resource read failed"), { + code: "EIO", + }); + const handle = bytesHandle(image, (length) => { + if (length === 16) { + controller.abort(failure); + throw failure; + } + }); + await expect( + locateDenoStandalone(handle, image.length, controller.signal), + ).rejects.toBe(failure); +}); + it("fails closed when a readable D3N0L4ND resource sits beside an unreadable RT_RCDATA branch", async () => { const fixture = peResourceFixture( true, diff --git a/src/artifacts/deno/DenoStandaloneLocation.ts b/src/artifacts/deno/DenoStandaloneLocation.ts index 5832674935..ec02613973 100644 --- a/src/artifacts/deno/DenoStandaloneLocation.ts +++ b/src/artifacts/deno/DenoStandaloneLocation.ts @@ -7,7 +7,7 @@ import { import type { FileHandle } from "node:fs/promises"; import { - isMachoZeroFillSection, + machoSectionBacking, readMachoSectionHeader, } from "../../domain/apple/machoSectionHeader.js"; import { @@ -26,9 +26,12 @@ import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclaration import { readElfFixedHeader } from "../../domain/elfFixedHeader.js"; import { MAX_INSPECT_ELF_NOTE_ENTRIES } from "../../domain/native/elfNotes.js"; import { + ELF_NOTE_HEADER_BYTES, elfNoteAlignment, - elfNoteLayout, - readElfNoteHeader, + elfNoteSectionStorage, + isElfNotePadding, + readElfNoteFrame, + type ElfNoteAlignment, } from "../../domain/native/elfNoteLayout.js"; import { MAX_INSPECT_PE_DIRECTORY_ENTRIES, @@ -55,7 +58,6 @@ const ELF64_PROGRAM_HEADER_BYTES = 56; const ELF32_PROGRAM_HEADER_BYTES = 32; const ELF64_SECTION_HEADER_BYTES = 64; const ELF32_SECTION_HEADER_BYTES = 40; -const SHT_NOTE = 7; const RT_RCDATA = 10; const RESOURCE_NAME = "D3N0L4ND"; const SECTION_NAME = "d3n0l4nd"; @@ -64,7 +66,6 @@ const SEGMENT_NAME = "__SUI"; const LINKEDIT_SEGMENT_NAME = "__LINKEDIT"; const ELF_NOTE_OWNER = Buffer.from("SUI\0", "latin1"); const ELF_NOTE_TYPE = 0x53554901; -const PE_HEADER_PROBE_BYTES = 64 * 1024; const INTEL_CHUNK_BYTES = 1024 * 1024; /** Trailer candidates examined before the search stops. */ const MAX_DENO_INTEL_TRAILER_SENTINELS = 64; @@ -179,7 +180,11 @@ const findDenoSection = async ( if (prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))) return collapseRanges(carrier, "elf", await locateElfNotes(carrier)); if (prefix[0] === 0x4d && prefix[1] === 0x5a) - return collapseRanges(carrier, "pe", await locatePeResources(carrier)); + return collapseRanges( + carrier, + "pe", + await locatePeResources(carrier, prefix), + ); return undefined; }; @@ -358,46 +363,19 @@ const namesDenoSection = (body: Uint8Array, at: number): boolean => * matching MachoImage, even when the file itself still holds them. */ const denoSectionRange = ( - record: { - readonly address: bigint; - readonly size: bigint; - readonly offset: number; - readonly flags: number; - }, - segment: { - readonly fileOffset: bigint; - readonly fileSize: bigint; - readonly address: bigint; - readonly memorySize: bigint; - }, + record: Parameters[0], + segment: Parameters[1], base: number, sliceSize: number, fileSize: number, ): SectionRange => { - if (isMachoZeroFillSection(record.flags)) - throw denoCarrierFailure("Mach-O d3n0l4nd section is zero-fill"); + const { issue } = machoSectionBacking(record, segment); + if (issue !== null) + throw denoCarrierFailure(`Mach-O d3n0l4nd section ${issue}`); if (record.size > BigInt(Number.MAX_SAFE_INTEGER)) throw denoCarrierFailure( "Mach-O d3n0l4nd section size is not a safe integer", ); - const virtualDelta = record.address - segment.address; - if ( - virtualDelta < 0n || - virtualDelta > segment.memorySize || - record.size > segment.memorySize - virtualDelta - ) - throw denoCarrierFailure( - "Mach-O d3n0l4nd section exceeds its segment's virtual extent", - ); - const segmentDelta = BigInt(record.offset) - segment.fileOffset; - if ( - segmentDelta < 0n || - segmentDelta > segment.fileSize || - record.size > segment.fileSize - segmentDelta - ) - throw denoCarrierFailure( - "Mach-O d3n0l4nd section exceeds its segment's file extent", - ); const length = Number(record.size); const fileOffset = record.offset; if ( @@ -536,7 +514,7 @@ const locateIntelTrailers = async ( interface ElfNoteTable { offset: number; length: number; - alignment: number; + alignment: ElfNoteAlignment; copies: number; } @@ -661,8 +639,9 @@ const locateElfNotes = async (carrier: Carrier): Promise => { damaged(parsed.error.message); continue; } - if (parsed.value.type !== SHT_NOTE) continue; - if (parsed.value.compressed) { + const storage = elfNoteSectionStorage(parsed.value); + if (storage === "not-note") continue; + if (storage === "compressed") { damaged("compressed ELF note sections are unsupported"); continue; } @@ -727,46 +706,53 @@ const scanElfNoteTable = async ( }; let cursor = 0; let notes = 0; - while (cursor + 12 <= table.length) { + while (cursor + ELF_NOTE_HEADER_BYTES <= table.length) { abortIfNeeded(carrier.signal); notes += 1; if (examined + notes * table.copies > MAX_INSPECT_ELF_NOTE_ENTRIES) { walk.damage ??= denoElfNoteLimit(); return notes; } - const header = await readExact(carrier, table.offset + cursor, 12); + const header = await readExact( + carrier, + table.offset + cursor, + ELF_NOTE_HEADER_BYTES, + ); if (header === undefined) return stop("ELF note header is truncated", notes); - const parsed = readElfNoteHeader(header, little); + const parsed = readElfNoteFrame( + header, + little, + table.alignment, + table.length - cursor, + ); if (!parsed.ok) return stop(parsed.error.message, notes); - const { namesz, descsz, type } = parsed.value; - const layout = elfNoteLayout(namesz, descsz, table.alignment); + const { namesz, descsz, type, descriptor, next, framing } = parsed.value; const sui = namesz === ELF_NOTE_OWNER.length && type === ELF_NOTE_TYPE; - if ( - !Number.isSafeInteger(layout.descriptor) || - !Number.isSafeInteger(layout.next) || - layout.next < 12 || - layout.next > table.length - cursor - ) { + if (framing !== "complete") { // The owner and descriptor name are read within the table, apart from // the claimed extent, so a confirmed Deno note still fails closed. - if (sui && (await confirmsSuiNote(carrier, table, cursor, layout))) + if (sui && (await confirmsSuiNote(carrier, table, cursor, descriptor))) throw denoCarrierFailure("ELF SUI note entry exceeds its table"); return stop("ELF note entry exceeds its table", notes); } if (sui) { - const name = await readExact(carrier, table.offset + cursor + 12, namesz); + const name = await readExact( + carrier, + table.offset + cursor + ELF_NOTE_HEADER_BYTES, + namesz, + ); if (name === undefined) return stop("ELF note name is truncated", notes); if (name.equals(ELF_NOTE_OWNER)) { const payload = await readSuiRange( carrier, - table.offset + cursor + layout.descriptor, + table.offset + cursor + descriptor, descsz, ); if (payload !== undefined) walk.found.push(payload); } } - cursor += layout.next; + cursor += next; } if (cursor >= table.length) return notes; // A table too short for any note still costs one read of its tail. @@ -796,7 +782,7 @@ const noteTableTailIssue = async ( ); if (tail === undefined) return denoCarrierFailure("ELF note table is truncated"); - if (tail.some((byte) => byte !== 0)) + if (!isElfNotePadding(tail)) return denoCarrierFailure("ELF note table has trailing non-zero bytes"); return undefined; }; @@ -806,17 +792,20 @@ const confirmsSuiNote = async ( carrier: Carrier, table: ElfNoteTable, cursor: number, - layout: { readonly descriptor: number }, + descriptor: number, ): Promise => { - const wanted = layout.descriptor + 2 + SECTION_NAME_BYTES.length; - if (!Number.isSafeInteger(wanted) || wanted > table.length - cursor) - return false; + const wanted = descriptor + 2 + SECTION_NAME_BYTES.length; + if (wanted > table.length - cursor) return false; const at = table.offset + cursor; - const name = await readExact(carrier, at + 12, ELF_NOTE_OWNER.length); + const name = await readExact( + carrier, + at + ELF_NOTE_HEADER_BYTES, + ELF_NOTE_OWNER.length, + ); if (name === undefined || !name.equals(ELF_NOTE_OWNER)) return false; const prefix = await readExact( carrier, - at + layout.descriptor, + at + descriptor, 2 + SECTION_NAME_BYTES.length, ); return ( @@ -852,17 +841,14 @@ const readSuiRange = async ( return { offset, length, embedding: "elf-note" }; }; -const locatePeResources = async (carrier: Carrier): Promise => { - const headers = await readExact( - carrier, - 0, - Math.min(carrier.fileSize, PE_HEADER_PROBE_BYTES), - ); - if (headers === undefined) return []; +const locatePeResources = async ( + carrier: Carrier, + prefix: Buffer, +): Promise => { let payloads: Awaited>; try { payloads = await locatePeResourcePayloads( - headers, + prefix, carrier.fileSize, (offset, length) => readExact(carrier, offset, length), RT_RCDATA, @@ -870,7 +856,9 @@ const locatePeResources = async (carrier: Carrier): Promise => { MAX_INSPECT_PE_DIRECTORY_ENTRIES, ); } catch (cause) { - throw artifactParseFailure(cause, carrier.signal); + // Range reads tag cancellation at its origin. Coincidence with the + // caller's abort reason cannot turn a physical read failure into cancellation. + throw artifactParseFailure(cause, undefined); } return payloads.map(({ offset, bytes }) => { if (bytes > MAX_INSPECT_PE_FILE_BYTES) throw denoPeLimit(); diff --git a/src/artifacts/nodeSea/NodeSeaLocation.ts b/src/artifacts/nodeSea/NodeSeaLocation.ts index 826de2cb04..194b34069c 100644 --- a/src/artifacts/nodeSea/NodeSeaLocation.ts +++ b/src/artifacts/nodeSea/NodeSeaLocation.ts @@ -4,7 +4,10 @@ import { readArtifactRange as readExact, } from "../ArtifactCarrierRange.js"; import { readMachoSegmentHeader } from "../../domain/apple/machoSegmentHeader.js"; -import { readMachoSectionHeader } from "../../domain/apple/machoSectionHeader.js"; +import { + machoSectionBacking, + readMachoSectionHeader, +} from "../../domain/apple/machoSectionHeader.js"; import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; @@ -42,11 +45,16 @@ import { readMachoHeaderPrefixFacts, } from "../../domain/apple/machoContainer.js"; import { readElfFixedHeader } from "../../domain/elfFixedHeader.js"; -import { readMachoLoadCommandTableHeader } from "../../domain/apple/machoLoadCommands.js"; import { + MachoLoadCommandCursor, + readMachoLoadCommandTableHeader, +} from "../../domain/apple/machoLoadCommands.js"; +import { + ELF_NOTE_HEADER_BYTES, elfNoteAlignment, - elfNoteLayout, - readElfNoteHeader, + elfNoteSectionStorage, + isElfNotePadding, + readElfNoteFrame, } from "../../domain/native/elfNoteLayout.js"; import { NODE_SEA_DUPLICATE_BLOB, @@ -62,13 +70,11 @@ import { import { sha256Hex } from "../../kernel/sha256Hex.js"; const PT_NOTE = 4; -const SHT_NOTE = 7; const RT_RCDATA = 10; const RESOURCE_NAME = "NODE_SEA_BLOB"; const SEA_SECTION = "__NODE_SEA_BLOB"; const FUSE_LENGTH = "NODE_SEA_FUSE_".length + 32 + 2; // PE header structures must fit this prefix for the bounded name probe. -const PE_HEADER_PROBE_BYTES = 64 * 1024; /** One injected blob inside a native carrier. Offsets are carrier file offsets. */ export interface NodeSeaLocation { @@ -145,7 +151,11 @@ export const locateNodeSea = async ( await locateElfNotes(carrier, prefix), ); if (prefix[0] === 0x4d && prefix[1] === 0x5a) - return collapseRanges(carrier, "pe", await locatePeResources(carrier)); + return collapseRanges( + carrier, + "pe", + await locatePeResources(carrier, prefix), + ); return undefined; }; @@ -296,7 +306,6 @@ const locateThinMachO = async ( const { headerSize, littleEndian: little, - commandCount: ncmds, commandBytes: sizeofcmds, } = framing.value; const limits = carrier.limits ?? DEFAULT_NODE_SEA_READER_LIMITS; @@ -311,22 +320,17 @@ const locateThinMachO = async ( const commands = await readExact(carrier, base + headerSize, sizeofcmds); if (commands === undefined) return []; const found: BlobRange[] = []; - let offset = 0; - let seen = 0; - while (offset + 8 <= commands.length && seen < ncmds) { + const cursor = new MachoLoadCommandCursor(framing.value); + while (cursor.nextOffset !== null) { abortIfNeeded(carrier.signal); - const cmd = readU32(commands, offset, little); - const cmdsize = readU32(commands, offset + 4, little); - if (cmdsize < 8 || offset + cmdsize > commands.length) { - if (found.length > 0) - throw formatFailure(NODE_SEA_MACHO_COMMANDS_TRUNCATED); - return found; - } + const read = cursor.read(commands.subarray(cursor.nextOffset)); + if (!read.ok) break; + const { command: cmd, offset, size } = read.value; if (cmd === LC.SEGMENT || cmd === LC.SEGMENT_64) { const segment64 = cmd === LC.SEGMENT_64; const sectionSize = segment64 ? 80 : 68; const parsedSegment = readMachoSegmentHeader( - commands.subarray(offset, offset + cmdsize), + commands.subarray(offset, offset + size), segment64, little, ); @@ -342,10 +346,7 @@ const locateThinMachO = async ( const segmentHeader = segment.headerSize; const nsects = segment.sectionCount; const table = offset + segmentHeader; - if ( - nsects > Math.floor((cmdsize - segmentHeader) / sectionSize) || - table + nsects * sectionSize > offset + cmdsize - ) + if (nsects > Math.floor((size - segmentHeader) / sectionSize)) throw formatFailure(NODE_SEA_MACHO_SEGMENT_TRUNCATED); for (let index = 0; index < nsects; index += 1) { const section = table + index * sectionSize; @@ -358,6 +359,9 @@ const locateThinMachO = async ( throw formatFailure(NODE_SEA_MACHO_SEGMENT_TRUNCATED); const record = parsedSection.value; if (cString(record.nameBytes, 0, 16) !== SEA_SECTION) continue; + const { issue } = machoSectionBacking(record, segment); + if (issue !== null) + throw formatFailure(`Mach-O Node SEA section ${issue}`); const length = Number(record.size); const fileOffset = record.offset; if (!Number.isSafeInteger(length)) @@ -371,10 +375,8 @@ const locateThinMachO = async ( } } } - offset += cmdsize; - seen += 1; } - if (found.length > 0 && (seen !== ncmds || offset !== commands.length)) + if (found.length > 0 && !cursor.finish().ok) throw formatFailure(NODE_SEA_MACHO_COMMANDS_TRUNCATED); return found; }; @@ -412,19 +414,23 @@ const locateElfNotes = async ( const minimumProgram = elf64 ? 56 : 32; const minimumSection = elf64 ? 64 : 40; const found: BlobRange[] = []; - let opaque = false; - // Every note header occupies at least 12 bytes, so disjoint tables hold at - // most one note per 12 file bytes. Headers that point at the same bytes - // would otherwise rescan them once per declaration. - const scan: NoteScan = { little, notes: Math.floor(carrier.fileSize / 12) }; + let opaque: string | undefined; + // Each note header takes at least 12 file bytes. The containing program or + // section header also makes room in this allowance for one short tail read. + // Overlapping declarations must not repeatedly scan the same bytes. + const scan: NoteScan = { + little, + frames: Math.floor(carrier.fileSize / ELF_NOTE_HEADER_BYTES), + }; const programs = await readElfTables(carrier, { offset: phoff, count: phnum, entrySize: phentsize, minimumEntry: minimumProgram, }); - if (programs === undefined) opaque = phnum > 0; - else + if (programs === undefined && phnum > 0) + opaque = NODE_SEA_ELF_TABLE_TRUNCATED; + if (programs !== undefined) for (const entry of programs) { const parsedProgram = readElfProgramHeader( entry, @@ -454,15 +460,14 @@ const locateElfNotes = async ( scan, found.length > 0, ); - if (scanned === undefined) opaque = true; + if (scanned === undefined) opaque ??= NODE_SEA_ELF_TABLE_TRUNCATED; else for (const range of scanned) found.push(range); } // The runtime locates the blob through PT_NOTE segments. Injectors can // leave stale or misaligned SHT_NOTE entries, so section notes are only a // fallback when no program-header table is readable. if (programs !== undefined && phnum > 0) { - if (found.length > 0 && opaque) - throw formatFailure(NODE_SEA_ELF_TABLE_TRUNCATED); + if (found.length > 0 && opaque !== undefined) throw formatFailure(opaque); return found; } const sections = await readElfTables(carrier, { @@ -471,8 +476,9 @@ const locateElfNotes = async ( entrySize: shentsize, minimumEntry: minimumSection, }); - if (sections === undefined) opaque = opaque || shnum > 0; - else + if (sections === undefined && shnum > 0) + opaque ??= NODE_SEA_ELF_TABLE_TRUNCATED; + if (sections !== undefined) for (const entry of sections) { const parsedSection = readElfSectionHeader( entry, @@ -481,7 +487,13 @@ const locateElfNotes = async ( ); if (!parsedSection.ok) continue; const section = parsedSection.value; - if (section.type !== SHT_NOTE) continue; + const storage = elfNoteSectionStorage(section); + if (storage === "not-note") continue; + if (storage === "compressed") { + opaque ??= + "Compressed ELF note sections cannot establish raw Node SEA blob offsets"; + continue; + } const note = { offset: section.offset <= BigInt(Number.MAX_SAFE_INTEGER) @@ -502,11 +514,10 @@ const locateElfNotes = async ( scan, found.length > 0, ); - if (scanned === undefined) opaque = true; + if (scanned === undefined) opaque ??= NODE_SEA_ELF_TABLE_TRUNCATED; else for (const range of scanned) found.push(range); } - if (found.length > 0 && opaque) - throw formatFailure(NODE_SEA_ELF_TABLE_TRUNCATED); + if (found.length > 0 && opaque !== undefined) throw formatFailure(opaque); return found; }; @@ -552,12 +563,21 @@ const readElfTables = async ( return entries; }; -/** One carrier's note byte order and the note headers it may still read. */ +/** One carrier's note byte order and the framing reads it may still perform. */ interface NoteScan { readonly little: boolean; - notes: number; + frames: number; } +const chargeNoteFrame = (scan: NoteScan, confirmed: boolean): boolean => { + if (scan.frames === 0) { + if (confirmed) throw formatFailure(NODE_SEA_ELF_NOTES_REPEATED); + return false; + } + scan.frames -= 1; + return true; +}; + const scanElfNoteTable = async ( carrier: Carrier, note: { @@ -578,88 +598,81 @@ const scanElfNoteTable = async ( const alignment = elfNoteAlignment(note.align === 8 ? 8 : 4); const found: BlobRange[] = []; let cursor = 0; - while (cursor + 12 <= note.length) { + while (cursor + ELF_NOTE_HEADER_BYTES <= note.length) { abortIfNeeded(carrier.signal); - // Past the file's note capacity the tables overlap: an unconfirmed - // carrier stays unrecognized and a confirmed one fails closed. - if (scan.notes === 0) { - if (alreadyFound || found.length > 0) - throw formatFailure(NODE_SEA_ELF_NOTES_REPEATED); + if (!chargeNoteFrame(scan, alreadyFound || found.length > 0)) return undefined; - } - scan.notes -= 1; - const header = await readExact(carrier, note.offset + cursor, 12); + const header = await readExact( + carrier, + note.offset + cursor, + ELF_NOTE_HEADER_BYTES, + ); if (header === undefined) return failNoteTable(alreadyFound || found.length > 0); - const parsedHeader = readElfNoteHeader(header, scan.little); - if (!parsedHeader.ok) - return failNoteTable(alreadyFound || found.length > 0); - const { namesz, descsz } = parsedHeader.value; - if (cursor > note.length - 12 || namesz > note.length - cursor - 12) - return failNoteTable(alreadyFound || found.length > 0); - let layout: ReturnType; - try { - layout = elfNoteLayout(namesz, descsz, alignment); - } catch { - return failNoteTable(alreadyFound || found.length > 0); - } - if ( - !Number.isSafeInteger(layout.descriptor) || - !Number.isSafeInteger(layout.next) || - layout.next < 12 - ) + const frame = readElfNoteFrame( + header, + scan.little, + alignment, + note.length - cursor, + ); + if (!frame.ok || frame.value.framing === "truncated-name") return failNoteTable(alreadyFound || found.length > 0); + const { namesz, descsz, descriptor, next, framing } = frame.value; // Only the exact SEA owner matters here. A bounded prefix distinguishes // it without retaining an unrelated vendor's potentially long name. const name = await readExact( carrier, - note.offset + cursor + 12, + note.offset + cursor + ELF_NOTE_HEADER_BYTES, Math.min(namesz, RESOURCE_NAME.length + 1), ); if (name === undefined) return failNoteTable(alreadyFound || found.length > 0); const owner = cString(name, 0, name.length); - const descriptorFits = - layout.descriptor <= note.length - cursor && - descsz <= note.length - cursor - layout.descriptor; if (owner === RESOURCE_NAME) { - if (!descriptorFits) + if (framing === "truncated-descriptor") throw formatFailure(NODE_SEA_ELF_DESCRIPTOR_TRUNCATED); admitBlobBytes(carrier, descsz); - const blobOffset = note.offset + cursor + layout.descriptor; - if ( - blobOffset > carrier.fileSize || - descsz > carrier.fileSize - blobOffset - ) - throw formatFailure(NODE_SEA_ELF_DESCRIPTOR_TRUNCATED); - found.push({ offset: blobOffset, length: descsz }); + found.push({ offset: note.offset + cursor + descriptor, length: descsz }); } - if (layout.next > note.length - cursor) + if (framing !== "complete") + return failNoteTable(alreadyFound || found.length > 0); + cursor += next; + } + if (cursor < note.length) { + const confirmed = alreadyFound || found.length > 0; + if (!chargeNoteFrame(scan, confirmed)) return undefined; + const tail = await readExact( + carrier, + note.offset + cursor, + note.length - cursor, + ); + if (tail === undefined) return failNoteTable(confirmed); + if (!isElfNotePadding(tail)) return failNoteTable( - alreadyFound || found.length > 0 || owner === RESOURCE_NAME, + confirmed, + "ELF note table has trailing non-zero bytes", ); - cursor += layout.next; } return found; }; -const failNoteTable = (confirmed: boolean): undefined => { - if (confirmed) throw formatFailure(NODE_SEA_ELF_TABLE_TRUNCATED); +const failNoteTable = ( + confirmed: boolean, + detail = NODE_SEA_ELF_TABLE_TRUNCATED, +): undefined => { + if (confirmed) throw formatFailure(detail); return undefined; }; -const locatePeResources = async (carrier: Carrier): Promise => { +const locatePeResources = async ( + carrier: Carrier, + prefix: Buffer, +): Promise => { // Probe for the NODE_SEA_BLOB name first so a malformed resource tree in an // ordinary PE stays a native-classification concern, not a SEA failure. - const headers = await readExact( - carrier, - 0, - Math.min(carrier.fileSize, PE_HEADER_PROBE_BYTES), - ); if ( - headers === undefined || !(await hasPeResourceName( - headers, + prefix, carrier.fileSize, (offset, length) => readExact(carrier, offset, length), RT_RCDATA, @@ -725,6 +738,3 @@ const cString = (bytes: Buffer, offset: number, length: number): string => { while (end < limit && bytes[end] !== 0) end += 1; return bytes.toString("latin1", offset, end); }; - -const readU32 = (bytes: Buffer, offset: number, little: boolean): number => - little ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset); diff --git a/src/domain/apple/machoImage.ts b/src/domain/apple/machoImage.ts index 5dd09b4b32..5bc4cfd099 100644 --- a/src/domain/apple/machoImage.ts +++ b/src/domain/apple/machoImage.ts @@ -2,7 +2,7 @@ import { LC } from "./machoLoadCommandCodes.js"; import type { FileMapping, ZeroFillMapping } from "../virtualFileMapping.js"; import { decodeMachoFixedName } from "./appleMachoNames.js"; import { - isMachoZeroFillSection, + machoSectionBacking, readMachoSectionHeader, type MachoSectionHeader, } from "./machoSectionHeader.js"; @@ -144,10 +144,7 @@ export const readMachoImage = ( segmentMapping: mapping ?? null, segmentUnmapped: unmapped, unmapped: unmapped || mapping === undefined, - segmentAddress: address, - segmentMemorySize: memorySize, - segmentFileOffset: fileOffset, - segmentFileSize: fileSize, + segment: parsedSegment.value, }), ); } @@ -187,10 +184,7 @@ const machoImageSection = ({ segmentMapping, segmentUnmapped, unmapped, - segmentAddress, - segmentMemorySize, - segmentFileOffset, - segmentFileSize, + segment, }: { readonly fileBytes: number; readonly section: MachoSectionHeader; @@ -198,26 +192,13 @@ const machoImageSection = ({ readonly segmentMapping: FileMapping | null; readonly segmentUnmapped: boolean; readonly unmapped: boolean; - readonly segmentAddress: bigint; - readonly segmentMemorySize: bigint; - readonly segmentFileOffset: bigint; - readonly segmentFileSize: bigint; + readonly segment: Parameters[1]; }): ImageSection => { const { flags, address: sectionAddress, size: sectionSize } = section; const sectionOffset = BigInt(section.offset); const sectionName = decodeMachoFixedName(section.nameBytes); const name = `${decodeMachoFixedName(section.segmentNameBytes)},${sectionName}`; - const zeroFill = isMachoZeroFillSection(flags); - const addressDelta = sectionAddress - segmentAddress; - const fileDelta = sectionOffset - segmentFileOffset; - const inSegmentMemory = - addressDelta >= 0n && - addressDelta <= segmentMemorySize && - sectionSize <= segmentMemorySize - addressDelta; - const inSegmentFile = - fileDelta >= 0n && - fileDelta <= segmentFileSize && - sectionSize <= segmentFileSize - fileDelta; + const backing = machoSectionBacking(section, segment); const declaredRange = declaredFileRange( fileBytes, sectionOffset, @@ -226,8 +207,7 @@ const machoImageSection = ({ const range = unmapped ? { offset: 0, size: 0, file_backed: false } : declaredRange; - const fileBacked = - range.file_backed && !zeroFill && inSegmentMemory && inSegmentFile; + const fileBacked = range.file_backed && backing.issue === null; const readOnly = fileBacked && (protection & 1) !== 0 && @@ -249,7 +229,7 @@ const machoImageSection = ({ }, ...range, file_backed: fileBacked, - on_disk: declaredRange.file_backed && !zeroFill && inSegmentFile, + on_disk: declaredRange.file_backed && backing.onDisk, read_only: readOnly, compressed: false, }; diff --git a/src/domain/apple/machoSectionHeader.ts b/src/domain/apple/machoSectionHeader.ts index b03640e10f..b4a4555b30 100644 --- a/src/domain/apple/machoSectionHeader.ts +++ b/src/domain/apple/machoSectionHeader.ts @@ -12,7 +12,7 @@ export interface MachoSectionHeader { readonly flags: number; } -/** Fixed section/section_64 facts; mapping, zero-fill and display policies belong to callers. */ +/** Fixed section/section_64 facts; callers own mapping and display policies. */ export const readMachoSectionHeader = ( bytes: Uint8Array, wide: boolean, @@ -47,6 +47,51 @@ export const readMachoSectionHeader = ( export const isMachoZeroFillSection = (flags: number): boolean => [1, 0xc, 0x12].includes(flags & 0xff); +type SectionExtent = Pick< + MachoSectionHeader, + "address" | "size" | "offset" | "flags" +>; + +interface SegmentExtent { + readonly address: bigint; + readonly memorySize: bigint; + readonly fileOffset: bigint; + readonly fileSize: bigint; +} + +const extentContains = (size: bigint, extentSize: bigint, delta: bigint) => + delta >= 0n && delta <= extentSize && size <= extentSize - delta; + +/** File and virtual backing within the enclosing segment. Callers also check image bounds. */ +export const machoSectionBacking = ( + section: SectionExtent, + segment: SegmentExtent, +) => { + const { size } = section; + const zeroFill = isMachoZeroFillSection(section.flags); + const inSegmentFile = extentContains( + size, + segment.fileSize, + BigInt(section.offset) - segment.fileOffset, + ); + const inSegmentMemory = extentContains( + size, + segment.memorySize, + section.address - segment.address, + ); + // An out-of-range virtual address can still have bytes on disk. + return { + onDisk: !zeroFill && inSegmentFile, + issue: zeroFill + ? "is zero-fill" + : !inSegmentMemory + ? "exceeds its segment's virtual extent" + : !inSegmentFile + ? "exceeds its segment's file extent" + : null, + } as const; +}; + /** Admit a section's declared payload against the image that holds it. */ export const admitMachoSectionPayload = ( section: Pick, diff --git a/src/domain/desktop/elfDependencies.test.ts b/src/domain/desktop/elfDependencies.test.ts index 7ccb360e45..57e5367c43 100644 --- a/src/domain/desktop/elfDependencies.test.ts +++ b/src/domain/desktop/elfDependencies.test.ts @@ -50,6 +50,34 @@ describe("readElfDependencies", () => { }); }); + it.each([ + ["DT_STRTAB", 5, 4], + ["DT_STRSZ", 10, 5], + ["DT_RPATH", 15, 0], + ["DT_RUNPATH", 29, 3], + ] as const)("refuses a repeated %s singleton", async (_label, tag, row) => { + const image = elfImage({ + needed: ["libc.so.6"], + repeatNeeded: 1, + rpath: "/opt/old", + runpath: "$ORIGIN", + }); + expect(await dependencies(image)).toMatchObject({ + ok: true, + value: { needed: ["libc.so.6"], runpath: ["$ORIGIN"], rpath: [] }, + }); + + const offset = Number(image.readBigUInt64LE(64 + 56 + 8)); + const duplicate = offset + row * 16; + image.copy(image, offset + 2 * 16, duplicate, duplicate + 16); + expect(await dependencies(image)).toMatchObject({ + ok: false, + error: { + reason: `Duplicate dynamic tag 0x${tag.toString(16)}`, + }, + }); + }); + it("decodes each needed string once and refuses a table naming more libraries than the walk takes", async () => { const repeated = await dependencies( elfImage({ needed: ["libc.so.6"], repeatNeeded: 60_000 }), diff --git a/src/domain/desktop/elfDependencies.ts b/src/domain/desktop/elfDependencies.ts index 9c95057a42..dc062d0b96 100644 --- a/src/domain/desktop/elfDependencies.ts +++ b/src/domain/desktop/elfDependencies.ts @@ -3,13 +3,21 @@ import { desktopLibraryPolicy, type DesktopLibraryPolicy, } from "./libraryPolicy.js"; -import { readElfDynamicEntry } from "../elfDynamicEntry.js"; +import { + DT_NEEDED, + DT_RPATH, + DT_RUNPATH, + DT_STRTAB, + DT_STRSZ, + walkElfDynamicTable, +} from "../elfDynamicEntry.js"; import { admitElfFixedHeaderFacts, readElfHeaderFacts, } from "../elfFixedHeader.js"; import { admitElfLoadSegment, + elfLoadSpans, readElfProgramHeader, type ElfProgramHeader, } from "../elfProgramHeader.js"; @@ -17,7 +25,11 @@ import { observeElfStringTableEntry } from "../elfStringTable.js"; import { allKeyed, keyedBy, uniqueKeyed } from "../keyedCollection.js"; import { err, ok, type Result } from "../result.js"; import { decodeStrictUtf8 } from "../strictUtf8.js"; -import { resolveMappedFileOffset } from "../virtualFileMapping.js"; +import { + resolveMappedFileOffset, + type FileMapping, + type ZeroFillMapping, +} from "../virtualFileMapping.js"; /** Read up to `length` bytes at `offset`; fewer at the end of the file. */ export type ReadAt = (offset: number, length: number) => Promise; @@ -63,11 +75,12 @@ export interface ElfDependencies extends ElfLibraryIdentity { const PT_LOAD = 1; const PT_DYNAMIC = 2; -const DT_NEEDED = 1n; -const DT_STRTAB = 5n; -const DT_STRSZ = 10n; -const DT_RPATH = 15n; -const DT_RUNPATH = 29n; +const DEPENDENCY_SINGLETONS = new Set([ + DT_STRTAB, + DT_STRSZ, + DT_RPATH, + DT_RUNPATH, +]); const readExactly = async ( read: ReadAt, @@ -146,7 +159,6 @@ const dynamicTags = ( }, string > => { - const width = bits === 64 ? 16 : 8; const found = { needed: new Set(), runpath: new Set(), @@ -180,30 +192,36 @@ const dynamicTags = ( }, ], ]); - for (let at = 0; at + width <= table.length; at += width) { - const entry = readElfDynamicEntry( - table.subarray(at, at + width), - bits, - little, + const walked = walkElfDynamicTable( + table, + { bits, littleEndian: little }, + DEPENDENCY_SINGLETONS, + ({ tag, value }) => { + const list = lists.get(tag); + if (list !== undefined) { + list.offsets.add(value); + if (list.offsets.size > list.limit) + return err( + desktopLibraryLimit( + policy, + list.key, + `ELF dynamic table ${tag === DT_NEEDED ? "needed libraries" : "search path entries"}`, + ), + ); + } else if (tag === DT_STRTAB) found.strtab = value; + else if (tag === DT_STRSZ) found.strsz = value; + return undefined; + }, + ); + if (!walked.ok) + return err( + walked.error.kind === "visitor" + ? walked.error.error + : `Duplicate dynamic tag 0x${walked.error.tag.toString(16)}`, ); - if (!entry.ok) return err(entry.error.message); - const { tag, value } = entry.value; - if (tag === 0n) return ok(found); - const list = lists.get(tag); - if (list !== undefined) { - list.offsets.add(value); - if (list.offsets.size > list.limit) - return err( - desktopLibraryLimit( - policy, - list.key, - `ELF dynamic table ${tag === DT_NEEDED ? "needed libraries" : "search path entries"}`, - ), - ); - } else if (tag === DT_STRTAB) found.strtab = value; - else if (tag === DT_STRSZ) found.strsz = value; - } - return err("ELF dynamic table has no DT_NULL terminator"); + return walked.value.terminatorOffset === null + ? err("ELF dynamic table has no DT_NULL terminator") + : ok(found); }; /** The strings at the given offsets of the dynamic string table at file offset `at`, `bytes` long. */ @@ -331,24 +349,18 @@ const readDependencyTables = async ( return err("ELF dynamic string table is not mapped from the file"); if (strsz > BigInt(size)) return err("ELF dynamic string table is not mapped from the file"); - // PT_LOAD repeats by design; every segment maps file bytes. - const loads = allKeyed(programs, PT_LOAD); + const fileBacked: FileMapping[] = []; + const zeroFills: ZeroFillMapping[] = []; + for (const load of allKeyed(programs, PT_LOAD)) { + const span = elfLoadSpans(load); + if (span.fileBacked !== undefined) fileBacked.push(span.fileBacked); + if (span.zeroFill !== undefined) zeroFills.push(span.zeroFill); + } const stringsAt = resolveMappedFileOffset( - loads - .filter((segment) => segment.fileSize > 0n) - .map((segment) => ({ - address: segment.virtualAddress, - offset: Number(segment.offset), - size: Number(segment.fileSize), - })), + fileBacked, strtab, Number(strsz), - loads - .filter((segment) => segment.memorySize > segment.fileSize) - .map((segment) => ({ - address: segment.virtualAddress + segment.fileSize, - size: segment.memorySize - segment.fileSize, - })), + zeroFills, ); if (!stringsAt.ok) return err( diff --git a/src/domain/elfDynamicEntry.ts b/src/domain/elfDynamicEntry.ts index 48831c3690..529b2f2597 100644 --- a/src/domain/elfDynamicEntry.ts +++ b/src/domain/elfDynamicEntry.ts @@ -1,4 +1,35 @@ -import { err, ok } from "./result.js"; +import { err, ok, type Result } from "./result.js"; + +export const DT_NEEDED = 1n; +export const DT_HASH = 4n; +export const DT_STRTAB = 5n; +export const DT_SYMTAB = 6n; +export const DT_STRSZ = 10n; +export const DT_SYMENT = 11n; +export const DT_RPATH = 15n; +export const DT_RUNPATH = 29n; +export const DT_FLAGS = 30n; +export const DT_GNU_HASH = 0x6ffffef5n; +export const DT_FLAGS_1 = 0x6ffffffbn; + +export const elfDynamicEntryWidth = (bits: 32 | 64): 8 | 16 => + bits === 64 ? 16 : 8; + +const readDynamicWords = ( + view: DataView, + offset: number, + width: 8 | 16, + littleEndian: boolean, +) => ({ + tag: + width === 16 + ? view.getBigInt64(offset, littleEndian) + : BigInt(view.getInt32(offset, littleEndian)), + value: + width === 16 + ? view.getBigUint64(offset + 8, littleEndian) + : BigInt(view.getUint32(offset + 4, littleEndian)), +}); /** Fixed Elf32_Dyn/Elf64_Dyn: signed d_tag and unsigned d_un, without tag or value admission. */ export const readElfDynamicEntry = ( @@ -6,19 +37,64 @@ export const readElfDynamicEntry = ( bits: 32 | 64, littleEndian: boolean, ) => { - const wide = bits === 64; - if (bytes.byteLength < (wide ? 16 : 8)) + const width = elfDynamicEntryWidth(bits); + if (bytes.byteLength < width) return err({ kind: "malformed" as const, message: "ELF dynamic entry is truncated", }); const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - return ok({ - tag: wide - ? view.getBigInt64(0, littleEndian) - : BigInt(view.getInt32(0, littleEndian)), - value: wide - ? view.getBigUint64(8, littleEndian) - : BigInt(view.getUint32(4, littleEndian)), - }); + return ok(readDynamicWords(view, 0, width, littleEndian)); +}; + +type DynamicRow = ReturnType & { + readonly offset: number; + readonly singleton: boolean; +}; + +type DynamicTableFailure = + | { + readonly kind: "duplicate-singleton"; + readonly tag: bigint; + readonly firstOffset: number; + readonly offset: number; + } + | { readonly kind: "visitor"; readonly error: E }; + +/** + * Walk an admitted dynamic-table byte span in order. All offsets are relative + * to the span. DT_NULL closes the table and its value has no meaning. Only + * tags the caller consumes as singletons are tracked, so ignored extensions + * and repeated DT_NEEDED do not enlarge the reader's retained state. + */ +export const walkElfDynamicTable = ( + bytes: Uint8Array, + { + bits, + littleEndian, + }: { readonly bits: 32 | 64; readonly littleEndian: boolean }, + singletonTags: ReadonlySet, + visit: (row: DynamicRow) => Result | void, +): Result< + { readonly terminatorOffset: number | null }, + DynamicTableFailure +> => { + const width = elfDynamicEntryWidth(bits); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const firstOffsets = new Map(); + for (let offset = 0; offset + width <= bytes.byteLength; offset += width) { + const { tag, value } = readDynamicWords(view, offset, width, littleEndian); + if (tag === 0n) return ok({ terminatorOffset: offset }); + const singleton = singletonTags.has(tag); + if (singleton) { + const firstOffset = firstOffsets.get(tag); + if (firstOffset !== undefined) + return err({ kind: "duplicate-singleton", tag, firstOffset, offset }); + firstOffsets.set(tag, offset); + } + const visited = visit({ tag, value, offset, singleton }); + if (visited !== undefined && !visited.ok) + return err({ kind: "visitor", error: visited.error }); + } + return ok({ terminatorOffset: null }); }; diff --git a/src/domain/elfProgramHeader.ts b/src/domain/elfProgramHeader.ts index 5d588dea2e..d007aedddb 100644 --- a/src/domain/elfProgramHeader.ts +++ b/src/domain/elfProgramHeader.ts @@ -1,4 +1,5 @@ import { err, ok } from "./result.js"; +import type { FileMapping, ZeroFillMapping } from "./virtualFileMapping.js"; export const PT_INTERP = 3; @@ -52,3 +53,35 @@ export const admitElfLoadSegment = ( message: "ELF load segment sizes or addresses are invalid", }) : ok(null); + +export interface ElfLoadMappings { + readonly fileBacked: readonly FileMapping[]; + readonly zeroFills: readonly ZeroFillMapping[]; +} + +/** Project an admitted PT_LOAD into its file-backed prefix and zero-filled tail. */ +export const elfLoadSpans = ({ + virtualAddress, + offset, + fileSize, + memorySize, +}: Pick< + ElfProgramHeader, + "virtualAddress" | "offset" | "fileSize" | "memorySize" +>): { + readonly fileBacked: FileMapping | undefined; + readonly zeroFill: ZeroFillMapping | undefined; +} => ({ + fileBacked: + fileSize === 0n + ? undefined + : { + address: virtualAddress, + offset: Number(offset), + size: Number(fileSize), + }, + zeroFill: + memorySize > fileSize + ? { address: virtualAddress + fileSize, size: memorySize - fileSize } + : undefined, +}); diff --git a/src/domain/managed/managedPeReader.ts b/src/domain/managed/managedPeReader.ts index 2dea6dac20..d0f9c65245 100644 --- a/src/domain/managed/managedPeReader.ts +++ b/src/domain/managed/managedPeReader.ts @@ -1,10 +1,15 @@ import { observeMzWindowsHeader } from "../dosMz.js"; import { + PE_SIZE_OF_HEADERS_OFFSET, readPeOptionalHeaderFixedFields, readPeOptionalHeaderDirectory, type PeOptionalHeaderFixedFields, } from "../peOptionalHeader.js"; -import { readPeSectionHeader } from "../peSectionHeader.js"; +import { + observePeHeaderExtent, + PE_SECTION_HEADER_BYTES, + readPeSectionHeader, +} from "../peSectionHeader.js"; import type { ManagedParseIssue } from "./managedArtifact.js"; import { readPeCoffHeader } from "../peCoffHeader.js"; import { decodePeMachine } from "../peMachine.js"; @@ -381,19 +386,15 @@ const readOptionalHeader = ( const readSections = ( bytes: Buffer, - coff: CoffHeader, - optional: OptionalHeader, + sectionTableOffset: number, + sectionCount: number, ): readonly PeSection[] => { - const sectionOffset = add( - optional.optionalOffset, - coff.optionalSize, - "pe.sections", - ); - requireRange(bytes, sectionOffset, coff.sectionCount * 40, "pe.sections"); const sections: PeSection[] = []; - for (let index = 0; index < coff.sectionCount; index += 1) { - const offset = sectionOffset + index * 40; - const parsed = readPeSectionHeader(bytes.subarray(offset, offset + 40)); + for (let index = 0; index < sectionCount; index += 1) { + const offset = sectionTableOffset + index * PE_SECTION_HEADER_BYTES; + const parsed = readPeSectionHeader( + bytes.subarray(offset, offset + PE_SECTION_HEADER_BYTES), + ); if (!parsed.ok) throw managedFailure( "invalid-directory", @@ -476,13 +477,43 @@ export const readManagedPeLayout = (bytes: Buffer): ManagedPeLayout => { ); const coff = readCoffHeader(bytes); const optional = readOptionalHeader(bytes, coff); - const sections = readSections(bytes, coff, optional); + const { sectionTableOffset, sectionTableBytes, sizeOfHeadersState } = + observePeHeaderExtent({ + optionalHeaderOffset: optional.optionalOffset, + optionalHeaderSize: coff.optionalSize, + sectionCount: coff.sectionCount, + sizeOfHeaders: optional.fixed.sizeOfHeaders, + fileSize: bytes.length, + }); + requireRange(bytes, sectionTableOffset, sectionTableBytes, "pe.sections"); + const extentIssue: ManagedParseIssue | null = + sizeOfHeadersState === "valid" + ? null + : { + code: "invalid-directory", + scope: "pe.optional-header", + detail: + sizeOfHeadersState === "before-section-table-end" + ? "PE SizeOfHeaders ends before the section table ends" + : "PE SizeOfHeaders extends past the end of the file", + offset: optional.optionalOffset + PE_SIZE_OF_HEADERS_OFFSET, + }; + // Retain the header and any CLI declaration we can observe, but admit no + // RVA mappings from a section table outside a valid header envelope. + const sections = + extentIssue === null + ? readSections(bytes, sectionTableOffset, coff.sectionCount) + : []; const cliDirectoryRead = readCliDirectory(bytes, coff, optional); - const cliDirectoryState = cliDirectoryRead.kind; + const cliDirectoryState = + extentIssue !== null && cliDirectoryRead.kind === "absent" + ? "unreadable" + : cliDirectoryRead.kind; let cli: ManagedCliHeader | null = null; - let cliIssue: ManagedParseIssue | null = - cliDirectoryRead.kind === "unreadable" ? cliDirectoryRead.issue : null; - if (cliDirectoryRead.kind === "present") { + let cliIssue = + extentIssue ?? + (cliDirectoryRead.kind === "unreadable" ? cliDirectoryRead.issue : null); + if (cliIssue === null && cliDirectoryRead.kind === "present") { try { cli = readCliHeader(bytes, sections, cliDirectoryRead.directory); } catch (cause: unknown) { diff --git a/src/domain/native/elfImage.ts b/src/domain/native/elfImage.ts index 7d9c78fce3..56abe78724 100644 --- a/src/domain/native/elfImage.ts +++ b/src/domain/native/elfImage.ts @@ -1,5 +1,5 @@ import type { FileMapping, ZeroFillMapping } from "../virtualFileMapping.js"; -import { admitElfLoadSegment } from "../elfProgramHeader.js"; +import { admitElfLoadSegment, elfLoadSpans } from "../elfProgramHeader.js"; import { declaredFileRange, BinaryFormatFailure, @@ -39,19 +39,18 @@ export const readElfImage = ( file_size: size, memory_size: memorySize, } = program; - const admitted = admitElfLoadSegment( - { virtualAddress: address, memorySize, fileSize: size }, - bits, - ); + const span = { + virtualAddress: address, + offset: fileOffset, + memorySize, + fileSize: size, + }; + const admitted = admitElfLoadSegment(span, bits); if (!admitted.ok) throw new BinaryFormatFailure("malformed", admitted.error.message); - const mapping = { - ...(size === 0n - ? { offset: 0, size: 0 } - : reader.fileRange(fileOffset, size, "ELF load segment")), - address, - }; - if (mapping.size !== 0) { + if (size !== 0n) reader.fileRange(fileOffset, size, "ELF load segment"); + const { fileBacked: mapping, zeroFill } = elfLoadSpans(span); + if (mapping !== undefined) { mappings.push(mapping); loadRegions.push({ mapping, @@ -62,8 +61,7 @@ export const readElfImage = ( }); if ((flags & 1) !== 0) executableMappings.push(mapping); } - if (memorySize > size) - zeroFills.push({ address: address + size, size: memorySize - size }); + if (zeroFill !== undefined) zeroFills.push(zeroFill); } for (const section of directory.sections) { const range = declaredFileRange(bytes.length, section.offset, section.size); diff --git a/src/domain/native/elfNoteLayout.ts b/src/domain/native/elfNoteLayout.ts index a14b66bb70..6e64ba166f 100644 --- a/src/domain/native/elfNoteLayout.ts +++ b/src/domain/native/elfNoteLayout.ts @@ -1,25 +1,27 @@ import { err, ok } from "../result.js"; +export const ELF_NOTE_HEADER_BYTES = 12; +export type ElfNoteAlignment = 4 | 8; + +/** Which note section declarations can be walked at their raw file offsets. */ +export const elfNoteSectionStorage = (section: { + readonly type: number; + readonly compressed: boolean; +}): "not-note" | "compressed" | "uncompressed" => + section.type !== 7 + ? "not-note" + : section.compressed + ? "compressed" + : "uncompressed"; + /** ELF note padding follows binutils: only a declared alignment of 8 uses 8. */ -export const elfNoteAlignment = (declared: number | bigint): number => - declared === 8 || declared === 8n ? 8 : 4; +export const elfNoteAlignment = ( + declared: number | bigint, +): ElfNoteAlignment => (declared === 8 || declared === 8n ? 8 : 4); -/** Descriptor and next-note offsets relative to the note's 12-byte header. */ -export const elfNoteLayout = ( - namesz: number, - descsz: number, - alignment: number, -) => { - const descriptor = Math.ceil((12 + namesz) / alignment) * alignment; - return { - descriptor, - next: Math.ceil((descriptor + descsz) / alignment) * alignment, - }; -}; - -/** Fixed ELF note words; padding, owner names and descriptor admission belong to consumers. */ +/** Fixed ELF note words without interpreting the rest of the table. */ export const readElfNoteHeader = (bytes: Uint8Array, littleEndian: boolean) => { - if (bytes.byteLength < 12) + if (bytes.byteLength < ELF_NOTE_HEADER_BYTES) return err({ kind: "malformed" as const, message: "ELF note header is truncated", @@ -31,3 +33,35 @@ export const readElfNoteHeader = (bytes: Uint8Array, littleEndian: boolean) => { type: view.getUint32(8, littleEndian), }); }; + +/** + * Frame one note in the bytes left in its table. Align from the start of the + * header. Preserve offsets on incomplete extents for bounded owner checks. + */ +export const readElfNoteFrame = ( + bytes: Uint8Array, + littleEndian: boolean, + alignment: ElfNoteAlignment, + remaining: number, +) => { + const header = readElfNoteHeader(bytes, littleEndian); + if (!header.ok) return header; + const { namesz, descsz, type } = header.value; + const endOfName = ELF_NOTE_HEADER_BYTES + namesz; + const descriptor = Math.ceil(endOfName / alignment) * alignment; + const endOfDescriptor = descriptor + descsz; + const next = Math.ceil(endOfDescriptor / alignment) * alignment; + const framing = + endOfName > remaining + ? "truncated-name" + : endOfDescriptor > remaining + ? "truncated-descriptor" + : next > remaining + ? "truncated-padding" + : "complete"; + return ok({ namesz, descsz, type, descriptor, next, framing }); +}; + +/** A short remainder after the last aligned note may be zero padding. */ +export const isElfNotePadding = (bytes: Uint8Array): boolean => + bytes.every((byte) => byte === 0); diff --git a/src/domain/native/nativeAotPe.ts b/src/domain/native/nativeAotPe.ts index 94a51379bb..9f325097fd 100644 --- a/src/domain/native/nativeAotPe.ts +++ b/src/domain/native/nativeAotPe.ts @@ -2,7 +2,11 @@ import { Budget } from "../budget.js"; import { observeMzWindowsHeader } from "../dosMz.js"; import { readPeOptionalHeaderFixedFields } from "../peOptionalHeader.js"; import { readPeCoffHeader } from "../peCoffHeader.js"; -import { readPeSectionHeader } from "../peSectionHeader.js"; +import { + observePeHeaderExtent, + PE_SECTION_HEADER_BYTES, + readPeSectionHeader, +} from "../peSectionHeader.js"; import { AnalysisInputError, AnalysisResourceConstraintError, @@ -669,17 +673,25 @@ class PeImage { throw new NativeAotAdmissionError({ code: "unsupported_image_extent" }); if (this.imageBase + BigInt(this.sizeOfImage) > 1n << 64n) throw new NativeAotAdmissionError({ code: "address_domain" }); - const sectionOffset = optional + optionalSize; - this.#range(sectionOffset, count * 40); + const { sectionTableOffset, sectionTableBytes, sizeOfHeadersState } = + observePeHeaderExtent({ + optionalHeaderOffset: optional, + optionalHeaderSize: optionalSize, + sectionCount: count, + sizeOfHeaders: this.#sizeOfHeaders, + fileSize: bytes.length, + }); + this.#range(sectionTableOffset, sectionTableBytes); if ( - this.#sizeOfHeaders < sectionOffset + count * 40 || - this.#sizeOfHeaders > this.#bytes.length || + sizeOfHeadersState !== "valid" || this.#sizeOfHeaders > this.sizeOfImage ) throw new NativeAotAdmissionError({ code: "headers_do_not_fit" }); this.sections = Array.from({ length: count }, (_, index) => { - const p = sectionOffset + index * 40; - const parsed = readPeSectionHeader(bytes.subarray(p, p + 40)); + const p = sectionTableOffset + index * PE_SECTION_HEADER_BYTES; + const parsed = readPeSectionHeader( + bytes.subarray(p, p + PE_SECTION_HEADER_BYTES), + ); if (!parsed.ok) throw new NativeAotAdmissionError({ code: "section_header_truncated" }); const section = parsed.value; diff --git a/src/domain/native/nativeSectionDirectory.ts b/src/domain/native/nativeSectionDirectory.ts index 35bc491504..dcba616148 100644 --- a/src/domain/native/nativeSectionDirectory.ts +++ b/src/domain/native/nativeSectionDirectory.ts @@ -5,12 +5,15 @@ import { import { mzWindowsHeaderLayoutLimitation, parseMzHeaderEvidence, - withMzWindowsHeaderSignature, } from "../dosMz.js"; import { readElfSectionHeader } from "../elfSectionHeader.js"; import { readElfProgramHeader } from "../elfProgramHeader.js"; -import { readPeCoffHeader } from "../peCoffHeader.js"; -import { readPeSectionHeader } from "../peSectionHeader.js"; +import { observePeCoffFrame, PE_COFF_FRAME_BYTES } from "../peCoffHeader.js"; +import { + PE_SECTION_HEADER_BYTES, + peSectionTableExtent, + readPeSectionHeader, +} from "../peSectionHeader.js"; import { readElfTableDeclarations, validateElfDeclaredRanges, @@ -359,23 +362,14 @@ export function* readPeSectionDirectory( throw new BinaryFormatFailure("unsupported", limitation); } const pe = observed.offset; - const coff = new BinaryReader( - yield request(fileSize, BigInt(pe), 24n), - true, - "pe", - ); - const confirmed = withMzWindowsHeaderSignature( - dos.bytes, - fileSize, - evidence, - { offset: pe, bytes: coff.bytes }, - ).windowsHeader; - if (confirmed.state !== "declared" || confirmed.signature !== "PE") - return reject("PE signature is invalid"); - const limitation = mzWindowsHeaderLayoutLimitation(confirmed); + // Native sections require a complete PE frame before decoding its fields. + request(fileSize, BigInt(pe), BigInt(PE_COFF_FRAME_BYTES)); + const frame = yield* observePeCoffFrame(dos.bytes, fileSize, evidence); + if (frame.kind !== "pe") return reject("PE signature is invalid"); + const limitation = mzWindowsHeaderLayoutLimitation(frame.observation); if (limitation !== undefined) throw new BinaryFormatFailure("unsupported", limitation); - const parsedCoff = readPeCoffHeader(coff.bytes.subarray(4, 24)); + const { coff: parsedCoff } = frame; if (!parsedCoff.ok) return reject(parsedCoff.error.message); const { sectionCount: count, @@ -386,7 +380,11 @@ export function* readPeSectionDirectory( symbolCount, } = parsedCoff.value; const optional = readPeOptionalHeaderStructure( - yield request(fileSize, BigInt(pe + 24), BigInt(optionalSize)), + yield request( + fileSize, + BigInt(pe + PE_COFF_FRAME_BYTES), + BigInt(optionalSize), + ), ); if (!optional.ok) { switch (optional.error.reason) { @@ -403,12 +401,21 @@ export function* readPeSectionDirectory( } } const { bits } = optional.value; - const start = pe + 24 + optionalSize; - const table = yield request(fileSize, BigInt(start), BigInt(count) * 40n); + const { sectionTableOffset, sectionTableBytes } = peSectionTableExtent( + pe + PE_COFF_FRAME_BYTES, + optionalSize, + count, + ); + const table = yield request( + fileSize, + BigInt(sectionTableOffset), + BigInt(sectionTableBytes), + ); const sections: NativeSection[] = []; for (let index = 0; index < count; index++) { + const at = index * PE_SECTION_HEADER_BYTES; const parsed = readPeSectionHeader( - table.subarray(index * 40, (index + 1) * 40), + table.subarray(at, at + PE_SECTION_HEADER_BYTES), ); if (!parsed.ok) return reject(parsed.error.message); const row = parsed.value; @@ -416,7 +423,7 @@ export function* readPeSectionDirectory( index, name: row.name, name_state: "known", - header_offset: start + index * 40, + header_offset: sectionTableOffset + at, offset: BigInt(row.offset), size: BigInt(row.size), address: BigInt(row.virtual_address), diff --git a/src/domain/native/peImage.ts b/src/domain/native/peImage.ts index f423a806ee..6f38a1386f 100644 --- a/src/domain/native/peImage.ts +++ b/src/domain/native/peImage.ts @@ -1,7 +1,11 @@ import type { FileMapping, ZeroFillMapping } from "../virtualFileMapping.js"; import { readPeCoffHeader } from "../peCoffHeader.js"; import { readPeOptionalHeader } from "../peMachine.js"; -import { readPeSectionHeader } from "../peSectionHeader.js"; +import { + PE_SECTION_HEADER_BYTES, + peSectionTableExtent, + readPeSectionHeader, +} from "../peSectionHeader.js"; import { mzWindowsHeaderLayoutLimitation, parseMzHeaderEvidence, @@ -109,20 +113,25 @@ export const readPeImage = (bytes: Buffer): PeImage => { offset: 0, size: Math.min(sizeOfHeaders, bytes.length), }; - const start = reader.table( - BigInt(optional + optionalSize), + const { sectionTableOffset, sectionTableBytes } = peSectionTableExtent( + optional, + optionalSize, count, - 40, + ); + const { offset: tableAt, size: tableSize } = reader.fileRange( + BigInt(sectionTableOffset), + BigInt(sectionTableBytes), "PE sections", ); + const sectionTable = bytes.subarray(tableAt, tableAt + tableSize); const mappings: FileMapping[] = []; const executableMappings: FileMapping[] = []; const zeroFills: ZeroFillMapping[] = []; const sections: PeImageSection[] = []; for (let index = 0; index < count; index++) { - const entry = start + index * 40; + const entry = index * PE_SECTION_HEADER_BYTES; const section = readPeSectionHeader( - reader.range(entry, 40, "PE section header"), + sectionTable.subarray(entry, entry + PE_SECTION_HEADER_BYTES), ); if (!section.ok) throw new BinaryFormatFailure(section.error.kind, section.error.message); diff --git a/src/domain/pe/peImageHeaders.ts b/src/domain/pe/peImageHeaders.ts new file mode 100644 index 0000000000..2c3712367a --- /dev/null +++ b/src/domain/pe/peImageHeaders.ts @@ -0,0 +1,184 @@ +import { parseMzHeaderEvidence } from "../dosMz.js"; +import { BinaryFormatFailure } from "../binaryContainer.js"; +import { malformedInput } from "../parseFailure.js"; +import { observePeCoffFrame, PE_COFF_FRAME_BYTES } from "../peCoffHeader.js"; +import { observePeHeaderExtent } from "../peSectionHeader.js"; +import { + readPeOptionalHeaderStructure, + type PeDataDirectory, + type PeOptionalHeaderFailure, +} from "../peOptionalHeader.js"; + +const OPTIONAL_HEADER_FAILURES: Readonly< + Record +> = { + "truncated-magic": "Truncated PE optional header.", + "unsupported-magic": "Unsupported PE optional header magic.", + "truncated-fixed-fields": "Truncated PE data directory count.", + "truncated-directory-table": + "PE directory count exceeds its optional header.", +}; + +/** The bytes violate the PE structure this parser admits. */ +export const peFailure = (message: string): never => { + throw malformedInput("pe", message); +}; + +export const requirePeRange = ( + bytes: Buffer, + offset: number, + length: number, +): void => requirePeExtent(bytes.length, offset, length); + +export const requirePeExtent = ( + fileSize: number, + offset: number, + length: number, +): void => { + if ( + !Number.isSafeInteger(offset) || + !Number.isSafeInteger(length) || + offset < 0 || + length < 0 || + offset > fileSize - length + ) + peFailure( + `PE range ${String(offset)} + ${String(length)} leaves the artifact.`, + ); +}; + +interface HeaderRead { + readonly offset: number; + readonly size: number; +} + +interface PeImageHeaders { + readonly machine: number; + readonly format: "pe32" | "pe32-plus"; + readonly sectionCount: number; + readonly optionalHeaderOffset: number; + readonly directoryOffset: number; + readonly dataDirectories: readonly PeDataDirectory[]; + readonly headerSize: number; + readonly sectionTable: Buffer; +} + +export type PeRangeReader = ( + offset: number, + bytes: number, +) => Promise; + +const headerRead = ( + fileSize: number, + offset: number, + bytes: number, +): HeaderRead => { + requirePeExtent(fileSize, offset, bytes); + return { offset, size: bytes }; +}; + +/** Admit the PE header directory using its declared spans in either source. */ +function* peImageHeaderReads( + prefix: Buffer, + fileSize: number, +): Generator { + requirePeRange(prefix, 0, 64); + if (prefix[0] !== 0x4d || prefix[1] !== 0x5a) + peFailure("Expected an MZ PE image."); + const evidence = parseMzHeaderEvidence(prefix, fileSize); + const frame = yield* observePeCoffFrame(prefix, fileSize, evidence); + const observed = frame.observation; + if (observed.state === "absent" && evidence.dos.ok) + throw new BinaryFormatFailure( + "unsupported", + "DOS MZ images do not contain PE resource or certificate tables", + ); + if (observed.state === "declared" && observed.signature !== "PE") + throw new BinaryFormatFailure( + "unsupported", + `${observed.signature} images do not contain PE resource or certificate tables`, + ); + if (frame.kind !== "pe") + return peFailure( + "MZ header does not declare a PE image in the inspected bytes.", + ); + const pe = frame.observation.offset; + requirePeExtent(fileSize, pe, PE_COFF_FRAME_BYTES); + const { coff } = frame; + if (!coff.ok) return peFailure(coff.error.message); + const { sectionCount, optionalHeaderSize, machine } = coff.value; + const optionalHeaderOffset = pe + PE_COFF_FRAME_BYTES; + const optional = yield headerRead( + fileSize, + optionalHeaderOffset, + optionalHeaderSize, + ); + if (optionalHeaderSize < 64) peFailure("Truncated PE optional header."); + const parsed = readPeOptionalHeaderStructure(optional); + if (!parsed.ok) + return peFailure(OPTIONAL_HEADER_FAILURES[parsed.error.reason]); + const { + sizeOfHeaders: headerSize, + format, + directoryOffset, + dataDirectories, + } = parsed.value; + const { sectionTableOffset, sectionTableBytes, sizeOfHeadersState } = + observePeHeaderExtent({ + optionalHeaderOffset, + optionalHeaderSize, + sectionCount, + sizeOfHeaders: headerSize, + fileSize, + }); + const sectionRead = headerRead( + fileSize, + sectionTableOffset, + sectionTableBytes, + ); + if (sizeOfHeadersState !== "valid") peFailure("Invalid PE SizeOfHeaders."); + const sectionTable = yield sectionRead; + return { + machine, + format, + sectionCount, + optionalHeaderOffset, + directoryOffset, + dataDirectories, + headerSize, + sectionTable, + }; +} + +/** Admit headers over one complete image without copying or inspecting section payloads. */ +export const readPeImageHeaders = (bytes: Buffer) => { + const steps = peImageHeaderReads(bytes, bytes.length); + let next = steps.next(); + while (!next.done) { + const { offset, size } = next.value; + next = steps.next(bytes.subarray(offset, offset + size)); + } + return next.value; +}; + +/** Admit the same headers from bounded file reads, skipping the DOS stub and padding. */ +export const readPeImageHeadersAt = async ( + prefix: Buffer, + fileSize: number, + read: PeRangeReader, +) => { + const steps = peImageHeaderReads(prefix, fileSize); + let next = steps.next(); + while (!next.done) { + const { offset, size: bytes } = next.value; + // A PE can declare no sections. The caller need not support empty I/O. + const record = + bytes === 0 || offset + bytes <= prefix.length + ? prefix.subarray(offset, offset + bytes) + : await read(offset, bytes); + if (record === undefined || record.length !== bytes) + return peFailure(`Truncated PE header range at ${String(offset)}.`); + next = steps.next(record); + } + return next.value; +}; diff --git a/src/domain/pe/peResourceInventory.test.ts b/src/domain/pe/peResourceInventory.test.ts index 287315461f..bec08dd01a 100644 --- a/src/domain/pe/peResourceInventory.test.ts +++ b/src/domain/pe/peResourceInventory.test.ts @@ -236,6 +236,29 @@ describe("portable PE resource parsing", () => { }); }); +it.each([false, true])( + "rejects descending numeric sibling IDs without sorting the resource tree (PE32+ = %s)", + async (plus) => { + const { bytes, directoryOffsets } = peResourceFixture(plus, [ + { type: 10, name: 4, language: 1, payload: Buffer.from("a") }, + { type: 10, name: 9, language: 1, payload: Buffer.from("b") }, + ]); + const ordered = await parse(bytes); + expect(ordered.resources.map(({ name }) => name)).toEqual([ + { kind: "id", id: 4 }, + { kind: "id", id: 9 }, + ]); + const nameDirectory = directoryOffsets[1]; + if (nameDirectory === undefined) throw new Error("Missing name directory"); + bytes.writeUInt32LE(9, nameDirectory + 16); + bytes.writeUInt32LE(4, nameDirectory + 24); + await expect(parse(bytes)).rejects.toMatchObject({ + kind: "malformed", + message: "PE resource directory numeric IDs are out of order.", + }); + }, +); + describe("PE header admission and bounded traversal", () => { it.each([ [ @@ -584,7 +607,7 @@ describe("PE resource ownership boundaries", () => { const probeSeaName = (bytes: Buffer) => hasPeResourceName( - bytes, + bytes.subarray(0, 64), bytes.length, async (offset, length) => offset < 0 || length > bytes.length - offset @@ -597,7 +620,7 @@ const probeSeaName = (bytes: Buffer) => const payloadsOf = (bytes: Buffer, name = "NODE_SEA_BLOB") => locatePeResourcePayloads( - bytes, + bytes.subarray(0, 64), bytes.length, async (offset, length) => offset < 0 || length > bytes.length - offset diff --git a/src/domain/pe/peResourceInventory.ts b/src/domain/pe/peResourceInventory.ts index 0c3b58927d..159c489a09 100644 --- a/src/domain/pe/peResourceInventory.ts +++ b/src/domain/pe/peResourceInventory.ts @@ -1,7 +1,9 @@ import { + PE_RESOURCE_DATA_ENTRY_BYTES, PE_RESOURCE_DIRECTORY_BYTES, PE_RESOURCE_ENTRY_BYTES, PE_RESOURCE_NAME_PREFIX_BYTES, + readPeResourceDataEntryFacts, readPeResourceDirectoryFacts, readPeResourceEntryFacts, readPeResourceNameFacts, @@ -17,11 +19,8 @@ import type { PeResources, } from "../native/peResources.js"; import { decodeLimit, type LimitRef } from "../parseFailure.js"; -import { - peFailure, - readPeResourceLayout, - requirePeRange, -} from "./peResourceLayout.js"; +import { peFailure, requirePeRange } from "./peImageHeaders.js"; +import { readPeResourceLayout } from "./peResourceLayout.js"; type PeResourceLayout = ReturnType; @@ -193,6 +192,7 @@ export const parsePeResources = async ( account(directory); directories.push(directory); const keys = new Set(); + let previousId = -1; const nested = new Set([...ancestors, at]); for (let index = 0; index < count; index++) { if (index % 128 === 0) { @@ -213,6 +213,11 @@ export const parsePeResources = async ( if (keys.has(key)) peFailure("Duplicate identity within a resource directory."); keys.add(key); + if (identity.kind === "id") { + if (identity.id < previousId) + peFailure("PE resource directory numeric IDs are out of order."); + previousId = identity.id; + } const next = [...path, identity]; const locations = [ ...entryLocations, @@ -230,9 +235,10 @@ export const parsePeResources = async ( peFailure( "Unsupported resource leaf outside the type/name/language profile.", ); - const data = relative(offset, 16); - const rva = bytes.readUInt32LE(data); - const size = bytes.readUInt32LE(data + 4); + const data = relative(offset, PE_RESOURCE_DATA_ENTRY_BYTES); + const { rva, size, codePage, reserved } = readPeResourceDataEntryFacts( + bytes.subarray(data, data + PE_RESOURCE_DATA_ENTRY_BYTES), + ); const payloadOffset = layout.map(rva, size); const [type, name, language] = next; if (type === undefined || name === undefined || language === undefined) @@ -243,9 +249,13 @@ export const parsePeResources = async ( name, language, entry_locations: locations, - data_entry_location: recordRange(data, 16, "data-entry"), - code_page: bytes.readUInt32LE(data + 8), - reserved: bytes.readUInt32LE(data + 12), + data_entry_location: recordRange( + data, + PE_RESOURCE_DATA_ENTRY_BYTES, + "data-entry", + ), + code_page: codePage, + reserved, payload: { rva, location: recordRange(payloadOffset, size, "payload"), diff --git a/src/domain/pe/peResourceLayout.ts b/src/domain/pe/peResourceLayout.ts index 5975e71a22..2f4eeffa2f 100644 --- a/src/domain/pe/peResourceLayout.ts +++ b/src/domain/pe/peResourceLayout.ts @@ -1,60 +1,26 @@ import { + PE_RESOURCE_DATA_ENTRY_BYTES, PE_RESOURCE_DIRECTORY_BYTES, PE_RESOURCE_ENTRY_BYTES, PE_RESOURCE_NAME_PREFIX_BYTES, + readPeResourceDataEntryFacts, readPeResourceDirectoryFacts, readPeResourceEntryFacts, readPeResourceNameFacts, } from "./peResourceTreeFacts.js"; -import { parseMzHeaderEvidence } from "../dosMz.js"; import { BinaryFormatFailure } from "../binaryContainer.js"; -import { malformedInput, ParseFailureError } from "../parseFailure.js"; -import { readPeCoffHeader } from "../peCoffHeader.js"; -import { readPeSectionHeader } from "../peSectionHeader.js"; +import { ParseFailureError } from "../parseFailure.js"; import { - readPeOptionalHeaderStructure, - type PeOptionalHeaderFailure, -} from "../peOptionalHeader.js"; - -const PE_RESOURCE_DATA_ENTRY_BYTES = 16; - -const OPTIONAL_HEADER_FAILURES: Readonly< - Record -> = { - "truncated-magic": "Truncated PE optional header.", - "unsupported-magic": "Unsupported PE optional header magic.", - "truncated-fixed-fields": "Truncated PE data directory count.", - "truncated-directory-table": - "PE directory count exceeds its optional header.", -}; - -/** The bytes violate the PE structure this parser admits. */ -export const peFailure = (message: string): never => { - throw malformedInput("pe", message); -}; - -export const requirePeRange = ( - bytes: Buffer, - offset: number, - length: number, -): void => requirePeExtent(bytes.length, offset, length); - -const requirePeExtent = ( - fileSize: number, - offset: number, - length: number, -): void => { - if ( - !Number.isSafeInteger(offset) || - !Number.isSafeInteger(length) || - offset < 0 || - length < 0 || - offset > fileSize - length - ) - peFailure( - `PE range ${String(offset)} + ${String(length)} leaves the artifact.`, - ); -}; + PE_SECTION_HEADER_BYTES, + readPeSectionHeader, +} from "../peSectionHeader.js"; +import { + peFailure, + readPeImageHeaders, + readPeImageHeadersAt, + type PeRangeReader, + requirePeExtent, +} from "./peImageHeaders.js"; interface Section { readonly rva: number; @@ -86,76 +52,13 @@ const intersectsResource = ( ); }; -/** - * Shared PE header admission: signature, optional header, data directories, - * and a section table that fits inside SizeOfHeaders. `bytes` may be a file - * prefix that holds the header structures; file-space ranges are checked - * against `fileSize`. - */ -export const readPeHeaders = (bytes: Buffer, fileSize = bytes.length) => { - requirePeRange(bytes, 0, 64); - if (bytes.readUInt16LE(0) !== 0x5a4d) peFailure("Expected an MZ PE image."); - const evidence = parseMzHeaderEvidence(bytes, fileSize); - const observed = evidence.windowsHeader; - if (observed.state === "absent" && evidence.dos.ok) - throw new BinaryFormatFailure( - "unsupported", - "DOS MZ images do not contain PE resource or certificate tables", - ); - if (observed.state === "declared" && observed.signature !== "PE") - throw new BinaryFormatFailure( - "unsupported", - `${observed.signature} images do not contain PE resource or certificate tables`, - ); - if (observed.state === "candidate" || observed.state === "signature-needed") - requirePeRange(bytes, observed.offset, 24); - if (observed.state !== "declared" || observed.signature !== "PE") - return peFailure( - "MZ header does not declare a PE image in the inspected bytes.", - ); - const pe = observed.offset; - requirePeRange(bytes, pe, 24); - const coff = readPeCoffHeader(bytes.subarray(pe + 4, pe + 24)); - if (!coff.ok) return peFailure(coff.error.message); - const { - sectionCount, - optionalHeaderSize: optionalSize, - machine, - } = coff.value; - const optionalHeaderOffset = pe + 24; - requirePeRange(bytes, optionalHeaderOffset, optionalSize); - if (optionalSize < 64) peFailure("Truncated PE optional header."); - const parsed = readPeOptionalHeaderStructure( - bytes.subarray(optionalHeaderOffset, optionalHeaderOffset + optionalSize), - ); - if (!parsed.ok) - return peFailure(OPTIONAL_HEADER_FAILURES[parsed.error.reason]); - const { - sizeOfHeaders: headerSize, - format, - directoryOffset, - dataDirectories, - } = parsed.value; - const table = optionalHeaderOffset + optionalSize; - requirePeRange(bytes, table, sectionCount * 40); - if (headerSize < table + sectionCount * 40 || headerSize > fileSize) - peFailure("Invalid PE SizeOfHeaders."); - return { - machine, - format, - sectionCount, - optionalHeaderOffset, - directoryOffset, - dataDirectories, - headerSize, - table, - }; -}; - /** Header admission and unambiguous file-backed RVA mapping, independent of section names. */ -export const readPeResourceLayout = ( - bytes: Buffer, - fileSize = bytes.length, +export const readPeResourceLayout = (bytes: Buffer) => + mapPeResourceLayout(readPeImageHeaders(bytes), bytes.length); + +const mapPeResourceLayout = ( + headers: ReturnType, + fileSize: number, ) => { const { machine, @@ -165,12 +68,14 @@ export const readPeResourceLayout = ( directoryOffset, dataDirectories, headerSize, - table, - } = readPeHeaders(bytes, fileSize); + sectionTable, + } = headers; const sections: Section[] = []; for (let index = 0; index < sectionCount; index++) { - const at = table + index * 40; - const parsed = readPeSectionHeader(bytes.subarray(at, at + 40)); + const at = index * PE_SECTION_HEADER_BYTES; + const parsed = readPeSectionHeader( + sectionTable.subarray(at, at + PE_SECTION_HEADER_BYTES), + ); if (!parsed.ok) return peFailure(parsed.error.message); const row = parsed.value; const section = { @@ -271,11 +176,6 @@ export interface PeResourcePayloadRange { readonly bytes: number; } -type PeResourceRead = ( - offset: number, - length: number, -) => Promise; - /** Budgeted reads relative to one admitted resource root. */ class PeResourceTree { #examined = 0; @@ -283,7 +183,7 @@ class PeResourceTree { constructor( readonly layout: ReturnType, private readonly root: number, - private readonly read: PeResourceRead, + private readonly read: PeRangeReader, private readonly maxEntries: number, ) {} @@ -306,14 +206,15 @@ class PeResourceTree { } } -const openPeResourceTree = ( - headers: Buffer, +const openPeResourceTree = async ( + prefix: Buffer, fileSize: number, - read: PeResourceRead, + read: PeRangeReader, maxEntries: number, -): PeResourceTree | undefined => { +): Promise => { try { - const layout = readPeResourceLayout(headers, fileSize); + const headers = await readPeImageHeadersAt(prefix, fileSize, read); + const layout = mapPeResourceLayout(headers, fileSize); if (layout.size < PE_RESOURCE_DIRECTORY_BYTES) return undefined; return new PeResourceTree( layout, @@ -392,19 +293,19 @@ async function* namedResourceTargets( /** * Bounded admission probe: whether the root type directory holds a `typeId` - * subdirectory naming `name`. Reads only the header prefix and the + * subdirectory naming `name`. Reads only the header records and the * directories on that path; an unadmitted layout or malformed tree reports * false so callers can leave full resource parsing to confirmed carriers. */ export const hasPeResourceName = async ( - headers: Buffer, + prefix: Buffer, fileSize: number, - read: PeResourceRead, + read: PeRangeReader, typeId: number, name: string, maxEntries: number, ): Promise => { - const tree = openPeResourceTree(headers, fileSize, read, maxEntries); + const tree = await openPeResourceTree(prefix, fileSize, read, maxEntries); if (tree === undefined) return false; const first = await namedResourceTargets(tree, typeId, name, { unresolved: false, @@ -420,14 +321,14 @@ export const hasPeResourceName = async ( * failure, as is any `typeId` branch the walk could not examine. */ export const locatePeResourcePayloads = async ( - headers: Buffer, + prefix: Buffer, fileSize: number, - read: PeResourceRead, + read: PeRangeReader, typeId: number, name: string, maxEntries: number, ): Promise => { - const tree = openPeResourceTree(headers, fileSize, read, maxEntries); + const tree = await openPeResourceTree(prefix, fileSize, read, maxEntries); if (tree === undefined) return []; const found: PeResourcePayloadRange[] = []; const walk: NamedResourceWalk = { unresolved: false }; @@ -451,11 +352,8 @@ export const locatePeResourcePayloads = async ( ); if (data === undefined) return peFailure(`PE ${name} resource data entry is truncated.`); - const bytes = data.readUInt32LE(4); - found.push({ - offset: tree.layout.map(data.readUInt32LE(0), bytes), - bytes, - }); + const { rva, size } = readPeResourceDataEntryFacts(data); + found.push({ offset: tree.layout.map(rva, size), bytes: size }); } if (found.length === before) return peFailure(`PE ${name} resource has no data entry.`); diff --git a/src/domain/pe/peResourceTreeFacts.ts b/src/domain/pe/peResourceTreeFacts.ts index 536c49de53..3307c20c4e 100644 --- a/src/domain/pe/peResourceTreeFacts.ts +++ b/src/domain/pe/peResourceTreeFacts.ts @@ -1,6 +1,9 @@ +import { BinaryReader } from "../binaryContainer.js"; + /** Fixed PE resource records; callers own interval, budget and tree admission. */ export const PE_RESOURCE_DIRECTORY_BYTES = 16; export const PE_RESOURCE_ENTRY_BYTES = 8; +export const PE_RESOURCE_DATA_ENTRY_BYTES = 16; export const PE_RESOURCE_NAME_PREFIX_BYTES = 2; /** Decode an already-admitted IMAGE_RESOURCE_DIRECTORY record. */ @@ -47,3 +50,14 @@ export const readPeResourceNameFacts = (bytes: Buffer) => { const utf16Units = bytes.readUInt16LE(0); return { utf16Units, payloadBytes: utf16Units * 2 }; }; + +/** Decode an already-admitted IMAGE_RESOURCE_DATA_ENTRY record. */ +export const readPeResourceDataEntryFacts = (bytes: Buffer) => { + const record = new BinaryReader(bytes, true, "pe"); + return { + rva: record.u32(0), + size: record.u32(4), + codePage: record.u32(8), + reserved: record.u32(12), + }; +}; diff --git a/src/domain/pe/peResources.fixture.ts b/src/domain/pe/peResources.fixture.ts index 822065809e..14f824ded3 100644 --- a/src/domain/pe/peResources.fixture.ts +++ b/src/domain/pe/peResources.fixture.ts @@ -43,7 +43,11 @@ export const peResourceFixture = ( ], sectionBytes = 65536, recordAlignment: 2 | 4 = 4, + peOffset = 0x80, ) => { + const optional = peOffset + 24; + const headerBytes = Math.ceil((optional + 240 + 40) / 512) * 512 + 512; + const resourceRva = Math.max(0x2000, Math.ceil(headerBytes / 4096) * 4096); const tree: Tree = { children: new Map() }; for (const resource of resources) { let parent = tree; @@ -122,38 +126,38 @@ export const peResourceFixture = ( for (const { dataAt, resource } of leaves) { const payloadAt = allocate(resource.payload.length, 4); resource.payload.copy(section, payloadAt); - section.writeUInt32LE(0x2000 + payloadAt, dataAt); + section.writeUInt32LE(resourceRva + payloadAt, dataAt); section.writeUInt32LE(resource.payload.length, dataAt + 4); section.writeUInt32LE(65001, dataAt + 8); } const rawSize = Math.ceil(cursor / 512) * 512; - const bytes = Buffer.alloc(0x400 + rawSize); + const bytes = Buffer.alloc(headerBytes + rawSize); bytes.writeUInt16LE(0x5a4d, 0); - bytes.writeUInt32LE(0x80, 60); - bytes.writeUInt32LE(0x4550, 0x80); - bytes.writeUInt16LE(plus ? 0x8664 : 0x14c, 0x84); - bytes.writeUInt16LE(1, 0x86); + bytes.writeUInt32LE(peOffset, 60); + bytes.writeUInt32LE(0x4550, peOffset); + bytes.writeUInt16LE(plus ? 0x8664 : 0x14c, peOffset + 4); + bytes.writeUInt16LE(1, peOffset + 6); const optionalSize = plus ? 240 : 224; - bytes.writeUInt16LE(optionalSize, 0x94); - bytes.writeUInt16LE(plus ? 0x20b : 0x10b, 0x98); - bytes.writeUInt32LE(0x400, 0x98 + 60); - bytes.writeUInt32LE(16, 0x98 + (plus ? 108 : 92)); - const directoryAt = 0x98 + (plus ? 112 : 96) + 16; - bytes.writeUInt32LE(0x2000, directoryAt); + bytes.writeUInt16LE(optionalSize, peOffset + 20); + bytes.writeUInt16LE(plus ? 0x20b : 0x10b, optional); + bytes.writeUInt32LE(headerBytes, optional + 60); + bytes.writeUInt32LE(16, optional + (plus ? 108 : 92)); + const directoryAt = optional + (plus ? 112 : 96) + 16; + bytes.writeUInt32LE(resourceRva, directoryAt); bytes.writeUInt32LE(cursor, directoryAt + 4); - const sectionAt = 0x98 + optionalSize; + const sectionAt = optional + optionalSize; bytes.write(".rsrc", sectionAt, "ascii"); bytes.writeUInt32LE(cursor, sectionAt + 8); - bytes.writeUInt32LE(0x2000, sectionAt + 12); + bytes.writeUInt32LE(resourceRva, sectionAt + 12); bytes.writeUInt32LE(rawSize, sectionAt + 16); - bytes.writeUInt32LE(0x400, sectionAt + 20); - section.copy(bytes, 0x400, 0, rawSize); + bytes.writeUInt32LE(headerBytes, sectionAt + 20); + section.copy(bytes, headerBytes, 0, rawSize); return { bytes, directoryAt, sectionAt, - entryOffsets: entryOffsets.map((at) => at + 0x400), - directoryOffsets: directories.map((at) => at + 0x400), - dataOffsets: leaves.map(({ dataAt }) => dataAt + 0x400), + entryOffsets: entryOffsets.map((at) => at + headerBytes), + directoryOffsets: directories.map((at) => at + headerBytes), + dataOffsets: leaves.map(({ dataAt }) => dataAt + headerBytes), }; }; diff --git a/src/domain/peCoffHeader.ts b/src/domain/peCoffHeader.ts index 4a4e843f84..83861ef56b 100644 --- a/src/domain/peCoffHeader.ts +++ b/src/domain/peCoffHeader.ts @@ -1,9 +1,74 @@ import { BinaryReader } from "./binaryContainer.js"; +import { + withMzWindowsHeaderSignature, + type MzHeaderEvidence, + type MzWindowsHeaderObservation, +} from "./dosMz.js"; import { err, ok } from "./result.js"; +const PE_SIGNATURE_BYTES = 4; +const PE_COFF_HEADER_BYTES = 20; +export const PE_COFF_FRAME_BYTES = PE_SIGNATURE_BYTES + PE_COFF_HEADER_BYTES; + +type PeCoffFrame = + | { + readonly kind: "other"; + readonly observation: MzWindowsHeaderObservation; + } + | { + readonly kind: "pe"; + readonly observation: Extract< + MzWindowsHeaderObservation, + { state: "declared" } + >; + readonly coff: ReturnType; + }; + +/** + * Borrow the signature and its COFF record in one bounded observation. A + * short frame may still identify an NE/LE/LX signature or a truncated PE. + * Drivers own exact-read behavior and consumers own format admission. + */ +export function* observePeCoffFrame( + prefix: Buffer, + fileSize: number, + evidence: MzHeaderEvidence, +): Generator< + { readonly offset: number; readonly size: number }, + PeCoffFrame, + Buffer +> { + const pending = evidence.windowsHeader; + if ( + pending.state !== "signature-needed" && + !(pending.state === "declared" && pending.signature === "PE") + ) + return { kind: "other", observation: pending }; + const { offset } = pending; + const size = Math.min(PE_COFF_FRAME_BYTES, Math.max(0, fileSize - offset)); + const cached = offset + size <= prefix.length; + const frame = cached + ? prefix.subarray(offset, offset + size) + : yield { offset, size }; + const observation = + cached && pending.state === "declared" + ? pending + : withMzWindowsHeaderSignature(prefix, fileSize, evidence, { + offset, + bytes: frame, + }).windowsHeader; + return observation.state === "declared" && observation.signature === "PE" + ? { + kind: "pe", + observation, + coff: readPeCoffHeader(frame.subarray(PE_SIGNATURE_BYTES)), + } + : { kind: "other", observation }; +} + /** Fixed 20-byte COFF record, excluding the PE signature; callers own admission. */ export const readPeCoffHeader = (bytes: Buffer) => { - if (bytes.length < 20) + if (bytes.length < PE_COFF_HEADER_BYTES) return err({ kind: "malformed" as const, message: "PE COFF header is truncated", diff --git a/src/domain/peOptionalHeader.ts b/src/domain/peOptionalHeader.ts index 8f5c049e47..94a4de8be1 100644 --- a/src/domain/peOptionalHeader.ts +++ b/src/domain/peOptionalHeader.ts @@ -1,5 +1,7 @@ import { err, ok, type Result } from "./result.js"; +export const PE_SIZE_OF_HEADERS_OFFSET = 60; + /** Raw data-directory words; entry 4 names file bytes, while resource entry 2 names an RVA. */ export interface PeDataDirectory { readonly address: number; @@ -82,7 +84,7 @@ export const readPeOptionalHeaderFixedFields = ( // SizeOfHeaders ends at byte 64. DllCharacteristics, at offset 70, is only // present when the declared header covers that word. NativeAOT and other // mapping-field consumers admit a 64-byte header. - if (bytes.byteLength < 64) + if (bytes.byteLength < PE_SIZE_OF_HEADERS_OFFSET + 4) return err({ kind: "malformed", reason: "truncated-fixed-fields", @@ -98,7 +100,7 @@ export const readPeOptionalHeaderFixedFields = ( sectionAlignment: view.getUint32(32, true), fileAlignment: view.getUint32(36, true), sizeOfImage: view.getUint32(56, true), - sizeOfHeaders: view.getUint32(60, true), + sizeOfHeaders: view.getUint32(PE_SIZE_OF_HEADERS_OFFSET, true), dllCharacteristics: bytes.byteLength >= 72 ? view.getUint16(70, true) : null, directoryOffset, diff --git a/src/domain/peSectionHeader.ts b/src/domain/peSectionHeader.ts index 4251f183aa..33bbc56f29 100644 --- a/src/domain/peSectionHeader.ts +++ b/src/domain/peSectionHeader.ts @@ -1,8 +1,49 @@ import { err, ok } from "./result.js"; +export const PE_SECTION_HEADER_BYTES = 40; + +/** Locate the COFF section table from the declared optional-header span. */ +export const peSectionTableExtent = ( + optionalHeaderOffset: number, + optionalHeaderSize: number, + sectionCount: number, +) => ({ + sectionTableOffset: optionalHeaderOffset + optionalHeaderSize, + sectionTableBytes: sectionCount * PE_SECTION_HEADER_BYTES, +}); + +/** Observe the declared combined header extent separately from the available prefix. */ +export const observePeHeaderExtent = ({ + optionalHeaderOffset, + optionalHeaderSize, + sectionCount, + sizeOfHeaders, + fileSize, +}: { + readonly optionalHeaderOffset: number; + readonly optionalHeaderSize: number; + readonly sectionCount: number; + readonly sizeOfHeaders: number; + readonly fileSize: number; +}) => { + // These offsets and counts come from the fixed-width PE and COFF readers. + const { sectionTableOffset, sectionTableBytes } = peSectionTableExtent( + optionalHeaderOffset, + optionalHeaderSize, + sectionCount, + ); + const sizeOfHeadersState = + sizeOfHeaders < sectionTableOffset + sectionTableBytes + ? "before-section-table-end" + : sizeOfHeaders > fileSize + ? "past-file-end" + : "valid"; + return { sectionTableOffset, sectionTableBytes, sizeOfHeadersState }; +}; + /** Fixed COFF section facts; callers own file/range and mapping admission. */ export const readPeSectionHeader = (bytes: Buffer) => { - if (bytes.length < 40) + if (bytes.length < PE_SECTION_HEADER_BYTES) return err({ kind: "malformed" as const, message: "PE section header is truncated", diff --git a/src/domain/virtualFileMapping.ts b/src/domain/virtualFileMapping.ts index 9211071b28..35ac5f251a 100644 --- a/src/domain/virtualFileMapping.ts +++ b/src/domain/virtualFileMapping.ts @@ -14,10 +14,17 @@ export interface ZeroFillMapping { } /** Why a declared virtual span does not establish one contiguous file span. */ -export interface VirtualFileMappingFailure { - readonly reason: "invalid-size" | "unmapped" | "ambiguous"; - readonly message: string; -} +export type VirtualFileMappingFailure = + | { + readonly reason: "invalid-size" | "ambiguous"; + readonly message: string; + } + | { + readonly reason: "unmapped"; + readonly message: string; + /** A gap does not erase the zero-initialized ranges within the request. */ + readonly overlapsZeroFill: boolean; + }; /** Map a physically contiguous virtual span across consistent adjacent ranges. */ export const resolveMappedFileOffset = ( @@ -31,7 +38,18 @@ export const resolveMappedFileOffset = ( reason: "invalid-size", message: "Virtual span size is invalid", }); - const end = address + BigInt(size); + const spanBytes = BigInt(size); + const end = address + spanBytes; + const overlapsZeroFill = () => + zeroFills.some(({ address: start, size: bytes }) => + spansOverlap(address, spanBytes, start, bytes), + ); + const unmapped = () => + err({ + reason: "unmapped" as const, + message: "Virtual address or string range is not file mapped", + overlapsZeroFill: overlapsZeroFill(), + }); let found: number | undefined; const covered: { start: bigint; end: bigint }[] = []; let whollyCovered = size === 0; @@ -55,37 +73,23 @@ export const resolveMappedFileOffset = ( if (start === address && overlapEnd === end) whollyCovered = true; else if (!whollyCovered) covered.push({ start, end: overlapEnd }); } - if (found === undefined) - return err({ - reason: "unmapped", - message: "Virtual address or string range is not file mapped", - }); + if (found === undefined) return unmapped(); if (!whollyCovered) { covered.sort((left, right) => left.start < right.start ? -1 : left.start > right.start ? 1 : 0, ); let cursor = address; for (const span of covered) { - if (span.start > cursor) - return err({ - reason: "unmapped", - message: "Virtual address or string range is not file mapped", - }); + if (span.start > cursor) return unmapped(); if (span.end > cursor) cursor = span.end; } - if (cursor < end) - return err({ - reason: "unmapped", - message: "Virtual address or string range is not file mapped", - }); - } - for (const zeroFill of zeroFills) { - if (spansOverlap(address, BigInt(size), zeroFill.address, zeroFill.size)) - return err({ - reason: "ambiguous", - message: "Virtual address has ambiguous file and zero-fill mappings", - }); + if (cursor < end) return unmapped(); } + if (overlapsZeroFill()) + return err({ + reason: "ambiguous", + message: "Virtual address has ambiguous file and zero-fill mappings", + }); return ok(found); }; diff --git a/src/dotnet/ManagedArtifactInspector.test.ts b/src/dotnet/ManagedArtifactInspector.test.ts index aa1114e626..1e2afe0db1 100644 --- a/src/dotnet/ManagedArtifactInspector.test.ts +++ b/src/dotnet/ManagedArtifactInspector.test.ts @@ -231,6 +231,42 @@ describe("managed CLI directory availability", () => { }); }); +it.each(["before the section table", "past the file"])( + "reports partial coverage when SizeOfHeaders ends %s", + (extent) => { + const bytes = buildManagedPeFixture(); + const optional = bytes.readUInt32LE(0x3c) + 24; + bytes.writeUInt32LE( + extent === "before the section table" ? 0x100 : bytes.length + 1, + optional + 60, + ); + + expect( + inspectManagedArtifactBytes(bytes, managedPeFixtureTarget(bytes)), + ).toMatchObject({ + pe: { + machine: 0x014c, + optional_header: "pe32", + section_count: 1, + cli: null, + }, + classification: { status: "malformed" }, + metadata: { status: "malformed" }, + coverage: { + state: "partial", + issues: [ + { + code: "invalid-directory", + scope: "pe.optional-header", + detail: expect.stringContaining("SizeOfHeaders"), + offset: optional + 60, + }, + ], + }, + }); + }, +); + describe("managed artifact inventory", () => { it.each([ { moduleRowCount: 0, assemblyRowCount: 1, scope: "metadata.Module" }, @@ -289,6 +325,7 @@ describe("managed artifact inventory", () => { fixture.copy(bytes, 0, 0, 0x0200); fixture.copy(bytes, sectionDataOffset, 0x0200, 0x1000); bytes.writeUInt16LE(97, coffOffset + 2); + bytes.writeUInt32LE(sectionDataOffset, coffOffset + 20 + 60); bytes.writeUInt32LE(sectionDataOffset, sectionOffset + 20); const result = inspectManagedArtifactBytes( diff --git a/src/dotnet/ManagedArtifactInspector.ts b/src/dotnet/ManagedArtifactInspector.ts index eea34e526a..833570ddee 100644 --- a/src/dotnet/ManagedArtifactInspector.ts +++ b/src/dotnet/ManagedArtifactInspector.ts @@ -111,13 +111,12 @@ const unavailableResult = ( ): ManagedArtifactInspection => { const malformed = layout.cliDirectoryState !== "absent"; const issues = layout.cliIssue === null ? [] : [layout.cliIssue]; - const limitations = malformed - ? [ - "The PE declares a CLI directory, but its CLI header could not be admitted.", - ] - : [ - "The PE has no CLI data directory; managed metadata and CIL are unavailable.", - ]; + const limitation = + layout.cliDirectoryState === "unreadable" + ? (layout.cliIssue?.detail ?? "The PE CLI directory could not be read.") + : malformed + ? "The PE declares a CLI directory, but its CLI header could not be admitted." + : "The PE has no CLI data directory; managed metadata and CIL are unavailable."; return managedArtifactInspectionSchema.parse( admitManagedProjection({ ...base(target, bytes, layout), @@ -132,7 +131,7 @@ const unavailableResult = ( code: malformed ? "cli-directory-malformed" : "cli-directory-absent", - detail: limitations[0], + detail: limitation, file_offset: layout.cliIssue?.offset ?? null, }, ], @@ -153,7 +152,7 @@ const unavailableResult = ( state: malformed ? "partial" : "unavailable", issues, }, - limitations, + limitations: [limitation], }), ); }; diff --git a/src/flutter/ElfBuildId.ts b/src/flutter/ElfBuildId.ts index 7bb37d68c2..3deacbadcc 100644 --- a/src/flutter/ElfBuildId.ts +++ b/src/flutter/ElfBuildId.ts @@ -5,9 +5,12 @@ import { MAX_FLUTTER_BUILD_ID_BYTES } from "../domain/flutter/flutterBuildAnalys import type { FileHandle } from "node:fs/promises"; import { setImmediate as yieldToEventLoop } from "node:timers/promises"; import { + ELF_NOTE_HEADER_BYTES, elfNoteAlignment, - elfNoteLayout, - readElfNoteHeader, + elfNoteSectionStorage, + isElfNotePadding, + readElfNoteFrame, + type ElfNoteAlignment, } from "../domain/native/elfNoteLayout.js"; import { readElfHeader, @@ -73,7 +76,7 @@ export const readElfBuildIds = async ( const h = parsed.header; const ranges = new Map< string, - { offset: number; size: number; alignment: number } + { offset: number; size: number; alignment: ElfNoteAlignment } >(); let compressedNotes = false; tables: for (const table of [ @@ -114,7 +117,13 @@ export const readElfBuildIds = async ( ); if (!parsedRecord.ok) return failure(parsedRecord.error.message); const record = parsedRecord.value; - if (record.type !== (table.program ? 4 : 7)) continue; + const storage = + "size" in record + ? elfNoteSectionStorage(record) + : record.type === 4 + ? "uncompressed" + : "not-note"; + if (storage === "not-note") continue; const offset = Number(record.offset); const size = Number("fileSize" in record ? record.fileSize : record.size); if ( @@ -123,16 +132,14 @@ export const readElfBuildIds = async ( size > totalBytes - offset ) return failure("ELF note range is not file-backed"); - if ("size" in record) { - if (record.compressed) { - if (!compressedNotes) { - failures.push({ - reason: "Compressed ELF note sections are unsupported", - }); - compressedNotes = true; - } - continue; + if (storage === "compressed") { + if (!compressedNotes) { + failures.push({ + reason: "Compressed ELF note sections are unsupported", + }); + compressedNotes = true; } + continue; } if (size === 0) continue; const alignment = elfNoteAlignment(record.alignment); @@ -161,38 +168,42 @@ export const readElfBuildIds = async ( assertArtifactReadActive(signal); yieldedAt = at; } - if (notes.length - at < 12) { - if (notes.subarray(at).some((byte) => byte !== 0)) + if (notes.length - at < ELF_NOTE_HEADER_BYTES) { + if (!isElfNotePadding(notes.subarray(at))) return failure("ELF note header is truncated"); break; } - const parsedHeader = readElfNoteHeader(notes.subarray(at, at + 12), true); - if (!parsedHeader.ok) return failure(parsedHeader.error.message); - const { namesz, descsz, type } = parsedHeader.value; - const layout = elfNoteLayout(namesz, descsz, range.alignment); - if (layout.next > notes.length - at) + const frame = readElfNoteFrame( + notes.subarray(at, at + ELF_NOTE_HEADER_BYTES), + true, + range.alignment, + notes.length - at, + ); + if (!frame.ok) return failure(frame.error.message); + const { namesz, descsz, type, descriptor, next, framing } = frame.value; + if (framing !== "complete") return failure("ELF note entry exceeds its declared note range"); - const descriptor = at + layout.descriptor; - const end = descriptor + descsz; - if (end > notes.length) - return failure("ELF note descriptor exceeds its declared note range"); + const nameOffset = at + ELF_NOTE_HEADER_BYTES; if ( namesz === 4 && type === 3 && - notes.subarray(at + 12, at + 16).equals(Buffer.from("GNU\0")) + notes + .subarray(nameOffset, nameOffset + namesz) + .equals(Buffer.from("GNU\0")) ) { if (descsz < 1 || descsz > MAX_FLUTTER_BUILD_ID_BYTES) return failure( `GNU build-id descriptor is outside the 1–${MAX_FLUTTER_BUILD_ID_BYTES} byte projection`, ); - const candidate = notes.subarray(descriptor, end).toString("hex"); + const start = at + descriptor; + const candidate = notes.subarray(start, start + descsz).toString("hex"); if (!candidates.has(candidate) && candidates.size === MAX_BUILD_IDS) return failure( "ELF build-id candidates exceed the 64-value evidence budget", ); candidates.add(candidate); } - at += layout.next; + at += next; } } assertArtifactReadActive(signal); diff --git a/src/gpu/GpuElfKernels.ts b/src/gpu/GpuElfKernels.ts index 299d4a218d..4d97d303ad 100644 --- a/src/gpu/GpuElfKernels.ts +++ b/src/gpu/GpuElfKernels.ts @@ -6,7 +6,11 @@ import { } from "./AmdGpuTarget.js"; import type { GpuPayloadTarget } from "./GpuObject.js"; import { err, ok, type Result } from "../domain/result.js"; -import { elfNoteLayout } from "../domain/native/elfNoteLayout.js"; +import { + ELF_NOTE_HEADER_BYTES, + elfNoteSectionStorage, + readElfNoteFrame, +} from "../domain/native/elfNoteLayout.js"; import { CudaMetadataBudget, readCudaInfo, @@ -458,7 +462,7 @@ export const readAmdElfMetadata = async ( }; for (const section of directory.sections) { - if (section.type !== 7) continue; + if (elfNoteSectionStorage(section) === "not-note") continue; const sectionSize = gpuCount(section.size); if (sectionSize > AMD_METADATA_BYTES - retainedBytes) throw new BinaryResourceFailure( @@ -467,24 +471,30 @@ export const readAmdElfMetadata = async ( "AMDGPU ELF note discovery exceeds the 8 MiB retained metadata budget", ); retainedBytes += sectionSize; - const bytes = await sectionBytes(source, section), - r = new BinaryReader(bytes, directory.little, "elf"); + const bytes = await sectionBytes(source, section); for (let p = 0; p < bytes.length;) { - if (bytes.length - p < 12) rejectGpu("Truncated ELF note header"); - const namesize = r.u32(p), - size = r.u32(p + 4), - type = r.u32(p + 8); // AMDGPU metadata uses four-byte note padding regardless of section alignment. - const layout = elfNoteLayout(namesize, size, 4); - const nameOffset = p + 12, - desc = p + layout.descriptor, - end = p + layout.next; - r.range(nameOffset, namesize, "ELF note vendor"); - r.range(desc, size, "ELF note descriptor"); - if (end > bytes.length) - rejectGpu("ELF note alignment extends outside its section"); + const frame = readElfNoteFrame( + bytes.subarray(p, p + ELF_NOTE_HEADER_BYTES), + directory.little, + 4, + bytes.length - p, + ); + if (!frame.ok) return rejectGpu(frame.error.message); + const { + namesz, + descsz: size, + type, + descriptor, + next, + framing, + } = frame.value; + if (framing !== "complete") + rejectGpu("ELF note entry exceeds its declared note section"); + const nameOffset = p + ELF_NOTE_HEADER_BYTES; + const desc = p + descriptor; const vendor = bytes - .subarray(nameOffset, nameOffset + namesize) + .subarray(nameOffset, nameOffset + namesz) .toString("latin1") .replace(/\0$/u, ""); if (vendor === "AMDGPU" && type === 32) { @@ -514,7 +524,7 @@ export const readAmdElfMetadata = async ( "Legacy AMDGPU YAML metadata is outside MessagePack coverage", ); } - p = end; + p += next; } } targetMetadata.note_coverage = diff --git a/src/native/elf/ElfDependencyParser.test.ts b/src/native/elf/ElfDependencyParser.test.ts index 5a15bc26a3..24f033403d 100644 --- a/src/native/elf/ElfDependencyParser.test.ts +++ b/src/native/elf/ElfDependencyParser.test.ts @@ -44,6 +44,133 @@ const parse = ( const defaultNeeded = ["libstdc++.so.6", "libm.so.6", "libc.so.6"]; +const elf64ProgramHeaders = (original: Buffer) => { + const phoff = Number(original.readBigUInt64LE(32)); + const phentsize = original.readUInt16LE(54); + const phnum = original.readUInt16LE(56); + const programHeaders = Array.from( + { length: phnum }, + (_, index) => phoff + index * phentsize, + ); + return { phoff, phentsize, phnum, programHeaders }; +}; + +const elf64DynamicTags = (original: Buffer, headers: readonly number[]) => { + const dynamic = headers.find((offset) => original.readUInt32LE(offset) === 2); + if (dynamic === undefined) throw new Error("Expected PT_DYNAMIC"); + const start = Number(original.readBigUInt64LE(dynamic + 8)); + const count = Number(original.readBigUInt64LE(dynamic + 32)) / 16; + return new Map( + Array.from({ length: count }, (_, index) => { + const offset = start + index * 16; + return [ + original.readBigInt64LE(offset), + original.readBigUInt64LE(offset + 8), + ]; + }), + ); +}; + +const shortenElf64IdentityLoad = ( + original: Buffer, + bytes: Buffer, + { phoff, programHeaders }: ReturnType, + end: bigint, +) => { + const load = programHeaders.find( + (offset) => original.readUInt32LE(offset) === 1, + ); + if (load === undefined) throw new Error("Expected PT_LOAD"); + const movedLoad = original.length + load - phoff; + bytes.writeBigUInt64LE(end, movedLoad + 32); + bytes.writeBigUInt64LE(end, movedLoad + 40); +}; + +const appendElf64ZeroFill = ( + original: Buffer, + { phoff, phentsize, phnum }: ReturnType, +) => { + const bytes = Buffer.concat([ + original, + Buffer.alloc((phnum + 1) * phentsize), + ]); + original.copy(bytes, original.length, phoff, phoff + phnum * phentsize); + bytes.writeBigUInt64LE(BigInt(original.length), 32); + bytes.writeUInt16LE(phnum + 1, 56); + const alias = original.length + phnum * phentsize; + bytes.writeUInt32LE(1, alias); + bytes.writeUInt32LE(4, alias + 4); + bytes.writeBigUInt64LE(1n, alias + 40); + bytes.writeBigUInt64LE(1n, alias + 48); + return { bytes, alias }; +}; + +it.each([ + { stripped: true, unmappedTail: false }, + { stripped: false, unmappedTail: false }, + { stripped: false, unmappedTail: true }, +])( + "leaves dynamic strings unknown on a zero-fill overlap (stripped: $stripped, unmapped tail: $unmappedTail)", + ({ stripped, unmappedTail }) => { + const original = elfDependencyFixture({ bits: 64, little: true, stripped }); + const headers = elf64ProgramHeaders(original); + const tags = elf64DynamicTags(original, headers.programHeaders); + const stringAddress = tags.get(5n); + const stringSize = tags.get(10n); + if (stringAddress === undefined || stringSize === undefined) + throw new Error("Expected DT_STRTAB and DT_STRSZ"); + const { bytes, alias } = appendElf64ZeroFill(original, headers); + if (unmappedTail) + // The table starts in the identity mapping, but its section alone describes the tail. + shortenElf64IdentityLoad(original, bytes, headers, stringAddress + 2n); + bytes.writeBigUInt64LE(stringAddress + stringSize, alias + 16); + expect(parse(bytes).needed.map(({ name }) => name)).toEqual(defaultNeeded); + + // The initial NUL byte still maps uniquely; a later string byte does not. + bytes.writeBigUInt64LE(stringAddress + 1n, alias + 16); + const report = parse(bytes); + expect(report.needed.map(({ name }) => name)).toEqual([null, null, null]); + expect(report.coverage.status).toBe("partial"); + expect(report.issues).toContainEqual( + expect.objectContaining({ + code: "table_unavailable", + message: "ELF dynamic string table has ambiguous file mappings", + }), + ); + }, +); + +it.each([false, true])( + "keeps independent dependency names when dynamic symbol bytes disagree (string table gap: %s)", + (stringGap) => { + const original = elfDependencyFixture(); + const headers = elf64ProgramHeaders(original); + const tags = elf64DynamicTags(original, headers.programHeaders); + const symtab = tags.get(6n); + const strtab = tags.get(5n); + if (symtab === undefined || strtab === undefined) + throw new Error("Expected DT_SYMTAB and DT_STRTAB"); + const { bytes, alias } = appendElf64ZeroFill(original, headers); + if (stringGap) + shortenElf64IdentityLoad(original, bytes, headers, strtab + 2n); + bytes.writeBigUInt64LE(BigInt(original.length), alias + 16); + expect(parse(bytes).imports.map(({ name }) => name)).toEqual([ + "printf", + "memcpy", + "_ZSt4cout", + "abort", + "_exit", + ]); + + // The symbol table start stays mapped; a later symbol occupies both kinds of storage. + bytes.writeBigUInt64LE(symtab + 24n, alias + 16); + const report = parse(bytes); + expect(report.needed.map(({ name }) => name)).toEqual(defaultNeeded); + expect(report.imports).toEqual([]); + expect(report.coverage.status).toBe("partial"); + }, +); + /** The version_unresolved issue a GNU version table reports at its own offset. */ const versionTableIssue = (table: { readonly location: { readonly offset: number } | null; diff --git a/src/native/elf/ElfDependencyParser.ts b/src/native/elf/ElfDependencyParser.ts index 6daa3336a9..58accc7764 100644 --- a/src/native/elf/ElfDependencyParser.ts +++ b/src/native/elf/ElfDependencyParser.ts @@ -1,10 +1,28 @@ import { keyedBy, uniqueKeyed } from "../../domain/keyedCollection.js"; import { decodeLimit, ParseFailureError } from "../../domain/parseFailure.js"; import { errorMessage } from "../../kernel/errorMessage.js"; -import { readElfDynamicEntry } from "../../domain/elfDynamicEntry.js"; +import { + DT_FLAGS, + DT_FLAGS_1, + DT_GNU_HASH, + DT_HASH, + DT_NEEDED, + DT_RPATH, + DT_RUNPATH, + DT_STRTAB, + DT_STRSZ, + DT_SYMENT, + DT_SYMTAB, + walkElfDynamicTable, +} from "../../domain/elfDynamicEntry.js"; import { validateElfSectionTablePresence } from "../../domain/elfDeclaredRanges.js"; import { readElfFixedHeader } from "../../domain/elfFixedHeader.js"; -import { readElfProgramHeader } from "../../domain/elfProgramHeader.js"; +import { + admitElfLoadSegment, + elfLoadSpans, + readElfProgramHeader, + type ElfLoadMappings, +} from "../../domain/elfProgramHeader.js"; import { readElfRawTableDeclarations } from "../../domain/elfRawTableDeclarations.js"; import { readElfSectionHeader } from "../../domain/elfSectionHeader.js"; import { @@ -44,7 +62,11 @@ import { createFileMappingIndex, mappedFileOffset, } from "../../domain/binaryContainer.js"; -import type { FileMapping } from "../../domain/virtualFileMapping.js"; +import { + resolveMappedFileOffset, + type FileMapping, + type ZeroFillMapping, +} from "../../domain/virtualFileMapping.js"; import { architectureForElfMachine } from "../../domain/native/elfImage.js"; import { Budget } from "../../domain/budget.js"; @@ -60,24 +82,12 @@ const SHT_GNU_HASH = 0x6ffffff6; const SHT_GNU_VERDEF = 0x6ffffffd; const SHT_GNU_VERNEED = 0x6ffffffe; const SHT_GNU_VERSYM = 0x6fffffff; -const DT_NULL = 0; -const DT_NEEDED = 1; -const DT_HASH = 4; -const DT_STRTAB = 5; -const DT_SYMTAB = 6; -const DT_STRSZ = 10; -const DT_SYMENT = 11; -const DT_SONAME = 14; -const DT_RPATH = 15; -const DT_RUNPATH = 29; -const DT_FLAGS = 30; -const DT_GNU_HASH = 0x6ffffef5; -const DT_VERSYM = 0x6ffffff0; -const DT_FLAGS_1 = 0x6ffffffb; -const DT_VERDEF = 0x6ffffffc; -const DT_VERDEFNUM = 0x6ffffffd; -const DT_VERNEED = 0x6ffffffe; -const DT_VERNEEDNUM = 0x6fffffff; +const DT_SONAME = 14n; +const DT_VERSYM = 0x6ffffff0n; +const DT_VERDEF = 0x6ffffffcn; +const DT_VERDEFNUM = 0x6ffffffdn; +const DT_VERNEED = 0x6ffffffen; +const DT_VERNEEDNUM = 0x6fffffffn; const VER_FLG_BASE = 1; const VER_FLG_WEAK = 2; /** @@ -148,12 +158,6 @@ const fail = (message: string): never => { const hex = (value: number | bigint): string => `0x${value.toString(16)}`; -/** Class-width tag value, or null when it is wider than every known DT_* tag. */ -const asTag = (tag: bigint, bits: 32 | 64): number | null => { - const word = BigInt.asUintN(bits, tag); - return word > 0xffffffffn ? null : Number(word); -}; - const asNumber = (value: bigint, label: string): number => { if (value > BigInt(Number.MAX_SAFE_INTEGER)) fail(`${label} is not representable`); @@ -371,12 +375,17 @@ const searchPath = ( }; const mapAddress = ( - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, address: bigint, size: number, ): number | null => { try { - return mappedFileOffset(mappings, address, size); + return mappedFileOffset( + mappings.fileBacked, + address, + size, + mappings.zeroFills, + ); } catch (cause) { if (cause instanceof BinaryMappingFailure) return null; throw cause; @@ -385,44 +394,68 @@ const mapAddress = ( /** File-offset end of the PT_LOAD mapping that contains a virtual address. */ const mappedExtentEnd = ( - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, address: bigint, ): number | null => { - for (const mapping of mappings) - if ( - address >= mapping.address && - address < mapping.address + BigInt(mapping.size) - ) - return mapping.offset + mapping.size; - return null; + const mapping = mappings.fileBacked.find( + (range) => + address >= range.address && address < range.address + BigInt(range.size), + ); + if (mapping === undefined) return null; + let end = mapping.address + BigInt(mapping.size); + for (const zeroFill of mappings.zeroFills) + if (zeroFill.address > address && zeroFill.address < end) + end = zeroFill.address; + return mapping.offset + Number(end - mapping.address); }; +interface SectionAdmission { + readonly declaration: SectionFacts | undefined; + readonly table: SectionFacts | undefined; +} + /** - * DT_* entries are the load-time facts. A section header describing the same - * table is accepted only when it names the same address, maps to the same file - * bytes, and agrees on any declared size; otherwise the dynamic declaration wins. + * Admit the section declaration at the agreed start, then check its table + * extent. A conflicting extent does not invalidate the section header's links. */ const agreedSection = ( section: SectionFacts | undefined, declared: bigint | undefined, - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, label: string, issues: ElfDependencyIssue[], sizeAgrees: (section: SectionFacts) => boolean = () => true, -): SectionFacts | undefined => { - if (section === undefined || declared === undefined) return section; - if ( - section.address === declared && - mapAddress(mappings, declared, 1) === section.offset && - sizeAgrees(section) - ) - return section; +): SectionAdmission => { + if (section === undefined || declared === undefined) + return { declaration: section, table: section }; + let declaration: SectionFacts | undefined; + if (section.address === declared && sizeAgrees(section)) { + const mapped = resolveMappedFileOffset( + mappings.fileBacked, + declared, + Math.max(1, section.size), + mappings.zeroFills, + ); + const start = mapped.ok ? mapped.value : mapAddress(mappings, declared, 1); + if (start === section.offset) { + declaration = section; + if ( + mapped.ok || + (mapped.error.reason === "unmapped" && !mapped.error.overlapsZeroFill) + ) + // A plain gap still allows recovery from the section's file bytes. + return { declaration, table: section }; + } + } issues.push({ code: "malformed_entry", location: hex(section.offset), - message: `${label} section header disagrees with its dynamic-table declaration; using the dynamic declaration`, + message: + declaration === undefined + ? `${label} section header disagrees with its dynamic-table declaration; using the dynamic declaration` + : `${label} section extent conflicts with its load mapping. Using the dynamic declaration`, }); - return undefined; + return { declaration, table: undefined }; }; const sectionInsideFile = (section: SectionFacts, fileBytes: number): boolean => @@ -454,7 +487,7 @@ const tableFromSection = ( }; const tableFromVirtual = ( - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, address: bigint | undefined, size: number, ): LocatedTable | null => { @@ -498,10 +531,10 @@ const sysvSymbolCountAt = ( */ const mappedHashWords = ( reader: BinaryReader, - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, address: bigint, ): ElfHashWordReader => { - const index = createFileMappingIndex(mappings); + const index = createFileMappingIndex(mappings.fileBacked, mappings.zeroFills); return (offset) => { if (offset < 0) return err("precedes its table"); let at: number; @@ -520,7 +553,7 @@ const mappedHashWords = ( const sysvSymbolCount = ( reader: BinaryReader, - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, address: bigint, ): number | null => { const count = readElfHashSymbolCount( @@ -556,7 +589,7 @@ const gnuSymbolCount = function* ( }; const locateVersionTable = ( - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, fileBytes: number, section: SectionFacts | undefined, address: bigint | undefined, @@ -671,7 +704,9 @@ export const readElfDependenciesSteps = function* ( if (phentsize < (bits === 64 ? 56 : 32)) fail("ELF program header width is invalid."); reader.range(phoff, phnum * phentsize, "ELF program headers"); - const mappings: FileMapping[] = []; + const fileBacked: FileMapping[] = []; + const zeroFills: ZeroFillMapping[] = []; + const mappings: ElfLoadMappings = { fileBacked, zeroFills }; let interp: Range | null = null; let dynamic: Range | null = null; for (let index = 0; index < phnum; index += 1) { @@ -696,63 +731,48 @@ export const readElfDependenciesSteps = function* ( continue; } if (program.type !== PT_LOAD) continue; + const admitted = admitElfLoadSegment(program, bits); + if (!admitted.ok) return fail(admitted.error.message); const range = fileRange(program.offset, program.fileSize, "PT_LOAD"); - if (range.bytes === 0) continue; - reader.range(range.offset, range.bytes, "PT_LOAD"); - mappings.push({ - address: program.virtualAddress, - offset: range.offset, - size: range.bytes, - }); + if (range.bytes > 0) reader.range(range.offset, range.bytes, "PT_LOAD"); + const spans = elfLoadSpans(program); + if (spans.fileBacked !== undefined) fileBacked.push(spans.fileBacked); + if (spans.zeroFill !== undefined) zeroFills.push(spans.zeroFill); } const issues: ElfDependencyIssue[] = []; const interpreter = parseInterpreter(reader, interp, issues); if (dynamic === null) return emptyInventory(artifact, identity, interpreter, issues); - reader.range(dynamic.offset, dynamic.bytes, "PT_DYNAMIC"); - const entrySize = bits === 64 ? 16 : 8; - const unique = new Map(); - const addresses = new Map(); + const table = reader.range(dynamic.offset, dynamic.bytes, "PT_DYNAMIC"); + const unique = new Map(); + const addresses = new Map(); const neededOffsets: number[] = []; - let terminated = false; - for ( - let base = dynamic.offset; - base + entrySize <= dynamic.offset + dynamic.bytes; - base += entrySize - ) { - const parsedEntry = readElfDynamicEntry( - bytes.subarray(base, base + entrySize), - bits, - reader.little, + const walked = walkElfDynamicTable( + table, + { bits, littleEndian: reader.little }, + UNIQUE_DYNAMIC_TAGS, + ({ tag, value, singleton }) => { + if (tag === DT_NEEDED) { + neededOffsets.push(asNumber(value, "DT_NEEDED")); + charge( + neededOffsets.length, + input.max_needed, + MAX_INSPECT_ELF_DEPENDENCY_NEEDED, + "DT_NEEDED entries", + "max_needed", + ); + } else if (ADDRESS_DYNAMIC_TAGS.has(tag)) addresses.set(tag, value); + else if (singleton) + unique.set(tag, asNumber(value, `DT tag ${hex(tag)}`)); + }, + ); + if (!walked.ok) + return fail( + walked.error.kind === "duplicate-singleton" + ? `Duplicate dynamic tag ${hex(walked.error.tag)}` + : walked.error.error, ); - if (!parsedEntry.ok) return fail(parsedEntry.error.message); - const tag = asTag(parsedEntry.value.tag, bits); - if (tag === null) continue; - if (tag === DT_NULL) { - terminated = true; - break; - } - if (tag === DT_NEEDED) { - neededOffsets.push(asNumber(parsedEntry.value.value, "DT_NEEDED")); - charge( - neededOffsets.length, - input.max_needed, - MAX_INSPECT_ELF_DEPENDENCY_NEEDED, - "DT_NEEDED entries", - "max_needed", - ); - continue; - } - if (!UNIQUE_DYNAMIC_TAGS.has(tag)) continue; - if (unique.has(tag) || addresses.has(tag)) - fail(`Duplicate dynamic tag ${hex(tag)}`); - if (ADDRESS_DYNAMIC_TAGS.has(tag)) { - addresses.set(tag, parsedEntry.value.value); - continue; - } - unique.set(tag, asNumber(parsedEntry.value.value, `DT tag ${hex(tag)}`)); - } - if (!terminated) + if (walked.value.terminatorOffset === null) issues.push({ code: "malformed_entry", location: hex(dynamic.offset), @@ -779,31 +799,35 @@ export const readElfDependenciesSteps = function* ( }); return undefined; }; - const sectionOf = (type: number, tag: number, label: string) => + const sectionOf = (type: number, tag: bigint, label: string) => agreedSection( sectionOfType(type, label), addresses.get(tag), mappings, label, issues, - ); + ).table; const syment = unique.get(DT_SYMENT); - const dynsymSection = agreedSection( - sectionOfType(SHT_DYNSYM, ".dynsym"), - addresses.get(DT_SYMTAB), - mappings, - ".dynsym", - issues, - (section) => - syment === undefined || - section.entrySize === 0 || - section.entrySize === syment, - ); + const { declaration: symbolDeclaration, table: dynsymSection } = + agreedSection( + sectionOfType(SHT_DYNSYM, ".dynsym"), + addresses.get(DT_SYMTAB), + mappings, + ".dynsym", + issues, + (section) => + syment === undefined || + section.entrySize === 0 || + section.entrySize === syment, + ); const strsz = unique.get(DT_STRSZ); const linkedStrings = - dynsymSection === undefined ? undefined : sectionFacts[dynsymSection.link]; - const dynstrSection = agreedSection( - linkedStrings?.type === 3 ? linkedStrings : undefined, + symbolDeclaration === undefined + ? undefined + : sectionFacts[symbolDeclaration.link]; + const stringSection = linkedStrings?.type === 3 ? linkedStrings : undefined; + const { table: dynstrSection } = agreedSection( + stringSection, addresses.get(DT_STRTAB), mappings, ".dynstr", @@ -819,18 +843,50 @@ export const readElfDependenciesSteps = function* ( const verdefSection = sectionOf(SHT_GNU_VERDEF, DT_VERDEF, ".gnu.version_d"); const hashSection = sectionOf(5, DT_HASH, ".hash"); const gnuHashSection = sectionOf(SHT_GNU_HASH, DT_GNU_HASH, ".gnu.hash"); - const dynstrTable = - tableFromSection(dynstrSection, bytes.length, "Dynamic string", issues) ?? - tableFromVirtual(mappings, addresses.get(DT_STRTAB), strsz ?? 0); + const strtab = addresses.get(DT_STRTAB); + const mappedStrings = + strtab === undefined + ? undefined + : resolveMappedFileOffset( + fileBacked, + strtab, + Math.max(1, strsz ?? dynstrSection?.size ?? 0), + zeroFills, + ); + const mappingFailure = + mappedStrings?.ok === false ? mappedStrings.error : undefined; + // A section can recover an unmapped span, but cannot provide file bytes + // where the load mapping supplies zeros or conflicts. + const ambiguousStrings = + mappingFailure?.reason === "ambiguous" || + (mappingFailure?.reason === "unmapped" && + mappingFailure.overlapsZeroFill && + stringSection?.address === strtab); + const dynstrTable = ambiguousStrings + ? null + : (tableFromSection( + dynstrSection, + bytes.length, + "Dynamic string", + issues, + ) ?? + (mappedStrings?.ok === true + ? { + offset: mappedStrings.value, + size: strsz ?? 0, + location: { offset: mappedStrings.value, bytes: strsz ?? 0 }, + } + : null)); if ( dynstrTable === null && - (neededOffsets.length > 0 || unique.has(DT_SONAME)) + (ambiguousStrings || neededOffsets.length > 0 || unique.has(DT_SONAME)) ) issues.push({ code: "table_unavailable", location: hex(dynamic.offset), - message: - "Dynamic string table could not be located from section headers or DT_STRTAB", + message: ambiguousStrings + ? "ELF dynamic string table has ambiguous file mappings" + : "Dynamic string table could not be located from section headers or DT_STRTAB", }); const dynstr = new DynamicStrings( dynstrTable === null @@ -1158,11 +1214,11 @@ const readSections = ( const locateSymbolCount = function* ( reader: BinaryReader, - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, dynsym: SectionFacts | undefined, hash: SectionFacts | undefined, gnuHash: SectionFacts | undefined, - tags: ReadonlyMap, + tags: ReadonlyMap, bits: 32 | 64, entrySize: number, issues: ElfDependencyIssue[], @@ -1232,7 +1288,7 @@ const followVersionLink = ( const parseVerneed = ( reader: BinaryReader, bytes: Buffer, - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, dynstr: DynamicStrings, section: SectionFacts | undefined, address: bigint | undefined, @@ -1377,7 +1433,7 @@ const parseVerneed = ( const parseVerdef = ( reader: BinaryReader, bytes: Buffer, - mappings: readonly FileMapping[], + mappings: ElfLoadMappings, dynstr: DynamicStrings, section: SectionFacts | undefined, address: bigint | undefined, diff --git a/src/native/elf/ElfNoteParser.ts b/src/native/elf/ElfNoteParser.ts index 66227a1d2d..108553e223 100644 --- a/src/native/elf/ElfNoteParser.ts +++ b/src/native/elf/ElfNoteParser.ts @@ -15,9 +15,12 @@ import { type ElfFixedHeader, } from "../../domain/elfFixedHeader.js"; import { + ELF_NOTE_HEADER_BYTES, elfNoteAlignment as noteAlignment, - elfNoteLayout, - readElfNoteHeader, + elfNoteSectionStorage, + isElfNotePadding, + readElfNoteFrame, + type ElfNoteAlignment, } from "../../domain/native/elfNoteLayout.js"; import type { ElfNotes, @@ -39,7 +42,6 @@ import { import { sha256Hex } from "../../kernel/sha256Hex.js"; const PT_NOTE = 4; -const SHT_NOTE = 7; const SHT_STRTAB = 3; const HEX_DESCRIPTOR_LIMIT = 64; @@ -266,7 +268,7 @@ const parseNoteStream = ( reader: ElfReader, offset: number, size: number, - alignment: number, + alignment: ElfNoteAlignment, maxEntries: number, examined: { count: number }, text: TextBudget, @@ -278,7 +280,7 @@ const parseNoteStream = ( reader.require(offset, size); const notes: ParsedNote[] = []; let at = 0; - while (at + 12 <= size) { + while (at + ELF_NOTE_HEADER_BYTES <= size) { assertArtifactReadActive(signal); examined.count += 1; if (examined.count > maxEntries) @@ -288,31 +290,29 @@ const parseNoteStream = ( { name: "max_entries", maximum: maxEntries, required: examined.count }, ); const header = offset + at; - const parsedHeader = readElfNoteHeader( - reader.slice(header, 12), + const frame = readElfNoteFrame( + reader.slice(header, ELF_NOTE_HEADER_BYTES), reader.little, + alignment, + size - at, ); - if (!parsedHeader.ok) return fail(parsedHeader.error.message); - const { namesz, descsz, type } = parsedHeader.value; - // Align offsets from the start of this note. Independently rounding - // namesz/descsz disagrees with binutils when alignment is 8 because the - // 12-byte note header is not 8-aligned (GNU property namesz=4 then starts - // its descriptor at 16, not 20). - const { descriptor: descRel, next: nextRel } = elfNoteLayout( + if (!frame.ok) return fail(frame.error.message); + const { namesz, descsz, - alignment, - ); - const next = at + nextRel; - if (next > size) fail("ELF note entry exceeds its table."); - if (next <= at) fail("ELF note alignment did not advance."); - const nameBytes = reader.slice(header + 12, namesz); + type, + descriptor: descRel, + next, + framing, + } = frame.value; + if (framing !== "complete") fail("ELF note entry exceeds its table."); + const nameBytes = reader.slice(header + ELF_NOTE_HEADER_BYTES, namesz); const descriptor = reader.slice(header + descRel, descsz); const ownerEnd = nameBytes.indexOf(0); const ownerBytes = ownerEnd < 0 ? namesz : ownerEnd; chargeText(text, ownerBytes + namesz * 2); notes.push({ - location: { offset: header, bytes: next - at }, + location: { offset: header, bytes: next }, namesz, descsz, type, @@ -324,12 +324,9 @@ const parseNoteStream = ( descriptor, descriptor_offset: header + descRel, }); - at = next; + at += next; } - if ( - at < size && - reader.slice(offset + at, size - at).some((byte) => byte !== 0) - ) + if (at < size && !isElfNotePadding(reader.slice(offset + at, size - at))) fail("ELF note table has trailing non-zero bytes."); return notes; }; @@ -959,7 +956,8 @@ export const parseElfNotes = ( ); if (!parsedSection.ok) return fail(parsedSection.error.message); const section = parsedSection.value; - if (section.type !== SHT_NOTE) continue; + const storage = elfNoteSectionStorage(section); + if (storage === "not-note") continue; const nameOffset = section.nameOffset; if ( section.offset > BigInt(Number.MAX_SAFE_INTEGER) || @@ -969,7 +967,7 @@ export const parseElfNotes = ( const fileOffset = Number(section.offset); const fileSize = Number(section.size); reader.require(fileOffset, fileSize); - if (section.compressed) + if (storage === "compressed") throw new BinaryFormatFailure( "unsupported", "Compressed ELF note sections are unsupported; descriptor file offsets require uncompressed note storage.", diff --git a/src/native/hardening/ElfHardening.ts b/src/native/hardening/ElfHardening.ts index ab8cd714b3..1750afbf2d 100644 --- a/src/native/hardening/ElfHardening.ts +++ b/src/native/hardening/ElfHardening.ts @@ -8,7 +8,20 @@ import { keyedBy, uniqueKeyed, } from "../../domain/keyedCollection.js"; -import { readElfDynamicEntry } from "../../domain/elfDynamicEntry.js"; +import { + DT_FLAGS, + DT_FLAGS_1, + DT_GNU_HASH, + DT_HASH, + DT_RPATH, + DT_RUNPATH, + DT_STRTAB, + DT_STRSZ, + DT_SYMENT, + DT_SYMTAB, + elfDynamicEntryWidth, + walkElfDynamicTable, +} from "../../domain/elfDynamicEntry.js"; import { elfArchitecture } from "../../domain/elfFixedHeader.js"; import { admitElfLoadSegment } from "../../domain/elfProgramHeader.js"; import { readElfSymbol } from "../../domain/elfSymbol.js"; @@ -28,7 +41,10 @@ import { MAX_BINARY_HARDENING_SYMBOL_SCAN_BYTES, MAX_BINARY_HARDENING_TABLE_ENTRIES, } from "../../domain/native/binaryHardening.js"; -import { elfNoteAlignment } from "../../domain/native/elfNoteLayout.js"; +import { + elfNoteAlignment, + elfNoteSectionStorage, +} from "../../domain/native/elfNoteLayout.js"; import { MAX_INSPECT_ELF_NOTE_ENTRIES } from "../../domain/native/elfNotes.js"; import { elfStringTableText, @@ -60,19 +76,7 @@ const ET_EXEC = 2; const ET_DYN = 3; const SHT_SYMTAB = 2; const SHT_STRTAB = 3; -const SHT_NOTE = 7; const SHT_DYNSYM = 11; -const DT_NULL = 0n; -const DT_HASH = 4n; -const DT_STRTAB = 5n; -const DT_SYMTAB = 6n; -const DT_STRSZ = 10n; -const DT_SYMENT = 11n; -const DT_RPATH = 15n; -const DT_RUNPATH = 29n; -const DT_FLAGS = 30n; -const DT_GNU_HASH = 0x6ffffef5n; -const DT_FLAGS_1 = 0x6ffffffbn; const DT_BIND_NOW = 24n; const DF_BIND_NOW = 0x8n; const DF_1_NOW = 0x1n; @@ -185,7 +189,6 @@ export const readElfHardening = ( assertElfDeclaredRangesFromBuffer(bytes); const { bits, little, machine, programs, sections } = directory; const headerWidth = bits === 64 ? 56 : 32; - const dynamicWidth = bits === 64 ? 16 : 8; const propertyAlign = bits === 64 ? 8 : 4; const loads = programs.filter(isSpan).filter((program) => program.type === 1); for (const load of loads) { @@ -221,14 +224,7 @@ export const readElfHardening = ( const dynamic = dynamicPrograms[0] === undefined ? null - : readDynamic( - bytes, - dynamicPrograms[0], - bits, - little, - dynamicWidth, - mapVa, - ); + : readDynamic(bytes, dynamicPrograms[0], bits, little, mapVa); let symbols: SymbolScan; try { symbols = readSymbols( @@ -411,9 +407,9 @@ const readDynamic = ( program: Extract, bits: 32 | 64, little: boolean, - width: number, mapVa: MapVa, ): DynamicTable => { + const width = elfDynamicEntryWidth(bits); const offset = exact(program.offset, "PT_DYNAMIC offset"); const size = exact(program.size, "PT_DYNAMIC size"); if (size % width !== 0) @@ -423,29 +419,23 @@ const readDynamic = ( if (size > bytes.length - offset) malformed("ELF PT_DYNAMIC extends outside the file"); const entries = new Map(); - let terminated = false; - for (let index = 0; index < count; index += 1) { - const at = offset + index * width; - const parsed = readElfDynamicEntry( - bytes.subarray(at, at + width), - bits, - little, + const walked = walkElfDynamicTable( + bytes.subarray(offset, offset + size), + { bits, littleEndian: little }, + SINGULAR_DYNAMIC_TAGS, + ({ tag, value, offset: entryOffset, singleton }) => { + if (singleton) + entries.set(tag, { value, offset: offset + entryOffset, bytes: width }); + }, + ); + if (!walked.ok) + return malformed( + walked.error.kind === "duplicate-singleton" + ? `ELF dynamic tag ${walked.error.tag.toString()} is duplicated` + : walked.error.error, ); - if (!parsed.ok) malformed(parsed.error.message); - if (parsed.value.tag === DT_NULL) { - terminated = true; - break; - } - if (!SINGULAR_DYNAMIC_TAGS.has(parsed.value.tag)) continue; - if (entries.has(parsed.value.tag)) - malformed(`ELF dynamic tag ${parsed.value.tag.toString()} is duplicated`); - entries.set(parsed.value.tag, { - value: parsed.value.value, - offset: at, - bytes: width, - }); - } - if (!terminated) malformed("ELF dynamic table has no DT_NULL terminator"); + if (walked.value.terminatorOffset === null) + malformed("ELF dynamic table has no DT_NULL terminator"); const strtab = entries.get(DT_STRTAB); const strsz = entries.get(DT_STRSZ); if ((strtab === undefined) !== (strsz === undefined)) @@ -911,13 +901,13 @@ const readFeatureNotes = ( const otherSpans: NoteSpan[] = []; let incomplete: string | null = null; for (const section of sections) { - if (section.type !== SHT_NOTE) continue; + const storage = elfNoteSectionStorage(section); + if (storage === "not-note") continue; // An empty note section owns no bytes, so it has nothing to walk. if (section.size === 0n) continue; - if (section.compressed) + if (storage === "compressed") { incomplete ??= "A compressed SHT_NOTE section may hold GNU property notes, and its descriptors were not read."; - if (section.compressed) { if (!section.file_backed) continue; otherSpans.push({ offset: exact(section.offset, "SHT_NOTE offset"), diff --git a/src/native/pe/PeCertificateParser.test.ts b/src/native/pe/PeCertificateParser.test.ts index 0b638b0451..879b10bfb0 100644 --- a/src/native/pe/PeCertificateParser.test.ts +++ b/src/native/pe/PeCertificateParser.test.ts @@ -815,6 +815,17 @@ it("admits ASN.1 nesting at the depth budget and refuses one level more", () => }); }); +it("retains overlay certificate evidence with unrelated section bytes outside the file", () => { + const bytes = peCertificateFixture(); + const section = 0x98 + 224; + bytes.writeUInt32LE(512, section + 16); + bytes.writeUInt32LE(bytes.length, section + 20); + expect(parse(bytes)).toMatchObject({ + coverage: { status: "complete", certificates: 1 }, + entries: [{ location: { offset: 0x200 } }], + }); +}); + it("rejects headers whose section table does not fit SizeOfHeaders", () => { const bytes = peWithoutCertificateTableFixture(); bytes.writeUInt16LE(0xffff, 0x86); diff --git a/src/native/pe/PeCertificateParser.ts b/src/native/pe/PeCertificateParser.ts index fa857e2c72..a0ddb70dba 100644 --- a/src/native/pe/PeCertificateParser.ts +++ b/src/native/pe/PeCertificateParser.ts @@ -13,7 +13,7 @@ import { PeCertificateAsn1Failure, readAsn1, } from "./PeCertificateAsn1.js"; -import { readPeHeaders } from "../../domain/pe/peResourceLayout.js"; +import { readPeImageHeaders } from "../../domain/pe/peImageHeaders.js"; import { sha256Hex } from "../../kernel/sha256Hex.js"; const fail = (message: string): never => { @@ -23,7 +23,7 @@ const fail = (message: string): never => { /** Shared PE header admission, with malformed headers as format failures. */ const readCertificateImageHeaders = (bytes: Buffer) => { try { - return readPeHeaders(bytes); + return readPeImageHeaders(bytes); } catch (cause) { throw artifactParseFailure(cause, undefined); } diff --git a/tests/conformance/formats/mzPeAdmission.test.ts b/tests/conformance/formats/mzPeAdmission.test.ts index ed8a41f997..e2715eccb0 100644 --- a/tests/conformance/formats/mzPeAdmission.test.ts +++ b/tests/conformance/formats/mzPeAdmission.test.ts @@ -13,7 +13,10 @@ import { inspectDesktopFile } from "../../../src/artifacts/DesktopFileInspection import type { DesktopFile } from "../../../src/domain/desktopApplication.js"; import { readManagedPeLayout } from "../../../src/domain/managed/managedPeReader.js"; import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js"; -import { readPeHeaders } from "../../../src/domain/pe/peResourceLayout.js"; +import { + readPeImageHeaders, + readPeImageHeadersAt, +} from "../../../src/domain/pe/peImageHeaders.js"; import { peResourceFixture } from "../../../src/domain/pe/peResources.fixture.js"; import { ElectronFuseService } from "../../../src/application/electron/ElectronFuseService.js"; import { ElectronFuseProvider } from "../../../src/electron/ElectronFuseProvider.js"; @@ -45,7 +48,7 @@ it("keeps relocation-owned DOS bytes out of managed PE layout", () => { it("keeps relocation-owned DOS bytes out of PE resource/certificate header admission", () => { const bytes = relocationOwnedPointer(peResourceFixture().bytes); - expect(() => readPeHeaders(bytes)).toThrow(/PE/u); + expect(() => readPeImageHeaders(bytes)).toThrow(/PE/u); }); it("keeps relocation-owned DOS bytes out of NativeAOT metadata recovery", () => { @@ -139,7 +142,7 @@ it("preserves recognized PE records after short DOS headers in complete-byte rea readManagedPeLayout(shortDosHeader(buildManagedPeFixture())), ).not.toThrow(); expect(() => - readPeHeaders(shortDosHeader(peResourceFixture().bytes)), + readPeImageHeaders(shortDosHeader(peResourceFixture().bytes)), ).not.toThrow(); const bytes = shortDosHeader(nativeAotPeFixture()); expect( @@ -206,17 +209,50 @@ it("preserves desktop PE observations after a short DOS header", async () => { ); }); -it("keeps a PE signature outside an inspected prefix unresolved until its required range is read", () => { +it("keeps a PE signature outside an inspected prefix unresolved until its required range is read", async () => { const bytes = peResourceFixture().bytes; const prefix = bytes.subarray(0, 64); expect(observeMzWindowsHeader(prefix, bytes.length)).toMatchObject({ state: "signature-needed", offset: 128, }); - expect(() => readPeHeaders(bytes)).not.toThrow(); - expect(() => readPeHeaders(prefix, bytes.length)).toThrow( - "PE range 128 + 24 leaves the artifact.", + await expect( + readPeImageHeadersAt(prefix, bytes.length, async (offset, length) => + offset + length <= prefix.length + ? prefix.subarray(offset, offset + length) + : undefined, + ), + ).rejects.toThrow("Truncated PE header range at 128."); + const reads: { offset: number; length: number }[] = []; + await expect( + readPeImageHeadersAt(prefix, bytes.length, async (offset, length) => { + reads.push({ offset, length }); + return bytes.subarray(offset, offset + length); + }), + ).resolves.toEqual(readPeImageHeaders(bytes)); + // The borrowed source supplies the signature and fixed COFF record once. + expect(reads.filter(({ offset }) => offset >= 128 && offset < 152)).toEqual([ + { offset: 128, length: 24 }, + ]); +}); + +it("recognizes a bounded non-PE Windows signature without requiring a COFF record", async () => { + const bytes = peResourceFixture().bytes.subarray(0, 130); + bytes.write("NE", 128, "ascii"); + const reads: { offset: number; length: number }[] = []; + await expect( + readPeImageHeadersAt( + bytes.subarray(0, 64), + bytes.length, + async (offset, length) => { + reads.push({ offset, length }); + return bytes.subarray(offset, offset + length); + }, + ), + ).rejects.toThrow( + "NE images do not contain PE resource or certificate tables", ); + expect(reads).toEqual([{ offset: 128, length: 2 }]); }); it("does not inventory PE GPU sections from relocation-owned DOS bytes", async () => {