feat(native)!: give the native structural decoding allowance a per-call max_structure_bytes (#14626)

* feat(native)!: give the native structural decoding allowance a per-call max_structure_bytes

The 16 MiB structural budget on native header, section, load-command and
ELF dynamic-directory table reads, and on decoded section names, was a
fixed ceiling with no override. inspect_elf_unwind_ranges,
inspect_kernel_module, inspect_elf_debug_link, inspect_dwarf_units,
inspect_binary_hardening and inspect_native_initializers now accept
max_structure_bytes (64 bytes to 512 MiB, default 16 MiB) and report
details.limit when it stops them.

binaryContainer owns the default, the limit name and the failure
(nativeStructureFailure); the directory readers take a
NativeDirectoryBudgets object in place of the positional decoded-name
budget, and Mach-O, the ELF dynamic directory and the ELF pointer
relocation pass take the same budget. Other allowances that shared the
"structure" limit name now carry their own: the PE per-name decode, the
retained DWARF section bound (derived from the admitted image), and the
hardening table-entry count. The ELF dependency provider's structural
projection was unreachable and is removed.

Part of #14235.

BREAKING CHANGE: refusals at the structural budget report
reported_limits.boundary "max_structure_bytes" instead of "structure".

* fix(native): apply max_structure_bytes to the ELF hardening dynamic table and scope its help

inspect_binary_hardening read PT_DYNAMIC under its entry count only, so a sectionless ELF could exceed the selected max_structure_bytes; the dynamic table is now checked first. The shared help no longer names tables a reader does not bound, and the limits reference states hardening's Mach-O and PE coverage. The initializer CLI recovery test asserts a parsed successful report.

* fix(native): refuse a partial ELF hardening dynamic table as malformed before its budget
This commit is contained in:
morluto authored and GitHub committed 2026-11-25 22:04:06 -05:00
1 parent 4f66985978
commit e540cbdafd
43 files changed
+603 -252

No files matched your search

+3 -1
View File
@@ -268,7 +268,9 @@ without restarting REA. The original complete artifact and its identity are
preserved. An unchanged retry cannot increase a deterministic allowance.
The shared native container reader separately bounds structural table decoding
to 16 MiB. None of these Go controls changes that boundary. Inline strings must
to 16 MiB, the default of `max_structure_bytes` on the static native readers.
`inspect_go_binary` has no such control, and none of these Go controls changes
that boundary. Inline strings must
also fit their actual mapped source range. Identical search spans with the same
virtual alignment are searched once; partially overlapping spans consume the
cumulative search budget. Oversized complete reports fail without partial
+20
View File
@@ -101,6 +101,26 @@ accepts `max_native_index_bytes` (default 1 GiB) for the estimated ELF pointer
index of `binary_path`; its refusal reports the same kind of limit. See
[IL2CPP metadata](../il2cpp-metadata.md#native-method-addresses).
### Native table structure budget
`inspect_elf_unwind_ranges`, `inspect_kernel_module`, `inspect_elf_debug_link`,
`inspect_dwarf_units`, `inspect_binary_hardening` and
`inspect_native_initializers` accept `max_structure_bytes` (CLI
`--max-structure-bytes`, 64 bytes to 512 MiB, default 16 MiB). It bounds one
header, section, load-command or ELF dynamic-directory table read, and,
separately, the section names decoded from the section-name table, before the
decoded records are allocated. A refusal is a `memory` resource constraint
whose `details.limit` names `max_structure_bytes`, its effective value, range
and default; `details.reported_limits.boundary` is `max_structure_bytes`.
`max_file_bytes` does not raise it. `inspect_elf_debug_link` still counts
decoded section names against `max_file_bytes` as well. For `inspect_binary_hardening` it
covers the ELF header tables, section names and dynamic table; Mach-O load
commands keep the Mach-O command reader's own limit, and the PE headers it reads
are bounded by the PE format.
The Go, Rust and IL2CPP readers and `inspect_native_exports` read the same
tables with the 16 MiB default and report it as a fixed allowance.
### Static reader read allowance
`inspect_pe_imports`, `inspect_pe_resources`, `inspect_pe_load_config`,
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "c2417cfbfd1a4976",
"input compact": "dd9984f2fafaf1c9",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "2a73dbbb4bbaef8b",
"input compact": "3ab333428b5133c4",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "7cfc4e2a07bf4fff",
"input compact": "0b9ed6b14ffac536",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "9a9a8438a4b6e9f0",
"input compact": "eb43cfe89670b28c",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "9f3ed49a3c380bd6",
"input compact": "ca891ab3a866f2ad",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
@@ -1,6 +1,6 @@
{
"schemas": {
"input compact": "546bf32e9f7eb381",
"input compact": "05b6c37dc36da5cd",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
+8 -28
View File
@@ -256,10 +256,14 @@
}
},
"src/native/dwarf/DwarfUnitsProvider.ts": {
"\"The native structural decoding allowance\"": {
"\"The PE section-name decoding allowance\"": {
"class": "pending",
"issue": 14235,
"reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control."
"reason": "The 65,536-byte per-name COFF string-table decode is a resource policy; the aggregate is max_structure_bytes."
},
"\"The retained DWARF section bound\"": {
"class": "derived",
"reason": "Retained file-backed sections cannot exceed the admitted image size; the bound is the selected file and grows with it."
},
"DWARF_DECOMPRESSED_SECTION_ALLOWANCE": {
"class": "pending",
@@ -268,11 +272,6 @@
}
},
"src/native/elf/ElfDebugLinkProvider.ts": {
"\"The ELF structural decoding allowance\"": {
"class": "pending",
"issue": 14235,
"reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control."
},
"\"The whole-file debug candidate read allowance\"": {
"class": "pending",
"issue": 14235,
@@ -285,11 +284,6 @@
}
},
"src/native/elf/ElfDependenciesProvider.ts": {
"\"The ELF structural decoding allowance\"": {
"class": "pending",
"issue": 14235,
"reason": "ELF dependency entry allowances are resource policies; the text budget is derived from the admitted image length."
},
"text ? \"The ELF dependency text budget fixed by the admitted image length\" : `The ELF dependency ${limit.name} allowance`": {
"class": "pending",
"issue": 14235,
@@ -303,20 +297,6 @@
"reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control."
}
},
"src/native/elf/ElfUnwindRangesProvider.ts": {
"\"The ELF structural decoding allowance\"": {
"class": "pending",
"issue": 14235,
"reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control."
}
},
"src/native/elf/KernelModuleProvider.ts": {
"\"The ELF structural decoding allowance\"": {
"class": "pending",
"issue": 14235,
"reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control."
}
},
"src/native/exports/NativeExportsProvider.ts": {
"\"The native export inventory allowance\"": {
"class": "pending",
@@ -335,10 +315,10 @@
}
},
"src/native/hardening/BinaryHardeningProvider.ts": {
"\"The binary hardening structural allowance\"": {
"\"The binary hardening table-entry allowance\"": {
"class": "pending",
"issue": 14235,
"reason": "Native reader structural, text and inventory allowances are resource policies without a per-call control."
"reason": "The ELF dynamic table entry count is a resource policy; symbol-table excess already degrades to unresolved rows."
}
},
"src/native/initializers/NativeInitializersProvider.ts": {
+12 -3
View File
@@ -13,6 +13,7 @@ import {
} from "./machoSegmentHeader.js";
import {
declaredFileRange,
DEFAULT_NATIVE_STRUCTURE_BYTES,
requireBinaryTableBudget,
BinaryFormatFailure,
BinaryReader,
@@ -30,12 +31,14 @@ import { readByteSourceSlice, type ByteSource } from "../byteSource.js";
/** Read thin Mach-O images, retaining the slice's exact file-backed mappings. */
export const readMachoImage = (
bytes: Buffer,
structureBytes: number = DEFAULT_NATIVE_STRUCTURE_BYTES,
): Extract<BinaryContainer, { format: "macho" }> =>
readMachoImageCore(bytes, bytes.length);
readMachoImageCore(bytes, bytes.length, structureBytes);
/** Same thin Mach-O header and section read over a random-access source without buffering the full image. */
export const readMachoImageFromReader = async (
source: ByteSource,
structureBytes: number = DEFAULT_NATIVE_STRUCTURE_BYTES,
): Promise<Extract<BinaryContainer, { format: "macho" }>> => {
const headerPrefix = await readByteSourceSlice(
source,
@@ -58,18 +61,23 @@ export const readMachoImageFromReader = async (
offset: table.headerSize,
},
);
requireBinaryTableBudget(BigInt(table.commandBytes), "Mach-O load commands");
requireBinaryTableBudget(
BigInt(table.commandBytes),
"Mach-O load commands",
structureBytes,
);
const tableBytes = await readByteSourceSlice(
source,
0,
table.headerSize + table.commandBytes,
);
return readMachoImageCore(tableBytes, source.size);
return readMachoImageCore(tableBytes, source.size, structureBytes);
};
const readMachoImageCore = (
bytes: Buffer,
fileBytes: number,
structureBytes: number,
): Extract<BinaryContainer, { format: "macho" }> => {
const parsed = readMachoLoadCommandDeclarations(bytes, fileBytes);
if (!parsed.ok) throw new BinaryFormatFailure("malformed", parsed.error);
@@ -95,6 +103,7 @@ const readMachoImageCore = (
commandBytes,
1,
"Mach-O load commands",
structureBytes,
);
const mappings: FileMapping[] = [];
const loadRegions: LoadRegion[] = [];
+53 -13
View File
@@ -96,17 +96,53 @@ export class BinaryResourceFailure extends ParseFailureError<"limit"> {
message: string,
allowance: string = boundary,
readonly unit?: "bytes" | "entries",
required?: number | bigint,
) {
super({
kind: "limit",
format: "native-binary",
detail: message,
limit: { name: allowance, maximum: maximum_bytes },
limit: {
name: allowance,
maximum: maximum_bytes,
...(required === undefined ? {} : { required }),
},
});
this.name = "BinaryResourceFailure";
}
}
/**
* `max_structure_bytes` when omitted: the bytes of one native directory or
* load-command table read, and of the section names decoded from it.
*/
export const DEFAULT_NATIVE_STRUCTURE_BYTES = 16 * 1024 * 1024;
/** Limit name a `BinaryResourceFailure` carries for `max_structure_bytes`. */
export const NATIVE_STRUCTURE_LIMIT = "max_structure_bytes";
/** A native table read or decoded section-name set above `max_structure_bytes`. */
export const nativeStructureFailure = (
what: string,
requiredBytes: bigint | number,
maximumBytes: number,
): BinaryResourceFailure =>
new BinaryResourceFailure(
"structure",
maximumBytes,
`${what} requires ${String(requiredBytes)} bytes, above max_structure_bytes (${String(maximumBytes)})`,
NATIVE_STRUCTURE_LIMIT,
"bytes",
requiredBytes,
);
/** Whether a resource failure stopped at `max_structure_bytes`. */
export const isNativeStructureFailure = (
cause: unknown,
): cause is BinaryResourceFailure =>
cause instanceof BinaryResourceFailure &&
cause.failure.limit.name === NATIVE_STRUCTURE_LIMIT;
/** The exceeded maximum as fixed-ceiling facts; the unit only when its producer named it. */
export const binaryResourceCeiling = (
failure: BinaryResourceFailure,
@@ -459,10 +495,16 @@ export class BinaryReader {
return result;
}
table(offset: bigint, count: number, width: number, label: string): number {
table(
offset: bigint,
count: number,
width: number,
label: string,
structureBytes: number = DEFAULT_NATIVE_STRUCTURE_BYTES,
): number {
const size = BigInt(count) * BigInt(width);
const range = this.fileRange(offset, size, label);
requireBinaryTableBudget(size, label);
requireBinaryTableBudget(size, label, structureBytes);
return range.offset;
}
}
@@ -483,16 +525,14 @@ export const createBinaryReaderCache = (little: boolean, format: string) => {
};
};
/** Reject oversized structural tables before reading their bytes. */
export const requireBinaryTableBudget = (size: bigint, label: string): void => {
if (size > 16n * 1024n * 1024n)
throw new BinaryResourceFailure(
"structure",
16 * 1024 * 1024,
`${label} exceeds the 16 MiB structural decoding budget`,
"structure",
"bytes",
);
/** Reject a structural table above `max_structure_bytes` before reading its bytes. */
export const requireBinaryTableBudget = (
size: bigint,
label: string,
structureBytes: number = DEFAULT_NATIVE_STRUCTURE_BYTES,
): void => {
if (size > BigInt(structureBytes))
throw nativeStructureFailure(label, size, structureBytes);
};
/** Admit a declared file span, or mark it unbacked when it leaves the file. */
+8 -3
View File
@@ -1,4 +1,7 @@
import { BinaryReader } from "./binaryContainer.js";
import {
BinaryReader,
DEFAULT_NATIVE_STRUCTURE_BYTES,
} from "./binaryContainer.js";
import { err, ok, type Result } from "./result.js";
export const DT_NEEDED = 1n;
@@ -27,12 +30,14 @@ export const admitElfDynamicDirectory = (
fileBytes: number,
span: { readonly offset: bigint; readonly size: bigint },
bits: 32 | 64,
maximum: number = DEFAULT_NATIVE_STRUCTURE_BYTES,
): Result<
{ readonly offset: number; readonly size: number; readonly width: number },
| { readonly kind: "malformed"; readonly message: string }
| {
readonly kind: "capacity";
readonly message: string;
readonly size: number;
readonly maximum: number;
}
> => {
@@ -50,11 +55,11 @@ export const admitElfDynamicDirectory = (
const size = Number(span.size);
const { width, trailingBytes } = elfDynamicTableGeometry(size, bits);
if (trailingBytes !== 0) return malformed();
const maximum = 16 * 1024 * 1024;
if (size > maximum)
return err({
kind: "capacity",
message: "ELF dynamic directory exceeds the 16 MiB structural allowance",
message: `ELF dynamic directory requires ${String(size)} bytes, above the ${String(maximum)}-byte structural allowance`,
size,
maximum,
});
return ok({ offset: Number(span.offset), size, width });
+2
View File
@@ -7,6 +7,7 @@ import {
} from "../binaryTargetTypes.js";
import { digestSchema } from "../digests.js";
import { absoluteLocalPathStringSchema } from "../localPath.js";
import { maxStructureBytesSchema } from "./nativeStructureBudget.js";
/** Hard ceiling on the caller-selected input read budget. */
export const MAX_INSPECT_BINARY_HARDENING_FILE_BYTES = 536870912;
@@ -26,6 +27,7 @@ export const inspectBinaryHardeningInputSchema = z.strictObject({
path: absoluteLocalPathStringSchema.describe(
"Absolute filesystem path to an ELF, PE, or Mach-O image",
),
max_structure_bytes: maxStructureBytesSchema,
max_file_bytes: z
.number()
.int()
+2
View File
@@ -14,6 +14,7 @@ import {
absoluteLocalPathStringSchema,
localPathStringSchema,
} from "../localPath.js";
import { maxStructureBytesSchema } from "./nativeStructureBudget.js";
/** Hard ceiling on the caller-selected input read budget. */
export const MAX_INSPECT_DWARF_UNITS_FILE_BYTES = 536870912;
@@ -236,6 +237,7 @@ export const inspectDwarfUnitsInputSchema = z.strictObject({
path: absoluteLocalPathStringSchema.describe(
"Absolute filesystem path to an ELF, Mach-O, or PE image",
),
max_structure_bytes: maxStructureBytesSchema,
max_file_bytes: z
.number()
.int()
+2
View File
@@ -9,6 +9,7 @@ import {
MINIMUM_ELF_READ_FILE_BYTES,
type ElfReadBudgets,
} from "./elfReadBudgets.js";
import { maxStructureBytesSchema } from "./nativeStructureBudget.js";
const uint = z.number().int().min(0).max(0xffffffff);
const crc32Hex = z.string().regex(/^[0-9a-f]{8}$/u);
@@ -219,6 +220,7 @@ export const inspectElfDebugLinkInputSchema = z.strictObject({
.describe(
"Optional absolute path of one caller-selected file to verify against the debuglink CRC32 and GNU build-id",
),
max_structure_bytes: maxStructureBytesSchema,
max_file_bytes: z
.number()
.int()
+7 -16
View File
@@ -17,6 +17,7 @@ import {
type ElfSectionDirectory,
} from "./nativeSectionDirectory.js";
import { bufferByteSource, type ByteSource } from "../byteSource.js";
import type { NativeDirectoryBudgets } from "./nativeStructureBudget.js";
type ElfSection = Extract<ImageSection, { format: "elf" }>;
@@ -200,15 +201,11 @@ export const architectureForElfMachine = (machine: number): string => {
export const readElfImage = (
bytes: Buffer,
operation: string,
maximumSourceAndDecodedNamesBytes?: number,
budgets?: NativeDirectoryBudgets,
): Extract<BinaryContainer, { format: "elf" }> =>
readElfImageFromDirectory(
bytes,
readElfDirectoryFromBuffer(
bytes,
operation,
maximumSourceAndDecodedNamesBytes,
),
readElfDirectoryFromBuffer(bytes, operation, budgets),
);
/** Same image as {@link readElfImage}. Section names yield through `pause`. */
@@ -216,14 +213,14 @@ export const readElfImageCooperative = async (
bytes: Buffer,
operation: string,
pause: ZstandardFramePause,
maximumSourceAndDecodedNamesBytes?: number,
budgets?: NativeDirectoryBudgets,
decode?: CooperativeElfSectionNameDecoder,
): Promise<Extract<BinaryContainer, { format: "elf" }>> =>
readElfImageFromReader(
bufferByteSource(bytes),
operation,
pause,
maximumSourceAndDecodedNamesBytes,
budgets,
decode,
);
@@ -232,16 +229,10 @@ export const readElfImageFromReader = async (
source: ByteSource,
operation: string,
pause: ZstandardFramePause,
maximumSourceAndDecodedNamesBytes?: number,
budgets?: NativeDirectoryBudgets,
decode?: CooperativeElfSectionNameDecoder,
): Promise<Extract<BinaryContainer, { format: "elf" }>> =>
readElfImageFromDirectorySize(
source.size,
await readElfDirectoryFromReader(
source,
pause,
operation,
maximumSourceAndDecodedNamesBytes,
decode,
),
await readElfDirectoryFromReader(source, pause, operation, budgets, decode),
);
+19 -1
View File
@@ -24,6 +24,7 @@ import {
BinaryReader,
createFileMappingIndex,
isZeroFilledSpan,
nativeStructureFailure,
type ElfDynamicSegment,
} from "../binaryContainer.js";
import { ParseFailureError } from "../parseFailure.js";
@@ -138,6 +139,12 @@ export interface ElfPointerRelocationInput {
>[];
readonly mappings: readonly FileMapping[];
readonly zeroFills: readonly ZeroFillMapping[];
/**
* The caller's `max_structure_bytes` for the dynamic directory. A caller
* that owns that control passes it and receives its failure; the IL2CPP
* and JNI loaders omit it and keep their native-index-capacity failure.
*/
readonly structureBytes?: number | undefined;
}
// JNI sparse consumers retain per-write provenance; streaming materializers do not.
@@ -527,9 +534,20 @@ function* dynamicTags(
const declaration = input.dynamicSegments[0];
if (declaration === undefined)
return { values: new Map(), ambiguous: new Set() };
const table = admitElfDynamicDirectory(bytes.length, declaration, input.bits);
const table = admitElfDynamicDirectory(
bytes.length,
declaration,
input.bits,
input.structureBytes,
);
if (!table.ok) {
if (table.error.kind === "malformed") return malformed(table.error.message);
if (input.structureBytes !== undefined)
throw nativeStructureFailure(
"The ELF dynamic directory",
table.error.size,
table.error.maximum,
);
throw new ElfPointerRelocationFailure(
"native-index-capacity",
table.error.message,
+2
View File
@@ -4,6 +4,7 @@ import { knownCoverageStatusSchema } from "../coverage.js";
import { digestSchema } from "../digests.js";
import { absoluteLocalPathStringSchema } from "../localPath.js";
import { ELF_OBJECT_TYPE_NAMES } from "./elfNotes.js";
import { maxStructureBytesSchema } from "./nativeStructureBudget.js";
const uint = z.number().int().min(0).max(0xffffffff);
const hexAddress = z.string().regex(/^0x[0-9a-f]+$/u);
@@ -120,6 +121,7 @@ export const inspectElfUnwindRangesInputSchema = z.strictObject({
path: absoluteLocalPathStringSchema.describe(
"Absolute filesystem path to an ELF image",
),
max_structure_bytes: maxStructureBytesSchema,
max_file_bytes: z
.number()
.int()
+2
View File
@@ -7,6 +7,7 @@ import { digestSchema } from "../digests.js";
import { fixedTupleSchema } from "../fixedTupleSchema.js";
import { absoluteLocalPathStringSchema } from "../localPath.js";
import { ELF_OBJECT_TYPE_NAMES } from "./elfNotes.js";
import { maxStructureBytesSchema } from "./nativeStructureBudget.js";
const uint = z.number().int().min(0).max(0xffffffff);
const uint8 = z.number().int().min(0).max(255);
@@ -229,6 +230,7 @@ export const inspectKernelModuleInputSchema = z.strictObject({
path: absoluteLocalPathStringSchema.describe(
"Absolute filesystem path to an ELF kernel module or a compressed .ko container",
),
max_structure_bytes: maxStructureBytesSchema,
max_file_bytes: z
.number()
.int()
+2
View File
@@ -8,6 +8,7 @@ import {
} from "../binaryTargetTypes.js";
import { digestSchema } from "../digests.js";
import { absoluteLocalPathStringSchema } from "../localPath.js";
import { maxStructureBytesSchema } from "./nativeStructureBudget.js";
/** Hard ceiling on the caller-selected input read budget. */
export const MAX_INSPECT_NATIVE_INITIALIZERS_FILE_BYTES = 536870912;
@@ -67,6 +68,7 @@ export const inspectNativeInitializersInputSchema = z.strictObject({
path: absoluteLocalPathStringSchema.describe(
"Absolute filesystem path to an ELF or Mach-O image",
),
max_structure_bytes: maxStructureBytesSchema,
max_file_bytes: z
.number()
.int()
+38 -44
View File
@@ -23,8 +23,9 @@ import { readPeOptionalHeaderStructure } from "../peOptionalHeader.js";
import {
BinaryFormatFailure,
BinaryReader,
BinaryResourceFailure,
DEFAULT_NATIVE_STRUCTURE_BYTES,
declaredFileRange,
nativeStructureFailure,
type ElfDynamicSegment,
} from "../binaryContainer.js";
import {
@@ -41,6 +42,7 @@ import {
ZstandardFrameAllowanceError,
} from "../compression/zstandardFrameAllowance.js";
import { bufferByteSource, type ByteSource } from "../byteSource.js";
import type { NativeDirectoryBudgets } from "./nativeStructureBudget.js";
/** A borrowed positional source. Drivers own admission, cancellation and file identity. */
export interface NativeReadRequest {
@@ -123,7 +125,6 @@ export type ElfSectionDirectory = NativeSectionDirectory & {
readonly elf_type: number;
};
const STRUCTURE_BYTES = 16 * 1024 * 1024;
const reject = (message: string): never => {
throw new BinaryFormatFailure("malformed", message);
};
@@ -139,10 +140,11 @@ const exact = (value: bigint): number => {
reject("Native offset exceeds exact host precision");
return Number(value);
};
const request = (
const directoryRequest = (
fileSize: number,
offset: bigint,
size: bigint,
structureBytes: number,
): NativeReadRequest => {
if (
offset < 0n ||
@@ -151,13 +153,11 @@ const request = (
size > BigInt(fileSize) - offset
)
reject("Native directory range is truncated or outside the file");
if (size > BigInt(STRUCTURE_BYTES))
throw new BinaryResourceFailure(
"structure",
STRUCTURE_BYTES,
"Native directory exceeds the 16777216-byte (16 MiB) structural decoding budget. This release has no runtime override.",
"structure",
"bytes",
if (size > BigInt(structureBytes))
throw nativeStructureFailure(
"A native directory read",
size,
structureBytes,
);
return { offset: exact(offset), size: exact(size) };
};
@@ -165,8 +165,13 @@ const request = (
/** One ELF interpretation for in-memory images and bounded descriptor-backed inspections. */
export function* readElfSectionDirectory(
fileSize: number,
maximumSourceAndDecodedNamesBytes?: number,
budgets: NativeDirectoryBudgets = {},
): Generator<NativeReadRequest, ElfSectionDirectory, Buffer> {
const structureBytes =
budgets.structureBytes ?? DEFAULT_NATIVE_STRUCTURE_BYTES;
const maximumSourceAndDecodedNamesBytes = budgets.sourceAndDecodedNamesBytes;
const request = (fileSize: number, offset: bigint, size: bigint) =>
directoryRequest(fileSize, offset, size, structureBytes);
const prefix = yield request(fileSize, 0n, 16n);
const headerSize = elfFixedHeaderWidth(prefix[4] === 1 ? 32 : 64);
const bytes = yield request(fileSize, 0n, BigInt(headerSize));
@@ -194,7 +199,7 @@ export function* readElfSectionDirectory(
BigInt(program_count) * BigInt(program_width),
);
// At most one record per table entry, bounded before allocation by the
// existing 16 MiB table allowance and minimum 32/56-byte ELF record width.
// max_structure_bytes table allowance and minimum 32/56-byte ELF record width.
for (let index = 0; index < program_count; index++) {
const at = index * program_width;
const parsedProgram = readElfProgramHeader(
@@ -264,10 +269,7 @@ export function* readElfSectionDirectory(
namesSection.size,
);
const rawNames = yield namesRange;
const structuralRemaining = Math.max(
0,
STRUCTURE_BYTES - rawNames.length,
);
const structuralRemaining = Math.max(0, structureBytes - rawNames.length);
const callerRemaining =
maximumSourceAndDecodedNamesBytes === undefined
? structuralRemaining
@@ -307,12 +309,10 @@ export function* readElfSectionDirectory(
maximumSourceAndDecodedNamesBytes,
);
if (admitted.state === "limit")
throw new BinaryResourceFailure(
"structure",
STRUCTURE_BYTES,
`Decoded ELF section names require ${String(admitted.requiredBytes)} bytes, above the ${String(structuralRemaining)}-byte remaining structural budget`,
"structure",
"bytes",
throw nativeStructureFailure(
"The ELF section-name table and its decoded names",
BigInt(rawNames.length) + admitted.requiredBytes,
structureBytes,
);
if (admitted.state === "unsupported")
section_names_limitation = `ELF section names are unavailable because compression type ${String(admitted.compressionType)} is unsupported`;
@@ -343,13 +343,11 @@ export function* readElfSectionDirectory(
if (decoded === undefined) {
const observed = observeElfStringTableEntry(names, nameOffset, 65536);
nameBytes += observed.examinedBytes;
if (nameBytes > STRUCTURE_BYTES)
throw new BinaryResourceFailure(
"structure",
STRUCTURE_BYTES,
"Decoded ELF section names exceed the 16 MiB structural budget",
"structure",
"bytes",
if (nameBytes > structureBytes)
throw nativeStructureFailure(
"Decoded ELF section names",
nameBytes,
structureBytes,
);
decoded = {
name: elfStringTableText(observed),
@@ -411,7 +409,10 @@ export function* readElfSectionDirectory(
export function* readPeSectionDirectory(
fileSize: number,
structureBytes: number = DEFAULT_NATIVE_STRUCTURE_BYTES,
): Generator<NativeReadRequest, NativeSectionDirectory, Buffer> {
const request = (fileSize: number, offset: bigint, size: bigint) =>
directoryRequest(fileSize, offset, size, structureBytes);
const dos = new BinaryReader(yield request(fileSize, 0n, 64n), true, "pe");
if (dos.u16(0) !== 0x5a4d) reject("Missing DOS MZ header");
const evidence = parseMzHeaderEvidence(dos.bytes, fileSize);
@@ -563,12 +564,12 @@ const projectDirectoryFrameAllowance = (
export const readElfDirectoryFromBuffer = (
bytes: Buffer,
operation: string,
maximumSourceAndDecodedNamesBytes?: number,
budgets?: NativeDirectoryBudgets,
): ElfSectionDirectory => {
try {
return driveFromBuffer(
bytes,
readElfSectionDirectory(bytes.length, maximumSourceAndDecodedNamesBytes),
readElfSectionDirectory(bytes.length, budgets),
);
} catch (cause) {
return projectDirectoryFrameAllowance(operation, cause);
@@ -583,26 +584,23 @@ export const readElfDirectoryFromBufferCooperative = async (
bytes: Buffer,
pause: ZstandardFramePause,
operation: string,
maximumSourceAndDecodedNamesBytes?: number,
budgets?: NativeDirectoryBudgets,
decode?: CooperativeElfSectionNameDecoder,
): Promise<ElfSectionDirectory> =>
readElfDirectoryFromReader(
bufferByteSource(bytes),
pause,
operation,
maximumSourceAndDecodedNamesBytes,
budgets,
decode,
);
const driveElfDirectoryFromSource = async (
source: ByteSource,
decode: CooperativeElfSectionNameDecoder,
maximumSourceAndDecodedNamesBytes?: number,
budgets?: NativeDirectoryBudgets,
): Promise<ElfSectionDirectory> => {
const steps = readElfSectionDirectory(
source.size,
maximumSourceAndDecodedNamesBytes,
);
const steps = readElfSectionDirectory(source.size, budgets);
let next = steps.next();
while (!next.done) {
const step = next.value;
@@ -634,16 +632,12 @@ export const readElfDirectoryFromReader = async (
source: ByteSource,
pause: ZstandardFramePause,
operation: string,
maximumSourceAndDecodedNamesBytes?: number,
budgets?: NativeDirectoryBudgets,
decode: CooperativeElfSectionNameDecoder = (request) =>
decodeElfSectionNameRequestCooperative(request, pause),
): Promise<ElfSectionDirectory> => {
try {
return await driveElfDirectoryFromSource(
source,
decode,
maximumSourceAndDecodedNamesBytes,
);
return await driveElfDirectoryFromSource(source, decode, budgets);
} catch (cause) {
return projectDirectoryFrameAllowance(operation, cause);
}
@@ -0,0 +1,59 @@
import { z } from "zod";
import type { AnalysisParameterLimit } from "../analysisSettings.js";
import {
DEFAULT_NATIVE_STRUCTURE_BYTES,
NATIVE_STRUCTURE_LIMIT,
} from "../binaryContainer.js";
/**
* `max_structure_bytes`: the bytes of one native table read (ELF program and
* section header tables, the ELF section-name table, the PE headers and
* section table, Mach-O load commands, the ELF dynamic directory) and,
* separately, of the section names decoded from it. Decoded records are
* proportional to the table bytes, so the budget bounds that representation
* before it is allocated.
*/
export const NATIVE_STRUCTURE_BYTES = {
/** An ELF64 file header. */
minimum: 64,
maximum: 512 * 1024 * 1024,
default_value: DEFAULT_NATIVE_STRUCTURE_BYTES,
} as const;
/** The optional per-call field every native reader that decodes these tables accepts. */
export const maxStructureBytesSchema = z
.number()
.int()
.min(NATIVE_STRUCTURE_BYTES.minimum)
.max(NATIVE_STRUCTURE_BYTES.maximum)
.optional()
.describe(
"Maximum bytes of one native header, section or load-command table this reader decodes, and of the section names decoded from it (default 16 MiB)",
);
/** Caller-selected native directory budgets; omitted fields keep their defaults. */
export interface NativeDirectoryBudgets {
/** `max_structure_bytes`. */
readonly structureBytes?: number | undefined;
/**
* Source file bytes plus decoded section names, when the caller selected a
* combined `max_file_bytes` read budget for them.
*/
readonly sourceAndDecodedNamesBytes?: number | undefined;
}
/**
* The per-call control that stopped a native table read, named by its
* contract field; each adapter names the option that sets it.
*/
export const nativeStructureLimit = (
effectiveValue: number,
): AnalysisParameterLimit => ({
control_kind: "parameter",
parameter: NATIVE_STRUCTURE_LIMIT,
effective_value: effectiveValue,
unit: "bytes",
...NATIVE_STRUCTURE_BYTES,
applies_at: "next_call",
});
+36 -18
View File
@@ -14,6 +14,8 @@ import {
BinaryFormatFailure,
BinaryReader,
BinaryResourceFailure,
DEFAULT_NATIVE_STRUCTURE_BYTES,
nativeStructureFailure,
type ImageSection,
} from "../../domain/binaryContainer.js";
import {
@@ -45,7 +47,10 @@ const MACHO_DWARF_SEGMENT = "__DWARF,";
const MACHO_ZERO_FILL_TYPES = new Set([0x1, 0xc, 0x12]);
const SPLIT_DEBUG_INFO = ".debug_info.dwo";
export const MAX_PE_SECTION_NAME_BYTES = 65536;
export const MAX_PE_DECODED_NAME_BYTES = 16 * 1024 * 1024;
/** Limit name of the per-name COFF string-table decode allowance. */
export const PE_SECTION_NAME_LIMIT = "pe-section-name-bytes";
/** Limit name of the retained-section bound: at most the admitted image size. */
export const DWARF_RETAINED_SECTIONS_LIMIT = "retained-dwarf-section-bytes";
const DUPLICATE_SECTION =
"Duplicate section; the first file-backed copy was read";
@@ -165,7 +170,7 @@ const storedDwarfSections = (source: ByteSource) => {
"structure",
source.size,
"Retained file-backed DWARF sections would exceed the admitted image size.",
"structure",
DWARF_RETAINED_SECTIONS_LIMIT,
"bytes",
);
const bytes = await readSourceSlice(source, offset, size);
@@ -180,8 +185,13 @@ export const locateDwarfSectionsFromHandle = async (
source: ByteSource,
maximumDecodedBytes = MAX_DWARF_DECOMPRESSED_SECTION_BYTES,
pause?: ZstandardFramePause,
structureBytes = DEFAULT_NATIVE_STRUCTURE_BYTES,
): Promise<LocatedDwarfImage> => {
const budget: InflateBudget = { allowance: maximumDecodedBytes, used: 0 };
const budget: InflateBudget = {
allowance: maximumDecodedBytes,
used: 0,
structureBytes,
};
const magic = await readSourceSlice(source, 0, Math.min(4, source.size));
if (hasElfMagic(magic)) return finish(await locateElf(source, budget, pause));
if (hasDosMzMagic(magic)) return finish(await locatePe(source, budget));
@@ -368,6 +378,8 @@ interface ImageIdentity {
interface InflateBudget {
readonly allowance: number;
used: number;
/** `max_structure_bytes` for the image's directory and decoded section names. */
readonly structureBytes: number;
}
/** One row per name and reason, so repeated sections cannot grow the report. */
@@ -478,6 +490,7 @@ const locateElf = async (
source,
pause ?? (() => Promise.resolve()),
"inspect_dwarf_units",
{ structureBytes: budget.structureBytes },
);
if (directory.section_names_limitation !== undefined)
throw new BinaryFormatFailure(
@@ -630,8 +643,8 @@ const locatePe = async (
source: ByteSource,
budget: InflateBudget,
): Promise<ImageIdentity> => {
const directory = await readPeDirectory(source);
const names = await peSectionNames(source, directory);
const directory = await readPeDirectory(source, budget.structureBytes);
const names = await peSectionNames(source, directory, budget.structureBytes);
const candidates: Candidate[] = [];
const satisfied = new Set<DwarfSectionRole>();
const readStored = storedDwarfSections(source);
@@ -676,8 +689,8 @@ const locatePe = async (
};
};
const readPeDirectory = async (source: ByteSource) => {
const steps = readPeSectionDirectory(source.size);
const readPeDirectory = async (source: ByteSource, structureBytes: number) => {
const steps = readPeSectionDirectory(source.size, structureBytes);
let next = steps.next();
while (!next.done) {
const { offset, size } = next.value;
@@ -690,6 +703,7 @@ const readPeDirectory = async (source: ByteSource) => {
const peSectionNames = async (
source: ByteSource,
directory: NativeSectionDirectory,
structureBytes: number,
): Promise<ReadonlyMap<number, string>> => {
const { sections } = directory;
const names = new Map<number, string>();
@@ -757,7 +771,7 @@ const peSectionNames = async (
}
// Reserve two bytes per character before allocating a JavaScript string.
const remainingCharacters = Math.floor(
(MAX_PE_DECODED_NAME_BYTES - decodedNameBytes) / 2,
(structureBytes - decodedNameBytes) / 2,
);
const maximumCharacters = Math.min(
MAX_PE_SECTION_NAME_BYTES,
@@ -766,15 +780,19 @@ const peSectionNames = async (
const end = Math.min(strings.length, at + maximumCharacters + 1);
const relativeNul = strings.subarray(at, end).indexOf(0);
if (relativeNul < 0 && end - at > maximumCharacters)
throw new BinaryResourceFailure(
"structure",
remainingCharacters < MAX_PE_SECTION_NAME_BYTES
? MAX_PE_DECODED_NAME_BYTES
: MAX_PE_SECTION_NAME_BYTES,
remainingCharacters < MAX_PE_SECTION_NAME_BYTES
? "Decoded PE section names exceed the 16 MiB structural budget"
: "PE section name exceeds the 65536-byte decoding allowance",
);
throw remainingCharacters < MAX_PE_SECTION_NAME_BYTES
? nativeStructureFailure(
"Decoded PE section names",
decodedNameBytes + (end - at) * 2,
structureBytes,
)
: new BinaryResourceFailure(
"structure",
MAX_PE_SECTION_NAME_BYTES,
"PE section name exceeds the 65536-byte decoding allowance",
PE_SECTION_NAME_LIMIT,
"bytes",
);
const nul = relativeNul < 0 ? -1 : at + relativeNul;
if (nul < 0)
throw new BinaryFormatFailure(
@@ -793,7 +811,7 @@ const locateMacho = async (
source: ByteSource,
budget: InflateBudget,
): Promise<ImageIdentity> => {
const image = await readMachoImageFromReader(source);
const image = await readMachoImageFromReader(source, budget.structureBytes);
const candidates: Candidate[] = [];
const satisfied = new Set<DwarfSectionRole>();
const readStored = storedDwarfSections(source);
+32 -5
View File
@@ -9,7 +9,10 @@ import {
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { readMachoImageFromReader } from "../../domain/apple/machoImage.js";
import { BinaryResourceFailure } from "../../domain/binaryContainer.js";
import {
BinaryResourceFailure,
DEFAULT_NATIVE_STRUCTURE_BYTES,
} from "../../domain/binaryContainer.js";
import {
MAX_DWARF_DECOMPRESSED_SECTION_BYTES,
inspectDwarfUnitsInputSchema,
@@ -24,7 +27,6 @@ import { DwarfUnitsProvider } from "./DwarfUnitsProvider.js";
import {
DwarfSectionAllowanceFailure,
locateDwarfSectionsFromHandle,
MAX_PE_DECODED_NAME_BYTES,
MAX_PE_SECTION_NAME_BYTES,
} from "./DwarfSections.js";
import {
@@ -48,6 +50,7 @@ const inspect = async (
readonly architecture?: "x86" | "x86_64" | "arm" | "arm64";
readonly offset?: number;
readonly limit?: number;
readonly max_structure_bytes?: number;
} = {},
) => {
const root = await createTestTempDirectory("rea-dwarf-units-");
@@ -321,9 +324,10 @@ it("bounds individual PE long names before decoding", async () => {
expect(read.error).toBeInstanceOf(AnalysisResourceConstraintError);
expect(read.error).toMatchObject({
reportedLimits: {
boundary: "structure",
boundary: "pe-section-name-bytes",
maximum: MAX_PE_SECTION_NAME_BYTES,
},
fixedAllowance: { name: "The PE section-name decoding allowance" },
});
});
@@ -341,12 +345,35 @@ it("bounds aggregate PE name decoding for overlapping string-table offsets", asy
expect(read.error).toBeInstanceOf(AnalysisResourceConstraintError);
expect(read.error).toMatchObject({
reportedLimits: {
boundary: "structure",
maximum: MAX_PE_DECODED_NAME_BYTES,
boundary: "max_structure_bytes",
maximum: DEFAULT_NATIVE_STRUCTURE_BYTES,
},
limit: {
control_kind: "parameter",
parameter: "max_structure_bytes",
effective_value: DEFAULT_NATIVE_STRUCTURE_BYTES,
default_value: DEFAULT_NATIVE_STRUCTURE_BYTES,
maximum: 512 * 1024 * 1024,
applies_at: "next_call",
},
});
});
it("admits aggregate PE name decoding with a larger max_structure_bytes", async () => {
const read = await inspect(
peImage([
{ name: "x".repeat(65536), body: Buffer.alloc(0) },
...Array.from({ length: 299 }, (_, index) => ({
name: `/${String(index + 5)}`,
body: Buffer.alloc(0),
})),
]),
{ max_structure_bytes: 64 * 1024 * 1024 },
);
if (!read.ok) throw read.error;
expect(read.value.debug_info).toBe("absent");
});
it("rejects an unterminated PE long name within the decoding allowance", async () => {
const image = peImage([{ name: ".debug_info", body: Buffer.alloc(0) }]);
image[image.length - 1] = 120;
+17 -5
View File
@@ -27,12 +27,15 @@ import { err, ok } from "../../domain/result.js";
import {
binaryResourceCeiling,
BinaryResourceFailure,
isNativeStructureFailure,
} from "../../domain/binaryContainer.js";
import { nativeStructureConstraint } from "../nativeStructureConstraint.js";
import { requireSelectedNativeImageFromReader } from "../../domain/apple/machoSliceSelection.js";
import { parseDwarfCompileUnits } from "./DwarfUnitParser.js";
import {
DwarfSectionAllowanceFailure,
locateDwarfSectionsFromHandle,
PE_SECTION_NAME_LIMIT,
type DebugInfoAvailability,
type LocatedDwarfImage,
} from "./DwarfSections.js";
@@ -99,6 +102,7 @@ export class DwarfUnitsProvider {
async () => {
await yieldArtifactRead(options?.signal);
},
input.max_structure_bytes,
);
return dwarfUnitsSchema.parse(
buildReport(
@@ -282,16 +286,24 @@ const dwarfUnitsFailure = (
},
),
);
if (isNativeStructureFailure(failure))
return nativeStructureConstraint(OPERATION, failure);
if (failure instanceof BinaryResourceFailure)
return parseLimitConstraint(
OPERATION,
"memory",
failure,
fixedAllowanceOptions(
"The native structural decoding allowance",
"parser",
binaryResourceCeiling(failure),
),
failure.failure.limit.name === PE_SECTION_NAME_LIMIT
? fixedAllowanceOptions(
"The PE section-name decoding allowance",
"parser",
binaryResourceCeiling(failure),
)
: fixedAllowanceOptions(
"The retained DWARF section bound",
"parser",
binaryResourceCeiling(failure),
),
);
return undefined;
},
+12 -3
View File
@@ -15,6 +15,7 @@ import {
BinaryResourceFailure,
} from "../../domain/binaryContainer.js";
import { elfObjectTypeName } from "../../domain/native/elfNotes.js";
import type { NativeDirectoryBudgets } from "../../domain/native/nativeStructureBudget.js";
import {
zstandardFrameAllowanceCause,
type ZstandardFrameAllowanceError,
@@ -97,6 +98,14 @@ const isRethrownBudget = (cause: unknown): boolean =>
isParseLimit(cause, "elf-notes") ||
cause instanceof BinaryResourceFailure;
/** The caller's directory budgets: decoded section names count against max_file_bytes. */
const directoryBudgets = (
input: InspectElfDebugLinkInput,
): NativeDirectoryBudgets => ({
structureBytes: input.max_structure_bytes,
sourceAndDecodedNamesBytes: input.max_file_bytes,
});
interface LocatedSection {
readonly status: SectionStatus;
readonly location: { offset: number; bytes: number } | null;
@@ -668,7 +677,7 @@ const readCandidateIdentity = (
throw preparedImage.error;
image =
preparedImage?.value ??
readElfImage(content, ELF_DEBUG_LINK_OPERATION, input.max_file_bytes);
readElfImage(content, ELF_DEBUG_LINK_OPERATION, directoryBudgets(input));
} catch (cause) {
frameAllowance = zstandardFrameAllowanceCause(cause);
if (frameAllowance === undefined) {
@@ -940,7 +949,7 @@ export const parseElfDebugLinkFromHandle = async (
source,
ELF_DEBUG_LINK_OPERATION,
pause,
input.max_file_bytes,
directoryBudgets(input),
(request) => {
sectionNames = request;
return decode(request);
@@ -1025,7 +1034,7 @@ export const verifyElfDebugCandidateCooperative = async (
candidate.prefix,
ELF_DEBUG_LINK_OPERATION,
pause,
input.max_file_bytes,
directoryBudgets(input),
decode,
),
);
+4 -15
View File
@@ -33,10 +33,8 @@ import {
import { err, ok } from "../../domain/result.js";
import type { AnalysisPartialObservation } from "../../domain/analysisErrorBase.js";
import { ELF_DEBUG_LINK_PROVIDER } from "../../domain/investigationProviders.js";
import {
binaryResourceCeiling,
BinaryResourceFailure,
} from "../../domain/binaryContainer.js";
import { isNativeStructureFailure } from "../../domain/binaryContainer.js";
import { nativeStructureConstraint } from "../nativeStructureConstraint.js";
import {
continueGnuDebuglinkCrc32,
parseElfDebugLinkFromHandle,
@@ -362,17 +360,8 @@ const elfDebugLinkFailure = (
field,
),
});
if (failure instanceof BinaryResourceFailure)
return parseLimitConstraint(
OPERATION,
"memory",
failure,
fixedAllowanceOptions(
"The ELF structural decoding allowance",
"parser",
binaryResourceCeiling(failure),
),
);
if (isNativeStructureFailure(failure))
return nativeStructureConstraint(OPERATION, failure);
if (isParseLimit(failure, "elf-notes")) {
const entryBudget = failure.failure.limit.name === "max_entries";
return parseLimitConstraint(
-15
View File
@@ -26,10 +26,6 @@ import {
} from "../../domain/native/elfDependencies.js";
import { err, ok } from "../../domain/result.js";
import { ELF_DEPENDENCIES_PROVIDER } from "../../domain/investigationProviders.js";
import {
BinaryResourceFailure,
binaryResourceCeiling,
} from "../../domain/binaryContainer.js";
import { parseElfDependenciesFromHandle } from "./ElfDependencyParser.js";
const OPERATION = "inspect_elf_dependencies";
@@ -125,17 +121,6 @@ const elfDependenciesFailure = (
description: "ELF image",
fallbackMessage: "ELF dependency inspection failed.",
recognise: (failure) => {
if (failure instanceof BinaryResourceFailure)
return parseLimitConstraint(
OPERATION,
"memory",
failure,
fixedAllowanceOptions(
"The ELF structural decoding allowance",
"parser",
binaryResourceCeiling(failure),
),
);
if (isParseLimit(failure, "elf-dependencies")) {
const limit = failure.failure.limit;
const parameter = (
+4 -16
View File
@@ -14,7 +14,6 @@ import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
import { classifyProviderFailure } from "../../providers/classifyProviderFailure.js";
import { offlineArtifactFailureDialect } from "../../providers/offlineArtifactFailure.js";
import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js";
import {
MAX_INSPECT_ELF_UNWIND_FILE_BYTES,
MAX_INSPECT_ELF_UNWIND_RANGES,
@@ -23,10 +22,8 @@ import {
} from "../../domain/native/elfUnwindRanges.js";
import { err, ok } from "../../domain/result.js";
import { ELF_UNWIND_RANGES_PROVIDER } from "../../domain/investigationProviders.js";
import {
BinaryResourceFailure,
binaryResourceCeiling,
} from "../../domain/binaryContainer.js";
import { isNativeStructureFailure } from "../../domain/binaryContainer.js";
import { nativeStructureConstraint } from "../nativeStructureConstraint.js";
import {
ELF_UNWIND_FORMAT,
ELF_UNWIND_RECORD_LIMIT,
@@ -130,17 +127,8 @@ const elfUnwindFailure = (
: `Request a smaller limit than ${String(input.limit)}, or page with offset; the ${String(limit.maximum)}-byte symbol-name text allowance is fixed, and max_ranges and max_file_bytes do not raise it.`,
});
}
if (failure instanceof BinaryResourceFailure)
return parseLimitConstraint(
OPERATION,
"memory",
failure,
fixedAllowanceOptions(
"The ELF structural decoding allowance",
"parser",
binaryResourceCeiling(failure),
),
);
if (isNativeStructureFailure(failure))
return nativeStructureConstraint(OPERATION, failure);
return undefined;
},
fileSize: (failure) =>
+1
View File
@@ -277,6 +277,7 @@ export const parseElfUnwindRangesFromHandle = async (
source,
() => yieldArtifactRead(signal),
OPERATION,
{ structureBytes: input.max_structure_bytes },
);
const steps = elfUnwindRangesSteps(
source.size,
+1
View File
@@ -805,6 +805,7 @@ export const parseKernelModuleFromHandle = async (
source,
"inspect_kernel_module",
() => yieldArtifactRead(signal),
{ structureBytes: input.max_structure_bytes },
);
const facts = headerFacts(image);
if (facts.type !== 1) return notApplicable(artifact, facts);
+4 -16
View File
@@ -12,7 +12,6 @@ import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
import { classifyProviderFailure } from "../../providers/classifyProviderFailure.js";
import { offlineArtifactFailureDialect } from "../../providers/offlineArtifactFailure.js";
import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js";
import {
MAX_INSPECT_KERNEL_MODULE_ENTRIES,
MAX_INSPECT_KERNEL_MODULE_FILE_BYTES,
@@ -21,10 +20,8 @@ import {
} from "../../domain/native/kernelModule.js";
import { err, ok } from "../../domain/result.js";
import { KERNEL_MODULE_PROVIDER } from "../../domain/investigationProviders.js";
import {
BinaryResourceFailure,
binaryResourceCeiling,
} from "../../domain/binaryContainer.js";
import { isNativeStructureFailure } from "../../domain/binaryContainer.js";
import { nativeStructureConstraint } from "../nativeStructureConstraint.js";
import { parseKernelModuleFromHandle } from "./KernelModuleParser.js";
const OPERATION = "inspect_kernel_module";
@@ -112,17 +109,8 @@ const kernelModuleFailure = (
description: "kernel module",
fallbackMessage: "Kernel module inspection failed.",
recognise: (failure, origin) => {
if (failure instanceof BinaryResourceFailure)
return parseLimitConstraint(
OPERATION,
"memory",
failure,
fixedAllowanceOptions(
"The ELF structural decoding allowance",
"parser",
binaryResourceCeiling(failure),
),
);
if (isNativeStructureFailure(failure))
return nativeStructureConstraint(OPERATION, failure);
if (
origin === "owned-or-classified" &&
failure instanceof ArtifactReaderFailure &&
@@ -215,7 +215,7 @@ it("rejects truncated, duplicate and over-budget ELF tables", () => {
expect(findRow(overBudget.rows, "nx").state).toBe("enabled");
expect(findRow(overBudget.rows, "stack_protector")).toMatchObject({
state: "unknown",
note: expect.stringContaining("structural budget"),
note: expect.stringContaining("table allowance"),
});
expect(findRow(overBudget.rows, "fortify").state).toBe("unknown");
const longPath = "A".repeat(70000);
@@ -2040,3 +2040,45 @@ it("locates the __restrict section that makes dyld restrict an image", async ()
).toBe("__restrict\0\0\0\0\0\0");
}
});
it("bounds the ELF dynamic table by max_structure_bytes", () => {
const fixture = elfHardeningFixture({ sections: false });
// Pad the image so PT_DYNAMIC can declare zero entries after its DT_NULL.
const bytes = Buffer.concat([fixture, Buffer.alloc(1024)]);
const phoff = Number(bytes.readBigUInt64LE(32));
const phnum = bytes.readUInt16LE(56);
let dynamicSize = 0;
for (let index = 0; index < phnum; index++) {
const at = phoff + index * 56;
if (bytes.readUInt32LE(at) !== 2) continue;
const offset = Number(bytes.readBigUInt64LE(at + 8));
dynamicSize = Math.floor((bytes.length - offset) / 16) * 16;
bytes.writeBigUInt64LE(BigInt(dynamicSize), at + 32);
bytes.writeBigUInt64LE(BigInt(dynamicSize), at + 40);
}
const tableBytes = Math.max(64, phnum * 56);
expect(dynamicSize).toBeGreaterThan(tableBytes);
expect(() => readElfHardening(bytes, undefined, tableBytes)).toThrow(
expect.objectContaining({
failure: expect.objectContaining({
limit: {
name: "max_structure_bytes",
maximum: tableBytes,
required: dynamicSize,
},
}),
}),
);
expect(readElfHardening(bytes, undefined, dynamicSize).format).toBe("elf");
// A partial row stays a malformed target, not a budget refusal.
const partial = Buffer.from(bytes);
for (let index = 0; index < phnum; index++) {
const at = phoff + index * 56;
if (partial.readUInt32LE(at) !== 2) continue;
partial.writeBigUInt64LE(BigInt(dynamicSize - 8), at + 32);
partial.writeBigUInt64LE(BigInt(dynamicSize - 8), at + 40);
}
expect(() => readElfHardening(partial, undefined, tableBytes)).toThrow(
"not a whole number of entries",
);
});
+19 -11
View File
@@ -28,10 +28,12 @@ import { BINARY_HARDENING_PROVIDER } from "../../domain/investigationProviders.j
import {
hasElfMagic,
BinaryResourceFailure,
isNativeStructureFailure,
binaryResourceCeiling,
} from "../../domain/binaryContainer.js";
import { readElfHardeningFromHandle } from "./ElfHardening.js";
import { readMachoHardeningFromHandle } from "./MachoHardening.js";
import { nativeStructureConstraint } from "../nativeStructureConstraint.js";
import { readPeHardeningFromHandle } from "./PeHardening.js";
const OPERATION = "inspect_binary_hardening";
@@ -86,7 +88,11 @@ export class BinaryHardeningProvider implements BinaryHardeningPort {
artifact,
format: "elf" as const,
images: [
await readElfHardeningFromHandle(handle, options?.signal),
await readElfHardeningFromHandle(
handle,
options?.signal,
input.max_structure_bytes,
),
],
limitations: [...BINARY_HARDENING_LIMITATIONS],
};
@@ -140,16 +146,18 @@ const binaryHardeningFailure = (
artifactReadBudgetConstraint(OPERATION, failure, {
max_file_bytes: input.max_file_bytes,
}) ??
(failure instanceof BinaryResourceFailure
? parseLimitConstraint(OPERATION, "capacity", failure, {
path: input.path,
...fixedAllowanceOptions(
"The binary hardening structural allowance",
"parser",
binaryResourceCeiling(failure),
),
})
: undefined),
(isNativeStructureFailure(failure)
? nativeStructureConstraint(OPERATION, failure, input.path)
: failure instanceof BinaryResourceFailure
? parseLimitConstraint(OPERATION, "capacity", failure, {
path: input.path,
...fixedAllowanceOptions(
"The binary hardening table-entry allowance",
"parser",
binaryResourceCeiling(failure),
),
})
: undefined),
fileSize: (failure) =>
artifactFileCeilingConstraint(
OPERATION,
+36 -7
View File
@@ -65,6 +65,8 @@ import {
import {
BinaryFormatFailure,
BinaryResourceFailure,
DEFAULT_NATIVE_STRUCTURE_BYTES,
nativeStructureFailure,
BinaryReader,
} from "../../domain/binaryContainer.js";
import {
@@ -139,8 +141,8 @@ const budgetFailure = (count: number, label: string): BinaryResourceFailure =>
new BinaryResourceFailure(
"structure",
MAX_BINARY_HARDENING_TABLE_ENTRIES,
`${label} has ${String(count)} entries, above the ${String(MAX_BINARY_HARDENING_TABLE_ENTRIES)}-entry structural budget. This release has no runtime override.`,
"structure",
`${label} has ${String(count)} entries, above the ${String(MAX_BINARY_HARDENING_TABLE_ENTRIES)}-entry table allowance. This release has no runtime override.`,
"hardening-table-entries",
"entries",
);
@@ -210,11 +212,19 @@ function* readSlice(
export const readElfHardening = (
bytes: Buffer,
signal?: AbortSignal,
structureBytes?: number,
): BinaryHardeningImage => {
assertArtifactReadActive(signal);
const directory = readElfDirectoryFromBuffer(bytes, OPERATION);
const directory = readElfDirectoryFromBuffer(bytes, OPERATION, {
structureBytes,
});
assertElfDeclaredRangesFromBuffer(bytes);
const steps = elfHardeningSteps(bytes.length, directory, signal);
const steps = elfHardeningSteps(
bytes.length,
directory,
signal,
structureBytes ?? DEFAULT_NATIVE_STRUCTURE_BYTES,
);
let next = steps.next();
while (!next.done) {
const step = next.value;
@@ -228,12 +238,14 @@ export const readElfHardening = (
export const readElfHardeningFromHandle = async (
source: ByteSource,
signal?: AbortSignal,
structureBytes?: number,
): Promise<BinaryHardeningImage> => {
assertArtifactReadActive(signal);
const directory = await readElfDirectoryFromReader(
source,
() => yieldArtifactRead(signal),
OPERATION,
{ structureBytes },
);
assertArtifactReadActive(signal);
await assertElfDeclaredRangesFromReader(source);
@@ -242,7 +254,12 @@ export const readElfHardeningFromHandle = async (
source.prefix !== undefined && offset + length <= source.prefix.length
? Promise.resolve(source.prefix.subarray(offset, offset + length))
: source.readRange(offset, length);
const steps = elfHardeningSteps(source.size, directory, signal);
const steps = elfHardeningSteps(
source.size,
directory,
signal,
structureBytes ?? DEFAULT_NATIVE_STRUCTURE_BYTES,
);
let next = steps.next();
while (!next.done) {
assertArtifactReadActive(signal);
@@ -255,7 +272,8 @@ export const readElfHardeningFromHandle = async (
function* elfHardeningSteps(
fileSize: number,
directory: ReturnType<typeof readElfDirectoryFromBuffer>,
signal?: AbortSignal,
signal: AbortSignal | undefined,
structureBytes: number,
): Generator<HardeningStep, BinaryHardeningImage, HardeningStepResult> {
const { bits, little, machine, programs, sections } = directory;
const headerWidth = bits === 64 ? 56 : 32;
@@ -294,7 +312,14 @@ function* elfHardeningSteps(
const dynamic =
dynamicPrograms[0] === undefined
? null
: yield* readDynamic(fileSize, dynamicPrograms[0], bits, little, mapVa);
: yield* readDynamic(
fileSize,
dynamicPrograms[0],
bits,
little,
mapVa,
structureBytes,
);
let symbols: SymbolScan;
try {
symbols = yield* readSymbols(
@@ -509,12 +534,16 @@ function* readDynamic(
bits: 32 | 64,
little: boolean,
mapVa: MapVa,
structureBytes: number,
): Generator<HardeningStep, DynamicTable, HardeningStepResult> {
const offset = exact(program.offset, "PT_DYNAMIC offset");
const size = exact(program.size, "PT_DYNAMIC size");
const { width, trailingBytes } = elfDynamicTableGeometry(size, bits);
if (trailingBytes !== 0)
malformed("ELF PT_DYNAMIC size is not a whole number of entries");
// A malformed table is refused as malformed; only whole rows meet the budget.
if (size > structureBytes)
throw nativeStructureFailure("The ELF dynamic table", size, structureBytes);
const count = size / width;
budget(count, "ELF dynamic table");
const entries = new Map<bigint, DynamicEntry>();
+18 -8
View File
@@ -34,8 +34,9 @@ import {
BinaryFormatFailure,
BinaryMappingFailure,
BinaryReader,
BinaryResourceFailure,
createFileMappingIndex,
DEFAULT_NATIVE_STRUCTURE_BYTES,
nativeStructureFailure,
type ElfDynamicSegment,
type FileMappingIndex,
} from "../../domain/binaryContainer.js";
@@ -129,6 +130,8 @@ interface Source {
}
interface ElfScan {
/** `max_structure_bytes` for the dynamic directory. */
readonly structureBytes: number;
readonly reader: BinaryReader;
readonly bytes: Buffer;
readonly bits: 32 | 64;
@@ -169,16 +172,19 @@ const readDynamicTags = (
if (segment === undefined) return tags;
if (extra > 0)
throw new BinaryFormatFailure("malformed", "multiple PT_DYNAMIC segments");
const table = admitElfDynamicDirectory(scan.bytes.length, segment, scan.bits);
const table = admitElfDynamicDirectory(
scan.bytes.length,
segment,
scan.bits,
scan.structureBytes,
);
if (!table.ok) {
if (table.error.kind === "malformed")
throw new BinaryFormatFailure("malformed", table.error.message);
throw new BinaryResourceFailure(
"structure",
throw nativeStructureFailure(
"The ELF dynamic directory",
table.error.size,
table.error.maximum,
table.error.message,
"structure",
"bytes",
);
}
const { offset: start, size, width } = table.value;
@@ -643,6 +649,7 @@ const loadWrites = async (
dynamicSegments: image.elf.dynamicSegments,
mappings: image.mappings,
zeroFills: image.zero_fills,
structureBytes: scan.structureBytes,
},
{ unsupported: "record", wholeExtents: true },
);
@@ -965,20 +972,23 @@ export const readElfInitializers = async (
bytes: Buffer,
page: InitializerPage,
signal?: AbortSignal,
structureBytes: number = DEFAULT_NATIVE_STRUCTURE_BYTES,
): Promise<NativeInitializerInspection> => {
assertArtifactReadActive(signal);
const operation = "inspect_native_initializers";
const directory =
signal === undefined
? readElfDirectoryFromBuffer(bytes, operation)
? readElfDirectoryFromBuffer(bytes, operation, { structureBytes })
: await readElfDirectoryFromBufferCooperative(
bytes,
() => yieldArtifactRead(signal),
operation,
{ structureBytes },
);
assertArtifactReadActive(signal);
const image = readElfImageFromDirectory(bytes, directory);
const scan: ElfScan = {
structureBytes,
bytes,
reader: new BinaryReader(bytes, image.byte_order === "little", "elf"),
bits: image.bits,
+2 -1
View File
@@ -783,9 +783,10 @@ export const readMachoInitializers = async (
image: MachoInitializerImage,
page: InitializerPage,
signal?: AbortSignal,
structureBytes?: number,
): Promise<NativeInitializerInspection> => {
assertArtifactReadActive(signal);
const container = readMachoImage(image.bytes);
const container = readMachoImage(image.bytes, structureBytes);
const header = readMachoLoadCommandTableHeader(
image.bytes,
image.bytes.length,
@@ -16,9 +16,9 @@ import {
import {
hasElfMagic,
BinaryFormatFailure,
BinaryResourceFailure,
binaryResourceCeiling,
isNativeStructureFailure,
} from "../../domain/binaryContainer.js";
import { nativeStructureConstraint } from "../nativeStructureConstraint.js";
import type { NativeInitializersPort } from "../../ports/binaryDiagnostics/NativeInitializersPort.js";
import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
@@ -99,7 +99,7 @@ export const readNativeInitializers = async (
artifact: NativeInitializers["artifact"],
input: Pick<
InspectNativeInitializersInput,
"offset" | "limit" | "architecture" | "path"
"offset" | "limit" | "architecture" | "path" | "max_structure_bytes"
>,
signal?: AbortSignal,
): Promise<NativeInitializers> => {
@@ -111,7 +111,13 @@ export const readNativeInitializers = async (
input.architecture,
);
const page = { offset: input.offset, limit: input.limit };
const inspection = await inspectSelected(bytes, selected, page, signal);
const inspection = await inspectSelected(
bytes,
selected,
page,
signal,
input.max_structure_bytes,
);
return {
artifact,
...inspection,
@@ -124,6 +130,7 @@ const inspectSelected = async (
selected: ReturnType<typeof requireSelectedNativeImage>,
page: { readonly offset: number; readonly limit: number },
signal: AbortSignal | undefined,
structureBytes: number | undefined,
): Promise<NativeInitializerInspection> => {
if (hasElfMagic(selected.bytes)) {
if (selected.selection !== null)
@@ -131,7 +138,7 @@ const inspectSelected = async (
"malformed",
"ELF bytes are not a Mach-O slice",
);
return readElfInitializers(selected.bytes, page, signal);
return readElfInitializers(selected.bytes, page, signal, structureBytes);
}
if (!hasMachoMagic(container) && !hasMachoMagic(selected.bytes))
throw new BinaryFormatFailure(
@@ -153,6 +160,7 @@ const inspectSelected = async (
{ bytes: selected.bytes, fileBase: selected.fileOffset, slice },
page,
signal,
structureBytes,
);
};
@@ -200,15 +208,8 @@ const nativeInitializersFailure = (
},
),
});
if (failure instanceof BinaryResourceFailure)
return parseLimitConstraint(OPERATION, "capacity", failure, {
path: input.path,
...fixedAllowanceOptions(
"The native initializer structural allowance",
"parser",
binaryResourceCeiling(failure),
),
});
if (isNativeStructureFailure(failure))
return nativeStructureConstraint(OPERATION, failure, input.path);
if (
origin === "owned-or-classified" &&
failure instanceof ArtifactReaderFailure &&
+20
View File
@@ -0,0 +1,20 @@
import type { BinaryResourceFailure } from "../domain/binaryContainer.js";
import type { AnalysisResourceConstraintError } from "../domain/analysisErrorCore.js";
import { nativeStructureLimit } from "../domain/native/nativeStructureBudget.js";
import { parseLimitConstraint } from "../domain/parseFailureAnalysisError.js";
/**
* The refusal of a native table read above `max_structure_bytes`. The
* failure carries the value its reader enforced, so the limit reports what
* stopped this call.
*/
export const nativeStructureConstraint = (
operation: string,
failure: BinaryResourceFailure,
path?: string,
): AnalysisResourceConstraintError =>
parseLimitConstraint(operation, "memory", failure, {
...(path === undefined ? {} : { path }),
retryable: false,
limit: nativeStructureLimit(failure.maximum_bytes),
});
+36 -1
View File
@@ -225,15 +225,50 @@ cliTest.for([
? { path, failure_kind: "malformed" }
: {
reported_limits: {
boundary: "structure",
boundary: "max_structure_bytes",
maximum: dynamicTableCeiling,
},
limit: {
control_kind: "parameter",
parameter: "max_structure_bytes",
effective_value: dynamicTableCeiling,
default_value: dynamicTableCeiling,
applies_at: "next_call",
},
}),
},
});
},
);
cliTest(
"admits an oversized PT_DYNAMIC with a larger --max-structure-bytes",
async ({ cli }) => {
const root = await createTestTempDirectory(
"rea-native-init-structure-cli-",
);
const path = join(root, "library.so");
const bytes = elf64PieInitializers();
const size = dynamicTableCeiling + 16;
bytes.writeBigUInt64LE(BigInt(size), 120 + 32);
bytes.writeBigUInt64LE(BigInt(size), 120 + 40);
await writeFile(path, bytes);
await truncate(path, 0x300 + size);
const result = await cli.run({
arguments: [
"inspect-native-initializers",
path,
"--max-structure-bytes",
String(dynamicTableCeiling * 2),
"--json",
],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = contract.outputSchema.parse(result.json);
expect(evidence.normalized_result.entries.length).toBeGreaterThan(0);
},
);
cliTest(
"keeps unmapped ELF target locations null in public CLI Evidence",
async ({ cli }) => {
@@ -79,6 +79,36 @@ describe("ELF unwind range stable filesystem boundary", () => {
});
describe("ELF unwind range budgets", () => {
it("names max_structure_bytes when a header table exceeds it", async () => {
const root = await createTestTempDirectory("rea-elf-unwind-structure-");
const path = join(root, "program");
await writeFile(path, elfUnwindFixture());
const service = createElfUnwindRangesService();
try {
const refused = await service.inspect({ path, max_structure_bytes: 64 });
if (refused.ok) throw new Error("Expected a max_structure_bytes refusal");
expect(refused.error).toMatchObject({
_tag: "AnalysisResourceConstraintError",
resource: "memory",
limit: {
control_kind: "parameter",
parameter: "max_structure_bytes",
effective_value: 64,
unit: "bytes",
minimum: 64,
maximum: 512 * 1024 * 1024,
default_value: 16 * 1024 * 1024,
applies_at: "next_call",
},
});
expect(
(await service.inspect({ path, max_structure_bytes: 65536 })).ok,
).toBe(true);
} finally {
await service.close();
}
});
it("tells a caller over the symbol-name text allowance to request a smaller page", async () => {
const root = await createTestTempDirectory("rea-elf-unwind-names-");
const path = join(root, "program");
@@ -13,6 +13,33 @@ import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { expectFileSelectionErrors } from "../../support/expectFileSelectionErrors.js";
describe("kernel module stable filesystem boundary", () => {
it("names max_structure_bytes when its section table exceeds it", async () => {
const root = await createTestTempDirectory("rea-kernel-module-structure-");
const path = join(root, "demo.ko");
await writeFile(path, kernelModuleFixture());
const service = createKernelModuleService();
try {
const refused = await service.inspect({ path, max_structure_bytes: 64 });
if (refused.ok) throw new Error("Expected a max_structure_bytes refusal");
expect(refused.error).toMatchObject({
_tag: "AnalysisResourceConstraintError",
limit: {
control_kind: "parameter",
parameter: "max_structure_bytes",
effective_value: 64,
applies_at: "next_call",
},
});
const raised = await service.inspect({
path,
max_structure_bytes: 65536,
});
if (!raised.ok) throw raised.error;
} finally {
await service.close();
}
});
it("retains trailer fields but withholds an empty PKCS#7 range", async () => {
const root = await createTestTempDirectory("rea-kernel-module-empty-sig-");
const path = join(root, "demo.ko");
+1 -1
View File
@@ -63,7 +63,7 @@ it.each([false, true])(
code: "resource_constraint",
details: {
reported_limits: {
boundary: "structure",
boundary: "max_structure_bytes",
maximum: 16 * 1024 * 1024,
},
},