Skip to content

Commit 0b04d38

Browse files
fix(native): refuse truncated executable headers at target admission
Target admission accepted a thin Mach-O after reading only its magic and CPU type, so a 12-byte prefix opened as a valid arm64 executable and the first provider query failed as a generic execution failure. ELF headers were likewise accepted after 20 bytes, and a FAT file whose selected slice lies beyond its end was admitted. Require the complete fixed header (Mach-O 28 or 32 bytes, ELF 52 or 64), Mach-O load commands that fit in the file, and a selected FAT slice within the file, checking commitments against the file size rather than the probed prefix. Each refusal names the failed constraint. Fixes #1189 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e1afbc1 commit 0b04d38

6 files changed

Lines changed: 137 additions & 20 deletions

File tree

‎src/application/BinaryTargetResolver.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,9 @@ const readExecutableMetadata = async (
237237
const prefix = Buffer.alloc(4096);
238238
const prefixRead = await handle.read(prefix, 0, prefix.length, 0);
239239
const bytes = prefix.subarray(0, prefixRead.bytesRead);
240+
// Header commitments such as Mach-O load commands and FAT slices are
241+
// checked against the whole file, not the probed prefix.
242+
const fileSize = (await handle.stat()).size;
240243
if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a) {
241244
const offset = mzWindowsHeaderOffset(bytes);
242245
if (offset !== null) {
@@ -251,7 +254,6 @@ const readExecutableMetadata = async (
251254
? bytes.readUInt16LE(24) + bytes.readUInt16LE(6) * 4
252255
: 0;
253256
const headerBytes = bytes.length >= 28 ? bytes.readUInt16LE(8) * 16 : 0;
254-
const fileSize = (await handle.stat()).size;
255257
if (
256258
tableEnd > bytes.length &&
257259
tableEnd <= headerBytes &&
@@ -279,11 +281,12 @@ const readExecutableMetadata = async (
279281
return parseExecutableHeader(
280282
header.subarray(0, headerRead.bytesRead),
281283
hostArchitecture,
284+
fileSize,
282285
);
283286
}
284287
}
285288
}
286-
return parseExecutableHeader(bytes, hostArchitecture);
289+
return parseExecutableHeader(bytes, hostArchitecture, fileSize);
287290
};
288291

289292
const readPeMetadata = async (

‎src/domain/binaryTarget.fixture.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ export const elf = (
44
endian: number,
55
machine: number,
66
): Buffer => {
7-
const bytes = Buffer.alloc(20);
7+
const bytes = Buffer.alloc(class_ === 1 ? 52 : 64);
88
bytes.set([0x7f, 0x45, 0x4c, 0x46, class_, endian]);
99
if (endian === 1) bytes.writeUInt16LE(machine, 18);
1010
else bytes.writeUInt16BE(machine, 18);
@@ -13,7 +13,9 @@ export const elf = (
1313

1414
/** Build a minimal thin Mach-O header for binary-target parser tests. */
1515
export const thinMach = (magic: number, cpu: number): Buffer => {
16-
const bytes = Buffer.alloc(8);
16+
const bytes = Buffer.alloc(
17+
magic === 0xfeedfacf || magic === 0xcffaedfe ? 32 : 28,
18+
);
1719
bytes.writeUInt32BE(magic, 0);
1820
if (magic === 0xcefaedfe || magic === 0xcffaedfe) bytes.writeUInt32LE(cpu, 4);
1921
else bytes.writeUInt32BE(cpu, 4);

‎src/domain/binaryTarget.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,52 @@ describe("executable header parsing", () => {
9090
expect(parseExecutableHeader(truncatedDirectories, "x64").ok).toBe(false);
9191
});
9292
});
93+
94+
describe("executable header completeness", () => {
95+
const reason = (bytes: Buffer, fileSize = bytes.length) => {
96+
const result = parseExecutableHeader(bytes, "arm64", fileSize);
97+
return result.ok ? null : result.error;
98+
};
99+
100+
it.each([
101+
[
102+
thinMach(0xcffaedfe, 0x0100000c).subarray(0, 12),
103+
"a 64-bit header needs 32 bytes",
104+
],
105+
[
106+
thinMach(0xcefaedfe, 0x01000007).subarray(0, 27),
107+
"a 32-bit header needs 28 bytes",
108+
],
109+
[elf(1, 1, 62).subarray(0, 51), "an ELF32 header needs 52 bytes"],
110+
[elf(2, 1, 183).subarray(0, 63), "an ELF64 header needs 64 bytes"],
111+
])(
112+
"rejects a header shorter than its fixed size (%#)",
113+
(bytes, constraint) => {
114+
expect(reason(bytes)).toContain(constraint);
115+
},
116+
);
117+
118+
it("rejects Mach-O load commands that extend past the file", () => {
119+
const header = thinMach(0xcffaedfe, 0x0100000c);
120+
header.writeUInt32LE(100, 20);
121+
122+
expect(reason(header)).toBe(
123+
"truncated Mach-O load commands: the header declares 100 bytes after its 32-byte header; the file has 32",
124+
);
125+
// The resolver probes a prefix; commitments are checked against the file.
126+
expect(reason(header, 132)).toBeNull();
127+
});
128+
129+
it("rejects a FAT file whose host slice extends past the file", () => {
130+
const bytes = fat([0x01000007, 0x0100000c]);
131+
bytes.writeUInt32BE(4096, 8 + 20 + 8);
132+
bytes.writeUInt32BE(64, 8 + 20 + 12);
133+
134+
expect(reason(bytes, 4100)).toBe(
135+
"truncated FAT slice: the arm64 slice ends at byte 4160; the file has 4100",
136+
);
137+
expect(reason(bytes, 4160)).toBeNull();
138+
// Only the slice REA would analyze must be present.
139+
expect(parseExecutableHeader(bytes, "x64", 4100).ok).toBe(true);
140+
});
141+
});

‎src/domain/binaryTarget.ts‎

Lines changed: 51 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -35,28 +35,39 @@ export const parseExecutableHeader = (
3535
bytes.length >= 4 &&
3636
bytes.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))
3737
)
38-
return parseElf(bytes);
38+
return parseElf(bytes, fileSize);
3939
if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a)
4040
return parseMz(bytes, fileSize);
4141
if (bytes.length < 8) return err("truncated or unsupported binary header");
4242
const magic = bytes.readUInt32BE(0);
4343
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
44-
return parseThinMachO(bytes, magic);
44+
return parseThinMachO(bytes, magic, fileSize);
4545
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
46-
return parseFatMachO(bytes, magic, hostArchitecture);
46+
return parseFatMachO(bytes, magic, hostArchitecture, fileSize);
4747
return err("unsupported binary format");
4848
};
4949

