From 8da89da5e4e1959cd83c0c6ffbf9ce5380d80b10 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 13:11:47 -0500 Subject: [PATCH] perf(elf): fuse dynamic symbol hardening predicates into single-pass scan with __ prefix pre-filter (#13513) * perf(elf): fuse dynamic symbol hardening predicates into single-pass scan with __ prefix pre-filter (#13509) * fix(elf): share symbol decoding and preserve short fortify imports --- src/domain/elfSymbol.ts | 76 ++++++------ .../hardening/BinaryHardeningParsers.test.ts | 26 ++-- src/native/hardening/ElfHardening.ts | 111 ++++++++++++------ 3 files changed, 131 insertions(+), 82 deletions(-) diff --git a/src/domain/elfSymbol.ts b/src/domain/elfSymbol.ts index 547e93885f..bdd5814a93 100644 --- a/src/domain/elfSymbol.ts +++ b/src/domain/elfSymbol.ts @@ -5,12 +5,15 @@ import { err, ok, type Result } from "./result.js"; export const elfSymbolSize = (bits: 32 | 64): 16 | 24 => bits === 64 ? 24 : 16; -export interface ElfSymbol { +export interface ElfSymbolFields { readonly name_offset: number; readonly binding: number; readonly type: number; readonly other: number; readonly section_index: number; +} + +export interface ElfSymbol extends ElfSymbolFields { readonly value: bigint; readonly size: bigint; } @@ -24,45 +27,50 @@ const TRUNCATED_SYMBOL = Object.freeze( }), ); -/** - * Decode one fixed ELF32/ELF64 symbol record starting at `offset` without - * creating a temporary slice or BinaryReader; returns `null` when truncated. - */ +/** Decode the fixed symbol fields without materializing its address and size. */ +export const readElfSymbolFieldsAt = ( + bytes: Uint8Array, + offset: number, + bits: 32 | 64, + littleEndian: boolean, +): ElfSymbolFields | null => { + if ( + !Number.isSafeInteger(offset) || + offset < 0 || + offset > bytes.byteLength - elfSymbolSize(bits) + ) + return null; + const attributes = offset + (bits === 64 ? 4 : 12); + const info = bytes[attributes]!; + return { + name_offset: readUint32At(bytes, offset, littleEndian), + binding: info >>> 4, + type: info & 15, + other: bytes[attributes + 1]!, + section_index: readUint16At(bytes, attributes + 2, littleEndian), + }; +}; + +/** Decode one fixed ELF32/ELF64 symbol record without slicing its bytes. */ export const readElfSymbolAt = ( bytes: Uint8Array, offset: number, bits: 32 | 64, littleEndian: boolean, ): ElfSymbol | null => { - const size = elfSymbolSize(bits); - if ( - !Number.isSafeInteger(offset) || - offset < 0 || - offset > bytes.byteLength - size - ) - return null; - if (bits === 64) { - const info = bytes[offset + 4]!; - return { - name_offset: readUint32At(bytes, offset, littleEndian), - binding: info >>> 4, - type: info & 15, - other: bytes[offset + 5]!, - section_index: readUint16At(bytes, offset + 6, littleEndian), - value: readUint64At(bytes, offset + 8, littleEndian), - size: readUint64At(bytes, offset + 16, littleEndian), - }; - } - const info = bytes[offset + 12]!; - return { - name_offset: readUint32At(bytes, offset, littleEndian), - binding: info >>> 4, - type: info & 15, - other: bytes[offset + 13]!, - section_index: readUint16At(bytes, offset + 14, littleEndian), - value: BigInt(readUint32At(bytes, offset + 4, littleEndian)), - size: BigInt(readUint32At(bytes, offset + 8, littleEndian)), - }; + const fields = readElfSymbolFieldsAt(bytes, offset, bits, littleEndian); + if (fields === null) return null; + return bits === 64 + ? { + ...fields, + value: readUint64At(bytes, offset + 8, littleEndian), + size: readUint64At(bytes, offset + 16, littleEndian), + } + : { + ...fields, + value: BigInt(readUint32At(bytes, offset + 4, littleEndian)), + size: BigInt(readUint32At(bytes, offset + 8, littleEndian)), + }; }; /** Fixed ELF32/ELF64 symbol facts; consumers own definition, visibility and processor-flag policies. diff --git a/src/native/hardening/BinaryHardeningParsers.test.ts b/src/native/hardening/BinaryHardeningParsers.test.ts index 5eef05894a..8fca29acd9 100644 --- a/src/native/hardening/BinaryHardeningParsers.test.ts +++ b/src/native/hardening/BinaryHardeningParsers.test.ts @@ -1230,18 +1230,20 @@ it("cites a non-ASCII import name by its source bytes", () => { expect(bytes.subarray(at, at + 7).toString("latin1")).toBe(name); }); -it("treats the __chk_fail handler import as a FORTIFY sign", () => { - const bytes = elfHardeningFixture({ - fortify: true, - fortifyName: "__chk_fail", - }); - const image = readElfHardening(bytes); - const row = findRow(image.rows, "fortify"); - expect(row).toMatchObject({ state: "enabled", location: { bytes: 10 } }); - expect(row.basis).toContain("__chk_fail"); - const at = row.location?.offset ?? 0; - expect(bytes.subarray(at, at + 10).toString("latin1")).toBe("__chk_fail"); -}); +it.each(["__chk", "__chk_fail"])( + "recognizes the %s import as a FORTIFY sign", + (name) => { + const bytes = elfHardeningFixture({ fortify: true, fortifyName: name }); + const row = findRow(readElfHardening(bytes).rows, "fortify"); + expect(row).toMatchObject({ + state: "enabled", + location: { bytes: name.length }, + }); + expect(row.basis).toContain(name); + const at = row.location?.offset ?? 0; + expect(bytes.subarray(at, at + name.length).toString("latin1")).toBe(name); + }, +); it("keeps malformed name offsets malformed in both formats", async () => { await expect( diff --git a/src/native/hardening/ElfHardening.ts b/src/native/hardening/ElfHardening.ts index f2c89efb3a..2d4079385b 100644 --- a/src/native/hardening/ElfHardening.ts +++ b/src/native/hardening/ElfHardening.ts @@ -25,7 +25,10 @@ import { } from "../../domain/elfDynamicEntry.js"; import { elfArchitecture } from "../../domain/elfFixedHeader.js"; import { admitElfLoadSegment } from "../../domain/elfProgramHeader.js"; -import { elfSymbolSize, readElfSymbol } from "../../domain/elfSymbol.js"; +import { + elfSymbolSize, + readElfSymbolFieldsAt, +} from "../../domain/elfSymbol.js"; import { readElfGnuHashSymbolCount, readElfHashSymbolCount, @@ -274,7 +277,11 @@ const hardeningFromDirectory = ( // One import table above the entry budget must not drop PIE, NX, or RELRO. // The import rows stay unknown. if (!(cause instanceof BinaryResourceFailure)) throw cause; - symbols = { state: "unresolved", reason: cause.message, names: [] }; + symbols = { + state: "unresolved", + reason: cause.message, + ...EMPTY_SYMBOL_MATCHES, + }; } const features = readFeatureNotes( bytes, @@ -309,18 +316,14 @@ const hardeningFromDirectory = ( symbolRow( "stack_protector", symbols, - (name) => - name === "__stack_chk_fail" || name === "__stack_chk_fail_local", + symbols.stackProtector, "No __stack_chk_fail symbol was found in the dynamic symbol table. A static or stripped image can omit that import while still using a stack protector.", "The dynamic symbol table is absent, so stack protector use is unknown.", ), symbolRow( "fortify", symbols, - (name) => - name === "__fortify_fail" || - name === "__chk_fail" || - (name.startsWith("__") && name.endsWith("_chk")), + symbols.fortify, "No fortify symbol was found in the dynamic symbol table. A static or stripped image can omit those imports while still using FORTIFY.", "The dynamic symbol table is absent, so FORTIFY use is unknown.", ), @@ -496,18 +499,33 @@ type SymbolName = { readonly offset: number; readonly bytes: number; }; -/** `unresolved` keeps the names read so far. A sign among them still counts. */ +/** `unresolved` keeps any hardening signs read so far. A sign among them still counts. */ type SymbolScan = | { readonly state: "absent" | "scanned"; - readonly names: readonly SymbolName[]; + readonly stackProtector: SymbolName | undefined; + readonly fortify: SymbolName | undefined; } | { readonly state: "unresolved"; readonly reason: string; - readonly names: readonly SymbolName[]; + readonly stackProtector: SymbolName | undefined; + readonly fortify: SymbolName | undefined; }; +const EMPTY_SYMBOL_MATCHES = { + stackProtector: undefined, + fortify: undefined, +} as const; + +const isStackProtectorSymbol = (name: string): boolean => + name === "__stack_chk_fail" || name === "__stack_chk_fail_local"; + +const isFortifySymbol = (name: string): boolean => + name === "__fortify_fail" || + name === "__chk_fail" || + (name.startsWith("__") && name.endsWith("_chk")); + /** * The loader reads DT_SYMTAB and DT_STRTAB, so section headers cannot declare * imports. An SHT_DYNSYM section only supplies a count DT_HASH and DT_GNU_HASH @@ -531,12 +549,12 @@ const readSymbols = ( const symtab = dynamic?.entries.get(DT_SYMTAB); if (dynamic === null || symtab === undefined) return section === undefined - ? { state: "absent", names: [] } + ? { state: "absent", ...EMPTY_SYMBOL_MATCHES } : { state: "unresolved", reason: "An SHT_DYNSYM section exists, but no DT_SYMTAB declares it, so its names are not established as imports.", - names: [], + ...EMPTY_SYMBOL_MATCHES, }; const width = elfSymbolSize(bits); const syment = dynamic.entries.get(DT_SYMENT); @@ -553,7 +571,7 @@ const readSymbols = ( reason: dynamic.entries.has(DT_GNU_HASH) ? "DT_GNU_HASH has no hashed symbols and no agreeing SHT_DYNSYM section gives the count, so the dynamic symbol table could not be read." : "Neither DT_HASH nor DT_GNU_HASH is present and no agreeing SHT_DYNSYM section gives the count, so the dynamic symbol table could not be read.", - names: [], + ...EMPTY_SYMBOL_MATCHES, }; budget(count, "ELF dynamic symbol table"); const base = mapVa(symtab.value, BigInt(count * width)).offset; @@ -618,21 +636,25 @@ const readSymbolNames = ( stringFileOffset: number, ): SymbolScan => { const width = elfSymbolSize(bits); - const names: SymbolName[] = []; + let stackProtector: SymbolName | undefined; + let fortify: SymbolName | undefined; let scanned = 0; let unterminated = false; for (let index = 0; index < count; index += 1) { - const at = offset + index * width; - const symbol = readElfSymbol(bytes.subarray(at, at + width), bits, little); - if (!symbol.ok) malformed(symbol.error.message); - const nameOffset = symbol.value.name_offset; - if (nameOffset === 0) continue; - // SHN_UNDEF is an import. A defined export of the same name is not a sign - // that this image references the protector. - if (symbol.value.section_index !== 0) continue; - // An STB_LOCAL symbol is never resolved against another object, so it - // does not establish an external import. - if (symbol.value.binding === STB_LOCAL) continue; + const symbol = readElfSymbolFieldsAt( + bytes, + offset + index * width, + bits, + little, + ); + if (symbol === null) malformed("ELF symbol record is truncated"); + if ( + symbol.name_offset === 0 || + symbol.section_index !== 0 || + symbol.binding === STB_LOCAL + ) + continue; + const nameOffset = symbol.name_offset; const observed = observeElfStringTableEntry( strings, nameOffset, @@ -643,7 +665,8 @@ const readSymbolNames = ( return { state: "unresolved", reason: `ELF symbol name scans examined more than the ${String(MAX_BINARY_HARDENING_SYMBOL_SCAN_BYTES)}-byte structural budget, so this import sign is unknown.`, - names, + stackProtector, + fortify, }; if (observed.state === "outside") malformed("ELF dynamic symbol name offset is outside the string table"); @@ -652,19 +675,36 @@ const readSymbolNames = ( unterminated = true; continue; } - names.push({ - name: elfStringTableText(observed) ?? "", - offset: stringFileOffset + nameOffset, - bytes: observed.contentBytes, - }); + // The "__" prefix and "_chk" suffix can overlap in "__chk". + if ( + (stackProtector === undefined || fortify === undefined) && + observed.contentBytes >= 5 && + strings[nameOffset] === 0x5f && + strings[nameOffset + 1] === 0x5f + ) { + const name = elfStringTableText(observed) ?? ""; + if (stackProtector === undefined && isStackProtectorSymbol(name)) + stackProtector = { + name, + offset: stringFileOffset + nameOffset, + bytes: observed.contentBytes, + }; + if (fortify === undefined && isFortifySymbol(name)) + fortify = { + name, + offset: stringFileOffset + nameOffset, + bytes: observed.contentBytes, + }; + } } return unterminated ? { state: "unresolved", reason: `An undefined dynamic symbol name has no NUL within the string table or the ${String(MAX_BINARY_HARDENING_SYMBOL_NAME_BYTES)}-byte name budget, so this import sign is unknown.`, - names, + stackProtector, + fortify, } - : { state: "scanned", names }; + : { state: "scanned", stackProtector, fortify }; }; const hashWords = ( @@ -1109,11 +1149,10 @@ const relroRow = ( const symbolRow = ( property: "stack_protector" | "fortify", symbols: SymbolScan, - match: (name: string) => boolean, + found: SymbolName | undefined, missing: string, absent: string, ): BinaryHardeningRow => { - const found = symbols.names.find(({ name }) => match(name)); if (found !== undefined) return row({ property,