diff --git a/src/application/MipsElfMetadata.ts b/src/application/MipsElfMetadata.ts index 8f2d97115..8fd9d0e89 100644 --- a/src/application/MipsElfMetadata.ts +++ b/src/application/MipsElfMetadata.ts @@ -3,6 +3,7 @@ import type { MipsAbiFlags, MipsElfMetadata, } from "../domain/binaryTargetTypes.js"; +import { readElfFixedHeader } from "../domain/elfFixedHeader.js"; import { err, ok, type Result } from "../domain/result.js"; import { readMipsElfSharedLoad, @@ -64,21 +65,22 @@ export const readMipsElfMetadata = async ( const header = await read(0, 52, "ELF32 header"); if (!header.ok) return header; const bytes = header.value; + const fixedHeader = readElfFixedHeader(bytes, fileSize); + if (!fixedHeader.ok) return fixedHeader; const little = metadata.byteOrder === "little"; const u16 = (data: Buffer, offset: number): number => little ? data.readUInt16LE(offset) : data.readUInt16BE(offset); const u32 = (data: Buffer, offset: number): number => little ? data.readUInt32LE(offset) : data.readUInt32BE(offset); if ( - bytes.toString("hex", 0, 4) !== "7f454c46" || - bytes[4] !== 1 || - bytes[5] !== (little ? 1 : 2) || + fixedHeader.value.elfClass !== 32 || + fixedHeader.value.byteOrder !== metadata.byteOrder || u16(bytes, 18) !== 8 || u16(bytes, 16) !== metadata.type || u32(bytes, 36) !== metadata.flags ) return err("MIPS ELF header no longer matches the resolved identity"); - if (bytes[6] !== 1 || u32(bytes, 20) !== 1 || u16(bytes, 40) !== 52) + if (fixedHeader.value.headerSize !== 52) return err("invalid MIPS ELF32 version or header size"); const tables = [ diff --git a/src/domain/binaryTarget.fixture.ts b/src/domain/binaryTarget.fixture.ts index 3e2c46147..7d8a0a7f9 100644 --- a/src/domain/binaryTarget.fixture.ts +++ b/src/domain/binaryTarget.fixture.ts @@ -5,9 +5,16 @@ export const elf = ( machine: number, ): Buffer => { const bytes = Buffer.alloc(class_ === 1 ? 52 : 64); - bytes.set([0x7f, 0x45, 0x4c, 0x46, class_, endian]); - if (endian === 1) bytes.writeUInt16LE(machine, 18); - else bytes.writeUInt16BE(machine, 18); + bytes.set([0x7f, 0x45, 0x4c, 0x46, class_, endian, 1]); + if (endian === 1) { + bytes.writeUInt16LE(machine, 18); + bytes.writeUInt32LE(1, 20); + bytes.writeUInt16LE(class_ === 1 ? 52 : 64, class_ === 1 ? 40 : 52); + } else { + bytes.writeUInt16BE(machine, 18); + bytes.writeUInt32BE(1, 20); + bytes.writeUInt16BE(class_ === 1 ? 52 : 64, class_ === 1 ? 40 : 52); + } return bytes; }; diff --git a/src/domain/binaryTarget.mips.test.ts b/src/domain/binaryTarget.mips.test.ts index e646daee1..ded2f18bf 100644 --- a/src/domain/binaryTarget.mips.test.ts +++ b/src/domain/binaryTarget.mips.test.ts @@ -7,10 +7,14 @@ const header = (little: boolean, bits: 32 | 64 = 32): Buffer => { if (little) { bytes.writeUInt16LE(2, 16); bytes.writeUInt16LE(8, 18); + bytes.writeUInt32LE(1, 20); + bytes.writeUInt16LE(bits === 32 ? 52 : 64, bits === 32 ? 40 : 52); bytes.writeUInt32LE(0x70001001, bits === 32 ? 36 : 48); } else { bytes.writeUInt16BE(2, 16); bytes.writeUInt16BE(8, 18); + bytes.writeUInt32BE(1, 20); + bytes.writeUInt16BE(bits === 32 ? 52 : 64, bits === 32 ? 40 : 52); bytes.writeUInt32BE(0x70001001, bits === 32 ? 36 : 48); } return bytes; diff --git a/src/domain/binaryTarget.riscv.test.ts b/src/domain/binaryTarget.riscv.test.ts index fcc77cf89..8af185e12 100644 --- a/src/domain/binaryTarget.riscv.test.ts +++ b/src/domain/binaryTarget.riscv.test.ts @@ -13,10 +13,14 @@ const header = ( if (little) { bytes.writeUInt16LE(type, 16); bytes.writeUInt16LE(machine, 18); + bytes.writeUInt32LE(1, 20); + bytes.writeUInt16LE(bits === 32 ? 52 : 64, bits === 32 ? 40 : 52); bytes.writeUInt32LE(flags, bits === 32 ? 36 : 48); } else { bytes.writeUInt16BE(type, 16); bytes.writeUInt16BE(machine, 18); + bytes.writeUInt32BE(1, 20); + bytes.writeUInt16BE(bits === 32 ? 52 : 64, bits === 32 ? 40 : 52); bytes.writeUInt32BE(flags, bits === 32 ? 36 : 48); } return bytes; diff --git a/src/domain/binaryTarget.test.ts b/src/domain/binaryTarget.test.ts index 7d4cf322c..6164e8c22 100644 --- a/src/domain/binaryTarget.test.ts +++ b/src/domain/binaryTarget.test.ts @@ -26,6 +26,13 @@ describe("executable header parsing", () => { expect(result.ok && result.value).toMatchObject({ format, architecture }); }); + it("retains ELF32 x86-64 identity for the x32 ABI", () => { + expect(parseExecutableHeader(elf(1, 1, 62), "x64")).toMatchObject({ + ok: true, + value: { format: "elf", architecture: "x86_64" }, + }); + }); + it("distinguishes native PE applications, DLLs, and managed assemblies", () => { const application = parseExecutableHeader(pe(0x8664), "x64"); const library = parseExecutableHeader(pe(0x8664, 64, 0x2002), "x64"); diff --git a/src/domain/binaryTarget.ts b/src/domain/binaryTarget.ts index eca1174d2..48da65960 100644 --- a/src/domain/binaryTarget.ts +++ b/src/domain/binaryTarget.ts @@ -7,6 +7,7 @@ import type { UniversalMachOSlice, } from "./binaryTargetTypes.js"; import { err, ok, type Result } from "./result.js"; +import { readElfFixedHeader } from "./elfFixedHeader.js"; import { observeMzWindowsHeader, parseDosMzHeader } from "./dosMz.js"; import { decodePeMachine } from "./peMachine.js"; import { @@ -191,20 +192,14 @@ const parseElf = ( bytes: Buffer, fileSize: number, ): Result => { - if (bytes.length < 6) return err("truncated ELF header"); - if (bytes[4] !== 1 && bytes[4] !== 2) return err("unsupported ELF class"); - const little = bytes[5] === 1; - if (!little && bytes[5] !== 2) return err("unsupported ELF endianness"); - const headerSize = bytes[4] === 1 ? 52 : 64; - if (bytes.length < headerSize) - return err( - `truncated ELF header: an ELF${bytes[4] === 1 ? 32 : 64} header needs ${headerSize} bytes; the file has ${fileSize}`, - ); + const fixedHeader = readElfFixedHeader(bytes, fileSize); + if (!fixedHeader.ok) return fixedHeader; + const { elfClass, byteOrder } = fixedHeader.value; + const little = byteOrder === "little"; const machine = little ? bytes.readUInt16LE(18) : bytes.readUInt16BE(18); const architecture = elfArchitecture(machine); if (architecture === undefined) return err("unsupported ELF architecture"); if (architecture === "mips" || architecture === "riscv") { - const elfClass = bytes[4] === 1 ? 32 : 64; const flagsOffset = elfClass === 32 ? 36 : 48; const metadata: ElfFamilyMetadata = { elfClass, diff --git a/src/domain/elfFixedHeader.test.ts b/src/domain/elfFixedHeader.test.ts new file mode 100644 index 000000000..b902635ac --- /dev/null +++ b/src/domain/elfFixedHeader.test.ts @@ -0,0 +1,61 @@ +import { expect, it } from "vitest"; +import { readElfFixedHeader } from "./elfFixedHeader.js"; +import { elf } from "./binaryTarget.fixture.js"; + +it.each([ + ["ELF32 little endian", 1, 1], + ["ELF32 big endian", 1, 2], + ["ELF64 little endian", 2, 1], + ["ELF64 big endian", 2, 2], +] as const)( + "reads common fixed header commitments for %s", + (_name, cls, data) => { + const bytes = elf(cls, data, cls === 1 ? 3 : 62); + expect(readElfFixedHeader(bytes)).toEqual({ + ok: true, + value: { + elfClass: cls === 1 ? 32 : 64, + byteOrder: data === 1 ? "little" : "big", + headerSize: cls === 1 ? 52 : 64, + }, + }); + }, +); + +it.each([ + [ + "identification version", + (bytes: Buffer) => { + bytes[6] = 0; + }, + ], + [ + "header version", + (bytes: Buffer) => { + bytes.writeUInt32LE(0, 20); + }, + ], + [ + "undersized declared header", + (bytes: Buffer) => { + bytes.writeUInt16LE(51, 40); + }, + ], + [ + "declared header beyond file", + (bytes: Buffer) => { + bytes.writeUInt16LE(53, 40); + }, + ], +])("rejects an invalid %s", (_name, corrupt) => { + const bytes = elf(1, 1, 3); + corrupt(bytes); + expect(readElfFixedHeader(bytes)).toMatchObject({ ok: false }); +}); + +it("checks declared header size against the whole file, not the prefix", () => { + const bytes = elf(2, 1, 62); + bytes.writeUInt16LE(128, 52); + expect(readElfFixedHeader(bytes, 128)).toMatchObject({ ok: true }); + expect(readElfFixedHeader(bytes, 127)).toMatchObject({ ok: false }); +}); diff --git a/src/domain/elfFixedHeader.ts b/src/domain/elfFixedHeader.ts new file mode 100644 index 000000000..3b98976c8 --- /dev/null +++ b/src/domain/elfFixedHeader.ts @@ -0,0 +1,55 @@ +import { err, ok, type Result } from "./result.js"; + +export interface ElfFixedHeader { + readonly elfClass: 32 | 64; + readonly byteOrder: "little" | "big"; + readonly headerSize: number; +} + +/** + * Validate the common, fixed ELF header commitments. + * + * `bytes` may be a bounded prefix. `totalBytes` is the containing file size, + * so the declared header extent is checked against the file without requiring + * the whole declared extent to be present in this prefix. + */ +export const readElfFixedHeader = ( + bytes: Buffer, + totalBytes = bytes.length, +): Result => { + if (bytes.length >= 4 && bytes.toString("hex", 0, 4) !== "7f454c46") + return err("not an ELF image"); + if (bytes.length < 16) return err("ELF identification is truncated"); + const classByte = bytes[4]; + if (classByte !== 1 && classByte !== 2) return err("unsupported ELF class"); + const dataByte = bytes[5]; + if (dataByte !== 1 && dataByte !== 2) + return err("unsupported ELF endianness"); + if (bytes[6] !== 1) return err("unsupported ELF identification version"); + + const elfClass = classByte === 1 ? 32 : 64; + const minimumSize = elfClass === 32 ? 52 : 64; + if ( + !Number.isSafeInteger(totalBytes) || + totalBytes < bytes.length || + totalBytes < minimumSize || + bytes.length < minimumSize + ) + return err( + `truncated ELF header: an ELF${elfClass} header needs ${minimumSize} bytes; the file has ${totalBytes}`, + ); + const littleEndian = dataByte === 1; + const readU16 = (offset: number): number => + littleEndian ? bytes.readUInt16LE(offset) : bytes.readUInt16BE(offset); + const readU32 = (offset: number): number => + littleEndian ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset); + if (readU32(20) !== 1) return err("unsupported ELF header version"); + const headerSize = readU16(elfClass === 32 ? 40 : 52); + if (headerSize < minimumSize || headerSize > totalBytes) + return err("invalid ELF header size"); + return ok({ + elfClass, + byteOrder: littleEndian ? "little" : "big", + headerSize, + }); +}; diff --git a/src/flutter/DartElf.ts b/src/flutter/DartElf.ts index 48285737d..a9bf00fa5 100644 --- a/src/flutter/DartElf.ts +++ b/src/flutter/DartElf.ts @@ -5,6 +5,7 @@ import { SNAPSHOT_HASH_OFFSET, SNAPSHOT_HASH_PATTERN, } from "./FlutterPayloadScan.js"; +import { readElfFixedHeader } from "../domain/elfFixedHeader.js"; /** Bounds-checked little-endian reader over one loaded buffer. */ class BoundedReader { @@ -80,24 +81,13 @@ export const readElfHeader = ( totalBytes: number = bytes.length, ) => { const reader = new BoundedReader(bytes); - const magic = reader.u32(0); - if (magic !== 0x464c457f) return { failure: { reason: "not an ELF image" } }; - const elfClass = reader.u8(4); - if (elfClass !== 1 && elfClass !== 2) - return { failure: { reason: `unsupported ELF class ${String(elfClass)}` } }; - const is64 = elfClass === 2; + const fixedHeader = readElfFixedHeader(bytes, totalBytes); + if (!fixedHeader.ok) return { failure: { reason: fixedHeader.error } }; + const is64 = fixedHeader.value.elfClass === 64; const headerBytes = is64 ? ELF_HEADER_MAX_BYTES : 52; - if ( - bytes.length < headerBytes || - !Number.isSafeInteger(totalBytes) || - totalBytes < headerBytes - ) - return { failure: { reason: "ELF header is truncated" } }; - if (reader.u8(5) !== 1) + if (fixedHeader.value.byteOrder !== "little") return { failure: { reason: "unsupported ELF byte order" } }; - if (reader.u8(6) !== 1 || reader.u32(0x14) !== 1) - return { failure: { reason: "unsupported ELF version" } }; - if (reader.u16(is64 ? 0x34 : 0x28) !== headerBytes) + if (fixedHeader.value.headerSize !== headerBytes) return { failure: { reason: "unsupported ELF header size" } }; const e_type = reader.u16(0x10); if (e_type !== 1 && e_type !== 2 && e_type !== ET_DYN) diff --git a/src/go/GoElfImage.ts b/src/go/GoElfImage.ts index f02473aae..fae00c40c 100644 --- a/src/go/GoElfImage.ts +++ b/src/go/GoElfImage.ts @@ -6,31 +6,19 @@ import { type GoFileMapping, type GoZeroFillMapping, } from "./GoBinaryContainer.js"; +import { readElfFixedHeader } from "../domain/elfFixedHeader.js"; /** Read ELF build-info sections and file-backed program mappings. */ export const readGoElfImage = (bytes: Buffer): GoBinaryContainer => { - if (bytes.length < 16) - throw new GoBinaryFormatFailure( - "malformed", - "ELF identification is truncated", - ); - const bits = bytes[4] === 1 ? 32 : bytes[4] === 2 ? 64 : null; - if (bits === null || ![1, 2].includes(bytes[5] ?? 0) || bytes[6] !== 1) - throw new GoBinaryFormatFailure( - "malformed", - "ELF class, byte order, or version is invalid", - ); - const reader = new GoBinaryReader(bytes, bytes[5] === 1); + const fixedHeader = readElfFixedHeader(bytes); + if (!fixedHeader.ok) + throw new GoBinaryFormatFailure("malformed", fixedHeader.error); + const { elfClass: bits, headerSize } = fixedHeader.value; + const reader = new GoBinaryReader( + bytes, + fixedHeader.value.byteOrder === "little", + ); const wide = bits === 64; - const minimum = wide ? 64 : 52; - reader.range(0, minimum, "ELF header"); - if (reader.u32(20) !== 1 || reader.u16(wide ? 52 : 40) < minimum) - throw new GoBinaryFormatFailure( - "malformed", - "ELF header version or size is invalid", - ); - const headerSize = reader.u16(wide ? 52 : 40); - reader.range(0, headerSize, "ELF declared header"); const phOffset = reader.word(wide ? 32 : 28, bits); const shOffset = reader.word(wide ? 40 : 32, bits); const phWidth = reader.u16(wide ? 54 : 42); diff --git a/tests/boundary/filesystem/binaryTarget.test.ts b/tests/boundary/filesystem/binaryTarget.test.ts index d3f363efa..e56055069 100644 --- a/tests/boundary/filesystem/binaryTarget.test.ts +++ b/tests/boundary/filesystem/binaryTarget.test.ts @@ -20,6 +20,7 @@ import { } from "../../../src/application/AppBundleExecutable.js"; import { dosMz, + elf, fat, pe, thinMach, @@ -846,3 +847,40 @@ describe("DOS binary target I/O", () => { }); }); }); + +it.each([ + [ + "EI_VERSION", + (bytes: Buffer) => { + bytes[6] = 0; + }, + ], + [ + "e_version", + (bytes: Buffer) => { + bytes.writeUInt32LE(0, 20); + }, + ], + [ + "e_ehsize", + (bytes: Buffer) => { + bytes.writeUInt16LE(51, 40); + }, + ], +])( + "rejects an ELF with malformed %s during public target opening", + async (_name, corrupt) => { + const directory = await createTestTempDirectory("rea-invalid-elf-header-"); + const path = join(directory, "invalid.elf"); + const bytes = elf(1, 1, 3); + corrupt(bytes); + await writeFile(path, bytes); + expect(await parseBinaryTarget(path)).toMatchObject({ + ok: false, + error: { + _tag: "BinaryTargetError", + constraint: "file_format_rejected", + }, + }); + }, +); diff --git a/tests/boundary/go/goBinaryImage.test.ts b/tests/boundary/go/goBinaryImage.test.ts index 0dc486a96..24321ecc8 100644 --- a/tests/boundary/go/goBinaryImage.test.ts +++ b/tests/boundary/go/goBinaryImage.test.ts @@ -227,11 +227,6 @@ it("rejects ELF header tables overlapping the native header", () => { expect(() => readGoBinaryImage(fixture.bytes)).toThrowError( /header|overlap/i, ); - const declaredSize = createGoBinaryFixture(); - declaredSize.bytes.writeUInt16LE(8192, 52); - expect(() => readGoBinaryImage(declaredSize.bytes)).toThrowError( - /truncated|range/i, - ); }); it("rejects contradictory aliases when a metadata address maps to different file bytes", () => {