From 9291cd62197eadb5306f4d1939ead32f4d136ddc Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:38:42 -0500 Subject: [PATCH] perf(elf): stream kernel module inspection over FileHandle (#13917) * perf(elf): stream kernel module inspection over FileHandle * test(elf): exercise streamed kernel module reads and finalization --- src/domain/native/elfImage.ts | 70 ++- src/domain/native/nativeSectionDirectory.ts | 62 ++ src/native/elf/KernelModuleParser.ts | 531 ++++++++++++++---- src/native/elf/KernelModuleProvider.ts | 55 +- .../boundary/filesystem/kernelModule.test.ts | 32 ++ .../nativeArtifactFinalization.test.ts | 2 + 6 files changed, 600 insertions(+), 152 deletions(-) diff --git a/src/domain/native/elfImage.ts b/src/domain/native/elfImage.ts index 850b847aff2..451d6b8d7d7 100644 --- a/src/domain/native/elfImage.ts +++ b/src/domain/native/elfImage.ts @@ -3,7 +3,6 @@ import { admitElfLoadSegment, elfLoadSpans } from "../elfProgramHeader.js"; import { declaredFileRange, BinaryFormatFailure, - BinaryReader, type BinaryContainer, type ElfDynamicSegment, type ImageSection, @@ -15,15 +14,42 @@ import type { CooperativeElfSectionNameDecoder } from "./elfSectionNameTable.js" import { readElfDirectoryFromBuffer, readElfDirectoryFromBufferCooperative, + readElfDirectoryFromReader, type ElfSectionDirectory, + type NativeByteSource, } from "./nativeSectionDirectory.js"; -export const readElfImageFromDirectory = ( - bytes: Buffer, +const requireElfFileRange = ( + fileSize: number, + offset: bigint, + size: bigint, + label: string, +): void => { + if ( + offset < 0n || + size < 0n || + offset > BigInt(Number.MAX_SAFE_INTEGER) || + size > BigInt(Number.MAX_SAFE_INTEGER) || + Number(offset) > fileSize + ) + throw new BinaryFormatFailure( + "malformed", + `${label} range is truncated or outside the file`, + { format: "elf", field: label }, + ); + if (Number(size) > fileSize - Number(offset)) + throw new BinaryFormatFailure( + "truncated", + `${label} range is truncated or outside the file`, + { format: "elf", offset: Number(offset), field: label }, + ); +}; + +const readElfImageFromDirectorySize = ( + fileSize: number, directory: ElfSectionDirectory, ): Extract => { const { bits } = directory; - const reader = new BinaryReader(bytes, directory.little, "elf"); const mappings: FileMapping[] = []; const loadRegions: LoadRegion[] = []; const executableMappings: FileMapping[] = []; @@ -53,7 +79,8 @@ export const readElfImageFromDirectory = ( const admitted = admitElfLoadSegment(span, bits); if (!admitted.ok) throw new BinaryFormatFailure("malformed", admitted.error.message); - if (size !== 0n) reader.fileRange(fileOffset, size, "ELF load segment"); + if (size !== 0n) + requireElfFileRange(fileSize, fileOffset, size, "ELF load segment"); const { fileBacked: mapping, zeroFill } = elfLoadSpans(span); if (mapping !== undefined) { mappings.push(mapping); @@ -69,7 +96,7 @@ export const readElfImageFromDirectory = ( if (zeroFill !== undefined) zeroFills.push(zeroFill); } for (const section of directory.sections) { - const range = declaredFileRange(bytes.length, section.offset, section.size); + const range = declaredFileRange(fileSize, section.offset, section.size); const { file_backed, compressed } = section; const read_only = section.type === 1 && @@ -101,7 +128,7 @@ export const readElfImageFromDirectory = ( }, architecture: architectureForElfMachine(directory.machine), bits, - byte_order: reader.little ? "little" : "big", + byte_order: directory.little ? "little" : "big", mappings, load_regions: loadRegions, executable_mappings: executableMappings, @@ -113,6 +140,12 @@ export const readElfImageFromDirectory = ( }; }; +export const readElfImageFromDirectory = ( + bytes: Buffer, + directory: ElfSectionDirectory, +): Extract => + readElfImageFromDirectorySize(bytes.length, directory); + /** Map ELF machine identifiers to stable architecture names. */ export const architectureForElfMachine = (machine: number): string => { const architecture = elfArchitecture(machine); @@ -163,8 +196,8 @@ export const readElfImageCooperative = async ( maximumSourceAndDecodedNamesBytes?: number, decode?: CooperativeElfSectionNameDecoder, ): Promise> => - readElfImageFromDirectory( - bytes, + readElfImageFromDirectorySize( + bytes.length, await readElfDirectoryFromBufferCooperative( bytes, pause, @@ -173,3 +206,22 @@ export const readElfImageCooperative = async ( decode, ), ); + +/** Read ELF sections and program mappings positionally without buffering the whole file. */ +export const readElfImageFromReader = async ( + source: NativeByteSource, + operation: string, + pause: ZstandardFramePause, + maximumSourceAndDecodedNamesBytes?: number, + decode?: CooperativeElfSectionNameDecoder, +): Promise> => + readElfImageFromDirectorySize( + source.size, + await readElfDirectoryFromReader( + source, + pause, + operation, + maximumSourceAndDecodedNamesBytes, + decode, + ), + ); diff --git a/src/domain/native/nativeSectionDirectory.ts b/src/domain/native/nativeSectionDirectory.ts index 80e0b615265..d8b7e5840d6 100644 --- a/src/domain/native/nativeSectionDirectory.ts +++ b/src/domain/native/nativeSectionDirectory.ts @@ -620,6 +620,68 @@ export const readElfDirectoryFromBufferCooperative = async ( } }; +/** Random-access byte source for positional native directory inspection. */ +export interface NativeByteSource { + readonly size: number; + readonly prefix?: Buffer; + readRange(offset: number, length: number): Promise; +} + +const driveElfDirectoryFromSource = async ( + source: NativeByteSource, + decode: CooperativeElfSectionNameDecoder, + maximumSourceAndDecodedNamesBytes?: number, +): Promise => { + const steps = readElfSectionDirectory( + source.size, + maximumSourceAndDecodedNamesBytes, + ); + let next = steps.next(); + while (!next.done) { + const step = next.value; + if ( + step.sectionNames !== undefined && + step.fulfillSectionNames !== undefined + ) { + step.fulfillSectionNames(await decode(step.sectionNames)); + next = steps.next(Buffer.alloc(0)); + continue; + } + const slice = + step.size === 0 + ? Buffer.alloc(0) + : source.prefix !== undefined && + step.offset + step.size <= source.prefix.length + ? source.prefix.subarray(step.offset, step.offset + step.size) + : await source.readRange(step.offset, step.size); + next = steps.next(slice); + } + return next.value; +}; + +/** + * Same directory as {@link readElfDirectoryFromBufferCooperative}, reading only + * the header, program/section tables, and section-name table from `source`. + */ +export const readElfDirectoryFromReader = async ( + source: NativeByteSource, + pause: ZstandardFramePause, + operation: string, + maximumSourceAndDecodedNamesBytes?: number, + decode: CooperativeElfSectionNameDecoder = (request) => + decodeElfSectionNameRequestCooperative(request, pause), +): Promise => { + try { + return await driveElfDirectoryFromSource( + source, + decode, + maximumSourceAndDecodedNamesBytes, + ); + } catch (cause) { + return projectDirectoryFrameAllowance(operation, cause); + } +}; + /** Reject a program or section payload the declared tables place outside these bytes. */ export const assertElfDeclaredRangesFromBuffer = (bytes: Buffer): void => { const checked = driveFromBuffer( diff --git a/src/native/elf/KernelModuleParser.ts b/src/native/elf/KernelModuleParser.ts index 2ec8c47992a..b4e06862f6c 100644 --- a/src/native/elf/KernelModuleParser.ts +++ b/src/native/elf/KernelModuleParser.ts @@ -25,7 +25,9 @@ import { import { readElfImage, readElfImageCooperative, + readElfImageFromReader, } from "../../domain/native/elfImage.js"; +import type { NativeByteSource } from "../../domain/native/nativeSectionDirectory.js"; import { kernelCompressionCodecAt } from "./KernelCompressionCodec.js"; import { sha256Hex } from "../../kernel/sha256Hex.js"; @@ -165,35 +167,15 @@ interface SectionUse { readonly limitations: Limitations; } -const parseModinfo = ( - bytes: Buffer, - section: ElfSection | undefined, +const parseModinfoStored = ( + stored: Buffer, + location: { offset: number; bytes: number }, + compressed: boolean, use: SectionUse, examined: { count: number }, input: InspectKernelModuleInput, ): NonNullable => { - if (section === undefined) - return { - status: use.namesComplete ? "absent" : "unknown", - location: null, - sha256: null, - entries: [], - reason: null, - }; - const location = locationOf(section); - if (section.type === 8 || location === null || !inFile(section, bytes.length)) - return { - status: "malformed", - location: null, - sha256: null, - entries: [], - reason: "modinfo_section_not_file_backed", - }; - const stored = bytes.subarray( - location.offset, - location.offset + location.bytes, - ); - if (section.compressed) + if (compressed) return { status: "unsupported", location, @@ -278,44 +260,19 @@ const parseModinfo = ( }; }; -const parseVersions = ( - bytes: Buffer, - section: ElfSection | undefined, +const parseVersionsStored = ( + stored: Buffer, + location: { offset: number; bytes: number }, + compressed: boolean, bits: 32 | 64, little: boolean, - use: SectionUse, examined: { count: number }, maxEntries: number, ): NonNullable => { const layout = bits === 64 ? "elf64_unsigned_long_name56" : "elf32_unsigned_long_name60"; const entryBytes = KERNEL_MODULE_VERSION_ENTRY_BYTES; - if (section === undefined) - return { - status: use.namesComplete ? "absent" : "unknown", - layout, - entry_bytes: entryBytes, - location: null, - sha256: null, - entries: [], - reason: null, - }; - const location = locationOf(section); - if (section.type === 8 || location === null || !inFile(section, bytes.length)) - return { - status: "malformed", - layout, - entry_bytes: entryBytes, - location: null, - sha256: null, - entries: [], - reason: "versions_section_not_file_backed", - }; - const stored = bytes.subarray( - location.offset, - location.offset + location.bytes, - ); - if (section.compressed) + if (compressed) return { status: "unsupported", layout, @@ -386,7 +343,7 @@ const presence = ( }; const sized = ( - bytes: Buffer, + fileLength: number, section: ElfSection | undefined, namesComplete: boolean, limitations: Limitations, @@ -399,7 +356,7 @@ const sized = ( bytes: null, compressed: null, }; - if (!inFile(section, bytes.length) || section.type === 8) { + if (!inFile(section, fileLength) || section.type === 8) { limitations.push( `${label} is declared but not file-backed, so its size is unknown.`, ); @@ -423,36 +380,53 @@ const sized = ( }; }; -const parseSignature = (bytes: Buffer): Report["signature"] => { +const parseSignatureTrailer = ( + fileLength: number, + tail: Buffer, +): + | { readonly done: true; readonly signature: Report["signature"] } + | { + readonly done: false; + readonly magic: { offset: number; bytes: number }; + readonly info: NonNullable["info"]>; + readonly pkcs7Offset: number; + readonly pkcs7Bytes: number; + } => { if ( - bytes.length < MAGIC.length || - !bytes.subarray(bytes.length - MAGIC.length).equals(MAGIC) + fileLength < MAGIC.length || + !tail.subarray(tail.length - MAGIC.length).equals(MAGIC) ) return { - status: "absent", - magic: null, - info: null, - pkcs7: null, - reason: null, + done: true, + signature: { + status: "absent", + magic: null, + info: null, + pkcs7: null, + reason: null, + }, }; const magic = { - offset: bytes.length - MAGIC.length, + offset: fileLength - MAGIC.length, bytes: MAGIC.length, }; if (magic.offset < MODULE_SIGNATURE_INFO_BYTES) return { - status: "malformed", - magic, - info: null, - pkcs7: null, - reason: "signature_trailer_truncated", + done: true, + signature: { + status: "malformed", + magic, + info: null, + pkcs7: null, + reason: "signature_trailer_truncated", + }, }; const infoOffset = magic.offset - MODULE_SIGNATURE_INFO_BYTES; - const footer = new BinaryReader( - bytes.subarray(infoOffset, magic.offset), - false, - "elf", + const infoSlice = tail.subarray( + tail.length - MAGIC.length - MODULE_SIGNATURE_INFO_BYTES, + tail.length - MAGIC.length, ); + const footer = new BinaryReader(infoSlice, false, "elf"); const info = { location: { offset: infoOffset, bytes: MODULE_SIGNATURE_INFO_BYTES }, algo: footer.u8(0), @@ -466,19 +440,25 @@ const parseSignature = (bytes: Buffer): Report["signature"] => { const isPkcs7 = info.id_type === MODULE_SIGNATURE_PKCS7_ID_TYPE; if (info.sig_len >= infoOffset || (isPkcs7 && info.sig_len === 0)) return { - status: "malformed", - magic, - info, - pkcs7: null, - reason: "signature_length_inconsistent", + done: true, + signature: { + status: "malformed", + magic, + info, + pkcs7: null, + reason: "signature_length_inconsistent", + }, }; if (!isPkcs7) return { - status: "unsupported", - magic, - info, - pkcs7: null, - reason: "signature_id_type_not_pkcs7", + done: true, + signature: { + status: "unsupported", + magic, + info, + pkcs7: null, + reason: "signature_id_type_not_pkcs7", + }, }; const parametersNonzero = info.algo !== 0 || @@ -488,19 +468,81 @@ const parseSignature = (bytes: Buffer): Report["signature"] => { info.pad.some((value) => value !== 0); if (parametersNonzero) return { - status: "malformed", - magic, - info, - pkcs7: null, - reason: "signature_parameters_nonzero", + done: true, + signature: { + status: "malformed", + magic, + info, + pkcs7: null, + reason: "signature_parameters_nonzero", + }, }; - const pkcs7 = bytes.subarray(infoOffset - info.sig_len, infoOffset); return { - status: "present", + done: false, magic, info, + pkcs7Offset: infoOffset - info.sig_len, + pkcs7Bytes: info.sig_len, + }; +}; + +const parseSignatureFromBuffer = (bytes: Buffer): Report["signature"] => { + const tailLen = Math.min( + bytes.length, + MAGIC.length + MODULE_SIGNATURE_INFO_BYTES, + ); + const trailer = parseSignatureTrailer( + bytes.length, + bytes.subarray(bytes.length - tailLen), + ); + if (trailer.done) return trailer.signature; + const pkcs7 = bytes.subarray( + trailer.pkcs7Offset, + trailer.pkcs7Offset + trailer.pkcs7Bytes, + ); + return { + status: "present", + magic: trailer.magic, + info: trailer.info, pkcs7: { - location: { offset: infoOffset - info.sig_len, bytes: info.sig_len }, + location: { offset: trailer.pkcs7Offset, bytes: trailer.pkcs7Bytes }, + sha256: sha256Hex(pkcs7), + }, + reason: null, + }; +}; + +const parseSignatureFromSource = async ( + source: NativeByteSource, +): Promise => { + const tailLen = Math.min( + source.size, + MAGIC.length + MODULE_SIGNATURE_INFO_BYTES, + ); + const tailOffset = source.size - tailLen; + const tail = + tailLen === 0 + ? Buffer.alloc(0) + : source.prefix !== undefined && + tailOffset + tailLen <= source.prefix.length + ? source.prefix.subarray(tailOffset, tailOffset + tailLen) + : await source.readRange(tailOffset, tailLen); + const trailer = parseSignatureTrailer(source.size, tail); + if (trailer.done) return trailer.signature; + const pkcs7 = + source.prefix !== undefined && + trailer.pkcs7Offset + trailer.pkcs7Bytes <= source.prefix.length + ? source.prefix.subarray( + trailer.pkcs7Offset, + trailer.pkcs7Offset + trailer.pkcs7Bytes, + ) + : await source.readRange(trailer.pkcs7Offset, trailer.pkcs7Bytes); + return { + status: "present", + magic: trailer.magic, + info: trailer.info, + pkcs7: { + location: { offset: trailer.pkcs7Offset, bytes: trailer.pkcs7Bytes }, sha256: sha256Hex(pkcs7), }, reason: null, @@ -515,15 +557,116 @@ const signatureLimitation = (signature: Report["signature"]): string => { return "The appended signature trailer was not accepted as an unvalidated PKCS#7 range."; }; -/** Decode kernel-module metadata from an admitted in-memory ELF image. */ -const parseKernelModuleImage = ( - bytes: Buffer, - artifact: Report["artifact"], - input: InspectKernelModuleInput, +const modinfoSectionLocation = ( + section: ElfSection | undefined, + fileLength: number, + use: SectionUse, +): + | { readonly ready: false; readonly result: NonNullable } + | { + readonly ready: true; + readonly location: { offset: number; bytes: number }; + readonly compressed: boolean; + } => { + if (section === undefined) + return { + ready: false, + result: { + status: use.namesComplete ? "absent" : "unknown", + location: null, + sha256: null, + entries: [], + reason: null, + }, + }; + const location = locationOf(section); + if (section.type === 8 || location === null || !inFile(section, fileLength)) + return { + ready: false, + result: { + status: "malformed", + location: null, + sha256: null, + entries: [], + reason: "modinfo_section_not_file_backed", + }, + }; + return { ready: true, location, compressed: section.compressed }; +}; + +const versionsSectionLocation = ( + section: ElfSection | undefined, + fileLength: number, + bits: 32 | 64, + use: SectionUse, +): + | { readonly ready: false; readonly result: NonNullable } + | { + readonly ready: true; + readonly location: { offset: number; bytes: number }; + readonly compressed: boolean; + } => { + const layout = + bits === 64 ? "elf64_unsigned_long_name56" : "elf32_unsigned_long_name60"; + const entryBytes = KERNEL_MODULE_VERSION_ENTRY_BYTES; + if (section === undefined) + return { + ready: false, + result: { + status: use.namesComplete ? "absent" : "unknown", + layout, + entry_bytes: entryBytes, + location: null, + sha256: null, + entries: [], + reason: null, + }, + }; + const location = locationOf(section); + if (section.type === 8 || location === null || !inFile(section, fileLength)) + return { + ready: false, + result: { + status: "malformed", + layout, + entry_bytes: entryBytes, + location: null, + sha256: null, + entries: [], + reason: "versions_section_not_file_backed", + }, + }; + return { ready: true, location, compressed: section.compressed }; +}; + +const readSourceRange = async ( + source: NativeByteSource, + offset: number, + length: number, +): Promise => + length === 0 + ? Buffer.alloc(0) + : source.prefix !== undefined && offset + length <= source.prefix.length + ? source.prefix.subarray(offset, offset + length) + : source.readRange(offset, length); + +interface KernelModulePrepared { + readonly facts: ReturnType; + readonly sections: readonly ElfSection[]; + readonly namesComplete: boolean; + readonly limitations: Limitations; + readonly use: SectionUse; + readonly examined: { count: number }; + readonly duplicateSections: () => boolean; + readonly modinfoSection: ElfSection | undefined; + readonly versionsSection: ElfSection | undefined; + readonly firstNamedSection: (name: string) => ElfSection | undefined; +} + +const prepareKernelModule = ( image: ReturnType, -): Report => { +): KernelModulePrepared => { const facts = headerFacts(image); - if (facts.type !== 1) return notApplicable(artifact, facts); const sections = image.sections.filter( (section): section is ElfSection => section.format === "elf", ); @@ -550,32 +693,49 @@ const parseKernelModuleImage = ( "Linux's module loader (find_sec) reads the first section with the name.", ); }; - const modinfo = parseModinfo( - bytes, - firstNamedSection(".modinfo"), + const modinfoSection = firstNamedSection(".modinfo"); + const versionsSection = firstNamedSection("__versions"); + return { + facts, + sections, + namesComplete, + limitations, use, examined, - input, - ); - const versions = parseVersions( - bytes, - firstNamedSection("__versions"), - image.bits, - image.byte_order === "little", - use, + duplicateSections: () => duplicateSections, + modinfoSection, + versionsSection, + firstNamedSection, + }; +}; + +const finalizeKernelModule = ( + fileLength: number, + artifact: Report["artifact"], + input: InspectKernelModuleInput, + prepared: KernelModulePrepared, + modinfo: NonNullable, + versions: NonNullable, + signature: Report["signature"], +): Report => { + const { + facts, + sections, + namesComplete, + limitations, examined, - input.max_entries, - ); + firstNamedSection, + } = prepared; const modulePresence = presence( firstNamedSection(".gnu.linkonce.this_module"), namesComplete, - bytes.length, + fileLength, ); const ksymtabNamed = sections.filter( (section) => section.name?.startsWith("__ksymtab") === true, ); const ksymtabSections = ksymtabNamed.filter( - (section) => section.type !== 8 && inFile(section, bytes.length), + (section) => section.type !== 8 && inFile(section, fileLength), ); const unbacked = ksymtabNamed.length - ksymtabSections.length; if (unbacked > 0) @@ -603,21 +763,20 @@ const parseKernelModuleImage = ( limitations.push( "Section names are incomplete, so a missing .modinfo, __versions, this_module, __ksymtab, .init.text, or .exit.text section is unknown rather than absent.", ); - const signature = parseSignature(bytes); - if (modinfo?.status === "absent") + if (modinfo.status === "absent") limitations.push("No .modinfo section was declared."); - if (versions?.status === "absent") + if (versions.status === "absent") limitations.push("No __versions section was declared."); limitations.push(signatureLimitation(signature)); const initText = sized( - bytes, + fileLength, firstNamedSection(".init.text"), namesComplete, limitations, ".init.text", ); const exitText = sized( - bytes, + fileLength, firstNamedSection(".exit.text"), namesComplete, limitations, @@ -630,7 +789,7 @@ const parseKernelModuleImage = ( section.entries.some((entry) => entry.status !== "observed"); const coveragePartial = !namesComplete || - duplicateSections || + prepared.duplicateSections() || unbacked > 0 || ksymtab.some((section) => section.reason !== null) || sectionIncomplete(modinfo) || @@ -670,6 +829,65 @@ const parseKernelModuleImage = ( }; }; +/** Decode kernel-module metadata from an admitted in-memory ELF image. */ +const parseKernelModuleImage = ( + bytes: Buffer, + artifact: Report["artifact"], + input: InspectKernelModuleInput, + image: ReturnType, +): Report => { + const facts = headerFacts(image); + if (facts.type !== 1) return notApplicable(artifact, facts); + const prepared = prepareKernelModule(image); + const modinfoLoc = modinfoSectionLocation( + prepared.modinfoSection, + bytes.length, + prepared.use, + ); + const modinfo = modinfoLoc.ready + ? parseModinfoStored( + bytes.subarray( + modinfoLoc.location.offset, + modinfoLoc.location.offset + modinfoLoc.location.bytes, + ), + modinfoLoc.location, + modinfoLoc.compressed, + prepared.use, + prepared.examined, + input, + ) + : modinfoLoc.result; + const versionsLoc = versionsSectionLocation( + prepared.versionsSection, + bytes.length, + image.bits, + prepared.use, + ); + const versions = versionsLoc.ready + ? parseVersionsStored( + bytes.subarray( + versionsLoc.location.offset, + versionsLoc.location.offset + versionsLoc.location.bytes, + ), + versionsLoc.location, + versionsLoc.compressed, + image.bits, + image.byte_order === "little", + prepared.examined, + input.max_entries, + ) + : versionsLoc.result; + return finalizeKernelModule( + bytes.length, + artifact, + input, + prepared, + modinfo, + versions, + parseSignatureFromBuffer(bytes), + ); +}; + export const parseKernelModule = ( bytes: Buffer, artifact: Report["artifact"], @@ -703,3 +921,74 @@ export const parseKernelModuleCooperative = async ( ) ); }; + +/** Decode kernel-module metadata positionally over a bounded file handle. */ +export const parseKernelModuleFromHandle = async ( + source: NativeByteSource, + artifact: Report["artifact"], + input: InspectKernelModuleInput, + signal?: AbortSignal, +): Promise => { + assertArtifactReadActive(signal); + const magicProbe = await readSourceRange(source, 0, Math.min(source.size, 8)); + const compressed = moduleCompressionReport(magicProbe, artifact); + if (compressed !== null) return compressed; + const image = await readElfImageFromReader( + source, + "inspect_kernel_module", + () => yieldArtifactRead(signal), + ); + const facts = headerFacts(image); + if (facts.type !== 1) return notApplicable(artifact, facts); + const prepared = prepareKernelModule(image); + const modinfoLoc = modinfoSectionLocation( + prepared.modinfoSection, + source.size, + prepared.use, + ); + const modinfo = modinfoLoc.ready + ? parseModinfoStored( + await readSourceRange( + source, + modinfoLoc.location.offset, + modinfoLoc.location.bytes, + ), + modinfoLoc.location, + modinfoLoc.compressed, + prepared.use, + prepared.examined, + input, + ) + : modinfoLoc.result; + const versionsLoc = versionsSectionLocation( + prepared.versionsSection, + source.size, + image.bits, + prepared.use, + ); + const versions = versionsLoc.ready + ? parseVersionsStored( + await readSourceRange( + source, + versionsLoc.location.offset, + versionsLoc.location.bytes, + ), + versionsLoc.location, + versionsLoc.compressed, + image.bits, + image.byte_order === "little", + prepared.examined, + input.max_entries, + ) + : versionsLoc.result; + const signature = await parseSignatureFromSource(source); + return finalizeKernelModule( + source.size, + artifact, + input, + prepared, + modinfo, + versions, + signature, + ); +}; diff --git a/src/native/elf/KernelModuleProvider.ts b/src/native/elf/KernelModuleProvider.ts index 32846163422..a5f464be227 100644 --- a/src/native/elf/KernelModuleProvider.ts +++ b/src/native/elf/KernelModuleProvider.ts @@ -9,8 +9,7 @@ import { stableArtifactInputFailure, projectArtifactCloseFailure, ArtifactReaderFailure, - type StableArtifactSnapshot, - readStableArtifact, + withStableArtifactHandle, artifactFilePrimaryFacts, type ArtifactFilePrimaryFacts, ArtifactResourceScope, @@ -32,9 +31,10 @@ import { BinaryResourceFailure, binaryResourceCeiling, } from "../../domain/binaryContainer.js"; -import { parseKernelModuleCooperative } from "./KernelModuleParser.js"; +import { parseKernelModuleFromHandle } from "./KernelModuleParser.js"; const OPERATION = "inspect_kernel_module"; +const HEADER_PREFIX_BYTES = 4096; /** Portable parser over one bounded, identity-checked regular file. */ export class KernelModuleProvider implements KernelModulePort { @@ -54,31 +54,42 @@ export class KernelModuleProvider implements KernelModulePort { } async inspect(input: InspectKernelModuleInput, options?: ExecutionOptions) { - let snapshot: StableArtifactSnapshot | undefined; + let observed: + | { readonly sha256: string; readonly bytes: number } + | undefined; try { return await this.#resources.run(async () => { - snapshot = await readStableArtifact( + const result = await withStableArtifactHandle( input.path, input.max_file_bytes, - options?.signal, - undefined, - this.#resources, - ); - return ok( - await parseKernelModuleCooperative( - snapshot.bytes, - { - path: input.path, - sha256: snapshot.sha256, - bytes: snapshot.bytes.length, + { + signal: options?.signal, + resourceScope: this.#resources, + retainBytes: (size) => Math.min(size, HEADER_PREFIX_BYTES), + onIdentity: (identity) => { + observed = identity; }, - input, - options?.signal, - ), + }, + (handle) => + parseKernelModuleFromHandle( + { + size: handle.size, + prefix: handle.prefix, + readRange: (offset, length) => handle.readRange(offset, length), + }, + { + path: input.path, + sha256: handle.sha256, + bytes: handle.size, + }, + input, + options?.signal, + ), ); + return ok(result); }); } catch (cause) { - return err(kernelModuleFailure(cause, input, snapshot)); + return err(kernelModuleFailure(cause, input, observed)); } } } @@ -182,7 +193,7 @@ const kernelModuleFailurePrimary = ( const kernelModuleFailure = ( cause: unknown, input: InspectKernelModuleInput, - snapshot?: StableArtifactSnapshot, + observed?: { readonly sha256: string; readonly bytes: number }, ) => { const primary = kernelModuleFailurePrimary( artifactFilePrimaryFacts(cause), @@ -194,6 +205,6 @@ const kernelModuleFailure = ( input.path, KERNEL_MODULE_PROVIDER.id, OPERATION, - snapshot, + observed, ); }; diff --git a/tests/boundary/filesystem/kernelModule.test.ts b/tests/boundary/filesystem/kernelModule.test.ts index eae49f84ff9..af553ef25e1 100644 --- a/tests/boundary/filesystem/kernelModule.test.ts +++ b/tests/boundary/filesystem/kernelModule.test.ts @@ -44,6 +44,38 @@ describe("kernel module stable filesystem boundary", () => { } }); + it("reads module metadata and signature beyond the retained prefix", async () => { + const root = await createTestTempDirectory("rea-kernel-module-positional-"); + const path = join(root, "demo.ko"); + // Enough section headers to place .modinfo and the signature beyond 4 KiB. + const bytes = kernelModuleFixture({ + sharedNameSections: { name: ".padding", count: 70 }, + }); + const firstSection = Number(bytes.readBigUInt64LE(40)) + 64; + const modinfoOffset = Number(bytes.readBigUInt64LE(firstSection + 24)); + expect(modinfoOffset).toBeGreaterThan(4096); + await writeFile(path, bytes); + const service = createKernelModuleService(); + try { + const result = await service.inspect({ path }); + if (!result.ok) throw result.error; + expect(result.value.normalized_result).toMatchObject({ + modinfo: { + entries: expect.arrayContaining([ + expect.objectContaining({ + key: "license", + value: "GPL", + location: { offset: modinfoOffset, bytes: expect.any(Number) }, + }), + ]), + }, + signature: { status: "present" }, + }); + } finally { + await service.close(); + } + }); + it("reports non-file and malformed ELF selections as caller input errors", async () => { const root = await createTestTempDirectory("rea-kernel-module-files-"); const path = join(root, "demo.ko"); diff --git a/tests/boundary/providers/nativeArtifactFinalization.test.ts b/tests/boundary/providers/nativeArtifactFinalization.test.ts index bb46122e7de..5bbcbbb5ad3 100644 --- a/tests/boundary/providers/nativeArtifactFinalization.test.ts +++ b/tests/boundary/providers/nativeArtifactFinalization.test.ts @@ -19,6 +19,7 @@ import { PeCertificatesProvider } from "../../../src/native/pe/PeCertificatesPro import { PeImportsProvider } from "../../../src/native/pe/PeImportsProvider.js"; import { elfNoteFixture } from "../../../src/native/elf/ElfNotes.fixture.js"; import { ElfNotesProvider } from "../../../src/native/elf/ElfNotesProvider.js"; +import { kernelModuleFixture } from "../../../src/native/elf/KernelModule.fixture.js"; import { KernelModuleProvider } from "../../../src/native/elf/KernelModuleProvider.js"; import { ElfDependenciesProvider } from "../../../src/native/elf/ElfDependenciesProvider.js"; import { NativeExportsProvider } from "../../../src/native/exports/NativeExportsProvider.js"; @@ -84,6 +85,7 @@ const cases = [ }, { name: "kernel modules", + fixture: kernelModuleFixture, make: () => { const provider = new KernelModuleProvider(); return {