From 905e4866c4696872813064d1a71ee2569d61e067 Mon Sep 17 00:00:00 2001 From: Thang Luu Date: Sun, 11 Oct 2026 00:02:06 +0900 Subject: [PATCH] feat(artifacts): inspect PE resource identities and payload ranges (#1482) * feat(artifacts): inspect PE resource identities and payload ranges * fix(artifacts): reject header payloads overlapping PE sections --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> --- .../skills/reverse-engineer-anything/SKILL.md | 5 +- .../references/native-and-artifacts.md | 12 + docs/binary-diagnostics.md | 45 +++ scripts/lib/catalog-builders.mjs | 11 +- src/application/CapabilityInventory.ts | 2 + src/application/InvestigationProviders.ts | 7 + .../binaryDiagnostics/PeResourcesPort.ts | 19 ++ .../PeResourcesService.test.ts | 64 ++++ .../binaryDiagnostics/PeResourcesService.ts | 183 ++++++++++ src/cli/binaryDiagnosticsCommands.ts | 26 ++ src/cliCommandNames.ts | 1 + src/composition/binaryDiagnostics.ts | 6 + .../native/binaryDiagnosticsToolContracts.ts | 19 ++ src/contracts/toolEffects.ts | 1 + src/domain/artifactOperationError.ts | 1 + src/domain/native/peResources.ts | 113 +++++++ src/generatedPackageMetadata.ts | 2 +- src/native/pe/PeResourceLayout.ts | 143 ++++++++ src/native/pe/PeResourceParser.test.ts | 261 +++++++++++++++ src/native/pe/PeResourceParser.ts | 315 ++++++++++++++++++ src/native/pe/PeResources.fixture.ts | 148 ++++++++ src/native/pe/PeResourcesProvider.ts | 83 +++++ src/server/createServer.ts | 8 + src/server/registerPeResourcesTool.ts | 32 ++ .../applications/peResources.test.ts | 147 ++++++++ tests/boundary/filesystem/peResources.test.ts | 43 +++ 26 files changed, 1694 insertions(+), 3 deletions(-) create mode 100644 src/application/binaryDiagnostics/PeResourcesPort.ts create mode 100644 src/application/binaryDiagnostics/PeResourcesService.test.ts create mode 100644 src/application/binaryDiagnostics/PeResourcesService.ts create mode 100644 src/domain/native/peResources.ts create mode 100644 src/native/pe/PeResourceLayout.ts create mode 100644 src/native/pe/PeResourceParser.test.ts create mode 100644 src/native/pe/PeResourceParser.ts create mode 100644 src/native/pe/PeResources.fixture.ts create mode 100644 src/native/pe/PeResourcesProvider.ts create mode 100644 src/server/registerPeResourcesTool.ts create mode 100644 tests/acceptance/applications/peResources.test.ts create mode 100644 tests/boundary/filesystem/peResources.test.ts diff --git a/.agents/skills/reverse-engineer-anything/SKILL.md b/.agents/skills/reverse-engineer-anything/SKILL.md index c78345ba1..f87a4e110 100644 --- a/.agents/skills/reverse-engineer-anything/SKILL.md +++ b/.agents/skills/reverse-engineer-anything/SKILL.md @@ -2,7 +2,7 @@ name: reverse-engineer-anything description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. metadata: - version: "35" + version: "36" --- # REA @@ -121,6 +121,9 @@ explicit path or endpoint and do not need it. Historical PIDs do not select live processes. Request `include_debugger_context` only when core-only mapping candidates help; see the [recorded crash guide](https://github.com/morluto/rea/blob/main/docs/recorded-crashes.md). +- PE resource type/name/language trees and static icon group references: + `inspect_pe_resources` with an explicit path. This portable operation requires + no active target or engine; opaque payloads retain file ranges and SHA-256. - Native executable, library, or analysis database: `open_binary`, then use focused analysis tools directly; call `binary_overview` when metadata or inventory context is useful and available from the selected provider. diff --git a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md index 1a018534a..7fa6a44d2 100644 --- a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -153,3 +153,15 @@ context. PSP/stack/device state remains unmodeled. See [DOS guide](https://githu ### Function annotations in Ghidra Use `annotate_native_function` for one function name and/or entry comments, with at least one explicit change. Review its annotation readback and refreshed dossier inline. Changes are atomic and session-scoped; empty comments clear them, omitted fields preserve them. Later MCP calls observe edits until close. CLI `annotate-native-function` returns the updated analysis before discarding the session. Original executable bytes are unchanged; edits invalidate immutable snapshots. Windows P0 does not admit database mutations. + +## Offline PE resource inventory + +Use `inspect_pe_resources` with an absolute `path`, or +`rea inspect-pe-resources ./selected.exe --json`, for portable PE32/PE32+ +resource inspection without opening a native target. Preserve returned Evidence: +type/name/language IDs and UTF-16 names, original directory/data/payload ranges, +code pages, payload hashes and static icon-group references. Same-language icon +resolution is explicit; missing references and size mismatch remain visible. +Other payloads are opaque, and this operation does not decode images or simulate +Windows resource loading. Consult the budgets and supported tree profile in +[offline binary diagnostics](https://github.com/morluto/rea/blob/main/docs/binary-diagnostics.md). diff --git a/docs/binary-diagnostics.md b/docs/binary-diagnostics.md index 08c8ad890..9820f3bcb 100644 --- a/docs/binary-diagnostics.md +++ b/docs/binary-diagnostics.md @@ -142,3 +142,48 @@ malformed limit reports remain unknown with their read failure preserved. A received signal alone does not establish its exact cause. Dynamic tags require a complete DT_NULL inside PT_DYNAMIC; interpreter names and ranges end at the first NUL, with any padding still represented by the original segment range. + +## Portable PE resources + +`inspect_pe_resources` / `inspect-pe-resources` inspects an explicit PE32 or +PE32+ file without an active target, native engine, Python, or Windows SDK: + +```sh +rea inspect-pe-resources ./selected.exe --json +``` + +```json +{ + "name": "inspect_pe_resources", + "arguments": { "path": "/artifacts/selected.exe" } +} +``` + +The complete Evidence identifies the stable artifact snapshot by path, byte +count and SHA-256. Resources retain separate type, name and language identities: +numeric IDs are distinct from UTF-16 names, whose original bytes are also +reported. Directory headers, entries, data entries and payloads retain original +file offsets and lengths. Each opaque payload has its own SHA-256; code page and +reserved data-entry fields are preserved. + +RT_GROUP_ICON records expose original image descriptors and RT_ICON candidates. +A reference resolves only when an icon with the same numeric ID and language +exists. Missing references, other-language candidates and declared-size mismatch +remain explicit. Encoded dimensions are preserved (zero denotes 256 pixels). +This is static reference inspection; no image decoding, language fallback, +resource loading or selected-file execution occurs. + +An absent resource data directory is a complete empty inventory. Malformed +headers, truncated tables, cycles, duplicate sibling identities, unbacked or +ambiguous RVA mappings, nonidentical overlapping ranges and unsupported tree +shapes fail explicitly, rather than returning partial inventories. Exact shared +payload ranges are supported. The supported tree has three levels: type, name, +and language. Other resource payload formats remain opaque. + +`max_file_bytes` defaults to 64 MiB (maximum 512 MiB); `max_entries` defaults to +4096 (maximum 65536). CLI options are `--max-file-bytes` and `--max-entries`. +Metadata is bounded to 8 MiB; exceeding any budget fails without truncation. +Large Evidence envelopes may require a caller-configured MCP transport receive +buffer because envelope copies add overhead. Requests honor cancellation during +snapshot reading, directory traversal and payload hashing. The operation reads +regular files only and rejects symbolic links. diff --git a/scripts/lib/catalog-builders.mjs b/scripts/lib/catalog-builders.mjs index 9218dc8e2..8f1e21572 100644 --- a/scripts/lib/catalog-builders.mjs +++ b/scripts/lib/catalog-builders.mjs @@ -158,7 +158,16 @@ export const providerCatalog = (sources) => { { identity: sources.pwntoolsProvider.PWNTOOLS_PROVIDER_IDENTITY, contracts: - sources.binaryDiagnosticsContracts.BINARY_DIAGNOSTICS_TOOL_CONTRACTS, + sources.binaryDiagnosticsContracts.BINARY_DIAGNOSTICS_TOOL_CONTRACTS.filter( + ({ name }) => name !== "inspect_pe_resources", + ), + }, + { + identity: sources.artifactProviders.PE_RESOURCES_PROVIDER, + contracts: + sources.binaryDiagnosticsContracts.BINARY_DIAGNOSTICS_TOOL_CONTRACTS.filter( + ({ name }) => name === "inspect_pe_resources", + ), }, { identity: sources.evmProvider.EVMOLE_PROVIDER_IDENTITY, diff --git a/src/application/CapabilityInventory.ts b/src/application/CapabilityInventory.ts index a710b34af..539796f57 100644 --- a/src/application/CapabilityInventory.ts +++ b/src/application/CapabilityInventory.ts @@ -313,6 +313,8 @@ const workflowAvailabilityFor = ({ remediation: "On Linux x64, set absolute REA_PWNTOOLS_PYTHON to caller-supplied Python with pwntools 4.15.0. No active binary target is required.", }; + if (name === "inspect_pe_resources") + return { reason: "available", remediation: null }; if (name === "inspect_evm_interface") return policy.evmInterfaceEnabled === true ? { reason: "available", remediation: null } diff --git a/src/application/InvestigationProviders.ts b/src/application/InvestigationProviders.ts index 4861272a0..4e333ec27 100644 --- a/src/application/InvestigationProviders.ts +++ b/src/application/InvestigationProviders.ts @@ -37,6 +37,13 @@ export const MANAGED_STATIC_PROVIDER = Object.freeze({ version: "1", } as const); +/** Provider identity for portable, execution-free PE resource decoding. */ +export const PE_RESOURCES_PROVIDER = Object.freeze({ + id: "rea-pe-resources", + name: "REA PE resource parser", + version: "1", +} as const); + /** Provider identity for deterministic managed-code comparison workflows. */ export const MANAGED_WORKFLOW_PROVIDER = { id: "rea-dotnet-workflows", diff --git a/src/application/binaryDiagnostics/PeResourcesPort.ts b/src/application/binaryDiagnostics/PeResourcesPort.ts new file mode 100644 index 000000000..b1a7b53de --- /dev/null +++ b/src/application/binaryDiagnostics/PeResourcesPort.ts @@ -0,0 +1,19 @@ +import type { + ExecutionOptions, + ProviderIdentity, +} from "../AnalysisProvider.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import type { + InspectPeResourcesInput, + PeResources, +} from "../../domain/native/peResources.js"; +import type { Result } from "../../domain/result.js"; + +/** Stable read and PE decoding boundary, independent of an active disassembler session. */ +export interface PeResourcesPort { + readonly identity: ProviderIdentity; + inspect( + input: InspectPeResourcesInput, + options?: ExecutionOptions, + ): Promise>; +} diff --git a/src/application/binaryDiagnostics/PeResourcesService.test.ts b/src/application/binaryDiagnostics/PeResourcesService.test.ts new file mode 100644 index 000000000..8f451ca9f --- /dev/null +++ b/src/application/binaryDiagnostics/PeResourcesService.test.ts @@ -0,0 +1,64 @@ +import { createHash } from "node:crypto"; +import { expect, it } from "vitest"; +import { PeResourcesService } from "./PeResourcesService.js"; +import { PE_RESOURCES_PROVIDER } from "../InvestigationProviders.js"; +import { inspectPeResourcesInputSchema } from "../../domain/native/peResources.js"; +import { parsePeResources } from "../../native/pe/PeResourceParser.js"; +import { peResourceFixture } from "../../native/pe/PeResources.fixture.js"; +import { ok } from "../../domain/result.js"; + +const observedReport = () => { + const { bytes } = peResourceFixture(); + return parsePeResources( + bytes, + { + path: "/fixtures/example.exe", + bytes: bytes.length, + sha256: createHash("sha256").update(bytes).digest("hex"), + }, + inspectPeResourcesInputSchema.parse({ path: "/fixtures/example.exe" }), + ); +}; + +it.each([ + "different-path", + "outside-range", + "wrong-coverage", + "bad-icon-reference", +])( + "rejects invalid provider output before creating Evidence: %s", + async (problem) => { + const report = await observedReport(); + if (problem === "different-path") report.artifact.path = "/other.exe"; + if (problem === "outside-range") + report.resources[0]!.payload.location.offset = report.artifact.bytes; + if (problem === "wrong-coverage") report.coverage.resources = 99; + if (problem === "bad-icon-reference") + report.icon_groups[0]!.images[0]!.candidate_resource_indices = [999]; + const service = new PeResourcesService({ + identity: PE_RESOURCES_PROVIDER, + inspect: () => Promise.resolve(ok(report)), + }); + expect( + await service.inspect({ path: "/fixtures/example.exe" }), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisOutputError" } }); + }, +); + +it("discards an observation if the caller cancels while the provider completes", async () => { + const report = await observedReport(); + const controller = new AbortController(); + const service = new PeResourcesService({ + identity: PE_RESOURCES_PROVIDER, + inspect: () => { + controller.abort(); + return Promise.resolve(ok(report)); + }, + }); + expect( + await service.inspect( + { path: report.artifact.path }, + { signal: controller.signal }, + ), + ).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } }); +}); diff --git a/src/application/binaryDiagnostics/PeResourcesService.ts b/src/application/binaryDiagnostics/PeResourcesService.ts new file mode 100644 index 000000000..3c8a53704 --- /dev/null +++ b/src/application/binaryDiagnostics/PeResourcesService.ts @@ -0,0 +1,183 @@ +import { isAbsolute } from "node:path"; +import type { ExecutionOptions } from "../AnalysisProvider.js"; +import type { PeResourcesPort } from "./PeResourcesPort.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import { + AnalysisCancelledError, + AnalysisInputError, + AnalysisOutputError, +} from "../../domain/analysisErrorCore.js"; +import { createEvidence, type Evidence } from "../../domain/evidence.js"; +import { + inspectPeResourcesInputSchema, + peResourcesSchema, + type PeResources, + type PeResourceIdentity, +} from "../../domain/native/peResources.js"; +import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js"; +import { err, ok, type Result } from "../../domain/result.js"; + +/** Shared caller validation, output parsing and Evidence provenance for CLI/MCP. */ +export class PeResourcesService { + constructor(readonly provider: PeResourcesPort) {} + + async inspect( + rawInput: unknown, + options?: ExecutionOptions, + ): Promise> { + const operation = "inspect_pe_resources"; + if (options?.signal?.aborted) + return err(new AnalysisCancelledError(operation)); + const input = inspectPeResourcesInputSchema.safeParse(rawInput); + if (!input.success) + return err( + analysisInputErrorFromIssues(operation, input.error.issues, rawInput, { + cause: input.error, + }), + ); + if (!isAbsolute(input.data.path)) + return err( + new AnalysisInputError(operation, undefined, [ + { + path: ["path"], + reason: "invalid_format", + message: "Expected an absolute filesystem path on this host.", + }, + ]), + ); + const result = await this.provider.inspect(input.data, options); + if (!result.ok) return result; + if (options?.signal?.aborted) + return err(new AnalysisCancelledError(operation)); + const report = peResourcesSchema.safeParse(result.value); + if ( + !report.success || + report.data.artifact.path !== input.data.path || + !validReport( + report.data, + input.data.max_entries, + input.data.max_file_bytes, + ) + ) + return err( + new AnalysisOutputError( + operation, + "PE resource provider returned malformed output or changed artifact identity.", + ), + ); + const value = report.data; + return ok( + createEvidence( + { + path: value.artifact.path, + format: "pe", + sha256: value.artifact.sha256, + }, + this.provider.identity, + { + operation, + parameters: input.data, + result: value, + confidence: "observed", + limitations: value.limitations, + locations: [{ kind: "artifact-path", path: value.artifact.path }], + }, + ), + ); + } +} + +/** Check cross-field invariants before provider output becomes public Evidence. */ +const validReport = ( + report: PeResources, + maxEntries: number, + maxBytes: number, +): boolean => { + const inside = ({ offset, bytes }: { offset: number; bytes: number }) => + offset <= report.artifact.bytes - bytes; + if ( + report.artifact.bytes > maxBytes || + report.coverage.resources !== report.resources.length || + report.coverage.examined_entries > maxEntries || + report.coverage.examined_entries !== + report.directories.reduce( + (sum, item) => sum + item.named_entries + item.id_entries, + 0, + ) + ) + return false; + if ( + report.directory === null && + (report.directories.length > 0 || report.resources.length > 0) + ) + return false; + if ( + report.directory !== null && + (!inside(report.directory.location) || + !inside(report.directory.data_directory_location)) + ) + return false; + if (!report.directories.every((item) => inside(item.location))) return false; + if ( + !report.resources.every( + (item, index) => + item.index === index && + inside(item.data_entry_location) && + inside(item.payload.location) && + item.entry_locations.every(inside) && + [item.type, item.name, item.language].every( + (identity) => identity.kind === "id" || inside(identity.location), + ), + ) + ) + return false; + return report.icon_groups.every((group) => { + const resource = report.resources[group.resource_index]; + if ( + resource === undefined || + resource.type.kind !== "id" || + resource.type.id !== 14 + ) + return false; + return group.images.every( + (image) => + inside(image.location) && + image.location.offset >= resource.payload.location.offset && + image.location.offset + image.location.bytes <= + resource.payload.location.offset + resource.payload.location.bytes && + image.candidate_resource_indices.every((index) => { + const icon = report.resources[index]; + return ( + icon !== undefined && + icon.type.kind === "id" && + icon.type.id === 3 && + icon.name.kind === "id" && + icon.name.id === image.resource_id + ); + }) && + (image.same_language_resource_index === null + ? image.size_matches === null + : image.candidate_resource_indices.includes( + image.same_language_resource_index, + ) && + sameIdentity( + report.resources[image.same_language_resource_index]?.language, + resource.language, + ) && + image.size_matches === + (report.resources[image.same_language_resource_index]?.payload + .location.bytes === + image.declared_bytes)), + ); + }); +}; + +const sameIdentity = ( + left: PeResourceIdentity | undefined, + right: PeResourceIdentity, +): boolean => + left?.kind === "id" && right.kind === "id" + ? left.id === right.id + : left?.kind === "name" && + right.kind === "name" && + left.utf16le_hex === right.utf16le_hex; diff --git a/src/cli/binaryDiagnosticsCommands.ts b/src/cli/binaryDiagnosticsCommands.ts index 7174586bd..70c119900 100644 --- a/src/cli/binaryDiagnosticsCommands.ts +++ b/src/cli/binaryDiagnosticsCommands.ts @@ -3,6 +3,7 @@ import { resolve } from "node:path"; import { createRecordedCrashService, createBinaryLayoutService, + createPeResourcesService, } from "../composition/binaryDiagnostics.js"; import { CLI_COMMANDS } from "../cliCommandNames.js"; import { logCliCommand } from "../cliLogging.js"; @@ -10,6 +11,7 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import type { Logger } from "pino"; import type { CliInstance } from "./types.js"; import { withCommandCancellation } from "./commandCancellation.js"; +import { inspectPeResourcesInputSchema } from "../domain/native/peResources.js"; /** Inspect operator-selected files through the same shared workflow as MCP. */ export const registerBinaryDiagnosticsCommands = ( @@ -17,6 +19,30 @@ export const registerBinaryDiagnosticsCommands = ( logger: Logger, environment: Readonly, ): void => { + const pe = createPeResourcesService(); + cli.command(CLI_COMMANDS.inspectPeResources, { + description: + "Inspect PE resource identities, payload ranges, hashes and icon-group relationships", + args: z.object({ path: z.string().describe("Local PE32/PE32+ image") }), + options: z.object({ + maxFileBytes: inspectPeResourcesInputSchema.shape.max_file_bytes, + maxEntries: inspectPeResourcesInputSchema.shape.max_entries, + }), + run: ({ args, options }) => + withCommandCancellation((signal) => + logCliCommand(logger, CLI_COMMANDS.inspectPeResources, async () => { + const result = await pe.inspect( + { + path: resolve(args.path), + max_file_bytes: options.maxFileBytes, + max_entries: options.maxEntries, + }, + { signal }, + ); + return result.ok ? result.value : projectAnalysisError(result.error); + }), + ), + }); const service = createBinaryLayoutService(environment); cli.command(CLI_COMMANDS.inspectBinaryLayout, { description: diff --git a/src/cliCommandNames.ts b/src/cliCommandNames.ts index 99db69fb6..76b34a539 100644 --- a/src/cliCommandNames.ts +++ b/src/cliCommandNames.ts @@ -41,6 +41,7 @@ export const CLI_COMMANDS = Object.freeze({ inspectManagedArtifact: "inspect-managed-artifact", inspectRecordedCrash: "inspect-recorded-crash", inspectBinaryLayout: "inspect-binary-layout", + inspectPeResources: "inspect-pe-resources", inspectAnalysisView: "inspect-analysis-view", inspectFirmwareRegions: "inspect-firmware-regions", extractFirmware: "extract-firmware", diff --git a/src/composition/binaryDiagnostics.ts b/src/composition/binaryDiagnostics.ts index 7fab8d73a..afadee6c5 100644 --- a/src/composition/binaryDiagnostics.ts +++ b/src/composition/binaryDiagnostics.ts @@ -2,6 +2,12 @@ import { RecordedCrashService } from "../application/binaryDiagnostics/RecordedC import { PwntoolsRecordedCrashProvider } from "../native/pwntools/PwntoolsRecordedCrashProvider.js"; import { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js"; import { PwntoolsLayoutProvider } from "../native/pwntools/PwntoolsLayoutProvider.js"; +import { PeResourcesService } from "../application/binaryDiagnostics/PeResourcesService.js"; +import { PeResourcesProvider } from "../native/pe/PeResourcesProvider.js"; + +/** Portable PE inspection with no engine, installation or target acquisition. */ +export const createPeResourcesService = (): PeResourcesService => + new PeResourcesService(new PeResourcesProvider()); /** Compose the offline adapter without import-time I/O or dependency acquisition. */ export const createBinaryLayoutService = ( diff --git a/src/contracts/native/binaryDiagnosticsToolContracts.ts b/src/contracts/native/binaryDiagnosticsToolContracts.ts index 546692331..80dea5e62 100644 --- a/src/contracts/native/binaryDiagnosticsToolContracts.ts +++ b/src/contracts/native/binaryDiagnosticsToolContracts.ts @@ -13,6 +13,10 @@ import { import type { ToolContract } from "../toolContractTypes.js"; import { toolContractMetadata } from "../toolEffects.js"; import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js"; +import { + inspectPeResourcesInputSchema, + peResourcesSchema, +} from "../../domain/native/peResources.js"; /** Caller-selected delivery of completed binary layout Evidence. */ export const inspectBinaryLayoutRequestSchema = @@ -20,6 +24,21 @@ export const inspectBinaryLayoutRequestSchema = /** Offline binary diagnostics are independent of macOS process/UI providers. */ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [ + { + name: "inspect_pe_resources", + ...toolContractMetadata("inspect_pe_resources"), + kind: "native-provider", + description: + "Inspect one explicit local PE32/PE32+ image's complete bounded type/name/language resource tree without executing it or opening a disassembler. Returns numeric IDs versus original UTF-16 names, directory/data-entry file locations, payload RVA/file ranges, complete SHA-256 hashes and static RT_GROUP_ICON image-resource candidates. Language fallback, image decoding and actual shell/window loading remain unobserved. Reads a stable regular file; malformed or ambiguous mappings, non-identical overlapping ranges and exhausted budgets return no partial success. Portable on supported Node hosts; no Windows SDK or engine installation required.", + inputSchema: inspectPeResourcesInputSchema, + outputSchema: evidenceResultOf(peResourcesSchema), + examples: [ + { + title: "Inspect PE resource identities and icon relationships", + input: { path: "/artifacts/application.exe" }, + }, + ], + }, { name: "inspect_binary_layout", ...toolContractMetadata("inspect_binary_layout"), diff --git a/src/contracts/toolEffects.ts b/src/contracts/toolEffects.ts index 2c4cc0240..efd7a1ef6 100644 --- a/src/contracts/toolEffects.ts +++ b/src/contracts/toolEffects.ts @@ -80,6 +80,7 @@ export const TOOL_EFFECTS: Readonly> = { writesFilesystem: true, launchesProcess: true, }), + inspect_pe_resources: evidence, inspect_analysis_view: evidence, inspect_firmware_regions: effects({ mutatesSession: true, diff --git a/src/domain/artifactOperationError.ts b/src/domain/artifactOperationError.ts index 54ed89d15..8f47fa56e 100644 --- a/src/domain/artifactOperationError.ts +++ b/src/domain/artifactOperationError.ts @@ -11,6 +11,7 @@ export class ArtifactOperationError extends AnalysisError { readonly operation: | "inventory_artifact" | "inspect_artifact" + | "inspect_pe_resources" | "extract_artifact" | "decode_interface_builder" | "inspect_asset_catalog" diff --git a/src/domain/native/peResources.ts b/src/domain/native/peResources.ts new file mode 100644 index 000000000..977ac36ad --- /dev/null +++ b/src/domain/native/peResources.ts @@ -0,0 +1,113 @@ +import { z } from "zod"; + +const uint = z.number().int().min(0).max(0xffffffff); +const range = z.strictObject({ offset: uint, bytes: uint }); +const identity = z.discriminatedUnion("kind", [ + z.strictObject({ kind: z.literal("id"), id: uint }), + z.strictObject({ + kind: z.literal("name"), + name: z.string(), + utf16le_hex: z.string().regex(/^(?:[0-9a-f]{4})*$/), + location: range, + }), +]); + +/** Complete bounded inspection of a caller-selected PE image, without execution. */ +export const inspectPeResourcesInputSchema = z.strictObject({ + path: z.string().min(1).describe("Absolute filesystem path to a PE image"), + max_file_bytes: z + .number() + .int() + .min(64) + .max(536870912) + .default(67108864) + .describe("Maximum stable artifact bytes to read (default 64 MiB)"), + max_entries: z + .number() + .int() + .min(1) + .max(65536) + .default(4096) + .describe( + "Maximum resource directory entries to examine; exceeding the budget fails without partial success", + ), +}); + +/** Original file/RVA locations and resource identities; icon edges are static relationships. */ +export const peResourcesSchema = z.strictObject({ + artifact: z.strictObject({ + path: z.string().min(1), + sha256: z.string().regex(/^[a-f0-9]{64}$/), + bytes: uint, + }), + format: z.enum(["pe32", "pe32-plus"]), + machine: uint, + directory: z + .strictObject({ + rva: uint, + location: range, + data_directory_location: range, + }) + .nullable(), + directories: z.array( + z.strictObject({ + location: range, + characteristics: uint, + timestamp: uint, + major_version: uint, + minor_version: uint, + named_entries: uint, + id_entries: uint, + }), + ), + resources: z.array( + z.strictObject({ + index: uint, + type: identity, + name: identity, + language: identity, + entry_locations: z.array(range).length(3), + data_entry_location: range, + code_page: uint, + reserved: uint, + payload: z.strictObject({ + rva: uint, + location: range, + sha256: z.string().regex(/^[a-f0-9]{64}$/), + }), + }), + ), + icon_groups: z.array( + z.strictObject({ + resource_index: uint, + images: z.array( + z.strictObject({ + location: range, + width: uint, + height: uint, + color_count: uint, + reserved: uint, + planes: uint, + bit_count: uint, + declared_bytes: uint, + resource_id: uint, + candidate_resource_indices: z.array(uint), + same_language_resource_index: uint.nullable(), + size_matches: z.boolean().nullable(), + }), + ), + }), + ), + coverage: z.strictObject({ + status: z.literal("complete"), + examined_entries: uint, + resources: uint, + }), + limitations: z.array(z.string()), +}); + +export type PeResources = z.infer; +export type InspectPeResourcesInput = z.infer< + typeof inspectPeResourcesInputSchema +>; +export type PeResourceIdentity = PeResources["resources"][number]["type"]; diff --git a/src/generatedPackageMetadata.ts b/src/generatedPackageMetadata.ts index 468117b05..aaa5b9a80 100644 --- a/src/generatedPackageMetadata.ts +++ b/src/generatedPackageMetadata.ts @@ -5,5 +5,5 @@ export const PACKAGE_METADATA = { serverSdkVersion: "2.3.1", clientSdkVersion: "2.3.1", coreSdkVersion: "2.3.1", - skillVersion: "35", + skillVersion: "36", } as const; diff --git a/src/native/pe/PeResourceLayout.ts b/src/native/pe/PeResourceLayout.ts new file mode 100644 index 000000000..521c27083 --- /dev/null +++ b/src/native/pe/PeResourceLayout.ts @@ -0,0 +1,143 @@ +import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js"; + +export const peFailure = (message: string): never => { + throw new ArtifactReaderFailure("format", message); +}; + +export const requirePeRange = ( + bytes: Buffer, + offset: number, + length: number, +): void => { + if ( + !Number.isSafeInteger(offset) || + !Number.isSafeInteger(length) || + offset < 0 || + length < 0 || + offset > bytes.length - length + ) + peFailure( + `PE range ${String(offset)} + ${String(length)} leaves the artifact.`, + ); +}; + +interface Section { + readonly rva: number; + readonly virtualSize: number; + readonly offset: number; + readonly size: number; +} + +/** Header admission and unambiguous file-backed RVA mapping, independent of section names. */ +export const readPeResourceLayout = (bytes: Buffer) => { + requirePeRange(bytes, 0, 64); + if (bytes.readUInt16LE(0) !== 0x5a4d) peFailure("Expected an MZ PE image."); + const pe = bytes.readUInt32LE(60); + requirePeRange(bytes, pe, 24); + if (bytes.readUInt32LE(pe) !== 0x4550) peFailure("Expected a PE signature."); + const sectionCount = bytes.readUInt16LE(pe + 6); + const optionalSize = bytes.readUInt16LE(pe + 20); + const optional = pe + 24; + requirePeRange(bytes, optional, optionalSize); + if (optionalSize < 64) peFailure("Truncated PE optional header."); + const magic = bytes.readUInt16LE(optional); + if (magic !== 0x10b && magic !== 0x20b) + peFailure("Unsupported PE optional header magic."); + const countAt = magic === 0x10b ? 92 : 108; + const directoriesAt = countAt + 4; + if (optionalSize < directoriesAt) + peFailure("Truncated PE data directory count."); + const directoryCount = bytes.readUInt32LE(optional + countAt); + if (directoryCount > Math.floor((optionalSize - directoriesAt) / 8)) + peFailure("PE directory count exceeds its optional header."); + const headerSize = bytes.readUInt32LE(optional + 60); + const table = optional + optionalSize; + requirePeRange(bytes, table, sectionCount * 40); + if (headerSize < table + sectionCount * 40 || headerSize > bytes.length) + peFailure("Invalid PE SizeOfHeaders."); + const sections: Section[] = []; + for (let index = 0; index < sectionCount; index++) { + const at = table + index * 40; + const section = { + rva: bytes.readUInt32LE(at + 12), + virtualSize: bytes.readUInt32LE(at + 8), + offset: bytes.readUInt32LE(at + 20), + size: bytes.readUInt32LE(at + 16), + }; + if (section.rva + Math.max(section.virtualSize, section.size) > 0x100000000) + peFailure("PE section RVA range overflows."); + if (section.size > 0) { + requirePeRange(bytes, section.offset, section.size); + if (section.offset < headerSize) + peFailure("PE section raw bytes overlap headers."); + } + sections.push(section); + } + const backed = sections + .filter(({ size }) => size > 0) + .sort((left, right) => left.offset - right.offset); + for (let index = 1; index < backed.length; index++) { + const previous = backed[index - 1]; + const current = backed[index]; + if ( + previous !== undefined && + current !== undefined && + current.offset < previous.offset + previous.size + ) + peFailure("PE sections have overlapping raw file ranges."); + } + const map = (rva: number, size: number): number => { + if (rva + size > 0x100000000) peFailure("Resource RVA range overflows."); + const candidates = sections.filter( + (section) => + rva >= section.rva && + rva - section.rva < Math.max(section.size, section.virtualSize), + ); + if (rva < headerSize) { + if ( + sections.some( + (section) => + section.rva < rva + size && + section.rva + Math.max(section.size, section.virtualSize) > rva, + ) || + size > headerSize - rva + ) + peFailure("Ambiguous resource header RVA mapping."); + requirePeRange(bytes, rva, size); + return rva; + } + if (candidates.length !== 1) + peFailure("Resource RVA has missing or overlapping section mappings."); + const section = candidates[0]; + if (section === undefined) return peFailure("Missing resource section."); + const within = rva - section.rva; + if (within > section.size || size > section.size - within) + peFailure("Resource range is not entirely file-backed in one section."); + // A second section starting inside the requested interval is ambiguous too. + if ( + sections.some( + (other) => + other !== section && + other.rva < rva + size && + other.rva + Math.max(other.size, other.virtualSize) > rva, + ) + ) + peFailure("Resource interval intersects overlapping virtual sections."); + const offset = section.offset + within; + requirePeRange(bytes, offset, size); + return offset; + }; + const directoryAt = optional + directoriesAt + 16; + const rva = directoryCount > 2 ? bytes.readUInt32LE(directoryAt) : 0; + const size = directoryCount > 2 ? bytes.readUInt32LE(directoryAt + 4) : 0; + if ((rva === 0) !== (size === 0)) + peFailure("Inconsistent PE resource directory RVA/size."); + return { + format: magic === 0x10b ? ("pe32" as const) : ("pe32-plus" as const), + machine: bytes.readUInt16LE(pe + 4), + directoryAt, + rva, + size, + map, + }; +}; diff --git a/src/native/pe/PeResourceParser.test.ts b/src/native/pe/PeResourceParser.test.ts new file mode 100644 index 000000000..5c1b8626d --- /dev/null +++ b/src/native/pe/PeResourceParser.test.ts @@ -0,0 +1,261 @@ +import { createHash } from "node:crypto"; +import { describe, expect, it } from "vitest"; +import { + inspectPeResourcesInputSchema, + peResourcesSchema, +} from "../../domain/native/peResources.js"; +import { parsePeResources } from "./PeResourceParser.js"; +import { peResourceFixture } from "./PeResources.fixture.js"; + +const parse = (bytes: Buffer, maxEntries = 4096, signal?: AbortSignal) => + parsePeResources( + bytes, + { + path: "/fixtures/example.exe", + bytes: bytes.length, + sha256: createHash("sha256").update(bytes).digest("hex"), + }, + inspectPeResourcesInputSchema.parse({ + path: "/fixtures/example.exe", + max_entries: maxEntries, + }), + signal, + ); + +describe("portable PE resource parsing", () => { + it.each([false, true])( + "preserves original identities, ranges, hashes and icon candidates (PE32+ = %s)", + async (plus) => { + const { bytes } = peResourceFixture(plus); + const result = peResourcesSchema.parse(await parse(bytes)); + expect(result.format).toBe(plus ? "pe32-plus" : "pe32"); + expect(result.coverage).toMatchObject({ + status: "complete", + resources: 5, + }); + expect( + result.resources.map(({ type, name, language }) => [ + type, + name, + language, + ]), + ).toContainEqual([ + { kind: "id", id: 10 }, + { kind: "id", id: 7 }, + { kind: "id", id: 1041 }, + ]); + const named = result.resources.find(({ name }) => name.kind === "name"); + expect(named?.name).toMatchObject({ + kind: "name", + name: "7", + utf16le_hex: "3700", + }); + for (const resource of result.resources) { + const { offset, bytes: size } = resource.payload.location; + expect(resource.payload.rva - offset).toBe(0x1c00); + expect(resource.payload.sha256).toBe( + createHash("sha256") + .update(bytes.subarray(offset, offset + size)) + .digest("hex"), + ); + } + expect(result.icon_groups[0]?.images).toMatchObject([ + { + resource_id: 1, + candidate_resource_indices: [0, 1], + same_language_resource_index: 0, + size_matches: true, + }, + { + resource_id: 99, + candidate_resource_indices: [], + same_language_resource_index: null, + size_matches: null, + }, + ]); + }, + ); + + it("distinguishes an absent resource directory from a present empty tree", async () => { + const fixture = peResourceFixture(false, []); + expect(await parse(fixture.bytes)).toMatchObject({ + directory: { rva: 0x2000 }, + resources: [], + coverage: { resources: 0, examined_entries: 0 }, + }); + fixture.bytes.fill(0, fixture.directoryAt, fixture.directoryAt + 8); + expect(await parse(fixture.bytes)).toMatchObject({ + directory: null, + resources: [], + }); + }); + + it.each([ + [ + "truncated directory", + (fixture: ReturnType) => + fixture.bytes.writeUInt32LE(17, fixture.directoryAt + 4), + ], + [ + "cycle", + (fixture: ReturnType) => + fixture.bytes.writeUInt32LE( + 0x80000000, + (fixture.entryOffsets[0] ?? 0) + 4, + ), + ], + [ + "bad payload RVA", + (fixture: ReturnType) => + fixture.bytes.writeUInt32LE(0xfffffff0, fixture.dataOffsets[0]), + ], + [ + "overlapping payloads", + (fixture: ReturnType) => + fixture.bytes.writeUInt32LE( + fixture.bytes.readUInt32LE(fixture.dataOffsets[0]) + 1, + fixture.dataOffsets[1], + ), + ], + [ + "bad named counts", + (fixture: ReturnType) => + fixture.bytes.writeUInt16LE(1, 0x400 + 12), + ], + [ + "truncated data entry", + (fixture: ReturnType) => + fixture.bytes.writeUInt32LE( + 0x7fffffff, + (fixture.entryOffsets.at(-1) ?? 0) + 4, + ), + ], + ])("rejects %s without partial success", async (_name, mutate) => { + const fixture = peResourceFixture(); + mutate(fixture); + await expect(parse(fixture.bytes)).rejects.toMatchObject({ + reason: "format", + }); + }); +}); + +describe("PE header admission and bounded traversal", () => { + it.each([ + [ + "truncated DOS header", + (fixture: ReturnType) => + fixture.bytes.subarray(0, 63), + ], + [ + "invalid optional magic", + (fixture: ReturnType) => { + fixture.bytes.writeUInt16LE(0, 0x98); + return fixture.bytes; + }, + ], + [ + "unbacked virtual payload", + (fixture: ReturnType) => { + fixture.bytes.writeUInt32LE(0x10000, fixture.sectionAt + 8); + fixture.bytes.writeUInt32LE(0x8000, fixture.dataOffsets[0]); + return fixture.bytes; + }, + ], + [ + "duplicate sibling IDs", + (fixture: ReturnType) => { + fixture.bytes.writeUInt32LE( + fixture.bytes.readUInt32LE(fixture.entryOffsets[0]), + (fixture.entryOffsets[0] ?? 0) + 8, + ); + return fixture.bytes; + }, + ], + [ + "section beginning inside a header-backed payload", + (fixture: ReturnType) => { + fixture.bytes.writeUInt32LE(0x100, fixture.dataOffsets[0]); + fixture.bytes.writeUInt32LE(4, (fixture.dataOffsets[0] ?? 0) + 4); + fixture.bytes.writeUInt16LE(2, 0x86); + const section = fixture.sectionAt + 40; + fixture.bytes.writeUInt32LE(4, section + 8); + fixture.bytes.writeUInt32LE(0x102, section + 12); + fixture.bytes.writeUInt32LE(4, section + 16); + const rawOffset = fixture.bytes.length; + fixture.bytes = Buffer.concat([fixture.bytes, Buffer.alloc(4)]); + fixture.bytes.writeUInt32LE(rawOffset, section + 20); + return fixture.bytes; + }, + ], + [ + "overlapping virtual sections", + (fixture: ReturnType) => { + fixture.bytes.writeUInt16LE(2, 0x86); + fixture.bytes.copy( + fixture.bytes, + fixture.sectionAt + 40, + fixture.sectionAt, + fixture.sectionAt + 40, + ); + fixture.bytes.writeUInt32LE(0, fixture.sectionAt + 40 + 16); + return fixture.bytes; + }, + ], + [ + "malformed icon group", + (fixture: ReturnType) => { + const data = fixture.dataOffsets.at(-1) ?? 0; + const offset = fixture.bytes.readUInt32LE(data) - 0x1c00; + fixture.bytes.writeUInt16LE(3, offset + 4); + return fixture.bytes; + }, + ], + ])("rejects %s", async (_name, mutate) => { + await expect(parse(mutate(peResourceFixture()))).rejects.toMatchObject({ + reason: "format", + }); + }); + + it("keeps icon size mismatch and unresolved language distinct", async () => { + const fixture = peResourceFixture(); + const data = fixture.dataOffsets.at(-1) ?? 0; + const payload = fixture.bytes.readUInt32LE(data) - 0x1c00; + fixture.bytes.writeUInt32LE(123, payload + 14); + let report = await parse(fixture.bytes); + expect(report.icon_groups[0]?.images[0]).toMatchObject({ + same_language_resource_index: 0, + size_matches: false, + }); + const languageEntry = report.resources[4]?.entry_locations[2]?.offset ?? 0; + fixture.bytes.writeUInt32LE(2057, languageEntry); + report = await parse(fixture.bytes); + expect(report.icon_groups[0]?.images[0]).toMatchObject({ + candidate_resource_indices: [0, 1], + same_language_resource_index: null, + size_matches: null, + }); + }); + + it("preserves exact shared payload ranges and hashes", async () => { + const fixture = peResourceFixture(); + fixture.bytes.writeUInt32LE( + fixture.bytes.readUInt32LE(fixture.dataOffsets[0]), + fixture.dataOffsets[1], + ); + const result = await parse(fixture.bytes); + expect(result.resources[0]?.payload).toEqual(result.resources[1]?.payload); + }); + + it("enforces entry budgets before traversing large tables", async () => { + await expect(parse(peResourceFixture().bytes, 1)).rejects.toMatchObject({ + reason: "limit", + }); + }); + + it("allows cancellation while traversing resource entries", async () => { + const controller = new AbortController(); + const parsing = parse(peResourceFixture().bytes, 4096, controller.signal); + controller.abort(); + await expect(parsing).rejects.toThrow(); + }); +}); diff --git a/src/native/pe/PeResourceParser.ts b/src/native/pe/PeResourceParser.ts new file mode 100644 index 000000000..66b48b06c --- /dev/null +++ b/src/native/pe/PeResourceParser.ts @@ -0,0 +1,315 @@ +import { createHash } from "node:crypto"; +import { setImmediate } from "node:timers/promises"; +import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js"; +import type { + InspectPeResourcesInput, + PeResourceIdentity, + PeResources, +} from "../../domain/native/peResources.js"; +import { + peFailure, + readPeResourceLayout, + requirePeRange, +} from "./PeResourceLayout.js"; + +type Range = { offset: number; bytes: number }; +type OccupiedRange = Range & { + kind: "directory" | "name" | "data-entry" | "payload"; +}; +const METADATA_BYTES = 8 * 1024 * 1024; +const limit = (message: string): never => { + throw new ArtifactReaderFailure("limit", message); +}; +const identityKey = (id: PeResourceIdentity): string => + id.kind === "id" ? `id:${String(id.id)}` : `name:${id.utf16le_hex}`; + +/** Decode the conventional type/name/language tree; never infer payload meaning or runtime loading. */ +export const parsePeResources = async ( + bytes: Buffer, + artifact: PeResources["artifact"], + input: InspectPeResourcesInput, + signal?: AbortSignal, +): Promise => { + signal?.throwIfAborted(); + const layout = readPeResourceLayout(bytes); + const directories: PeResources["directories"] = []; + const resources: PeResources["resources"] = []; + const occupied: OccupiedRange[] = []; + const names = new Map(); + let examined = 0; + let metadataBytes = 0; + const account = (value: unknown): void => { + metadataBytes += Buffer.byteLength(JSON.stringify(value)); + if (metadataBytes > METADATA_BYTES) + limit( + "PE resource metadata exceeds the 8 MiB complete-result allocation budget.", + ); + }; + const root = layout.size === 0 ? 0 : layout.map(layout.rva, layout.size); + const relative = (at: number, length: number): number => { + if (at > layout.size - length || at < 0) + peFailure( + "Resource directory offset leaves the declared resource interval.", + ); + requirePeRange(bytes, root + at, length); + return root + at; + }; + const recordRange = ( + offset: number, + size: number, + kind: OccupiedRange["kind"], + ): Range => { + const range = { offset, bytes: size }; + if (size > 0) occupied.push({ ...range, kind }); + return range; + }; + const readIdentity = (encoded: number): PeResourceIdentity => { + if ((encoded & 0x80000000) === 0) return { kind: "id", id: encoded }; + const at = encoded & 0x7fffffff; + const previous = names.get(at); + if (previous !== undefined) return previous; + if (at % 2 !== 0) peFailure("Unaligned PE resource name."); + const start = relative(at, 2); + const length = bytes.readUInt16LE(start) * 2; + relative(at, 2 + length); + const raw = bytes.subarray(start + 2, start + 2 + length); + const value: PeResourceIdentity = { + kind: "name", + name: raw.toString("utf16le"), + utf16le_hex: raw.toString("hex"), + location: recordRange(start, 2 + length, "name"), + }; + names.set(at, value); + account(value); + return value; + }; + const visit = async ( + at: number, + path: PeResourceIdentity[], + entryLocations: Range[], + ancestors: ReadonlySet, + ): Promise => { + if (ancestors.has(at)) peFailure("Cyclic PE resource directory."); + if (at % 4 !== 0) peFailure("Unaligned PE resource directory."); + const header = relative(at, 16); + const named = bytes.readUInt16LE(header + 12); + const ids = bytes.readUInt16LE(header + 14); + const count = named + ids; + if (count > input.max_entries - examined) + limit( + "PE resource directory entry budget exceeded; no partial inventory was returned.", + ); + examined += count; + relative(at, 16 + 8 * count); + const directory = { + location: recordRange(header, 16 + 8 * count, "directory"), + characteristics: bytes.readUInt32LE(header), + timestamp: bytes.readUInt32LE(header + 4), + major_version: bytes.readUInt16LE(header + 8), + minor_version: bytes.readUInt16LE(header + 10), + named_entries: named, + id_entries: ids, + }; + directories.push(directory); + account(directory); + const keys = new Set(); + const nested = new Set([...ancestors, at]); + for (let index = 0; index < count; index++) { + if (index % 128 === 0) { + await setImmediate(); + signal?.throwIfAborted(); + } + const entry = header + 16 + index * 8; + const encoded = bytes.readUInt32LE(entry); + if (((encoded & 0x80000000) !== 0) !== index < named) + peFailure( + "Resource name/ID entry counts disagree with encoded identities.", + ); + const identity = readIdentity(encoded); + const key = identityKey(identity); + if (keys.has(key)) + peFailure("Duplicate identity within a resource directory."); + keys.add(key); + const next = [...path, identity]; + const locations = [...entryLocations, { offset: entry, bytes: 8 }]; + const target = bytes.readUInt32LE(entry + 4); + const offset = target & 0x7fffffff; + if ((target & 0x80000000) !== 0) { + if (next.length >= 3) + peFailure( + "Unsupported resource tree deeper than type/name/language.", + ); + await visit(offset, next, locations, nested); + } else { + if (next.length !== 3) + peFailure( + "Unsupported resource leaf outside the type/name/language profile.", + ); + const data = relative(offset, 16); + if (offset % 4 !== 0) peFailure("Unaligned resource data entry."); + const rva = bytes.readUInt32LE(data); + const size = bytes.readUInt32LE(data + 4); + const payloadOffset = layout.map(rva, size); + const [type, name, language] = next; + if (type === undefined || name === undefined || language === undefined) + return peFailure("Incomplete resource identity."); + const resource = { + index: resources.length, + type, + name, + language, + entry_locations: locations, + data_entry_location: recordRange(data, 16, "data-entry"), + code_page: bytes.readUInt32LE(data + 8), + reserved: bytes.readUInt32LE(data + 12), + payload: { + rva, + location: recordRange(payloadOffset, size, "payload"), + sha256: "0".repeat(64), + }, + }; + resources.push(resource); + account(resource); + } + } + }; + if (layout.size > 0) await visit(0, [], [], new Set()); + rejectOverlappingRanges(occupied); + const hashes = new Map(); + for (const resource of resources) { + const range = resource.payload.location; + const key = `${String(range.offset)}:${String(range.bytes)}`; + let digest = hashes.get(key); + if (digest === undefined) { + const hash = createHash("sha256"); + for (let offset = 0; offset < range.bytes; offset += 1048576) { + await setImmediate(); + signal?.throwIfAborted(); + hash.update( + bytes.subarray( + range.offset + offset, + range.offset + Math.min(range.bytes, offset + 1048576), + ), + ); + } + digest = hash.digest("hex"); + hashes.set(key, digest); + } + resource.payload.sha256 = digest; + } + const iconGroups = readIconGroups(bytes, resources, account); + const report: PeResources = { + artifact, + format: layout.format, + machine: layout.machine, + directory: + layout.size === 0 + ? null + : { + rva: layout.rva, + location: { offset: root, bytes: layout.size }, + data_directory_location: { offset: layout.directoryAt, bytes: 8 }, + }, + directories, + resources, + icon_groups: iconGroups, + coverage: { + status: "complete", + examined_entries: examined, + resources: resources.length, + }, + limitations: [ + "Static PE32/PE32+ type/name/language resource inventory; payloads other than RT_GROUP_ICON remain opaque.", + "Icon candidates are resource-table relationships. Language fallback, image decoding and actual shell/window loading are not observed.", + "Exact shared byte ranges are retained; non-identical overlapping resource structures or payloads are rejected.", + ], + }; + signal?.throwIfAborted(); + if (Buffer.byteLength(JSON.stringify(report)) > METADATA_BYTES) + limit("PE resource result exceeds the 8 MiB allocation budget."); + return report; +}; + +const rejectOverlappingRanges = (ranges: OccupiedRange[]): void => { + ranges.sort( + (left, right) => left.offset - right.offset || right.bytes - left.bytes, + ); + let previous: OccupiedRange | undefined; + for (const current of ranges) { + if ( + previous !== undefined && + current.offset < previous.offset + previous.bytes && + (current.offset !== previous.offset || + current.bytes !== previous.bytes || + current.kind !== previous.kind) + ) + peFailure("Non-identical resource byte ranges overlap."); + previous = current; + } +}; + +const readIconGroups = ( + bytes: Buffer, + resources: PeResources["resources"], + account: (value: unknown) => void, +): PeResources["icon_groups"] => { + const imagesById = new Map(); + for (const resource of resources) { + if ( + resource.type.kind !== "id" || + resource.type.id !== 3 || + resource.name.kind !== "id" + ) + continue; + const candidates = imagesById.get(resource.name.id) ?? []; + candidates.push(resource); + imagesById.set(resource.name.id, candidates); + } + return resources + .filter( + (resource) => resource.type.kind === "id" && resource.type.id === 14, + ) + .map((group) => { + const { offset, bytes: size } = group.payload.location; + if ( + size < 6 || + bytes.readUInt16LE(offset) !== 0 || + bytes.readUInt16LE(offset + 2) !== 1 + ) + peFailure("Malformed RT_GROUP_ICON header."); + const count = bytes.readUInt16LE(offset + 4); + if (size !== 6 + count * 14) + peFailure("RT_GROUP_ICON length does not match its image count."); + const images: PeResources["icon_groups"][number]["images"] = []; + for (let index = 0; index < count; index++) { + const at = offset + 6 + index * 14; + const id = bytes.readUInt16LE(at + 12); + const candidates = imagesById.get(id) ?? []; + const exact = candidates.find( + (resource) => + identityKey(resource.language) === identityKey(group.language), + ); + const declaredBytes = bytes.readUInt32LE(at + 8); + const image = { + location: { offset: at, bytes: 14 }, + width: bytes[at] ?? 0, + height: bytes[at + 1] ?? 0, + color_count: bytes[at + 2] ?? 0, + reserved: bytes[at + 3] ?? 0, + planes: bytes.readUInt16LE(at + 4), + bit_count: bytes.readUInt16LE(at + 6), + declared_bytes: declaredBytes, + resource_id: id, + candidate_resource_indices: candidates.map(({ index }) => index), + same_language_resource_index: exact?.index ?? null, + size_matches: + exact === undefined + ? null + : exact.payload.location.bytes === declaredBytes, + }; + account(image); + images.push(image); + } + return { resource_index: group.index, images }; + }); +}; diff --git a/src/native/pe/PeResources.fixture.ts b/src/native/pe/PeResources.fixture.ts new file mode 100644 index 000000000..803ae3377 --- /dev/null +++ b/src/native/pe/PeResources.fixture.ts @@ -0,0 +1,148 @@ +interface Resource { + readonly type: number | string; + readonly name: number | string; + readonly language: number | string; + readonly payload: Buffer; +} +interface Tree { + readonly children: Map< + string, + { identity: number | string; value: Tree | Resource } + >; +} + +const iconGroup = (): Buffer => { + const bytes = Buffer.alloc(34); + bytes.writeUInt16LE(1, 2); + bytes.writeUInt16LE(2, 4); + for (const [index, id] of [1, 99].entries()) { + const at = 6 + index * 14; + bytes[at] = 16; + bytes[at + 1] = 16; + bytes.writeUInt16LE(1, at + 4); + bytes.writeUInt16LE(32, at + 6); + bytes.writeUInt32LE(4, at + 8); + bytes.writeUInt16LE(id, at + 12); + } + return bytes; +}; + +/** Hand-authored PE resource bytes, independent of the production decoder. */ +export const peResourceFixture = ( + plus = false, + resources: readonly Resource[] = [ + { type: 3, name: 1, language: 1033, payload: Buffer.from("ICON") }, + { type: 3, name: 1, language: 1041, payload: Buffer.from("JAPN") }, + { type: 10, name: "7", language: 1033, payload: Buffer.from("Hello") }, + { type: 10, name: 7, language: 1041, payload: Buffer.from("World") }, + { type: 14, name: 42, language: 1033, payload: iconGroup() }, + ], +) => { + const tree: Tree = { children: new Map() }; + for (const resource of resources) { + let parent = tree; + for (const [depth, identity] of [ + resource.type, + resource.name, + resource.language, + ].entries()) { + const key = `${typeof identity}:${String(identity)}`; + let child = parent.children.get(key); + if (child === undefined) { + child = { + identity, + value: depth === 2 ? resource : { children: new Map() }, + }; + parent.children.set(key, child); + } + if ("children" in child.value) parent = child.value; + } + } + const section = Buffer.alloc(65536); + let cursor = 0; + const allocate = (size: number, alignment = 4): number => { + cursor = Math.ceil(cursor / alignment) * alignment; + const at = cursor; + cursor += size; + return at; + }; + const leaves: { dataAt: number; resource: Resource }[] = []; + const entryOffsets: number[] = []; + const directories: number[] = []; + const emit = (node: Tree): number => { + const children = [...node.children.values()].sort((left, right) => + typeof left.identity === typeof right.identity + ? typeof left.identity === "number" && + typeof right.identity === "number" + ? left.identity - right.identity + : String(left.identity).localeCompare(String(right.identity)) + : typeof left.identity === "string" + ? -1 + : 1, + ); + const at = allocate(16 + children.length * 8); + directories.push(at); + const named = children.filter( + ({ identity }) => typeof identity === "string", + ).length; + section.writeUInt16LE(named, at + 12); + section.writeUInt16LE(children.length - named, at + 14); + children.forEach(({ identity, value }, index) => { + const entry = at + 16 + index * 8; + entryOffsets.push(entry); + if (typeof identity === "string") { + const encoded = Buffer.from(identity, "utf16le"); + const nameAt = allocate(encoded.length + 2, 2); + section.writeUInt16LE(encoded.length / 2, nameAt); + encoded.copy(section, nameAt + 2); + section.writeUInt32LE(0x80000000 + nameAt, entry); + } else section.writeUInt32LE(identity, entry); + if ("children" in value) + section.writeUInt32LE(0x80000000 + emit(value), entry + 4); + else { + const dataAt = allocate(16); + section.writeUInt32LE(dataAt, entry + 4); + leaves.push({ dataAt, resource: value }); + } + }); + return at; + }; + emit(tree); + for (const { dataAt, resource } of leaves) { + const payloadAt = allocate(resource.payload.length); + resource.payload.copy(section, payloadAt); + section.writeUInt32LE(0x2000 + payloadAt, dataAt); + section.writeUInt32LE(resource.payload.length, dataAt + 4); + section.writeUInt32LE(65001, dataAt + 8); + } + const rawSize = Math.ceil(cursor / 512) * 512; + const bytes = Buffer.alloc(0x400 + rawSize); + bytes.writeUInt16LE(0x5a4d, 0); + bytes.writeUInt32LE(0x80, 60); + bytes.writeUInt32LE(0x4550, 0x80); + bytes.writeUInt16LE(plus ? 0x8664 : 0x14c, 0x84); + bytes.writeUInt16LE(1, 0x86); + const optionalSize = plus ? 240 : 224; + bytes.writeUInt16LE(optionalSize, 0x94); + bytes.writeUInt16LE(plus ? 0x20b : 0x10b, 0x98); + bytes.writeUInt32LE(0x400, 0x98 + 60); + bytes.writeUInt32LE(16, 0x98 + (plus ? 108 : 92)); + const directoryAt = 0x98 + (plus ? 112 : 96) + 16; + bytes.writeUInt32LE(0x2000, directoryAt); + bytes.writeUInt32LE(cursor, directoryAt + 4); + const sectionAt = 0x98 + optionalSize; + bytes.write(".rsrc", sectionAt, "ascii"); + bytes.writeUInt32LE(cursor, sectionAt + 8); + bytes.writeUInt32LE(0x2000, sectionAt + 12); + bytes.writeUInt32LE(rawSize, sectionAt + 16); + bytes.writeUInt32LE(0x400, sectionAt + 20); + section.copy(bytes, 0x400, 0, rawSize); + return { + bytes, + directoryAt, + sectionAt, + entryOffsets: entryOffsets.map((at) => at + 0x400), + directoryOffsets: directories.map((at) => at + 0x400), + dataOffsets: leaves.map(({ dataAt }) => dataAt + 0x400), + }; +}; diff --git a/src/native/pe/PeResourcesProvider.ts b/src/native/pe/PeResourcesProvider.ts new file mode 100644 index 000000000..50fb13a29 --- /dev/null +++ b/src/native/pe/PeResourcesProvider.ts @@ -0,0 +1,83 @@ +import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js"; +import { readStableArtifact } from "../../artifacts/readStableArtifact.js"; +import type { PeResourcesPort } from "../../application/binaryDiagnostics/PeResourcesPort.js"; +import type { ExecutionOptions } from "../../application/AnalysisProvider.js"; +import { ArtifactOperationError } from "../../domain/artifactOperationError.js"; +import { + AnalysisAccessDeniedError, + AnalysisCancelledError, + AnalysisResourceConstraintError, +} from "../../domain/analysisErrorCore.js"; +import type { InspectPeResourcesInput } from "../../domain/native/peResources.js"; +import { err, ok } from "../../domain/result.js"; +import { PE_RESOURCES_PROVIDER } from "../../application/InvestigationProviders.js"; +import { parsePeResources } from "./PeResourceParser.js"; + +/** Portable parser over one bounded, identity-checked regular file. */ +export class PeResourcesProvider implements PeResourcesPort { + readonly identity = PE_RESOURCES_PROVIDER; + + async inspect(input: InspectPeResourcesInput, options?: ExecutionOptions) { + try { + const snapshot = await readStableArtifact( + input.path, + input.max_file_bytes, + options?.signal, + ); + return ok( + await parsePeResources( + snapshot.bytes, + { + path: input.path, + sha256: snapshot.sha256, + bytes: snapshot.bytes.length, + }, + input, + options?.signal, + ), + ); + } catch (cause) { + if (options?.signal?.aborted) + return err( + new AnalysisCancelledError("inspect_pe_resources", { cause }), + ); + if (cause instanceof ArtifactReaderFailure && cause.reason === "limit") + return err( + new AnalysisResourceConstraintError( + "inspect_pe_resources", + "memory", + cause.message, + { + max_file_bytes: input.max_file_bytes, + max_entries: input.max_entries, + }, + { cause }, + ), + ); + if ( + cause instanceof Error && + "code" in cause && + (cause.code === "EACCES" || cause.code === "EPERM") + ) + return err( + new AnalysisAccessDeniedError( + "inspect_pe_resources", + input.path, + cause.code, + { cause }, + ), + ); + return err( + new ArtifactOperationError( + "inspect_pe_resources", + cause instanceof ArtifactReaderFailure ? cause.reason : "io", + undefined, + cause instanceof Error + ? cause.message + : "PE artifact inspection failed.", + { cause }, + ), + ); + } + } +} diff --git a/src/server/createServer.ts b/src/server/createServer.ts index 1d49156c1..63f71fa89 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -1,4 +1,6 @@ import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; +import { createPeResourcesService } from "../composition/binaryDiagnostics.js"; +import { registerPeResourcesTool } from "./registerPeResourcesTool.js"; import type { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js"; import { createEvmInterfaceService } from "../composition/evm.js"; import { registerEvmTools } from "./registerEvmTools.js"; @@ -317,6 +319,12 @@ const registerConfiguredAnalysisTools = ( evidenceById, ); registerAnalysisViewTool(server, toolLogger, evidenceById, recordEvidence); + registerPeResourcesTool( + server, + createPeResourcesService(), + toolLogger, + recordEvidence, + ); registerEvmTools( server, options.evmInterface ?? createEvmInterfaceService(environment), diff --git a/src/server/registerPeResourcesTool.ts b/src/server/registerPeResourcesTool.ts new file mode 100644 index 000000000..81e6fd852 --- /dev/null +++ b/src/server/registerPeResourcesTool.ts @@ -0,0 +1,32 @@ +import type { EvidenceMcpServer } from "./EvidenceMcpServer.js"; +import type { PeResourcesService } from "../application/binaryDiagnostics/PeResourcesService.js"; +import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js"; +import { toolContract } from "../contracts/toolContracts.js"; +import type { Logger } from "pino"; +import { logToolExecution } from "./toolLogging.js"; +import { toolRegistrationOptions } from "./toolRegistrationOptions.js"; + +/** Register the explicit-file PE resource workflow and retain its complete Evidence. */ +export const registerPeResourcesTool = ( + server: EvidenceMcpServer, + service: PeResourcesService, + logger: Logger, + recordEvidence?: EvidenceWriter["recordEvidence"], +): void => { + const contract = toolContract("inspect_pe_resources"); + server.registerTool( + contract.name, + toolRegistrationOptions(contract), + async (input, context) => { + const result = await logToolExecution(logger, contract.name, () => + service.inspect(input, { signal: context.mcpReq.signal }), + ); + if (!result.ok) return server.delivery.toCallToolResult(result, contract); + return server.delivery.toEvidenceToolResult( + result.value, + contract, + recordEvidence?.(result.value), + ); + }, + ); +}; diff --git a/tests/acceptance/applications/peResources.test.ts b/tests/acceptance/applications/peResources.test.ts new file mode 100644 index 000000000..dc40f3cbc --- /dev/null +++ b/tests/acceptance/applications/peResources.test.ts @@ -0,0 +1,147 @@ +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { createHash } from "node:crypto"; +import { readFile, writeFile } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import { expect } from "vitest"; +import { toolContract } from "../../../src/contracts/toolContracts.js"; +import { peResourcesSchema } from "../../../src/domain/native/peResources.js"; +import { peResourceFixture } from "../../../src/native/pe/PeResources.fixture.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { cliTest } from "../../support/cli/cliFixture.js"; + +cliTest( + "inspects PE32/PE32+ resources through compiled CLI and real stdio MCP without an active target", + async ({ cli }) => { + const root = await createTestTempDirectory("rea-pe-resource-acceptance-"); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("scripts/rea.mjs"), "mcp"], + cwd: process.cwd(), + env: { PATH: process.env.PATH ?? "", REA_LOG_LEVEL: "silent" }, + stderr: "pipe", + }); + const client = new Client({ name: "pe-resource-acceptance", version: "1" }); + const contract = toolContract("inspect_pe_resources"); + try { + await client.connect(transport); + const inventory = await client.listTools(); + expect(inventory.tools).toContainEqual( + expect.objectContaining({ + name: contract.name, + annotations: expect.objectContaining({ + readOnlyHint: false, + openWorldHint: false, + }), + }), + ); + const session = await client.callTool({ + name: "binary_session", + arguments: {}, + }); + expect(JSON.stringify(session.structuredContent)).toContain( + "inspect_pe_resources", + ); + for (const plus of [false, true]) { + const fixture = peResourceFixture(plus); + const path = join(root, plus ? "resource64.exe" : "resource32.exe"); + await writeFile(path, fixture.bytes); + const result = await cli.run({ + arguments: ["inspect-pe-resources", path, "--json"], + }); + expect(result.exitCode).toBe(0); + const evidence = contract.outputSchema.parse(result.json); + const report = peResourcesSchema.parse(evidence.normalized_result); + expect(evidence.subject?.digest).toMatchObject({ + sha256: createHash("sha256").update(fixture.bytes).digest("hex"), + }); + expect(report.coverage).toMatchObject({ + status: "complete", + resources: 5, + }); + expect(report.resources[0]?.payload.sha256).toBe( + createHash("sha256").update("ICON").digest("hex"), + ); + expect( + report.resources.find(({ name }) => name.kind === "name")?.name, + ).toMatchObject({ kind: "name", name: "7", utf16le_hex: "3700" }); + expect(report.icon_groups[0]?.images).toMatchObject([ + { + resource_id: 1, + candidate_resource_indices: [0, 1], + same_language_resource_index: 0, + }, + { + resource_id: 99, + candidate_resource_indices: [], + same_language_resource_index: null, + }, + ]); + const response = await client.callTool({ + name: contract.name, + arguments: { path }, + }); + expect(response.isError).not.toBe(true); + const mcp = contract.outputSchema.parse(response.structuredContent); + expect(mcp.evidence_id).toBe(evidence.evidence_id); + expect(mcp.normalized_result).toEqual(evidence.normalized_result); + const text = response.content.find(({ type }) => type === "text"); + if (text?.type !== "text") throw new Error("Missing MCP text Evidence"); + expect( + contract.outputSchema.parse(JSON.parse(text.text)).evidence_id, + ).toBe(evidence.evidence_id); + expect(await readFile(path)).toEqual(fixture.bytes); + } + const absent = peResourceFixture(); + absent.bytes.fill(0, absent.directoryAt, absent.directoryAt + 8); + const path = join(root, "absent.exe"); + await writeFile(path, absent.bytes); + const empty = await client.callTool({ + name: contract.name, + arguments: { path }, + }); + expect(empty.isError).not.toBe(true); + expect( + contract.outputSchema.parse(empty.structuredContent).normalized_result, + ).toMatchObject({ + directory: null, + resources: [], + coverage: { status: "complete", resources: 0 }, + }); + for (const arguments_ of [ + { path, max_file_bytes: 64 }, + { path: "relative.exe" }, + { path, extra: true }, + ]) { + const rejected = await client.callTool({ + name: contract.name, + arguments: arguments_, + }); + expect(rejected.isError).toBe(true); + expect( + contract.outputSchema.safeParse(rejected.structuredContent).success, + ).toBe(false); + } + const damaged = peResourceFixture(); + damaged.bytes.writeUInt32LE(17, damaged.directoryAt + 4); + const badPath = join(root, "damaged.exe"); + await writeFile(badPath, damaged.bytes); + const rejected = await client.callTool({ + name: contract.name, + arguments: { path: badPath }, + }); + expect(rejected.isError).toBe(true); + expect( + contract.outputSchema.safeParse(rejected.structuredContent).success, + ).toBe(false); + await client.ping(); + } finally { + try { + await client.close(); + } finally { + await transport.close(); + } + } + }, + 30_000, +); diff --git a/tests/boundary/filesystem/peResources.test.ts b/tests/boundary/filesystem/peResources.test.ts new file mode 100644 index 000000000..a343feaa1 --- /dev/null +++ b/tests/boundary/filesystem/peResources.test.ts @@ -0,0 +1,43 @@ +import { symlink, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { describe, expect, it } from "vitest"; +import { createPeResourcesService } from "../../../src/composition/binaryDiagnostics.js"; +import { peResourceFixture } from "../../../src/native/pe/PeResources.fixture.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +describe("PE resource stable filesystem boundary", () => { + it("rejects symlinks, missing files and directories without inventing empty inventory", async () => { + const root = await createTestTempDirectory("rea-pe-resource-files-"); + const path = join(root, "image.exe"); + const alias = join(root, "alias.exe"); + await writeFile(path, peResourceFixture().bytes); + await symlink(path, alias); + const service = createPeResourcesService(); + for (const candidate of [root, alias, join(root, "missing.exe")]) { + const result = await service.inspect({ path: candidate }); + if (result.ok) throw new Error("Expected file acquisition failure"); + expect(result.error._tag).toBe("ArtifactOperationError"); + } + }); + + it("returns typed resource and cancellation failures", async () => { + const root = await createTestTempDirectory("rea-pe-resource-budget-"); + const path = join(root, "image.exe"); + await writeFile(path, peResourceFixture().bytes); + const service = createPeResourcesService(); + for (const input of [ + { path, max_file_bytes: 64 }, + { path, max_entries: 1 }, + ]) { + const result = await service.inspect(input); + if (result.ok) throw new Error("Expected resource budget failure"); + expect(result.error._tag).toBe("AnalysisResourceConstraintError"); + } + const result = await service.inspect( + { path }, + { signal: AbortSignal.abort() }, + ); + if (result.ok) throw new Error("Expected cancellation"); + expect(result.error._tag).toBe("AnalysisCancelledError"); + }); +});