5050
const parseThinMachO = (
5151
bytes: Buffer,
5252
magic: number,
53+
fileSize: number,
5354
): Result<ExecutableMetadata, string> => {
54-
if (bytes.length < 8) return err("truncated Mach-O header");
55+
const is64 = magic === 0xfeedfacf || magic === 0xcffaedfe;
56+
const headerSize = is64 ? 32 : 28;
57+
if (bytes.length < headerSize)
58+
return err(
59+
`truncated Mach-O header: a ${is64 ? 64 : 32}-bit header needs ${headerSize} bytes; the file has ${fileSize}`,
60+
);
5561
const little = magic === 0xcefaedfe || magic === 0xcffaedfe;
56-
const architecture = machArchitecture(
57-
little ? bytes.readUInt32LE(4) : bytes.readUInt32BE(4),
58-
);
62+
const read = (offset: number): number =>
63+
little ? bytes.readUInt32LE(offset) : bytes.readUInt32BE(offset);
64+
const architecture = machArchitecture(read(4));
5965
if (architecture === undefined) return err("unsupported Mach-O architecture");
66+
const commandBytes = read(20);
67+
if (headerSize + commandBytes > fileSize)
68+
return err(
69+
`truncated Mach-O load commands: the header declares ${commandBytes} bytes after its ${headerSize}-byte header; the file has ${fileSize}`,
70+
);
6071
return ok({
6172
format: "mach-o",
6273
architecture,
@@ -68,6 +79,7 @@ const parseFatMachO = (
6879
bytes: Buffer,
6980
magic: number,
7081
host: NodeJS.Architecture,
82+
fileSize: number,
7183
): Result<ExecutableMetadata, string> => {
7284
const little = magic === 0xbebafeca || magic === 0xbfbafeca;
7385
const is64 = magic === 0xcafebabf || magic === 0xbfbafeca;
@@ -79,10 +91,24 @@ const parseFatMachO = (
7991
if (count === 0 || count > 128 || bytes.length < 8 + count * entrySize)
8092
return err("truncated or invalid FAT architecture table");
8193
const architectures: BinaryArchitecture[] = [];
94+
const sliceEnds = new Map<BinaryArchitecture, bigint>();
8295
for (let index = 0; index < count; index += 1) {
83-
const architecture = machArchitecture(read(8 + index * entrySize));
84-
if (architecture !== undefined && !architectures.includes(architecture))
85-
architectures.push(architecture);
96+
const entry = 8 + index * entrySize;
97+
const architecture = machArchitecture(read(entry));
98+
if (architecture === undefined || architectures.includes(architecture))
99+
continue;
100+
architectures.push(architecture);
101+
const offset = is64
102+
? little
103+
? bytes.readBigUInt64LE(entry + 8)
104+
: bytes.readBigUInt64BE(entry + 8)
105+
: BigInt(read(entry + 8));
106+
const size = is64
107+
? little
108+
? bytes.readBigUInt64LE(entry + 16)
109+
: bytes.readBigUInt64BE(entry + 16)
110+
: BigInt(read(entry + 12));
111+
sliceEnds.set(architecture, offset + size);
86112
}
87113
const preferred =
88114
host === "arm64"
@@ -96,18 +122,31 @@ const parseFatMachO = (
96122
: undefined;
97123
if (preferred === undefined || !architectures.includes(preferred))
98124
return err(`FAT binary has no host-compatible ${host} architecture`);
125+
const sliceEnd = sliceEnds.get(preferred) ?? 0n;
126+
if (sliceEnd > BigInt(fileSize))
127+
return err(
128+
`truncated FAT slice: the ${preferred} slice ends at byte ${sliceEnd}; the file has ${fileSize}`,
129+
);
99130
return ok({
100131
format: "mach-o",
101132
architecture: preferred,
102133
availableArchitectures: architectures,
103134
});
104135
};
105136

106-
const parseElf = (bytes: Buffer): Result<ExecutableMetadata, string> => {
107-
if (bytes.length < 20) return err("truncated ELF header");
137+
const parseElf = (
138+
bytes: Buffer,
139+
fileSize: number,
140+
): Result<ExecutableMetadata, string> => {
141+
if (bytes.length < 6) return err("truncated ELF header");
108142
if (bytes[4] !== 1 && bytes[4] !== 2) return err("unsupported ELF class");
109143
const little = bytes[5] === 1;
110144
if (!little && bytes[5] !== 2) return err("unsupported ELF endianness");
145+
const headerSize = bytes[4] === 1 ? 52 : 64;
146+
if (bytes.length < headerSize)
147+
return err(
148+
`truncated ELF header: an ELF${bytes[4] === 1 ? 32 : 64} header needs ${headerSize} bytes; the file has ${fileSize}`,
149+
);
111150
const machine = little ? bytes.readUInt16LE(18) : bytes.readUInt16BE(18);
112151
const architecture = elfArchitecture(machine);
113152
if (architecture === undefined) return err("unsupported ELF architecture");

‎tests/boundary/filesystem/binaryTarget.test.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,32 @@ describe("binary target I/O: explicit kinds and executable headers", () => {
325325
architecture: "x86_64",
326326
});
327327
});
328+
329+
it("refuses a truncated Mach-O header before any provider sees it", async () => {
330+
const directory = await createTestTempDirectory("rea-target-");
331+
const path = join(directory, "truncated");
332+
await writeFile(path, thinMach(0xcffaedfe, 0x0100000c).subarray(0, 12));
333+
const result = await parseBinaryTarget(path, directory, "arm64");
334+
expect(result.ok).toBe(false);
335+
expect(result.ok ? undefined : result.error).toMatchObject({
336+
path,
337+
reason:
338+
"truncated Mach-O header: a 64-bit header needs 32 bytes; the file has 12",
339+
});
340+
});
341+
342+
it("checks Mach-O load commands against the whole file beyond the probe", async () => {
343+
const directory = await createTestTempDirectory("rea-target-");
344+
const path = join(directory, "large-commands");
345+
const header = thinMach(0xcffaedfe, 0x0100000c);
346+
header.writeUInt32LE(8192, 20);
347+
await writeFile(path, Buffer.concat([header, Buffer.alloc(8192)]));
348+
const result = await parseBinaryTarget(path, directory, "arm64");
349+
expect(result.ok && result.value).toMatchObject({
350+
format: "mach-o",
351+
architecture: "arm64",
352+
});
353+
});
328354
});
329355

330356
describe("app executable filename fidelity", () => {

‎tests/boundary/providers/native/artifactProvider.directoryErrors.test.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { describe, expect, it } from "vitest";
66
import { parseBinaryTarget } from "../../../../src/application/BinaryTargetResolver.js";
77
import { ArtifactProvider } from "../../../../src/artifacts/ArtifactProvider.js";
88
import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js";
9+
import { thinMach } from "../../../../src/domain/binaryTarget.fixture.js";
910
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
1011

1112
describe("artifact directory diagnostics", () => {
@@ -22,10 +23,7 @@ describe("artifact directory diagnostics", () => {
2223
join(contentsPath, "Info.plist"),
2324
"<plist><dict><key>CFBundleExecutable</key><string>Fixture</string></dict></plist>",
2425
);
25-
const machHeader = Buffer.alloc(8);
26-
machHeader.writeUInt32BE(0xfeedfacf, 0);
27-
machHeader.writeUInt32BE(0x0100000c, 4);
28-
await writeFile(executablePath, machHeader);
26+
await writeFile(executablePath, thinMach(0xfeedfacf, 0x0100000c));
2927
await writeFile(blockedPath, "member contents");
3028
await chmod(blockedPath, 0);
3129
try {

0 commit comments

Comments
 (0)