fix(macho): validate symbol extents before the hardening scan limit (#12465)

fix(macho): validate hardening symbol extents before capacity
This commit is contained in:
morluto authored and GitHub committed 2026-11-19 18:23:37 +00:00
1 parent a627952bd5
commit 5a62623cd1
6 files changed
+82 -59

No files matched your search

@@ -46,7 +46,6 @@
"src/native/elf/KernelBuildConfig.ts": 7,
"src/native/elf/KernelModuleParser.ts": 5,
"src/native/hardening/ElfHardening.ts": 2,
"src/native/hardening/MachoHardening.ts": 4,
"src/native/initializers/ElfInitializerSymbols.ts": 4,
"src/native/initializers/MachoInitializers.ts": 22,
"src/native/initializers/NativeInitializersProvider.ts": 1,
+26 -6
View File
@@ -275,16 +275,18 @@ export const decodeMachoFixedWordFields = (
);
};
/** `symtab_command` fields from an admitted command body. Null when truncated. */
export const readMachoSymtabCommand = (
body: Uint8Array,
littleEndian: boolean,
): {
interface MachoSymtabDeclaration {
readonly symoff: number;
readonly nsyms: number;
readonly stroff: number;
readonly strsize: number;
} | null => {
}
/** `symtab_command` fields from an admitted command body. Null when truncated. */
export const readMachoSymtabCommand = (
body: Uint8Array,
littleEndian: boolean,
): MachoSymtabDeclaration | null => {
const fields = decodeMachoFixedWordFields(
LC.SYMTAB,
body.subarray(8),
@@ -302,6 +304,24 @@ export const readMachoSymtabCommand = (
return { symoff, nsyms, stroff, strsize };
};
/** Admit slice-relative LC_SYMTAB ranges before applying a consumer's scan allowance. */
export const admitMachoSymtabRanges = (
{ symoff, nsyms, stroff, strsize }: MachoSymtabDeclaration,
wide: boolean,
sliceSize: number,
): {
readonly width: 12 | 16;
readonly symbolsEnd: number;
readonly stringsEnd: number;
} | null => {
const width = wide ? 16 : 12;
const symbolsEnd = symoff + nsyms * width;
const stringsEnd = stroff + strsize;
return symbolsEnd <= sliceSize && stringsEnd <= sliceSize
? { width, symbolsEnd, stringsEnd }
: null;
};
/**
* `linkedit_data_command` fields from an admitted command body. Null when
* truncated or when `command` does not use the linkedit_data_command layout.
@@ -1082,9 +1082,7 @@ const machoSymbolPayload = (
: options.stackChk === false
? 1
: 0)) + (options.trailingBrokenStrx === true ? 1 : 0);
const storedSymbols =
options.nsyms !== undefined && options.nsyms > 4096 ? 0 : declaredSymbols;
const symbolBytes = Buffer.alloc(Math.max(storedSymbols, 0) * nlistWidth);
const symbolBytes = Buffer.alloc(declaredSymbols * nlistWidth);
const symbolType = options.definedSymbol === true ? 0x0f : 0x01;
const writeSymbol = (index: number, nameOffset: number): void => {
const at = index * nlistWidth;
@@ -1094,7 +1092,7 @@ const machoSymbolPayload = (
symbolBytes.writeUInt32LE(options.commonSize, at + 8);
};
if (options.symbolScanBudget === true) {
for (let index = 0; index < storedSymbols; index += 1)
for (let index = 0; index < declaredSymbols; index += 1)
writeSymbol(index, 1);
} else if (options.brokenStrx === true && symbolBytes.length >= 4)
writeSymbol(0, 50);
@@ -1104,7 +1102,7 @@ const machoSymbolPayload = (
)
writeSymbol(0, 1);
if (options.trailingBrokenStrx === true)
writeSymbol(storedSymbols - 1, strings.length + 50);
writeSymbol(declaredSymbols - 1, strings.length + 50);
return { wantSymtab, strings, declaredSymbols, symbolBytes };
};
@@ -455,26 +455,34 @@ it("keeps Mach-O siblings when one slice is big-endian, mismatched or malformed"
);
expect(oneSlice[0]?.slice?.architecture).toBe("arm64");
const hugeSymbols = (
await readMachoHardening(machoHardeningFixture({ nsyms: 65537 }))
)[0];
const hugeSlice = machoHardeningFixture({ nsyms: 65537 });
const hugeSymbols = (await readMachoHardening(hugeSlice))[0];
expect(hugeSymbols?.status).toBe("parsed");
expect(findRow(hugeSymbols?.rows ?? [], "pie").state).toBe("enabled");
expect(findRow(hugeSymbols?.rows ?? [], "stack_protector")).toMatchObject({
state: "unknown",
note: expect.stringContaining("structural budget"),
});
const hugeSlice = machoHardeningFixture({ nsyms: 65537 });
// The fixture ends with one string-table NUL after its symbol array.
const truncatedSymbols = hugeSlice.subarray(0, -2);
const truncatedStrings = hugeSlice.subarray(0, -1);
for (const truncated of [truncatedSymbols, truncatedStrings])
await expect(readMachoHardening(truncated)).rejects.toMatchObject({
kind: "malformed",
message: expect.stringContaining("table extends outside the slice"),
});
const kept = await readMachoHardening(
fatMachoHardeningFixture([
{ bytes: arm, cpuType: 0x0100000c, cpuSubtype: 0 },
{ bytes: hugeSlice, cpuType: 0x0100000c, cpuSubtype: 0 },
{ bytes: truncatedSymbols, cpuType: 0x0100000c, cpuSubtype: 0 },
]),
);
expect(kept[0]?.status).toBe("parsed");
expect(findRow(kept[0]?.rows ?? [], "pie").state).toBe("enabled");
expect(kept[1]?.status).toBe("parsed");
expect(findRow(kept[1]?.rows ?? [], "stack_protector").state).toBe("unknown");
expect(kept[2]).toMatchObject({ status: "malformed", rows: [] });
await expect(
readMachoHardening(machoHardeningFixture({ brokenStrx: true })),
).rejects.toMatchObject({ kind: "malformed" });
+24 -24
View File
@@ -5,6 +5,7 @@ import {
machoKnownArm64Subtype,
} from "../../domain/apple/machoCpuIdentity.js";
import {
admitMachoSymtabRanges,
MACHO_HEADER_FLAGS_OFFSET,
readMachoLinkeditDataCommand,
readMachoSymtabCommand,
@@ -34,7 +35,10 @@ import {
MAX_BINARY_HARDENING_TABLE_ENTRIES,
} from "../../domain/native/binaryHardening.js";
import { assertArtifactReadActive } from "../../resources/index.js";
import { BinaryFormatFailure } from "../../domain/binaryContainer.js";
import {
BinaryFormatFailure,
BinaryReader,
} from "../../domain/binaryContainer.js";
import { readMachoEncryption } from "../../domain/apple/machoEncryptionReader.js";
import {
frameLoadCommands,
@@ -569,44 +573,40 @@ const stackRow = (
);
const fields = readMachoSymtabCommand(symtab.body, true);
if (fields === null) malformed("Mach-O LC_SYMTAB command is truncated");
const { symoff, nsyms, stroff, strsize } = fields;
// One oversized symbol table must not drop the header rows or sibling slices.
if (nsyms > MAX_BINARY_HARDENING_TABLE_ENTRIES) return unknownStackBudget();
const width = wide ? 16 : 12;
if (
symoff > ref.size ||
stroff > ref.size ||
nsyms * width > ref.size - symoff ||
strsize > ref.size - stroff
)
const { symoff, nsyms, stroff } = fields;
const ranges = admitMachoSymtabRanges(fields, wide, ref.size);
if (ranges === null)
malformed("Mach-O symbol or string table extends outside the slice");
const symbolAt = ref.offset + symoff;
const stringAt = ref.offset + stroff;
const { width, symbolsEnd, stringsEnd } = ranges;
if (
nsyms * width > bytes.length - symbolAt ||
strsize > bytes.length - stringAt
symbolsEnd > bytes.length - ref.offset ||
stringsEnd > bytes.length - ref.offset
)
malformed("Mach-O symbol or string table extends outside the file");
const strings = bytes.subarray(stringAt, stringAt + strsize);
// Keep header rows and sibling slices when the backed table exceeds the scan limit.
if (nsyms > MAX_BINARY_HARDENING_TABLE_ENTRIES) return unknownStackBudget();
const symbols = new BinaryReader(
bytes.subarray(ref.offset + symoff, ref.offset + symbolsEnd),
true,
"macho",
);
const stringAt = ref.offset + stroff;
const strings = bytes.subarray(stringAt, ref.offset + stringsEnd);
let scanned = 0;
let unterminated = false;
let found: BinaryHardeningRow | null = null;
for (let index = 0; index < nsyms; index += 1) {
const entry = symbolAt + index * width;
const nameOffset = bytes.readUInt32LE(entry);
const entry = index * width;
const nameOffset = symbols.u32(entry);
if (nameOffset === 0) continue;
// N_STAB records use a different type namespace. Only an ordinary N_EXT
// with N_TYPE clear is an undefined external; defined exports are not imports.
const nType = bytes.readUInt8(entry + 4);
const nType = symbols.u8(entry + 4);
if ((nType & 0xe0) !== 0 || (nType & 0x0e) !== 0 || (nType & 0x01) === 0)
continue;
// A common definition shares those type bits but carries its size in
// n_value, so only a zero n_value names an import.
if (
bytes.readUInt32LE(entry + 8) !== 0 ||
(wide && bytes.readUInt32LE(entry + 12) !== 0)
)
continue;
if (symbols.word(entry + 8, wide ? 64 : 32) !== 0n) continue;
// After a match, later records are still admitted so symbol order cannot
// hide a damaged table; their names need not be read.
if (found !== null) {
+17 -19
View File
@@ -2,6 +2,7 @@ import { LC } from "../../domain/apple/machoLoadCommandCodes.js";
import { setImmediate as immediate } from "node:timers/promises";
import { assertArtifactReadActive } from "../../resources/index.js";
import {
admitMachoSymtabRanges,
MachoLoadCommandCursor,
readMachoLoadCommandTableHeader,
readMachoSymtabCommand,
@@ -211,7 +212,7 @@ interface SymbolTable {
readonly symoff: number;
readonly nsyms: number;
readonly strings: Buffer;
readonly wide: boolean;
readonly width: 12 | 16;
readonly little: boolean;
}
@@ -271,7 +272,6 @@ const readSymbols = (
const header = readMachoLoadCommandTableHeader(scan.bytes, scan.bytes.length);
if (!header.ok || header.value === null) return done();
const cursor = new MachoLoadCommandCursor(header.value);
const width = wide ? 16 : 12;
// One budget across every LC_SYMTAB, so repeated commands cannot multiply the work.
let budget = SYMBOL_SCAN;
const seen = new Set<string>();
@@ -286,17 +286,12 @@ const readSymbols = (
note(scan, "LC_SYMTAB is truncated.", "unknown");
return done();
}
const stringsEnd = table.stroff + table.strsize;
if (
table.symoff < 0 ||
table.stroff < 0 ||
table.strsize < 0 ||
stringsEnd > scan.bytes.length ||
table.nsyms > (scan.bytes.length - table.symoff) / width
) {
const ranges = admitMachoSymtabRanges(table, wide, scan.bytes.length);
if (ranges === null) {
note(scan, "LC_SYMTAB points outside the Mach-O image.", "unknown");
return done();
}
const { width, stringsEnd } = ranges;
const range = `${String(table.symoff)}:${String(table.nsyms)}:${String(table.stroff)}:${String(table.strsize)}`;
if (seen.has(range)) {
// Nothing is lost by skipping an identical copy, so coverage stays as it was.
@@ -311,7 +306,7 @@ const readSymbols = (
symoff: table.symoff,
nsyms: table.nsyms,
strings,
wide,
width,
little,
};
const count = Math.min(table.nsyms, budget);
@@ -628,19 +623,22 @@ const objectSymbol = (
): SlotRelocation => {
const table = walk.symbols.table;
if (table === null || index >= table.nsyms) return UNRESOLVED;
const width = table.wide ? 16 : 12;
const { width } = table;
const at = table.symoff + index * width;
const bytes = walk.scan.bytes;
if (at + width > bytes.length) return UNRESOLVED;
const strx = table.little ? bytes.readUInt32LE(at) : bytes.readUInt32BE(at);
const type = bytes[at + 4] ?? 0;
const value = table.wide
? table.little
? bytes.readBigUInt64LE(at + 8)
: bytes.readBigUInt64BE(at + 8)
: BigInt(
table.little ? bytes.readUInt32LE(at + 8) : bytes.readUInt32BE(at + 8),
);
const value =
width === 16
? table.little
? bytes.readBigUInt64LE(at + 8)
: bytes.readBigUInt64BE(at + 8)
: BigInt(
table.little
? bytes.readUInt32LE(at + 8)
: bytes.readUInt32BE(at + 8),
);
// Debugger stabs never name a relocation target.
if ((type & 0xe0) !== 0) return UNRESOLVED;
const ownName = () => nameAt(walk.scan, table.strings, strx);