diff --git a/docs/guides/native/go-binaries.md b/docs/guides/native/go-binaries.md index e6dcdaeaf94..9cc22ceac64 100644 --- a/docs/guides/native/go-binaries.md +++ b/docs/guides/native/go-binaries.md @@ -267,10 +267,9 @@ parameter and effective bytes; increase that parameter on the next call, 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, 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 +The shared native container reader separately bounds its ELF directory and +Mach-O load-command tables with `max_structure_bytes` (default 16 MiB); none of +the other 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 diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index 9db19a7aeb4..376c3022135 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -132,8 +132,13 @@ are bounded by the PE format. For `inspect_native_exports` it also bounds the ELF dynamic, symbol and version tables located through PT_DYNAMIC. -The Go, Rust and IL2CPP readers read the same tables with the 16 MiB default and -report it as a fixed allowance. +`inspect_go_binary` and `inspect_rust_binary` accept it for their ELF directory +and Mach-O load commands. The IL2CPP reader reads the same tables with the 16 +MiB default and reports it as a fixed allowance. + +`inspect_rust_binary` also accepts `max_wasm_sections` (WebAssembly sections +walked; default 65,536, at most 16,777,216). The walk stops at the first excess, +so the refusal reports no `required_value`. `inspect_native_exports` also accepts `max_entries` (export rows and declared symbol counts; default 262,144, at most 4,194,304) and `max_text_bytes` (name and diff --git a/docs/rust-binaries.md b/docs/rust-binaries.md index 64433cc4c76..0d95a6852d3 100644 --- a/docs/rust-binaries.md +++ b/docs/rust-binaries.md @@ -173,7 +173,7 @@ selects a universal Mach-O slice. | Compressed `.dep-v0` zlib | 1 MiB | Fixed | | Inflated JSON | Smaller of 8 MiB and 64 × the consumed stream | Fixed | | Distinct rustc hashes | 64 | `max_rustc_hashes` | -| WebAssembly sections | 65,536 | Fixed (`max_wasm_sections`) | +| WebAssembly sections | 65,536 (at most 16,777,216) | `max_wasm_sections` | Empty sections, truncated streams, nonpadding bytes after a zlib stream, invalid JSON, duplicate @@ -236,11 +236,15 @@ to retain a larger prefix; no restart is required. The complete-report byte allowance still applies. Optional compiler paths are shortened before they can displace independently observed dependency facts. -The synchronous WebAssembly section walk admits at most 65,536 section -payloads. A further section with a valid length and file extent triggers a -`cpu` resource constraint whose `reported_limits` name `max_wasm_sections`. -Invalid lengths and truncated extents retain their format diagnosis at the -limit. This allowance is fixed, so `producer_limits` does not raise it. +The synchronous WebAssembly section walk admits at most `max_wasm_sections` +section payloads (default 65,536, at most 16,777,216; see +[limits and recovery](reference/limits-and-recovery.md#native-table-structure-budget)). +A further section with a valid length and file extent triggers a `cpu` resource +constraint whose `details.limit` names `max_wasm_sections`. Raise +`max_wasm_sections` (CLI `--max-wasm-sections`) on the next call. The walk +stops at the first excess, so no `required_value` is reported. Invalid lengths +and truncated extents retain their format diagnosis at the limit. +`producer_limits` does not raise it. Reader architecture names remain verbatim in the report. Evidence subjects use the recognized canonical family: `386` maps to `x86`, `amd64` to `x86_64`, and diff --git a/scripts/verify/advertised-schemas/tools/inspect_go_binary.json b/scripts/verify/advertised-schemas/tools/inspect_go_binary.json index e9080567931..73b679fd12b 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_go_binary.json +++ b/scripts/verify/advertised-schemas/tools/inspect_go_binary.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "801e80c517f9408e", + "input compact": "76e008d5c9b4d474", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/advertised-schemas/tools/inspect_rust_binary.json b/scripts/verify/advertised-schemas/tools/inspect_rust_binary.json index 94c4601a1bd..cb2f93634a9 100644 --- a/scripts/verify/advertised-schemas/tools/inspect_rust_binary.json +++ b/scripts/verify/advertised-schemas/tools/inspect_rust_binary.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "1f21147802cdb88d", + "input compact": "255fa72437ffa3c1", "output compact": "4bda7c3651bfc579" }, "patterns": { diff --git a/scripts/verify/fixed-ceiling-registry.json b/scripts/verify/fixed-ceiling-registry.json index dca47e624bf..4c3ef22aba0 100644 --- a/scripts/verify/fixed-ceiling-registry.json +++ b/scripts/verify/fixed-ceiling-registry.json @@ -185,13 +185,6 @@ "reason": "Bounds Ghidra's own Ghidra/application.properties, a short key=value installation descriptor of the bring-your-own provider (about 1 KiB); no analysis input passes through it, and a larger file is not a Ghidra installation REA can drive." } }, - "src/go/GoBinaryProvider.ts": { - "\"The Go structural decoding allowance\"": { - "class": "pending", - "issue": 14235, - "reason": "Projects the shared native structural decoding allowance (BinaryResourceFailure), a resource policy." - } - }, "src/gpu/GpuCodeObjectsProvider.ts": { "\"The GPU object allowance\"": { "class": "pending", @@ -376,20 +369,10 @@ } }, "src/rust/RustBinaryProvider.ts": { - "\"The WebAssembly section-walk allowance\"": { - "class": "pending", - "issue": 14235, - "reason": "Rust container, dependency and WebAssembly section-walk allowances are resource policies." - }, "\"This Rust dependency parser allowance\"": { "class": "pending", "issue": 14235, "reason": "Rust container, dependency and WebAssembly section-walk allowances are resource policies." - }, - "\"This native container parser allowance\"": { - "class": "pending", - "issue": 14235, - "reason": "Rust container, dependency and WebAssembly section-walk allowances are resource policies." } }, "src/sqlite/SqliteDatabaseFailures.ts": { diff --git a/src/domain/go/goBinary.ts b/src/domain/go/goBinary.ts index bc91ad5c0f7..11ea5997218 100644 --- a/src/domain/go/goBinary.ts +++ b/src/domain/go/goBinary.ts @@ -13,6 +13,7 @@ import { localPathStringSchema, } from "../localPath.js"; import { canonicalBase64Schema } from "../stringPatterns.js"; +import { maxStructureBytesSchema } from "../native/nativeStructureBudget.js"; const sourceRangeSchema = z.strictObject({ offset: z.int().nonnegative(), @@ -191,6 +192,7 @@ export const inspectGoBinaryInputSchema = z "Also recover bounded inferred Go UTF-8 string literals referenced by static (ptr, len) headers in non-executable mapped data", ), ...goResourceBudgetFields, + max_structure_bytes: maxStructureBytesSchema, detail: z .enum(["complete", "summary"]) .optional() diff --git a/src/domain/native/nativeStructureBudget.ts b/src/domain/native/nativeStructureBudget.ts index 0484ded0653..d189b9ddb8f 100644 --- a/src/domain/native/nativeStructureBudget.ts +++ b/src/domain/native/nativeStructureBudget.ts @@ -1,10 +1,13 @@ import { z } from "zod"; +import type { AnalysisResourceConstraintError } from "../analysisErrorCore.js"; import type { AnalysisParameterLimit } from "../analysisSettings.js"; import { DEFAULT_NATIVE_STRUCTURE_BYTES, NATIVE_STRUCTURE_LIMIT, + type BinaryResourceFailure, } from "../binaryContainer.js"; +import { parseLimitConstraint } from "../parseFailureAnalysisError.js"; /** * `max_structure_bytes`: the bytes of one native table read (ELF program and @@ -57,3 +60,20 @@ export const nativeStructureLimit = ( ...NATIVE_STRUCTURE_BYTES, applies_at: "next_call", }); + +/** + * 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. The table that stopped the read is not necessarily the + * largest one a retry must pass, so no `required_value` is reported. + */ +export const nativeStructureConstraint = ( + operation: string, + failure: BinaryResourceFailure, + path?: string, +): AnalysisResourceConstraintError => + parseLimitConstraint(operation, "memory", failure, { + ...(path === undefined ? {} : { path }), + retryable: false, + limit: nativeStructureLimit(failure.maximum_bytes), + }); diff --git a/src/domain/native/readBinaryContainer.ts b/src/domain/native/readBinaryContainer.ts index 9f66dcd882d..52c8bccb58c 100644 --- a/src/domain/native/readBinaryContainer.ts +++ b/src/domain/native/readBinaryContainer.ts @@ -48,6 +48,8 @@ export const readBinaryContainerFromReader = async ( source: ByteSource, operation: string, pause: ZstandardFramePause, + /** `max_structure_bytes` for the ELF directory and Mach-O load commands. */ + structureBytes?: number, ): Promise => { const probeLength = Math.min(source.size, 64); const prefix = @@ -57,7 +59,7 @@ export const readBinaryContainerFromReader = async ( ? Buffer.alloc(0) : await source.readRange(0, probeLength); if (hasElfMagic(prefix)) - return readElfImageFromReader(source, operation, pause); + return readElfImageFromReader(source, operation, pause, { structureBytes }); if (prefix.subarray(0, 2).equals(Buffer.from("MZ"))) return readPeImageFromReader({ size: source.size, @@ -90,7 +92,7 @@ export const readBinaryContainerFromReader = async ( ); } if (readMachoHeaderPrefixFacts(prefix).format !== null) - return readMachoImageFromReader(source); + return readMachoImageFromReader(source, structureBytes); } throw new BinaryFormatFailure( "unsupported", diff --git a/src/domain/rust/rustBinary.ts b/src/domain/rust/rustBinary.ts index 2ae4a36eea8..c96e2472acd 100644 --- a/src/domain/rust/rustBinary.ts +++ b/src/domain/rust/rustBinary.ts @@ -18,6 +18,11 @@ import { machoSliceArchitectureSchema, machoTargetSelectionSchema, } from "../apple/machoTargetSelection.js"; +import { maxStructureBytesSchema } from "../native/nativeStructureBudget.js"; +import { + parameterBudgetLimit, + type ParameterBudget, +} from "../parameterBudget.js"; /** Known revisions used to interpret compatible cargo-auditable documents. */ export const RUST_AUDITABLE_FORMAT_VERSIONS = [0, 1, 8] as const; @@ -134,12 +139,37 @@ export const rustcPartialCoverage = ( }); /** One explicit local executable or library, independent of a disassembler target. */ +/** `max_wasm_sections`: WebAssembly sections walked in one module. */ +export const RUST_WASM_SECTION_BUDGET = { + minimum: 1, + maximum: 16_777_216, + default_value: 65_536, + unit: "count", +} as const satisfies ParameterBudget; + +/** The `max_wasm_sections` control that stopped a section walk. */ +export const rustWasmSectionLimit = (effectiveValue: number) => + parameterBudgetLimit( + "max_wasm_sections", + RUST_WASM_SECTION_BUDGET, + effectiveValue, + ); + export const inspectRustBinaryInputSchema = z.strictObject({ path: absoluteLocalPathStringSchema.describe( "Absolute filesystem path to the selected executable or library", ), architecture: machoSliceArchitectureSchema.exactOptional(), producer_limits: rustProducerLimitsField, + max_structure_bytes: maxStructureBytesSchema, + max_wasm_sections: z + .int() + .min(RUST_WASM_SECTION_BUDGET.minimum) + .max(RUST_WASM_SECTION_BUDGET.maximum) + .exactOptional() + .describe( + "Maximum WebAssembly sections to walk (default 65536); each costs a frame read", + ), max_rustc_hashes: z .int() .positive() diff --git a/src/go/GoBinaryImage.ts b/src/go/GoBinaryImage.ts index 5a29d633549..2fddee20778 100644 --- a/src/go/GoBinaryImage.ts +++ b/src/go/GoBinaryImage.ts @@ -55,6 +55,8 @@ export interface ReadGoBinaryImageOptions { readonly includeStringLiterals?: boolean; readonly checkActive?: (() => void) | undefined; readonly budgets?: Partial; + /** `max_structure_bytes` for the container's header tables. */ + readonly structureBytes?: number | undefined; } /** Stream Go build-info and optional string-literal inspection over a bounded FileHandle. */ @@ -67,6 +69,7 @@ export const readGoBinaryImageFromHandle = async ( source, "inspect_go_binary", pause, + options?.structureBytes, ); const budgets = goAnalysisBudgets(options?.budgets); const stringLiterals = diff --git a/src/go/GoBinaryProvider.ts b/src/go/GoBinaryProvider.ts index f14048833f1..c1c82afb8ec 100644 --- a/src/go/GoBinaryProvider.ts +++ b/src/go/GoBinaryProvider.ts @@ -32,7 +32,6 @@ import { type GoStringLiterals, type InspectGoBinaryInput, } from "../domain/go/goBinary.js"; -import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js"; import { err, ok, type Result } from "../domain/result.js"; import { readGoBinaryImageFromHandle, @@ -41,39 +40,33 @@ import { import { requireSelectedNativeImageFromReader } from "../domain/apple/machoSliceSelection.js"; import { BinaryResourceFailure, - binaryResourceCeiling, + isNativeStructureFailure, } from "../domain/binaryContainer.js"; +import { + NATIVE_STRUCTURE_BYTES, + nativeStructureConstraint, +} from "../domain/native/nativeStructureBudget.js"; const OPERATION = "inspect_go_binary"; const HEADER_PREFIX_BYTES = 4096; -const budgetRecovery = ( - parameter: keyof GoAnalysisBudgets, - value: number, -): string => - value < GO_ANALYSIS_BUDGET_MAXIMA[parameter] - ? `Increase ${parameter} above ${String(value)} (maximum ${String(GO_ANALYSIS_BUDGET_MAXIMA[parameter])}) on the next inspect_go_binary request; no restart is required.` - : `${parameter} is at its runtime representation maximum ${String(value)}; no larger value is supported. Preserve the complete selected artifact and report this boundary rather than repeating the unchanged request.`; - /** The per-call control of an exhausted budget, while a larger value is selectable. */ const budgetLimit = ( parameter: keyof GoAnalysisBudgets, value: number, -): { readonly limit?: AnalysisControlLimit } => - value < GO_ANALYSIS_BUDGET_MAXIMA[parameter] - ? { - limit: { - control_kind: "parameter", - parameter, - effective_value: value, - unit: parameter.endsWith("_bytes") ? "bytes" : "count", - minimum: 1, - maximum: GO_ANALYSIS_BUDGET_MAXIMA[parameter], - default_value: GO_ANALYSIS_BUDGET_DEFAULTS[parameter], - applies_at: "next_call", - }, - } - : {}; +): { readonly limit: AnalysisControlLimit } => ({ + // At its maximum the generated recovery asks for a narrower request. + limit: { + control_kind: "parameter", + parameter, + effective_value: value, + unit: parameter.endsWith("_bytes") ? "bytes" : "count", + minimum: 1, + maximum: GO_ANALYSIS_BUDGET_MAXIMA[parameter], + default_value: GO_ANALYSIS_BUDGET_DEFAULTS[parameter], + applies_at: "next_call", + }, +}); const failureFor = ( cause: unknown, @@ -91,6 +84,8 @@ const failureFor = ( path, description: "artifact", recognise: (failure, origin) => { + if (isNativeStructureFailure(failure)) + return nativeStructureConstraint(OPERATION, failure, path); if (failure instanceof BinaryResourceFailure) { const parameter = failure.boundary === "search" @@ -98,23 +93,17 @@ const failureFor = ( : failure.boundary === "build-info" ? "max_build_info_bytes" : undefined; + // Only the container's tables (max_structure_bytes, above) and these + // two Go budgets raise a resource failure here. + if (parameter === undefined) return undefined; return parseLimitConstraint( OPERATION, failure.boundary === "search" ? "cpu" : "memory", failure, { path, - ...(parameter === undefined - ? fixedAllowanceOptions( - "The Go structural decoding allowance", - "parser", - binaryResourceCeiling(failure), - ) - : { - retryable: false, - remediationAction: `${failure.boundary === "search" ? "The Go build-info header-search allowance" : "The Go build-info string allowance"} is ${String(budgets[parameter])} bytes. ${budgetRecovery(parameter, budgets[parameter])} Other byte and report budgets are independent. Repeating the unchanged request cannot raise this allowance.`, - ...budgetLimit(parameter, budgets[parameter]), - }), + retryable: false, + ...budgetLimit(parameter, budgets[parameter]), }, ); } @@ -135,7 +124,6 @@ const failureFor = ( { cause: failure, retryable: false, - remediationAction: `${budgetRecovery("max_input_bytes", budgets.max_input_bytes)} Report, build-info and structural allowances remain independent. Preserve the complete artifact; do not truncate required bytes.`, ...budgetLimit("max_input_bytes", budgets.max_input_bytes), }, ); @@ -166,7 +154,6 @@ const outputLimit = (path: string, maximumBytes: number) => }, { retryable: false, - remediationAction: `The Go complete-report allowance is ${String(maximumBytes)} bytes. ${budgetRecovery("max_report_bytes", maximumBytes)} This did not produce complete Evidence to page. MCP delivery limits remain independent.`, ...budgetLimit("max_report_bytes", maximumBytes), }, ); @@ -176,6 +163,7 @@ const limitationsFor = ( image: GoBinaryImage, stringLiterals: GoStringLiterals | undefined, budgets: GoAnalysisBudgets, + structureBytes: number, ): string[] => { const { build_info: info, @@ -187,7 +175,7 @@ const limitationsFor = ( stringLiterals === undefined ? "Only Go build information is inspected; function names, source mappings, type metadata and decompiled code are not recovered." : "Only Go build information and inferred static (ptr, len) string-header candidates are inspected; function names, source mappings, type metadata and decompiled code are not recovered.", - `Resource guards use max_input_bytes=${String(budgets.max_input_bytes)}, max_header_search_bytes=${String(budgets.max_header_search_bytes)}, max_build_info_bytes=${String(budgets.max_build_info_bytes)} and max_report_bytes=${String(budgets.max_report_bytes)}; increase the named per-call budget for the next inspection when needed. Native structural table decoding retains its separate 16 MiB bound. These are not operating-system memory or CPU limits.`, + `Resource guards use max_input_bytes=${String(budgets.max_input_bytes)}, max_header_search_bytes=${String(budgets.max_header_search_bytes)}, max_build_info_bytes=${String(budgets.max_build_info_bytes)} and max_report_bytes=${String(budgets.max_report_bytes)}; increase the named per-call budget for the next inspection when needed. Native structural table decoding uses max_structure_bytes=${String(structureBytes)}. These are not operating-system memory or CPU limits.`, ...(info !== null && (info.go_version === null || info.module_text === null) ? [ "Some embedded Go strings contain non-UTF8 bytes; undecodable text is null and exact source bytes are preserved as base64.", @@ -288,6 +276,8 @@ export class GoBinaryProvider implements GoBinaryPort { | { readonly sha256: string; readonly bytes: number } | undefined; const budgets = goAnalysisBudgets(input); + const structureBytes = + input.max_structure_bytes ?? NATIVE_STRUCTURE_BYTES.default_value; try { return await this.#resources.run(async () => { const parsedData = await withStableArtifactHandle( @@ -315,6 +305,7 @@ export class GoBinaryProvider implements GoBinaryPort { const imageOptions = { includeStringLiterals: input.include_string_literals === true, budgets, + structureBytes, checkActive: () => assertArtifactReadActive(options?.signal), }; const image = await readGoBinaryImageFromHandle( @@ -349,7 +340,12 @@ export class GoBinaryProvider implements GoBinaryPort { ? {} : { string_literals: stringLiterals }), limitations: [ - ...limitationsFor(image, stringLiterals, budgets), + ...limitationsFor( + image, + stringLiterals, + budgets, + structureBytes, + ), ...selected.limitations, ], }; diff --git a/src/native/dwarf/DwarfUnitsProvider.ts b/src/native/dwarf/DwarfUnitsProvider.ts index 6c69ddf2be3..c94335e0d1f 100644 --- a/src/native/dwarf/DwarfUnitsProvider.ts +++ b/src/native/dwarf/DwarfUnitsProvider.ts @@ -29,7 +29,7 @@ import { BinaryResourceFailure, isNativeStructureFailure, } from "../../domain/binaryContainer.js"; -import { nativeStructureConstraint } from "../nativeStructureConstraint.js"; +import { nativeStructureConstraint } from "../../domain/native/nativeStructureBudget.js"; import { requireSelectedNativeImageFromReader } from "../../domain/apple/machoSliceSelection.js"; import { parseDwarfCompileUnits } from "./DwarfUnitParser.js"; import { diff --git a/src/native/elf/ElfDebugLinkProvider.ts b/src/native/elf/ElfDebugLinkProvider.ts index bf7eacf7828..c05f315b0a5 100644 --- a/src/native/elf/ElfDebugLinkProvider.ts +++ b/src/native/elf/ElfDebugLinkProvider.ts @@ -29,7 +29,7 @@ import { err, ok } from "../../domain/result.js"; import type { AnalysisPartialObservation } from "../../domain/analysisErrorBase.js"; import { ELF_DEBUG_LINK_PROVIDER } from "../../domain/investigationProviders.js"; import { isNativeStructureFailure } from "../../domain/binaryContainer.js"; -import { nativeStructureConstraint } from "../nativeStructureConstraint.js"; +import { nativeStructureConstraint } from "../../domain/native/nativeStructureBudget.js"; import { continueGnuDebuglinkCrc32, parseElfDebugLinkFromHandle, diff --git a/src/native/elf/ElfUnwindRangesProvider.ts b/src/native/elf/ElfUnwindRangesProvider.ts index 6546904d614..3a47a55d156 100644 --- a/src/native/elf/ElfUnwindRangesProvider.ts +++ b/src/native/elf/ElfUnwindRangesProvider.ts @@ -23,7 +23,7 @@ import { import { err, ok } from "../../domain/result.js"; import { ELF_UNWIND_RANGES_PROVIDER } from "../../domain/investigationProviders.js"; import { isNativeStructureFailure } from "../../domain/binaryContainer.js"; -import { nativeStructureConstraint } from "../nativeStructureConstraint.js"; +import { nativeStructureConstraint } from "../../domain/native/nativeStructureBudget.js"; import { ELF_UNWIND_FORMAT, ELF_UNWIND_RECORD_LIMIT, diff --git a/src/native/elf/KernelModuleProvider.ts b/src/native/elf/KernelModuleProvider.ts index 69e013aae86..0c79346a2b7 100644 --- a/src/native/elf/KernelModuleProvider.ts +++ b/src/native/elf/KernelModuleProvider.ts @@ -20,7 +20,7 @@ import { import { err, ok } from "../../domain/result.js"; import { KERNEL_MODULE_PROVIDER } from "../../domain/investigationProviders.js"; import { isNativeStructureFailure } from "../../domain/binaryContainer.js"; -import { nativeStructureConstraint } from "../nativeStructureConstraint.js"; +import { nativeStructureConstraint } from "../../domain/native/nativeStructureBudget.js"; import { parseKernelModuleFromHandle } from "./KernelModuleParser.js"; const OPERATION = "inspect_kernel_module"; diff --git a/src/native/exports/NativeExportsProvider.ts b/src/native/exports/NativeExportsProvider.ts index 35ee2f9e403..37d5a634b64 100644 --- a/src/native/exports/NativeExportsProvider.ts +++ b/src/native/exports/NativeExportsProvider.ts @@ -31,7 +31,7 @@ import { DEFAULT_NATIVE_STRUCTURE_BYTES, isNativeStructureFailure, } from "../../domain/binaryContainer.js"; -import { nativeStructureConstraint } from "../nativeStructureConstraint.js"; +import { nativeStructureConstraint } from "../../domain/native/nativeStructureBudget.js"; import { NATIVE_EXPORT_LIMITS, type NativeExportLimit, diff --git a/src/native/hardening/BinaryHardeningProvider.ts b/src/native/hardening/BinaryHardeningProvider.ts index 9acc8b38136..bc108179db4 100644 --- a/src/native/hardening/BinaryHardeningProvider.ts +++ b/src/native/hardening/BinaryHardeningProvider.ts @@ -33,7 +33,7 @@ import { } from "../../domain/binaryContainer.js"; import { readElfHardeningFromHandle } from "./ElfHardening.js"; import { readMachoHardeningFromHandle } from "./MachoHardening.js"; -import { nativeStructureConstraint } from "../nativeStructureConstraint.js"; +import { nativeStructureConstraint } from "../../domain/native/nativeStructureBudget.js"; import { readPeHardeningFromHandle } from "./PeHardening.js"; const OPERATION = "inspect_binary_hardening"; diff --git a/src/native/initializers/NativeInitializersProvider.ts b/src/native/initializers/NativeInitializersProvider.ts index 364d2efb53a..276f0dc6115 100644 --- a/src/native/initializers/NativeInitializersProvider.ts +++ b/src/native/initializers/NativeInitializersProvider.ts @@ -17,7 +17,7 @@ import { BinaryFormatFailure, isNativeStructureFailure, } from "../../domain/binaryContainer.js"; -import { nativeStructureConstraint } from "../nativeStructureConstraint.js"; +import { nativeStructureConstraint } from "../../domain/native/nativeStructureBudget.js"; import type { NativeInitializersPort } from "../../ports/binaryDiagnostics/NativeInitializersPort.js"; import type { ExecutionOptions } from "../../ports/AnalysisProvider.js"; import type { AnalysisError } from "../../domain/analysisErrorBase.js"; diff --git a/src/native/nativeStructureConstraint.ts b/src/native/nativeStructureConstraint.ts deleted file mode 100644 index 6432bda3fa2..00000000000 --- a/src/native/nativeStructureConstraint.ts +++ /dev/null @@ -1,20 +0,0 @@ -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), - }); diff --git a/src/rust/RustBinaryImage.ts b/src/rust/RustBinaryImage.ts index e8b1d897063..195a57374f7 100644 --- a/src/rust/RustBinaryImage.ts +++ b/src/rust/RustBinaryImage.ts @@ -72,6 +72,8 @@ export const readRustBinaryImageFromHandle = async ( maxRustcHashes: number | undefined, maxOutputBytes: number | undefined, pause: ZstandardFramePause, + structureBytes?: number, + maxWasmSections?: number, ): Promise => { const effectiveMaxHashes = maxRustcHashes ?? DEFAULT_RUSTC_HASH_LIMIT; const effectiveMaxOutputBytes = @@ -82,12 +84,13 @@ export const readRustBinaryImageFromHandle = async ( Math.min(source.size, 8), ); const layout: RustImageLayout = hasWasmPreamble(preamble) - ? await wasmLayoutFromReader(source, pause) + ? await wasmLayoutFromReader(source, pause, maxWasmSections) : nativeLayoutFromContainer( await readBinaryContainerFromReader( source, "inspect_rust_binary", pause, + structureBytes, ), ); const { section_name, dependency, compiler_strings, ...identity } = layout; @@ -121,9 +124,10 @@ export const readRustBinaryImageFromHandle = async ( const wasmLayoutFromReader = async ( source: ByteSource, pause: ZstandardFramePause, + maxSections: number | undefined, ): Promise => { const { dependency_sections, data_section } = - await readRustWasmSectionsFromReader(source, pause); + await readRustWasmSectionsFromReader(source, pause, maxSections); if (dependency_sections.length > 1) throw duplicateDependencySection(); return { format: "wasm", diff --git a/src/rust/RustBinaryProvider.ts b/src/rust/RustBinaryProvider.ts index 1b21be0a616..e0f7f18c4f3 100644 --- a/src/rust/RustBinaryProvider.ts +++ b/src/rust/RustBinaryProvider.ts @@ -24,6 +24,8 @@ import { RUST_AUDITABLE_FORMAT_VERSIONS, rustBinarySchema, rustcPartialCoverage, + RUST_WASM_SECTION_BUDGET, + rustWasmSectionLimit, type InspectRustBinaryInput, type RustBinary, } from "../domain/rust/rustBinary.js"; @@ -38,11 +40,9 @@ import { RUST_AUDITABLE_FORMAT, RUST_AUDITABLE_GRAPH_LIMIT, } from "./RustAuditableReader.js"; -import { - BinaryResourceFailure, - binaryResourceCeiling, -} from "../domain/binaryContainer.js"; -import { MAX_WASM_SECTIONS, WASM_FORMAT } from "./RustWasmImage.js"; +import { isNativeStructureFailure } from "../domain/binaryContainer.js"; +import { nativeStructureConstraint } from "../domain/native/nativeStructureBudget.js"; +import { WASM_FORMAT } from "./RustWasmImage.js"; import { isParseLimit, parseLimitConstraint, @@ -126,6 +126,8 @@ export class RustBinaryProvider implements RustBinaryPort { input.max_rustc_hashes, limits.output_bytes, () => yieldArtifactRead(options?.signal), + input.max_structure_bytes, + input.max_wasm_sections, ), selected.fileOffset, ); @@ -146,7 +148,11 @@ export class RustBinaryProvider implements RustBinaryPort { ? {} : { selected_slice: selected.selection }), limitations: [ - ...limitationsFor(image), + ...limitationsFor( + image, + input.max_wasm_sections ?? + RUST_WASM_SECTION_BUDGET.default_value, + ), `Selected producer_limits.input_bytes=${String(limits.input_bytes)} and output_bytes=${String(limits.output_bytes)} bytes; compressed/inflated dependency parser limits remain independent.`, ...selected.limitations, ], @@ -223,12 +229,15 @@ const outputLimit = (path: string, maxOutputBytes: number) => /** Resource-guard guidance delivered with every Rust inspection report. */ const RUST_RESOURCE_GUARD_LIMITATION = `Default input and complete-report admission are ${String(RUST_PRODUCER_DEFAULTS.input_bytes)} and ${String(RUST_PRODUCER_DEFAULTS.output_bytes)} bytes; producer_limits.input_bytes/output_bytes select larger or smaller values for the next call without restart. Independent parser guards bound the compressed dependency stream to 1 MiB and inflated JSON to the smaller of 8 MiB and 64 times the consumed compressed-stream length. Report admission applies before package schema cloning, graph objects, or reverse-edge allocation.`; -const limitationsFor = (image: RustBinaryImage): string[] => [ +const limitationsFor = ( + image: RustBinaryImage, + maxWasmSections: number, +): string[] => [ "Embedded dependency metadata is file content. It does not authenticate package names, versions, sources, or the compiler that produced the binary.", `Only the .dep-v0 dependency section and compiler path strings in ${compilerPathSource(image.format)} are inspected. Functions, types, and runtime behavior are not recovered.`, ...(image.format === "wasm" ? [ - `WebAssembly declares no container word size, so bits is null. Memory address types were not inspected. At most ${MAX_WASM_SECTIONS} section payloads are examined.`, + `WebAssembly declares no container word size, so bits is null. Memory address types were not inspected. At most ${String(maxWasmSections)} section payloads (max_wasm_sections) are examined.`, ] : []), RUST_RESOURCE_GUARD_LIMITATION, @@ -383,16 +392,8 @@ const failureFor = ( path, description: "artifact", recognise: (failure, origin) => { - if (failure instanceof BinaryResourceFailure) - return parseLimitConstraint(OPERATION, "memory", failure, { - path, - legacyMaximumKey: "maximum_bytes", - ...fixedAllowanceOptions( - "This native container parser allowance", - "parser", - binaryResourceCeiling(failure), - ), - }); + if (isNativeStructureFailure(failure)) + return nativeStructureConstraint(OPERATION, failure, path); if (isParseLimit(failure, RUST_AUDITABLE_FORMAT)) { const { name, maximum } = failure.failure.limit; if (name === RUST_AUDITABLE_GRAPH_LIMIT) @@ -423,11 +424,8 @@ const failureFor = ( if (isParseLimit(failure, WASM_FORMAT)) return parseLimitConstraint(OPERATION, "cpu", failure, { path, - ...fixedAllowanceOptions( - "The WebAssembly section-walk allowance", - "work", - { limit: failure.failure.limit.maximum, unit: "sections" }, - ), + retryable: false, + limit: rustWasmSectionLimit(failure.failure.limit.maximum), }); if ( origin === "owned-or-classified" && diff --git a/src/rust/RustWasmImage.ts b/src/rust/RustWasmImage.ts index c0f254a0c03..e383a54cd90 100644 --- a/src/rust/RustWasmImage.ts +++ b/src/rust/RustWasmImage.ts @@ -8,16 +8,11 @@ import { unsupportedInput, } from "../domain/parseFailure.js"; import { readByteSourceSlice, type ByteSource } from "../domain/byteSource.js"; +import { RUST_WASM_SECTION_BUDGET } from "../domain/rust/rustBinary.js"; /** The ParseFailure format of WebAssembly section framing. */ export const WASM_FORMAT = "wasm"; -/** - * Producer output holds a few dozen sections. The format sets no bound, and a - * 256 MiB input of three-byte custom sections would otherwise keep this - * section walk busy for about 89 million sections. - */ -export const MAX_WASM_SECTIONS = 65_536; const PREAMBLE = Buffer.from("\0asm", "latin1"); const CORE_MODULE_VERSION = Buffer.from([1, 0, 0, 0]); const COMPONENT_LAYER = Buffer.from([1, 0]); @@ -53,6 +48,12 @@ const WASM_YIELD_INTERVAL = 256; export const readRustWasmSectionsFromReader = async ( source: ByteSource, pause?: ZstandardFramePause, + /** + * Producer output holds a few dozen sections. The format sets no bound, and + * a 256 MiB input of three-byte custom sections would otherwise keep this + * walk busy for about 89 million sections. + */ + maxSections: number = RUST_WASM_SECTION_BUDGET.default_value, ): Promise => { const readSlice = (offset: number, length: number) => readByteSourceSlice(source, offset, length); @@ -99,11 +100,12 @@ export const readRustWasmSectionsFromReader = async ( { offset: cursor, field: "section" }, ); // Admit one complete frame before charging any section payload work. - if (sections === MAX_WASM_SECTIONS) + // Sections are walked in turn, so the complete count is unknown here. + if (sections === maxSections) throw decodeLimit( WASM_FORMAT, - `WebAssembly module declares more than ${MAX_WASM_SECTIONS} sections`, - { name: "max_wasm_sections", maximum: MAX_WASM_SECTIONS }, + `WebAssembly module declares more than max_wasm_sections (${String(maxSections)}) sections`, + { name: "max_wasm_sections", maximum: maxSections }, { offset: cursor }, ); if (id === CUSTOM_SECTION) { diff --git a/tests/acceptance/rustBinaryCli.test.ts b/tests/acceptance/rustBinaryCli.test.ts index 5132472cc3e..01fe042e941 100644 --- a/tests/acceptance/rustBinaryCli.test.ts +++ b/tests/acceptance/rustBinaryCli.test.ts @@ -13,6 +13,7 @@ import { createRustImage, createRustWasmModule, createRustImageWithGoSection, + createWasmSectionFlood, RUSTC_HASH, rustDependencyPayload, } from "../fixtures/rust/image.js"; @@ -622,3 +623,87 @@ cliTest( ); }, ); + +cliTest( + "refuses a WebAssembly section walk past max_wasm_sections on CLI and MCP", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-rust-cli-wasm-sections-"); + const { client, call } = await connectLocalToolsMcp(); + const path = join(root, "sections.wasm"); + await writeFile(path, createWasmSectionFlood(8)); + const result = await cli.run({ + arguments: [ + "inspect-rust-binary", + path, + "--max-wasm-sections", + "4", + "--json", + ], + }); + expect(result.exitCode).toBe(1); + const response = await call("inspect_rust_binary", { + path, + max_wasm_sections: 4, + }); + const mcpError = parseMcpToolError(response).error; + const limit = { + control_kind: "parameter", + parameter: "max_wasm_sections", + effective_value: 4, + unit: "count", + minimum: 1, + maximum: 16_777_216, + default_value: 65_536, + applies_at: "next_call", + }; + const refusal = { + kind: "adjustable_budget", + operation: "inspect_rust_binary", + control: "max_wasm_sections", + effective_value: 4, + unit: "count", + range: { minimum: 1, maximum: 16_777_216 }, + default_value: 65_536, + }; + expect(mcpError).toMatchObject({ + code: "resource_constraint", + retryable: false, + details: { + operation: "inspect_rust_binary", + resource: "cpu", + reported_limits: { boundary: "max_wasm_sections", maximum: 4 }, + limit, + refusal, + }, + }); + expect(mcpError.details?.limit).not.toHaveProperty("required_value"); + expect(mcpError.details?.limit).not.toHaveProperty("cli_flag"); + expect(mcpError.remediation.action).toContain("max_wasm_sections"); + expect(mcpError.remediation.action).not.toContain("--max-wasm-sections"); + expect(result.json).toMatchObject({ + code: "resource_constraint", + retryable: false, + details: { + operation: "inspect_rust_binary", + resource: "cpu", + limit: { ...limit, cli_flag: "--max-wasm-sections" }, + refusal, + }, + }); + const cliRecovery = (result.json as { remediation?: { action?: string } }) + .remediation?.action; + expect(cliRecovery).toContain("--max-wasm-sections"); + expect(cliRecovery).toContain("rea inspect-rust-binary"); + const admitted = await cli.run({ + arguments: [ + "inspect-rust-binary", + path, + "--max-wasm-sections", + "8", + "--json", + ], + }); + expect(admitted.exitCode, admitted.stderr).toBe(0); + await client.ping(); + }, +); diff --git a/tests/boundary/go/goBinaryProvider.test.ts b/tests/boundary/go/goBinaryProvider.test.ts index 5371fc5b652..9c005a42cb8 100644 --- a/tests/boundary/go/goBinaryProvider.test.ts +++ b/tests/boundary/go/goBinaryProvider.test.ts @@ -5,6 +5,7 @@ import { expect, it, vi } from "vitest"; import { GoBinaryService } from "../../../src/application/go/GoBinaryService.js"; import { GoBinaryProvider } from "../../../src/go/GoBinaryProvider.js"; import { GO_ANALYSIS_BUDGET_DEFAULTS } from "../../../src/domain/go/goBinary.js"; +import { NATIVE_STRUCTURE_BYTES } from "../../../src/domain/native/nativeStructureBudget.js"; import { AnalysisTargetFailureError, AnalysisResourceConstraintError, @@ -27,11 +28,25 @@ it("reads Go build information from a PE32 image declaring one data directory", fixture.bytes.writeUInt32LE(1, 152 + 92); const path = join(root, "one-directory-pe32.exe"); await writeFile(path, fixture.bytes); - const result = await new GoBinaryProvider().inspect({ path }); - expect(result).toMatchObject({ - ok: true, - value: { build_info: { go_version: "go1.26.0" } }, + const structureBytes = NATIVE_STRUCTURE_BYTES.default_value * 2; + const result = await new GoBinaryProvider().inspect({ + path, + max_structure_bytes: structureBytes, }); + if (!result.ok) throw result.error; + expect(result.value.build_info).toMatchObject({ go_version: "go1.26.0" }); + expect( + result.value.limitations.some((limitation) => + limitation.includes(`max_structure_bytes=${String(structureBytes)}`), + ), + ).toBe(true); + expect( + result.value.limitations.some((limitation) => + limitation.includes( + `max_structure_bytes=${String(NATIVE_STRUCTURE_BYTES.default_value)}`, + ), + ), + ).toBe(false); }); it.each([false, true])( @@ -66,6 +81,12 @@ it.each([false, true])( boundary: "max_structure_bytes", maximum: 16 * 1024 * 1024, }, + limit: { + control_kind: "parameter", + parameter: "max_structure_bytes", + effective_value: 16 * 1024 * 1024, + }, + refusal: { kind: "adjustable_budget" }, }, }); else { diff --git a/tests/boundary/mcp/rustBinaryMcp.test.ts b/tests/boundary/mcp/rustBinaryMcp.test.ts index 48909e14ad7..6d50a231a60 100644 --- a/tests/boundary/mcp/rustBinaryMcp.test.ts +++ b/tests/boundary/mcp/rustBinaryMcp.test.ts @@ -114,7 +114,7 @@ fileInspectionTest( ); fileInspectionTest( - "refuses a WebAssembly section walk past its fixed work allowance", + "refuses a WebAssembly section walk past max_wasm_sections", async ({ client }) => { const root = await createTestTempDirectory("rea-rust-mcp-"); const path = join(root, "many-sections.wasm"); @@ -131,11 +131,22 @@ fileInspectionTest( operation: "inspect_rust_binary", resource: "cpu", reported_limits: { boundary: "max_wasm_sections", maximum: 65_536 }, + limit: { + control_kind: "parameter", + parameter: "max_wasm_sections", + effective_value: 65_536, + unit: "count", + minimum: 1, + maximum: 16_777_216, + default_value: 65_536, + }, refusal: { - kind: "fixed_ceiling", - allowance_kind: "work", - limit: 65_536, - unit: "sections", + kind: "adjustable_budget", + operation: "inspect_rust_binary", + control: "max_wasm_sections", + effective_value: 65_536, + unit: "count", + default_value: 65_536, }, }, }); diff --git a/tests/boundary/rust/rustBinaryBudget.test.ts b/tests/boundary/rust/rustBinaryBudget.test.ts index 6a6c7281436..70e05917e08 100644 --- a/tests/boundary/rust/rustBinaryBudget.test.ts +++ b/tests/boundary/rust/rustBinaryBudget.test.ts @@ -7,6 +7,7 @@ import { RustBinaryProvider } from "../../../src/rust/RustBinaryProvider.js"; import { createRustImage, createRustHashOverflowImage, + createWasmSectionFlood, } from "../../fixtures/rust/image.js"; import { elfFrameAllowanceFixture } from "../../fixtures/binaryDiagnostics/elfFrameAllowance.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -242,3 +243,31 @@ it("cancels a many-frame compressed ELF section-name table", async () => { spy.mockRestore(); } }); + +it("names max_wasm_sections when a module has more sections than it", async () => { + const root = await createTestTempDirectory("rea-rust-wasm-sections-"); + const path = join(root, "module.wasm"); + await writeFile(path, createWasmSectionFlood(8)); + const provider = new RustBinaryProvider(); + try { + const refused = await provider.inspect({ path, max_wasm_sections: 4 }); + if (refused.ok) throw new Error("Expected a max_wasm_sections refusal"); + expect(projectAnalysisError(refused.error)).toMatchObject({ + code: "resource_constraint", + details: { + limit: { + control_kind: "parameter", + parameter: "max_wasm_sections", + effective_value: 4, + default_value: 65_536, + }, + refusal: { kind: "adjustable_budget" }, + }, + }); + const admitted = await provider.inspect({ path, max_wasm_sections: 8 }); + if (!admitted.ok) throw admitted.error; + expect(admitted.value.format).toBe("wasm"); + } finally { + await provider.close(); + } +});