feat(native): inspect offline ELF layout through pwntools (#1037)

* feat(native): inspect offline ELF layout through pwntools

* fix(build): prepare offline ELF verification on clean runners

* fix(native): preserve snapshot acquisition cancellation

* fix(native): handle sectionless ELF and retain decoder diagnostics

* test(native): verify malformed symbol table entry sizes

* fix(native): respect inherited limits and unused segment fields

* fix(native): preserve packed relocations and decoder launch constraints

* fix(native): validate symbol spans and preserve resource failures

* fix(native): preserve diagnostic completeness and memory failures

* fix(native): guard bridge imports against allocation failures

* fix(native): validate relocation symbol and section references

* fix(native): retain diagnostics through compounded cleanup failures

* fix(native): preserve unresolved relocation section references

* fix(native): bound linkage evidence and preserve CPU signal diagnostics

* fix(native): preserve file-size resource failure evidence

* fix(native): retain opaque linkage names and late cancellation output

* test(native): make CPU-limit fixture robust across runners

* fix(native): verify resource failure branches before interpreting exits

* fix(native): validate declared ELF string references

* fix(native): validate section-name table before decoding

* fix(native): enforce canonical ELF name-table escapes
This commit is contained in:
Ysopwnable
2026-10-08 14:22:08 +08:00
committed by GitHub
parent 8d5c88f17c
commit 4fc6565b0f
59 changed files with 5068 additions and 45 deletions
+9
View File
@@ -33,6 +33,7 @@ type ProviderDescriptor = ProviderCapability;
export type AvailabilityPolicy = {
readonly processCaptureEnabled: boolean;
readonly optionalProviderLoadFailures?: OptionalProviderLoadFailures;
readonly binaryLayoutEnabled?: boolean;
readonly firmwareInspectionEnabled?: boolean;
readonly firmwareExtractionEnabled?: boolean;
readonly androidAnalysisEnabled?: boolean;
@@ -280,6 +281,14 @@ const workflowAvailabilityFor = ({
remediation:
"On Linux x64, provide an absolute REA_WAKARU_COMMAND for Wakaru 1.13.0 and util-linux prlimit. No binary target is required.",
};
if (name === "inspect_binary_layout")
return policy.binaryLayoutEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
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 (kind === "firmware-provider") {
const enabled =
name === "inspect_firmware_regions"
@@ -0,0 +1,17 @@
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type {
BinaryLayout,
InspectBinaryLayoutInput,
} from "../../domain/native/binaryLayout.js";
import type { Result } from "../../domain/result.js";
import type { ProviderIdentity } from "../AnalysisProvider.js";
/** Replaceable offline binary-layout provider; owns its parser and process protocol. */
export interface BinaryLayoutPort {
readonly identity: ProviderIdentity;
inspect(
input: InspectBinaryLayoutInput,
options?: ExecutionOptions,
): Promise<Result<BinaryLayout, AnalysisError>>;
}
@@ -0,0 +1,131 @@
import { expect, it } from "vitest";
import { BinaryLayoutService } from "./BinaryLayoutService.js";
import {
binaryLayoutFixture,
BINARY_LAYOUT_TEST_PROVIDER,
} from "../../../tests/fixtures/binaryDiagnostics/layout.js";
import { parseEvidence } from "../../domain/evidence.js";
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
import { err, ok } from "../../domain/result.js";
it("binds original bytes, inline observations, unknowns and producing identity", async () => {
const fixture = binaryLayoutFixture();
const service = new BinaryLayoutService({
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
const result = await service.inspect({ path: fixture.artifact.path });
if (!result.ok) throw result.error;
const evidence = parseEvidence(result.value);
expect(evidence.normalized_result).toEqual(fixture);
expect(evidence.raw_result).toEqual(fixture);
expect(evidence.subject?.digest.sha256).toBe(fixture.artifact.sha256);
expect(evidence.provider).toEqual(BINARY_LAYOUT_TEST_PROVIDER);
expect(evidence.confidence).toBe("observed");
});
it.each([
{ path: "relative.elf" },
{ path: "/selected.elf", approval: true },
{ path: 123 },
{},
])(
"rejects malformed selection before starting the provider: %j",
async (input) => {
const service = new BinaryLayoutService({
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => {
throw new Error("must not run");
},
});
expect(await service.inspect(input)).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
},
);
it("preserves a provider's actionable unsupported reason", async () => {
const failure = new AnalysisCapabilityUnavailableError(
"fixture-layout",
"inspect_binary_layout",
"ELF core belongs to recorded-crash analysis.",
);
const service = new BinaryLayoutService({
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => Promise.resolve(err(failure)),
});
expect(await service.inspect({ path: "/source.elf" })).toEqual(err(failure));
});
it("cancels before invocation and after an acquired observation", async () => {
const controller = new AbortController();
const service = new BinaryLayoutService({
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => {
controller.abort();
return Promise.resolve(ok(binaryLayoutFixture()));
},
});
expect(
await service.inspect(
{ path: "/artifacts/source-owned.elf" },
{ signal: controller.signal },
),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
capturedOutput: binaryLayoutFixture().diagnostics,
},
});
const untouched = new BinaryLayoutService({
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => {
throw new Error("must not run");
},
});
expect(
await untouched.inspect(
{ path: "/source.elf" },
{ signal: controller.signal },
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
});
it.each(["different-path", "invalid-digest", "outside-range"])(
"rejects provider evidence at the next boundary: %s",
async (problem) => {
const fixture = binaryLayoutFixture();
if (problem === "different-path") fixture.artifact.path = "/different.elf";
if (problem === "invalid-digest") fixture.artifact.sha256 = "unobserved";
if (problem === "outside-range")
fixture.segments.push({
index: 0,
type: "PT_LOAD",
offset: "0x80",
header_location: { offset: "0x0", bytes: "0x38" },
file_backing: "file",
file_size: "0x1",
memory_size: "0x1",
virtual_address: "0x20000000000001",
physical_address: "0x0",
alignment: "0x1",
flags: "0x5",
permissions: { read: true, write: false, execute: true },
});
const service = new BinaryLayoutService({
identity: BINARY_LAYOUT_TEST_PROVIDER,
inspect: () => Promise.resolve(ok(fixture)),
});
expect(
await service.inspect({ path: "/artifacts/source-owned.elf" }),
).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
capturedOutput: fixture.diagnostics,
},
});
},
);
@@ -0,0 +1,91 @@
import { isAbsolute } from "node:path";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { BinaryLayoutPort } from "./BinaryLayoutPort.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 {
inspectBinaryLayoutInputSchema,
binaryLayoutSchema,
} from "../../domain/native/binaryLayout.js";
import { projectInputIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
const OPERATION = "inspect_binary_layout";
/** Shared CLI/MCP validation and Evidence composition for offline layout inspection. */
export class BinaryLayoutService {
constructor(readonly provider: BinaryLayoutPort) {}
/** Bind complete observations to the caller-selected artifact before creating Evidence. */
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION));
const input = inspectBinaryLayoutInputSchema.safeParse(rawInput);
if (!input.success)
return err(
new AnalysisInputError(
OPERATION,
{ cause: input.error },
projectInputIssues(input.error.issues, rawInput),
),
);
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 inspected = await this.provider.inspect(input.data, options);
if (!inspected.ok) return inspected;
const diagnostics = binaryLayoutSchema.shape.diagnostics.safeParse(
inspected.value.diagnostics,
);
const outputOptions = diagnostics.success
? { capturedOutput: diagnostics.data }
: undefined;
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(OPERATION, outputOptions));
const report = binaryLayoutSchema.safeParse(inspected.value);
if (!report.success || report.data.artifact.path !== input.data.path)
return err(
new AnalysisOutputError(
OPERATION,
"Binary layout provider returned malformed evidence or changed the selected artifact identity.",
outputOptions,
),
);
const value = report.data;
return ok(
createEvidence(
{
path: value.artifact.path,
format: "elf",
architecture: "x86_64",
sha256: value.artifact.sha256,
},
this.provider.identity,
{
operation: OPERATION,
parameters: input.data,
result: value,
rawResult: value,
confidence: "observed",
limitations: value.limitations,
locations: [{ kind: "artifact-path", path: value.artifact.path }],
},
),
);
}
}
+2
View File
@@ -1,3 +1,4 @@
import { registerBinaryDiagnosticsCommands } from "./cli/binaryDiagnosticsCommands.js";
import { Cli } from "incur";
import { createLogger, parseLogLevel } from "./logger.js";
@@ -59,6 +60,7 @@ export const createCli = (
registerManagedCommands(cli, logger);
registerAndroidCommands(cli, logger, environment);
registerFirmwareCommands(cli, logger, environment);
registerBinaryDiagnosticsCommands(cli, logger, environment);
registerEvidenceCommands(cli, logger);
registerProcessCommands(cli, logger, environment);
registerBrowserCommands(cli, logger);
+35
View File
@@ -0,0 +1,35 @@
import { z } from "incur";
import { resolve } from "node:path";
import { createBinaryLayoutService } from "../composition/binaryDiagnostics.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "../logger.js";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
/** Inspect operator-selected files through the same shared workflow as MCP. */
export const registerBinaryDiagnosticsCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
): void => {
const service = createBinaryLayoutService(environment);
cli.command(CLI_COMMANDS.inspectBinaryLayout, {
description:
"Inspect binary file/linked layout without executing the selected object",
args: z.object({
path: z.string().describe("Local ELF binary or relocatable object"),
}),
run: ({ args }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectBinaryLayout, async () => {
const result = await service.inspect(
{ path: resolve(args.path) },
{ signal },
);
return result.ok ? result.value : projectAnalysisError(result.error);
}),
),
});
};
+1
View File
@@ -37,6 +37,7 @@ export const CLI_COMMANDS = Object.freeze({
resolveNativeCallTargets: "resolve-native-call-targets",
inspectAssetCatalog: "inspect-asset-catalog",
inspectManagedArtifact: "inspect-managed-artifact",
inspectBinaryLayout: "inspect-binary-layout",
inspectFirmwareRegions: "inspect-firmware-regions",
extractFirmware: "extract-firmware",
inspectAndroidPackage: "inspect-android-package",
+8
View File
@@ -0,0 +1,8 @@
import { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
import { PwntoolsLayoutProvider } from "../native/pwntools/PwntoolsLayoutProvider.js";
/** Compose the offline adapter without import-time I/O or dependency acquisition. */
export const createBinaryLayoutService = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): BinaryLayoutService =>
new BinaryLayoutService(new PwntoolsLayoutProvider(environment));
+2
View File
@@ -1,3 +1,4 @@
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
import { describe, expect, it } from "vitest";
import { z } from "zod";
@@ -69,6 +70,7 @@ describe("tool contract surface", () => {
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
...NATIVE_TOOL_CONTRACTS,
...BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...ANDROID_TOOL_CONTRACTS,
...FIRMWARE_TOOL_CONTRACTS,
+2
View File
@@ -9,6 +9,7 @@ const categorySchema = z.enum([
"truncated",
"cancelled",
"timeout",
"resource_constraint",
"unavailable",
"execution_failure",
]);
@@ -38,6 +39,7 @@ export const analysisErrorProjectionSchema = z.discriminatedUnion("code", [
generic("capability_unavailable"),
generic("provider_unavailable"),
generic("provider_timeout"),
generic("resource_constraint"),
generic("cancelled"),
z
.object({
@@ -0,0 +1,26 @@
import {
inspectBinaryLayoutInputSchema,
binaryLayoutSchema,
} from "../../domain/native/binaryLayout.js";
import type { ToolContract } from "../toolContractTypes.js";
import { toolContractMetadata } from "../toolEffects.js";
import { evidenceResultOf } from "../toolOutputSchemas.js";
/** Offline binary diagnostics are independent of macOS process/UI providers. */
export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
{
name: "inspect_binary_layout",
...toolContractMetadata("inspect_binary_layout"),
kind: "native-provider",
description:
"Inspect an explicit local binary without launching it as a host process. Returns file-backed section/segment ranges, linked addresses, original symbol/REL/RELA table identities, complete encoded RELR tables and upstream-derived offsets with unknown per-word locations/addends, raw name bytes, dependency/interpreter names and static mitigation inferences inline with artifact SHA-256 Evidence. Initial profile: ELF64 x86-64 little-endian EXEC/DYN/REL on Linux x64 via caller-supplied Python with unchanged pwntools 4.15.0, pyelftools 0.33 and Unicorn 2.1.2. Runtime addresses/library paths, overall relocation inventory completeness and complete derived GOT/PLT coverage remain unknown. Zero executable entry values mean absence; relocatable entries are not applicable. Upstream can emulate PLT instructions with Unicorn for derived static maps. Uses bounded complete output and owned temporary files/processes; malformed, unsupported or oversized objects return no partial success.",
inputSchema: inspectBinaryLayoutInputSchema,
outputSchema: evidenceResultOf(binaryLayoutSchema),
examples: [
{
title: "Inspect ELF linked and file layout",
input: { path: "/artifacts/application.elf" },
},
],
},
] as const satisfies readonly ToolContract[];
+2
View File
@@ -1,3 +1,4 @@
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
import { describe, expect, it } from "vitest";
import { ENHANCED_TOOL_CONTRACTS } from "./enhancedToolContracts.js";
@@ -23,6 +24,7 @@ const GROUPS = {
official: OFFICIAL_TOOL_CONTRACTS,
enhanced: ENHANCED_TOOL_CONTRACTS,
native: NATIVE_TOOL_CONTRACTS,
binary_diagnostics: BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
artifact: ARTIFACT_TOOL_CONTRACTS,
managed: MANAGED_TOOL_CONTRACTS,
android: ANDROID_TOOL_CONTRACTS,
+2
View File
@@ -1,3 +1,4 @@
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "./native/nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
@@ -23,6 +24,7 @@ export const TOOL_CONTRACTS = [
...OFFICIAL_TOOL_CONTRACTS,
...ENHANCED_TOOL_CONTRACTS,
...NATIVE_TOOL_CONTRACTS,
...BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...ANDROID_TOOL_CONTRACTS,
+5
View File
@@ -65,6 +65,11 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
launchesProcess: true,
accessesNetwork: true,
}),
inspect_binary_layout: effects({
mutatesSession: true,
writesFilesystem: true,
launchesProcess: true,
}),
inspect_firmware_regions: effects({
mutatesSession: true,
launchesProcess: true,
+21
View File
@@ -8,6 +8,7 @@ const ANALYSIS_ERROR_TAGS = [
"AnalysisCapabilityUnavailableError",
"AnalysisCancelledError",
"AnalysisTimeoutError",
"AnalysisResourceConstraintError",
"ProviderSelectionError",
"ProviderAdapterError",
"BrowserObservationError",
@@ -30,8 +31,28 @@ const ANALYSIS_ERROR_TAGS = [
/** Stable tag for an expected analysis failure. */
export type AnalysisErrorTag = (typeof ANALYSIS_ERROR_TAGS)[number];
/** Retained command output associated with a typed failure; truncation stays explicit. */
export interface AnalysisCapturedOutput {
readonly stdout: string;
readonly stderr: string;
readonly truncated: boolean;
}
/** Optional provider-neutral context that must survive typed error projection. */
export interface AnalysisErrorOptions extends ErrorOptions {
readonly capturedOutput?: AnalysisCapturedOutput;
}
/** Base class for expected analysis, provider, and session failures. */
export abstract class AnalysisError extends Error {
readonly capturedOutput: AnalysisCapturedOutput | undefined;
constructor(message: string, options?: AnalysisErrorOptions) {
super(message, options);
this.capturedOutput =
options?.capturedOutput === undefined
? undefined
: { ...options.capturedOutput };
}
abstract readonly _tag: AnalysisErrorTag;
readonly userMessage: string | undefined = undefined;
readonly userCategory: "cancelled" | undefined = undefined;
+29 -6
View File
@@ -1,5 +1,23 @@
import type { JsonValue } from "./jsonValue.js";
import { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisError,
type AnalysisErrorOptions,
} from "./analysisErrorBase.js";
/** Provider reported a resource failure, distinct from malformed input or unsupported coverage. */
export class AnalysisResourceConstraintError extends AnalysisError {
readonly _tag = "AnalysisResourceConstraintError";
constructor(
readonly operation: string,
readonly resource: "memory" | "cpu" | "file-size",
readonly reason: string,
readonly reportedLimits: Readonly<Record<string, JsonValue>> | null,
options?: AnalysisErrorOptions,
) {
super(`Resource constraint during ${operation}: ${reason}`, options);
}
}
/** Provider-neutral invalid analysis input or output at an application boundary. */
export class AnalysisProtocolError extends AnalysisError {
@@ -12,7 +30,7 @@ export class AnalysisInputError extends AnalysisError {
constructor(
readonly operation: string,
options?: ErrorOptions,
options?: AnalysisErrorOptions,
readonly issues: readonly AnalysisInputIssue[] = [],
) {
super(`Invalid analysis input for ${operation}`, options);
@@ -43,7 +61,7 @@ export class AnalysisOutputError extends AnalysisError {
constructor(
readonly operation: string,
readonly reason: string,
options?: ErrorOptions,
options?: AnalysisErrorOptions,
) {
super(`Invalid analysis output for ${operation}: ${reason}`, options);
}
@@ -58,7 +76,7 @@ export class AnalysisCapabilityUnavailableError extends AnalysisError {
readonly providerId: string,
readonly operation: string,
readonly reason: string,
options?: ErrorOptions & { readonly userMessage?: string },
options?: AnalysisErrorOptions & { readonly userMessage?: string },
) {
super(
`Provider ${providerId} cannot execute ${operation}: ${reason}`,
@@ -72,8 +90,11 @@ export class AnalysisCapabilityUnavailableError extends AnalysisError {
export class AnalysisCancelledError extends AnalysisError {
readonly _tag = "AnalysisCancelledError";
constructor(readonly operation: string) {
super(`Analysis operation was cancelled: ${operation}`);
constructor(
readonly operation: string,
options?: AnalysisErrorOptions,
) {
super(`Analysis operation was cancelled: ${operation}`, options);
}
}
@@ -84,9 +105,11 @@ export class AnalysisTimeoutError extends AnalysisError {
constructor(
readonly operation: string,
readonly timeoutMs: number,
options?: AnalysisErrorOptions,
) {
super(
`Analysis operation timed out after ${String(timeoutMs)}ms: ${operation}`,
options,
);
}
}
+10
View File
@@ -2,6 +2,7 @@ import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisInputError,
AnalysisResourceConstraintError,
} from "./analysisErrorCore.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
import {
@@ -32,6 +33,12 @@ import { type AnalysisErrorProjection } from "./analysisErrorProjection.js";
export const analysisErrorRemediationAction = (
error: AnalysisError,
): string => {
if (error instanceof AnalysisResourceConstraintError)
return error.resource === "cpu"
? "Review the reported worker CPU limits and observed signal. Retry with sufficient CPU time or a smaller artifact; REA retains tighter inherited limits."
: error.resource === "file-size"
? "Review the reported worker file-size limits and write failure. Retry with a sufficient file-size allowance for the evidence reply; REA retains tighter inherited limits."
: "Review the reported worker memory limits and available host memory. Retry with sufficient memory or a smaller artifact; REA retains tighter inherited limits.";
if (error instanceof HopperTimeoutError)
return error.providerState === "busy"
? "Check binary_session.analysis_activity, wait for the active Hopper request to finish, then retry."
@@ -123,12 +130,14 @@ const STATIC_ERROR_CATEGORIES: Readonly<
AnalysisCancelledError: "cancelled",
HopperCancelledError: "cancelled",
AnalysisTimeoutError: "timeout",
AnalysisResourceConstraintError: "resource_constraint",
HopperTimeoutError: "timeout",
NoBinaryOpenError: "unavailable",
BinaryTargetError: "unavailable",
};
export const analysisErrorUserMessage = (error: AnalysisError): string => {
if (error instanceof AnalysisResourceConstraintError) return error.reason;
if (error instanceof AnalysisAccessDeniedError)
return "Host filesystem permissions denied read access to the selected path.";
if (error instanceof AnalysisArtifactChangedError)
@@ -263,6 +272,7 @@ const KNOWN_ERROR_TAGS = {
AnalysisCapabilityUnavailableError: true,
AnalysisCancelledError: true,
AnalysisTimeoutError: true,
AnalysisResourceConstraintError: true,
ProviderSelectionError: true,
ProviderAdapterError: true,
BrowserObservationError: true,
@@ -3,6 +3,9 @@ import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
AnalysisCancelledError,
AnalysisTimeoutError,
AnalysisResourceConstraintError,
} from "./analysisErrorCore.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
import { BinaryTargetError } from "./configurationErrors.js";
@@ -16,6 +19,87 @@ import {
import { ProviderAdapterError } from "./providerAdapterError.js";
import { UnknownRegistryError } from "./unknownRegistryError.js";
import { projectAnalysisError } from "./analysisErrorProjection.js";
import { ProviderSelectionError } from "./providerSelectionError.js";
import { analysisErrorProjectionSchema } from "../contracts/errorSchemas.js";
const retainedOutput = {
stdout: "selected output\u0000",
stderr: "upstream warning",
truncated: true,
};
it.each([
["memory", null],
["memory", { address_space_bytes: 67108864 }],
["cpu", null],
["cpu", { cpu_seconds: 1 }],
["file-size", null],
["file-size", { file_size_bytes: 1024 }],
] as const)(
"projects reported %s constraints with observed or unknown limits: %j",
(resource, limits) => {
const projected = projectAnalysisError(
new AnalysisResourceConstraintError(
"inspect_binary_layout",
resource,
resource === "memory"
? "Memory allocation failed; exact cause unknown."
: "Observed SIGXCPU; exact signal cause unknown.",
limits,
{ capturedOutput: retainedOutput },
),
);
expect(projected).toMatchObject({
code: "resource_constraint",
category: "resource_constraint",
retryable: false,
details: {
resource,
reported_limits: limits,
captured_output: retainedOutput,
},
});
expect(projected.remediation.action).toContain(
resource === "cpu"
? "CPU"
: resource === "file-size"
? "file-size"
: "memory",
);
expect(projected.remediation.action).not.toContain("doctor");
expect(analysisErrorProjectionSchema.safeParse(projected).success).toBe(
true,
);
},
);
it.each([
new AnalysisInputError("inspect", { capturedOutput: retainedOutput }),
new AnalysisOutputError("inspect", "invalid reply", {
capturedOutput: retainedOutput,
}),
new AnalysisCapabilityUnavailableError(
"provider",
"inspect",
"unsupported profile",
{ capturedOutput: retainedOutput },
),
new AnalysisCancelledError("inspect", { capturedOutput: retainedOutput }),
new AnalysisTimeoutError("inspect", 30, { capturedOutput: retainedOutput }),
new ProviderSelectionError({
operation: "inspect",
reason: "provider_unavailable",
requestedProviderId: "provider",
candidateIds: [],
capturedOutput: retainedOutput,
}),
])(
"retains captured output without changing the typed primary failure: $._tag",
(failure) => {
expect(projectAnalysisError(failure).details?.captured_output).toEqual(
retainedOutput,
);
},
);
describe("analysis error projection: provider failures", () => {
it("projects the primary browser failure alongside incomplete cleanup", () => {
+16 -1
View File
@@ -14,6 +14,7 @@ import {
AnalysisInputError,
AnalysisOutputError,
AnalysisTimeoutError,
AnalysisResourceConstraintError,
} from "./analysisErrorCore.js";
import { ArtifactOperationError } from "./artifactOperationError.js";
import { BinaryTargetError } from "./configurationErrors.js";
@@ -39,7 +40,11 @@ export const projectAnalysisError = (
): AnalysisErrorProjection => {
assertKnownAnalysisErrorTag(error._tag);
const code = errorCode(error);
const details = errorDetails(error);
const primaryDetails = errorDetails(error);
const details =
error.capturedOutput === undefined
? primaryDetails
: { ...primaryDetails, captured_output: { ...error.capturedOutput } };
return {
code,
category: analysisErrorCategory(error),
@@ -138,6 +143,7 @@ const STATIC_ERROR_CODES = {
AnalysisCancelledError: "cancelled",
HopperCancelledError: "cancelled",
AnalysisTimeoutError: "provider_timeout",
AnalysisResourceConstraintError: "resource_constraint",
HopperTimeoutError: "provider_timeout",
HopperProcessError: "provider_unavailable",
HopperStartError: "provider_unavailable",
@@ -181,6 +187,13 @@ const errorDetails = (
const requestErrorDetails = (
error: AnalysisError,
): Readonly<Record<string, JsonValue>> | undefined => {
if (error instanceof AnalysisResourceConstraintError)
return {
operation: error.operation,
resource: error.resource,
reason: error.reason,
reported_limits: error.reportedLimits,
};
if (error instanceof AnalysisArtifactChangedError)
return {
operation: error.operation,
@@ -409,6 +422,7 @@ export interface AnalysisErrorProjection extends Readonly<
| "capability_unavailable"
| "provider_unavailable"
| "provider_timeout"
| "resource_constraint"
| "cancelled"
| "artifact_integrity_mismatch"
| "artifact_operation_failed"
@@ -427,6 +441,7 @@ export interface AnalysisErrorProjection extends Readonly<
| "truncated"
| "cancelled"
| "timeout"
| "resource_constraint"
| "unavailable"
| "execution_failure";
readonly message: string;
+362
View File
@@ -0,0 +1,362 @@
import { expect, it } from "vitest";
import { binaryLayoutSchema, type BinaryLayout } from "./binaryLayout.js";
const report = () => ({
artifact: { path: "/fixture.elf", sha256: "a".repeat(64), bytes: 128 },
format: "elf",
architecture: { machine: "EM_X86_64", bits: 64, byte_order: "little" },
image_type: "ET_EXEC",
entry_point: {
reported_value: "0x20000000000001",
meaning: "linked-virtual-address",
execution_status: "unknown",
},
runtime_load_base: null,
sections: [
{
index: 0,
name: {
display: "opaque",
bytes_base64: "b3BhcXVl",
location: { offset: "0x40", bytes: "0x7" },
unknown_reason: null,
},
name_offset: "0x0",
type: "SHT_NOBITS",
header_location: { offset: "0x0", bytes: "0x40" },
address: "0x20000000000001",
offset: "0xffffffffffffffff",
size: "0x2000",
alignment: "0x1",
flags: "0x3",
link: 0,
info: 0,
entry_size: "0x0",
file_backing: "none",
},
],
segments: [],
symbols: [],
relocations: [],
packed_relative_relocations: [],
relocation_inventory_completeness: "unknown",
linkage: {
needed_libraries: [],
interpreters: [],
got: [],
plt: [],
convenience_maps_completeness: "unknown",
runtime_library_paths: null,
},
mitigations: {
evidence_kind: "inferred",
position_independent: false,
nx_indicator: null,
executable_stack_indicator: false,
stack_canary_indicator: false,
relro: null,
},
diagnostics: { stdout: "", stderr: "", truncated: false },
limitations: [],
});
it("retains high linked values and NOBITS without inventing file backing", () => {
const value = binaryLayoutSchema.parse(report());
expect(value.entry_point.reported_value).toBe("0x20000000000001");
expect(value.sections[0]?.offset).toBe("0xffffffffffffffff");
expect(value.runtime_load_base).toBeNull();
});
it.each([
"file-backed-outside",
"header-outside",
"wrong-index",
"noncanonical-base64",
"wrong-machine",
"outside-elf64",
])("rejects a malformed source representation: %s", (problem) => {
const value = report();
const section = value.sections[0];
if (section === undefined) throw new Error("section missing");
if (problem === "file-backed-outside") section.file_backing = "file";
if (problem === "header-outside") section.header_location.offset = "0x80";
if (problem === "wrong-index") section.index = 1;
if (problem === "wrong-machine") value.architecture.machine = "EM_AARCH64";
if (problem === "outside-elf64")
value.entry_point.reported_value = "0x10000000000000000";
if (problem === "noncanonical-base64") section.name.bytes_base64 = "AR==";
expect(binaryLayoutSchema.safeParse(value).success).toBe(false);
});
it.each([
["PT_NULL", "0xffffffffffffffff", "none", null, true],
["PT_LOAD", "0x0", "none", { read: true, write: true, execute: false }, true],
[
"PT_LOAD",
"0x1",
"file",
{ read: true, write: false, execute: false },
false,
],
["PT_NULL", "0x1", "file", null, false],
[
"PT_NULL",
"0x1",
"none",
{ read: false, write: false, execute: false },
false,
],
[
"PT_LOAD",
"0x1",
"none",
{ read: true, write: false, execute: false },
false,
],
])(
"validates actual segment backing/meaning for %s size %s",
(type, fileSize, backing, permissions, valid) => {
const value = {
...report(),
segments: [
{
index: 0,
type,
header_location: { offset: "0x0", bytes: "0x38" },
offset: "0xffffffffffffffff",
file_size: fileSize,
memory_size: fileSize,
virtual_address: "0x0",
physical_address: "0x0",
alignment: "0x0",
flags: "0x0",
file_backing: backing,
permissions,
},
],
};
expect(binaryLayoutSchema.safeParse(value).success).toBe(valid);
},
);
it.each([
["ET_EXEC", "0x0", "absent", true],
["ET_DYN", "0x0", "linked-virtual-address", false],
["ET_REL", "0x0", "not-applicable", true],
["ET_EXEC", "0x1", "absent", false],
])(
"validates actual entry meaning: %s %s %s",
(imageType, entry, meaning, valid) => {
expect(
binaryLayoutSchema.safeParse({
...report(),
image_type: imageType,
entry_point: {
reported_value: entry,
meaning,
execution_status: "unknown",
},
}).success,
).toBe(valid);
},
);
it.each([
"valid",
"byte-length",
"section-identity",
"decoded-order",
"noncanonical-bytes",
])(
"retains original packed bytes and derived offset provenance: %s",
(problem) => {
const value = report();
const section = value.sections[0];
if (section === undefined) throw new Error("section missing");
section.type = "SHT_RELR";
section.file_backing = "file";
section.offset = "0x60";
section.size = "0x8";
const table = {
section_index: 0,
location: { offset: "0x60", bytes: "0x8" },
encoded_bytes_base64: "AAAAAAAAAAA=",
entries: [{ decoded_index: 0, reported_offset: "0x20000000000001" }],
offset_meaning: "linked-virtual-address",
evidence_kind: "derived",
entry_source_locations: null,
addends: null,
};
if (problem === "byte-length") table.location.bytes = "0x7";
if (problem === "section-identity") table.section_index = 1;
if (problem === "decoded-order")
table.entries[0] = { decoded_index: 1, reported_offset: "0x0" };
if (problem === "noncanonical-bytes") table.encoded_bytes_base64 = "AB==";
expect(
binaryLayoutSchema.safeParse({
...value,
packed_relative_relocations: [table],
}).success,
).toBe(problem === "valid");
},
);
it.each([
"valid",
"zero-symbol",
"zero-without-table",
"missing-table",
"wrong-table-kind",
"missing-symbol",
"symbol-outside-table",
"positive-without-table",
"owner-link-mismatch",
"wrong-meaning",
"valid-section-target",
"missing-target",
"wrong-target-owner",
"wrong-target-offset",
"undefined-target",
"inactive-target",
"false-resolved-zero-target",
"wrong-unknown-target",
"missing-string-table",
"wrong-string-table-kind",
])("validates relocation symbol reference semantics: %s", (problem) => {
const value = binaryLayoutSchema.parse(report());
value.artifact.bytes = 512;
const base = value.sections[0];
if (base === undefined) throw new Error("section missing");
value.sections.push(
{
...base,
index: 1,
type: "SHT_SYMTAB",
link: 3,
header_location: { offset: "0x40", bytes: "0x40" },
offset: "0x100",
size: "0x30",
entry_size: "0x18",
file_backing: "file",
},
{
...base,
index: 2,
type: "SHT_RELA",
header_location: { offset: "0x80", bytes: "0x40" },
offset: "0x130",
size: "0x18",
entry_size: "0x18",
link: 1,
file_backing: "file",
},
{
...base,
index: 3,
type: "SHT_STRTAB",
offset: "0x40",
size: "0x7",
file_backing: "file",
},
);
value.symbols.push({
table_index: 1,
entry_index: 1,
name: base.name,
name_offset: "0x0",
location: { offset: "0x118", bytes: "0x18" },
value: "0x0",
value_meaning: "undefined",
size: "0x0",
binding: "STB_GLOBAL",
type: "STT_NOTYPE",
visibility: "STV_DEFAULT",
section_index: "SHN_UNDEF",
});
const relocation: BinaryLayout["relocations"][number] = {
section_index: 2,
entry_index: 0,
reported_offset: "0x0",
target: { kind: "linked-virtual-address", address: "0x0" },
location: { offset: "0x130", bytes: "0x18" },
type: 1,
symbol_table_index: 1,
symbol_index: 1,
symbol_reference_meaning: "symbol-table-entry",
addend: "0",
};
const table = value.sections[1];
const owner = value.sections[2];
if (table === undefined || owner === undefined)
throw new Error("table or relocation owner missing");
if (problem.startsWith("zero")) {
relocation.symbol_index = 0;
relocation.symbol_reference_meaning = "zero-symbol-value";
}
if (problem === "zero-without-table" || problem === "positive-without-table")
owner.link = relocation.symbol_table_index = 0;
if (problem === "missing-table")
owner.link = relocation.symbol_table_index = 99;
if (problem === "wrong-table-kind") table.type = "SHT_PROGBITS";
if (problem === "missing-string-table") table.link = 99;
if (problem === "wrong-string-table-kind") table.link = 0;
if (problem === "missing-symbol") value.symbols = [];
if (problem === "symbol-outside-table") table.size = "0x18";
if (problem === "owner-link-mismatch") owner.link = 0;
if (problem === "wrong-meaning")
relocation.symbol_reference_meaning = "zero-symbol-value";
if (problem.includes("target")) {
value.image_type = "ET_REL";
value.entry_point.meaning = "not-applicable";
owner.info = 1;
relocation.target = {
kind: "section-offset",
section_index:
problem === "missing-target"
? 99
: problem === "wrong-target-owner"
? 2
: 1,
offset: problem === "wrong-target-offset" ? "0x1" : "0x0",
};
if (problem === "missing-target") owner.info = 99;
if (problem === "false-resolved-zero-target") {
owner.info = 0;
relocation.target.section_index = 0;
}
if (
["undefined-target", "inactive-target", "wrong-unknown-target"].includes(
problem,
)
) {
if (problem === "inactive-target")
value.sections.push({ ...base, index: 4, type: "SHT_NULL" });
owner.info =
problem === "undefined-target"
? 0
: problem === "inactive-target"
? 4
: 1;
relocation.target = {
kind: "unknown-section",
reported_section_index: owner.info,
offset: "0x0",
unknown_reason:
problem === "undefined-target"
? "undefined-section-reference"
: "inactive-section-header",
};
}
}
value.relocations.push(relocation);
expect(binaryLayoutSchema.safeParse(value).success).toBe(
[
"valid",
"zero-symbol",
"zero-without-table",
"valid-section-target",
"undefined-target",
"inactive-target",
].includes(problem),
);
});
+443
View File
@@ -0,0 +1,443 @@
import { z } from "zod";
const unsignedHex = z.string().regex(/^0x(?:0|[1-9a-f][0-9a-f]{0,15})$/);
const index = z.number().int().nonnegative();
const scalar = z.union([z.string(), z.number().int()]);
const range = z.strictObject({ offset: unsignedHex, bytes: unsignedHex });
const canonicalBase64 = z
.string()
.regex(
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$/,
);
const name = z.strictObject({
display: z.string(),
bytes_base64: canonicalBase64.nullable(),
location: range.nullable(),
unknown_reason: z.string().nullable(),
});
/** Explicit local object selection, independent of an active disassembler target. */
export const inspectBinaryLayoutInputSchema = z.strictObject({
path: z
.string()
.min(1)
.describe("Absolute filesystem path to the selected binary"),
});
/** File and linked-image evidence; numeric ELF values never pass through unsafe JSON numbers. */
const binaryLayoutObjectSchema = z.strictObject({
artifact: z.strictObject({
path: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: index,
}),
format: z.literal("elf"),
architecture: z.strictObject({
machine: z.literal("EM_X86_64"),
bits: z.literal(64),
byte_order: z.literal("little"),
}),
image_type: z.enum(["ET_EXEC", "ET_DYN", "ET_REL"]),
entry_point: z.strictObject({
reported_value: unsignedHex,
meaning: z.enum(["linked-virtual-address", "not-applicable", "absent"]),
execution_status: z.literal("unknown"),
}),
runtime_load_base: z.null(),
sections: z.array(
z.strictObject({
index,
name,
name_offset: unsignedHex,
type: scalar,
header_location: range,
address: unsignedHex,
offset: unsignedHex,
size: unsignedHex,
alignment: unsignedHex,
flags: unsignedHex,
link: index,
info: index,
entry_size: unsignedHex,
file_backing: z.enum(["file", "none"]),
}),
),
segments: z.array(
z.strictObject({
index,
type: scalar,
header_location: range,
offset: unsignedHex,
file_size: unsignedHex,
memory_size: unsignedHex,
virtual_address: unsignedHex,
physical_address: unsignedHex,
alignment: unsignedHex,
flags: unsignedHex,
file_backing: z.enum(["file", "none"]),
permissions: z
.strictObject({
read: z.boolean(),
write: z.boolean(),
execute: z.boolean(),
})
.nullable(),
}),
),
symbols: z.array(
z.strictObject({
table_index: index,
entry_index: index,
name,
name_offset: unsignedHex,
location: range,
value: unsignedHex,
value_meaning: z.enum([
"undefined",
"alignment",
"absolute-value",
"no-address",
"unknown-section-index",
"section-offset",
"tls-offset",
"linked-virtual-address",
]),
size: unsignedHex,
binding: scalar,
type: scalar,
visibility: scalar,
section_index: scalar,
}),
),
relocations: z.array(
z.strictObject({
section_index: index,
entry_index: index,
reported_offset: unsignedHex,
target: z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("section-offset"),
section_index: index,
offset: unsignedHex,
}),
z.strictObject({
kind: z.literal("linked-virtual-address"),
address: unsignedHex,
}),
z.strictObject({
kind: z.literal("unknown-section"),
reported_section_index: index,
offset: unsignedHex,
unknown_reason: z.enum([
"undefined-section-reference",
"inactive-section-header",
]),
}),
]),
location: range,
type: index,
symbol_table_index: index,
symbol_index: index,
symbol_reference_meaning: z.enum([
"zero-symbol-value",
"symbol-table-entry",
]),
addend: z
.string()
.regex(/^-?(?:0|[1-9][0-9]{0,18})$/)
.nullable(),
}),
),
packed_relative_relocations: z.array(
z.strictObject({
section_index: index,
location: range,
encoded_bytes_base64: canonicalBase64,
entries: z.array(
z.strictObject({ decoded_index: index, reported_offset: unsignedHex }),
),
offset_meaning: z.enum(["linked-virtual-address", "unknown"]),
evidence_kind: z.literal("derived"),
entry_source_locations: z.null(),
addends: z.null(),
}),
),
relocation_inventory_completeness: z.literal("unknown"),
linkage: z.strictObject({
needed_libraries: z.array(name),
interpreters: z.array(name),
got: z.array(
z.strictObject({ display_name: z.string(), address: unsignedHex }),
),
plt: z.array(
z.strictObject({ display_name: z.string(), address: unsignedHex }),
),
convenience_maps_completeness: z.literal("unknown"),
runtime_library_paths: z.null(),
}),
mitigations: z.strictObject({
evidence_kind: z.literal("inferred"),
position_independent: z.boolean(),
nx_indicator: z.boolean().nullable(),
executable_stack_indicator: z.boolean(),
stack_canary_indicator: z.boolean(),
relro: z.enum(["Partial", "Full"]).nullable(),
}),
diagnostics: z.strictObject({
stdout: z.string(),
stderr: z.string(),
truncated: z.boolean(),
}),
limitations: z.array(z.string()),
});
/** Decoder payload excludes the artifact identity observed by the owning process boundary. */
export const binaryLayoutPayloadSchema = binaryLayoutObjectSchema.omit({
artifact: true,
diagnostics: true,
});
/** Check source ranges again at the public boundary, independently of upstream parsing. */
export const binaryLayoutSchema = binaryLayoutObjectSchema.superRefine(
(value, context) => {
const size = BigInt(value.artifact.bytes);
const check = (
offset: string,
length: string,
path: (string | number)[],
): void => {
const start = BigInt(offset);
const bytes = BigInt(length);
if (start > size || bytes > size - start)
context.addIssue({
code: "custom",
path,
message:
"Reported file-backed range lies outside the selected artifact.",
});
};
const checkLocation = (
where: z.infer<typeof range>,
path: (string | number)[],
): void => check(where.offset, where.bytes, path);
const checkName = (
reported: z.infer<typeof name>,
path: (string | number)[],
): void => {
if (reported.location !== null)
checkLocation(reported.location, [...path, "location"]);
};
const expectedEntryMeaning =
value.image_type === "ET_REL"
? "not-applicable"
: value.entry_point.reported_value === "0x0"
? "absent"
: "linked-virtual-address";
if (value.entry_point.meaning !== expectedEntryMeaning)
context.addIssue({
code: "custom",
path: ["entry_point", "meaning"],
message:
"Entry meaning must distinguish zero/unused fields from an actual linked address.",
});
for (const [index, section] of value.sections.entries()) {
if (
(section.type === "SHT_SYMTAB" || section.type === "SHT_DYNSYM") &&
value.sections[section.link]?.type !== "SHT_STRTAB"
)
context.addIssue({
code: "custom",
path: ["sections", index, "link"],
message:
"Symbol tables must link to an existing string-table section.",
});
if (section.index !== index)
context.addIssue({
code: "custom",
path: ["sections", index, "index"],
message:
"Complete section order must preserve original producer indices.",
});
checkLocation(section.header_location, [
"sections",
index,
"header_location",
]);
checkName(section.name, ["sections", index, "name"]);
if (section.file_backing === "file")
check(section.offset, section.size, ["sections", index]);
}
for (const [index, segment] of value.segments.entries()) {
if (segment.index !== index)
context.addIssue({
code: "custom",
path: ["segments", index, "index"],
message:
"Complete segment order must preserve original producer indices.",
});
checkLocation(segment.header_location, [
"segments",
index,
"header_location",
]);
const hasFileBytes =
segment.type !== "PT_NULL" && BigInt(segment.file_size) !== 0n;
if (segment.file_backing !== (hasFileBytes ? "file" : "none"))
context.addIssue({
code: "custom",
path: ["segments", index, "file_backing"],
message:
"File backing must follow the reported segment type and file size.",
});
if ((segment.type === "PT_NULL") !== (segment.permissions === null))
context.addIssue({
code: "custom",
path: ["segments", index, "permissions"],
message:
"Unused PT_NULL flags have no permission meaning; other segment flags retain their interpretation.",
});
if (hasFileBytes)
check(segment.offset, segment.file_size, ["segments", index]);
}
for (const [index, symbol] of value.symbols.entries()) {
checkLocation(symbol.location, ["symbols", index, "location"]);
checkName(symbol.name, ["symbols", index, "name"]);
}
for (const [index, relocation] of value.relocations.entries())
checkLocation(relocation.location, ["relocations", index, "location"]);
validateRelocationReferences(value, context);
validatePackedRelativeTables(value, context, checkLocation);
for (const facet of ["needed_libraries", "interpreters"] as const)
for (const [index, reported] of value.linkage[facet].entries())
checkName(reported, ["linkage", facet, index]);
},
);
export type InspectBinaryLayoutInput = z.infer<
typeof inspectBinaryLayoutInputSchema
>;
export type BinaryLayout = z.infer<typeof binaryLayoutSchema>;
const validateRelocationReferences = (
value: z.output<typeof binaryLayoutObjectSchema>,
context: z.RefinementCtx,
): void => {
const symbols = new Set(
value.symbols.map(
(symbol) => `${symbol.table_index}:${symbol.entry_index}`,
),
);
for (const [index, relocation] of value.relocations.entries()) {
const owner = value.sections[relocation.section_index];
const target = relocation.target;
const targetMatches =
value.image_type === "ET_REL"
? target.kind === "section-offset"
? target.section_index !== 0 &&
target.section_index === owner?.info &&
value.sections[target.section_index] !== undefined &&
value.sections[target.section_index]?.type !== "SHT_NULL" &&
target.offset === relocation.reported_offset
: target.kind === "unknown-section" &&
target.reported_section_index === owner?.info &&
target.offset === relocation.reported_offset &&
(target.reported_section_index === 0
? target.unknown_reason === "undefined-section-reference"
: value.sections[target.reported_section_index]?.type ===
"SHT_NULL" &&
target.unknown_reason === "inactive-section-header")
: target.kind === "linked-virtual-address" &&
target.address === relocation.reported_offset;
if (!targetMatches)
context.addIssue({
code: "custom",
path: ["relocations", index, "target"],
message:
"Relocation target must preserve its reported offset and owner reference; SHN_UNDEF and inactive headers remain unknown rather than resolved sections.",
});
const table = value.sections[relocation.symbol_table_index];
const tableExists =
relocation.symbol_table_index !== 0 &&
(table?.type === "SHT_SYMTAB" || table?.type === "SHT_DYNSYM");
const positiveReferenceExists =
tableExists &&
BigInt(table.entry_size) >= 24n &&
BigInt(relocation.symbol_index) <
BigInt(table.size) / BigInt(table.entry_size) &&
symbols.has(
`${relocation.symbol_table_index}:${relocation.symbol_index}`,
);
if (
(owner?.type !== "SHT_REL" && owner?.type !== "SHT_RELA") ||
owner.link !== relocation.symbol_table_index ||
(relocation.symbol_table_index !== 0 && !tableExists) ||
(relocation.symbol_index !== 0 && !positiveReferenceExists) ||
relocation.symbol_reference_meaning !==
(relocation.symbol_index === 0
? "zero-symbol-value"
: "symbol-table-entry")
)
context.addIssue({
code: "custom",
path: ["relocations", index],
message:
"Relocation must preserve its REL/RELA owner and resolve positive symbol indices through the linked symbol table; index zero uses a zero symbol value.",
});
}
};
const validatePackedRelativeTables = (
value: z.output<typeof binaryLayoutObjectSchema>,
context: z.RefinementCtx,
checkLocation: (
location: z.output<typeof range>,
path: (string | number)[],
) => void,
): void => {
for (const [
tableIndex,
table,
] of value.packed_relative_relocations.entries()) {
checkLocation(table.location, [
"packed_relative_relocations",
tableIndex,
"location",
]);
const encodedBytes =
(table.encoded_bytes_base64.length * 3) / 4 -
(table.encoded_bytes_base64.endsWith("==")
? 2
: table.encoded_bytes_base64.endsWith("=")
? 1
: 0);
if (
!Number.isInteger(encodedBytes) ||
BigInt(encodedBytes) !== BigInt(table.location.bytes)
)
context.addIssue({
code: "custom",
path: ["packed_relative_relocations", tableIndex],
message:
"Complete packed table bytes must match its original file range.",
});
const section = value.sections[table.section_index];
if (
section?.type !== "SHT_RELR" ||
section.offset !== table.location.offset ||
section.size !== table.location.bytes
)
context.addIssue({
code: "custom",
path: ["packed_relative_relocations", tableIndex, "section_index"],
message:
"Packed relative evidence must retain its original RELR section identity and range.",
});
for (const [decoded, entry] of table.entries.entries())
if (entry.decoded_index !== decoded)
context.addIssue({
code: "custom",
path: ["packed_relative_relocations", tableIndex, "entries", decoded],
message: "Decoded offsets must preserve upstream iterator order.",
});
}
};
+11 -2
View File
@@ -1,5 +1,8 @@
import type { JsonValue } from "./jsonValue.js";
import { AnalysisError } from "./analysisErrorBase.js";
import {
AnalysisError,
type AnalysisCapturedOutput,
} from "./analysisErrorBase.js";
/** Stable failure classes for target-bound deep-provider selection. */
export type ProviderSelectionFailureReason =
@@ -19,6 +22,7 @@ export interface ProviderSelectionRejection {
/** Complete typed context for one failed deep-provider selection. */
export interface ProviderSelectionErrorOptions {
readonly capturedOutput?: AnalysisCapturedOutput;
readonly operation?: string;
readonly reason: ProviderSelectionFailureReason;
readonly requestedProviderId: string;
@@ -38,7 +42,12 @@ export class ProviderSelectionError extends AnalysisError {
constructor(options: ProviderSelectionErrorOptions) {
const operation = options.operation ?? "open_binary";
super(providerSelectionDiagnostic(options));
super(
providerSelectionDiagnostic(options),
options.capturedOutput === undefined
? undefined
: { capturedOutput: options.capturedOutput },
);
this.operation = operation;
this.reason = options.reason;
this.requestedProviderId = options.requestedProviderId;
+1 -1
View File
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.3.1",
clientSdkVersion: "2.3.1",
coreSdkVersion: "2.3.1",
skillVersion: "29",
skillVersion: "30",
} as const;
+245
View File
@@ -0,0 +1,245 @@
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import {
AnalysisError,
type AnalysisCapturedOutput,
} from "../../domain/analysisErrorBase.js";
import type { ProviderProcessSnapshot } from "../../process/ProviderProcess.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
AnalysisTimeoutError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { ProviderSelectionError } from "../../domain/providerSelectionError.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
import type { PwntoolsFailureEvidence } from "./PwntoolsResourceLimits.js";
import {
PWNTOOLS_PROVIDER_IDENTITY,
PWNTOOLS_LIMITS,
PWNTOOLS_MEMORY_FAILURE_EXIT,
PWNTOOLS_FILE_SIZE_FAILURE_EXIT,
} from "./PwntoolsRelease.js";
const OPERATION = "inspect_binary_layout";
/** Keep read, engine, output and owned-lifecycle failure reasons distinct. */
export const pwntoolsLayoutFailure = (
cause: unknown,
phase: string,
path: string,
executablePath = path,
failureEvidence: PwntoolsFailureEvidence = {},
): AnalysisError => {
const limitReport = failureEvidence.limits;
if (cause instanceof AnalysisError) return cause;
if (cause instanceof OwnedCommandFailure) {
const outputOptions =
cause.snapshot === null
? undefined
: { capturedOutput: capturedPwntoolsOutput(cause.snapshot) };
if (cause.cleanupFailure !== null)
return new ProviderCleanupError(
PWNTOOLS_PROVIDER_IDENTITY.id,
cause.resources,
{
reason: cause.cleanupFailure,
...(cause.snapshot === null
? {}
: {
captured_output: { ...capturedPwntoolsOutput(cause.snapshot) },
}),
previous_error: {
failure_kind: cause.reason,
message: cause.message,
exit_code: cause.snapshot?.exitCode ?? null,
signal: cause.snapshot?.signal ?? null,
stdout: cause.snapshot?.stdout.text ?? null,
stderr: cause.snapshot?.stderr.text ?? null,
},
},
{ operation: OPERATION, cause },
);
if (cause.reason === "cancelled")
return new AnalysisCancelledError(OPERATION, outputOptions);
if (cause.reason === "timeout")
return new AnalysisTimeoutError(
OPERATION,
PWNTOOLS_LIMITS.timeoutMs,
outputOptions,
);
if (cause.reason === "output-limit")
return new AnalysisOutputError(OPERATION, cause.message, outputOptions);
if (
cause.reason === "process" &&
(cause.snapshot?.signal === "SIGXFSZ" ||
(failureEvidence.marker?.resource === "file-size" &&
cause.snapshot?.exitCode === PWNTOOLS_FILE_SIZE_FAILURE_EXIT &&
cause.snapshot.signal === null))
)
return new AnalysisResourceConstraintError(
OPERATION,
"file-size",
(cause.snapshot.signal === "SIGXFSZ"
? "Owned Python terminated with SIGXFSZ; the exact signal cause is unknown."
: "The owned Python bridge reported EFBIG while writing a file; the exact write failure cause is unknown.") +
(limitReport?.failure === null || limitReport === undefined
? ""
: ` Effective limit report unavailable: ${limitReport.failure}`),
limitReport?.limits ?? null,
outputOptions,
);
if (cause.reason === "process" && cause.snapshot?.signal === "SIGXCPU")
return new AnalysisResourceConstraintError(
OPERATION,
"cpu",
"Owned Python terminated with SIGXCPU; the exact signal cause is unknown." +
(limitReport?.failure === null || limitReport === undefined
? ""
: ` Effective limit report unavailable: ${limitReport.failure}`),
limitReport?.limits ?? null,
outputOptions,
);
if (
cause.reason === "process" &&
failureEvidence.marker?.resource === "memory" &&
cause.snapshot?.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT &&
cause.snapshot.signal === null
)
return new AnalysisResourceConstraintError(
OPERATION,
"memory",
"The owned Python bridge reported a memory allocation failure without a structured reply; the exact allocation cause is unknown." +
(limitReport?.failure === null || limitReport === undefined
? ""
: ` Effective limit report unavailable: ${limitReport.failure}`),
limitReport?.limits ?? null,
outputOptions,
);
}
if (
cause instanceof Error &&
"code" in cause &&
"syscall" in cause &&
typeof cause.syscall === "string" &&
cause.syscall.startsWith("spawn ")
)
return pwntoolsUnavailable(
`Selected Python could not launch (${String(cause.code)}): ${executablePath}. Check the configured executable, its interpreter and host execute access.`,
executablePath,
String(cause.code),
);
if (cause instanceof ArtifactReaderFailure) {
if (cause.reason === "integrity")
return new AnalysisArtifactChangedError(OPERATION, path, cause.message, {
cause,
});
if (cause.reason === "cancelled")
return new AnalysisCancelledError(OPERATION);
if (
cause.reason === "limit" ||
cause.reason === "path" ||
cause.reason === "format"
)
return new AnalysisInputError(OPERATION, { cause }, [
{
path: ["path"],
reason: cause.reason === "limit" ? "out_of_range" : "invalid_format",
message: cause.message,
},
]);
}
if (cause instanceof Error && "code" in cause) {
if (phase === "configuration")
return pwntoolsUnavailable(
`Selected Python executable is unavailable (${String(cause.code)}): ${path}. Check the caller-selected path and execute access.`,
path,
String(cause.code),
);
if (
phase === "artifact-read" &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
cause,
});
if (
phase === "artifact-read" &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
)
return new AnalysisInputError(OPERATION, { cause }, [
{
path: ["path"],
reason: "invalid_value",
message: `Selected object could not be read (${String(cause.code)}): ${path}.`,
},
]);
}
return new ProviderAdapterError(PWNTOOLS_PROVIDER_IDENTITY.id, OPERATION, {
cause,
diagnostics: {
phase,
path,
reason: cause instanceof Error ? cause.message : String(cause),
...(failureEvidence.marker === undefined
? {}
: { resource_failure_marker: { ...failureEvidence.marker } }),
...(cause instanceof OwnedCommandFailure
? {
failure_kind: cause.reason,
exit_code: cause.snapshot?.exitCode ?? null,
signal: cause.snapshot?.signal ?? null,
stdout: cause.snapshot?.stdout.text ?? null,
stderr: cause.snapshot?.stderr.text ?? null,
...(cause.snapshot === null
? {}
: {
captured_output: {
...capturedPwntoolsOutput(cause.snapshot),
},
}),
}
: {}),
},
});
};
/** Report caller-selected engine absence with its actual configuration and host constraint. */
export const pwntoolsUnavailable = (
reason: string,
path: string,
systemCode?: string,
capturedOutput?: AnalysisCapturedOutput,
): ProviderSelectionError =>
new ProviderSelectionError({
...(capturedOutput === undefined ? {} : { capturedOutput }),
operation: OPERATION,
reason: "provider_unavailable",
requestedProviderId: PWNTOOLS_PROVIDER_IDENTITY.id,
candidateIds: [PWNTOOLS_PROVIDER_IDENTITY.id],
rejections: [
{
providerId: PWNTOOLS_PROVIDER_IDENTITY.id,
code: "provider_unavailable",
reason,
diagnostics: {
configuration_key: "REA_PWNTOOLS_PYTHON",
executable_path: path,
...(systemCode === undefined ? {} : { system_code: systemCode }),
},
},
],
});
/** Retain bounded text output and the shared supervisor's observed truncation flag. */
export const capturedPwntoolsOutput = (
snapshot: ProviderProcessSnapshot,
): AnalysisCapturedOutput => ({
stdout: snapshot.stdout.text,
stderr: snapshot.stderr.text,
truncated: snapshot.diagnosticTruncated === true,
});
@@ -0,0 +1,381 @@
import {
pwntoolsLayoutFailure,
pwntoolsUnavailable,
capturedPwntoolsOutput,
} from "./PwntoolsFailures.js";
import { randomUUID } from "node:crypto";
import { access, stat, writeFile } from "node:fs/promises";
import { constants } from "node:fs";
import { isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import type { BinaryLayoutPort } from "../../application/binaryDiagnostics/BinaryLayoutPort.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
} from "../../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
binaryLayoutPayloadSchema,
binaryLayoutSchema,
type BinaryLayout,
type InspectBinaryLayoutInput,
} from "../../domain/native/binaryLayout.js";
import { runOwnedCommand } from "../../process/OwnedCommand.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
import {
pwntoolsResourceLimitsSchema,
type PwntoolsLimitReport,
type PwntoolsFailureEvidence,
} from "./PwntoolsResourceLimits.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import {
PWNTOOLS_PROVIDER_IDENTITY,
PWNTOOLS_LIMITS,
PWNTOOLS_FILE_SIZE_FAILURE_EXIT,
PWNTOOLS_MEMORY_FAILURE_EXIT,
} from "./PwntoolsRelease.js";
const OPERATION = "inspect_binary_layout";
const decoded = binaryLayoutPayloadSchema;
const replySchema = z.discriminatedUnion("ok", [
z.strictObject({
ok: z.literal(true),
profile: z.literal(PWNTOOLS_PROVIDER_IDENTITY.version),
value: decoded,
}),
z.strictObject({
ok: z.literal(false),
reason: z.enum([
"format",
"unsupported",
"unavailable",
"resource-limit",
"output-limit",
"decoder",
]),
message: z.string(),
reported_limits: pwntoolsResourceLimitsSchema.nullable().optional(),
}),
]);
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
/** Thin owned-process adapter; all ELF parsing and heuristics come from unchanged upstream code. */
export class PwntoolsLayoutProvider implements BinaryLayoutPort {
readonly identity = PWNTOOLS_PROVIDER_IDENTITY;
constructor(
readonly environment: Readonly<NodeJS.ProcessEnv>,
readonly launcher?: Launcher,
readonly createRuntime: () => Promise<
Pick<PrivateRuntimeRoot, "path" | "close">
> = () => PrivateRuntimeRoot.create({ prefix: "rea-elf-layout-" }),
) {}
/** Snapshot one explicit artifact and return complete static observations without launching the selected object as a host process. */
async inspect(
input: InspectBinaryLayoutInput,
options?: ExecutionOptions,
): Promise<Result<BinaryLayout, AnalysisError>> {
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
let result: Result<BinaryLayout, AnalysisError>;
let phase: "configuration" | "artifact-read" | "decoder" = "configuration";
const executablePath = this.environment.REA_PWNTOOLS_PYTHON ?? "";
let selectedPath = executablePath;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
if (process.platform !== "linux" || process.arch !== "x64")
throw new AnalysisCapabilityUnavailableError(
this.identity.id,
OPERATION,
"The real-verified pwntools layout profile currently supports Linux x64 only.",
);
if (!isAbsolute(selectedPath))
throw pwntoolsUnavailable(
"Set REA_PWNTOOLS_PYTHON to an absolute caller-supplied Python executable with pwntools 4.15.0, pyelftools 0.33 and Unicorn 2.1.2; REA never installs Python or packages.",
selectedPath,
);
await access(selectedPath, constants.X_OK);
if (!(await stat(selectedPath)).isFile())
throw pwntoolsUnavailable(
"Selected Python executable must be a regular executable file, not a directory: " +
selectedPath,
selectedPath,
);
phase = "artifact-read";
selectedPath = input.path;
const snapshot = await readStableArtifact(
input.path,
PWNTOOLS_LIMITS.inputBytes,
options?.signal,
);
phase = "decoder";
root = await this.createRuntime();
const requestPath = join(root.path, "request.json");
const snapshotPath = join(root.path, "object.snapshot");
const replyPath = join(root.path, "reply.json");
await writeFile(snapshotPath, snapshot.bytes, {
flag: "wx",
mode: 0o600,
...(options?.signal === undefined ? {} : { signal: options.signal }),
});
await writeFile(
requestPath,
JSON.stringify({ snapshot_path: snapshotPath, reply_path: replyPath }),
{ flag: "wx", mode: 0o600 },
);
const execution = await runOwnedCommand(
{
command: this.environment.REA_PWNTOOLS_PYTHON ?? "",
arguments: [
"-I",
fileURLToPath(
new URL("../../../bridge/pwntools/layout.py", import.meta.url),
),
join(root.path, "resource.failure"),
requestPath,
],
cwd: root.path,
runId: `rea-elf-layout-${randomUUID()}`,
hostEnvironment: {
...this.environment,
PWNLIB_NOTERM: "1",
OPENBLAS_NUM_THREADS: "1",
OMP_NUM_THREADS: "1",
},
},
{
timeoutMs: PWNTOOLS_LIMITS.timeoutMs,
diagnosticBytes: PWNTOOLS_LIMITS.diagnosticBytes,
},
{
...(options?.signal === undefined ? {} : { signal: options.signal }),
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
},
);
const capturedOutput = capturedPwntoolsOutput(execution);
let reply: z.output<typeof replySchema>;
try {
const file = await readStableArtifact(
replyPath,
PWNTOOLS_LIMITS.outputBytes,
options?.signal,
);
reply = replySchema.parse(JSON.parse(file.bytes.toString("utf8")));
} catch (cause: unknown) {
if (options?.signal?.aborted)
throw new AnalysisCancelledError(OPERATION, { capturedOutput });
throw new AnalysisOutputError(
OPERATION,
`Owned ELF decoder reply failed for ${input.path}: ${cause instanceof z.ZodError ? cause.issues[0]?.message + " at " + (cause.issues[0]?.path.map(String).join(".") ?? "root") : cause instanceof Error ? cause.message : String(cause)}`,
{ cause, capturedOutput },
);
}
if (!reply.ok) {
if (reply.reason === "resource-limit")
throw new AnalysisResourceConstraintError(
OPERATION,
"memory",
reply.message,
reply.reported_limits ?? null,
{ capturedOutput },
);
if (reply.reason === "format")
throw new AnalysisInputError(OPERATION, { capturedOutput }, [
{
path: ["path"],
reason: "invalid_format",
message: reply.message,
},
]);
if (reply.reason === "unavailable")
throw pwntoolsUnavailable(
reply.message,
this.environment.REA_PWNTOOLS_PYTHON ?? "",
undefined,
capturedOutput,
);
if (reply.reason === "unsupported")
throw new AnalysisCapabilityUnavailableError(
this.identity.id,
OPERATION,
reply.message,
{ userMessage: reply.message, capturedOutput },
);
if (reply.reason === "output-limit")
throw new AnalysisOutputError(OPERATION, reply.message, {
capturedOutput,
});
throw new ProviderAdapterError(this.identity.id, OPERATION, {
diagnostics: {
phase,
failure_kind: reply.reason,
reason: reply.message,
stdout: execution.stdout.text,
stderr: execution.stderr.text,
captured_output: { ...capturedOutput },
},
});
}
const validated = binaryLayoutSchema.safeParse({
...reply.value,
artifact: {
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
diagnostics: {
stdout: execution.stdout.text,
stderr: execution.stderr.text,
truncated: capturedOutput.truncated,
},
});
if (!validated.success)
throw new AnalysisOutputError(
OPERATION,
`ELF reply contains invalid source ranges or value meanings: ${validated.error.issues[0]?.message ?? "schema mismatch"}`,
{ capturedOutput },
);
for (const table of validated.data.packed_relative_relocations) {
const start = Number(BigInt(table.location.offset));
const length = Number(BigInt(table.location.bytes));
if (
!Buffer.from(table.encoded_bytes_base64, "base64").equals(
snapshot.bytes.subarray(start, start + length),
)
)
throw new AnalysisOutputError(
OPERATION,
"Reported packed relocation bytes differ from the selected snapshot at their original file range.",
{ capturedOutput },
);
}
result = ok(validated.data);
} catch (cause: unknown) {
let limitReport: PwntoolsLimitReport | undefined;
let marker: PwntoolsFailureEvidence["marker"];
if (
cause instanceof OwnedCommandFailure &&
cause.snapshot?.signal === null &&
(cause.snapshot.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT ||
cause.snapshot.exitCode === PWNTOOLS_FILE_SIZE_FAILURE_EXIT) &&
root !== undefined
) {
try {
const reported = await readStableArtifact(
join(root.path, "resource.failure"),
1,
);
const expected =
cause.snapshot.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT
? "M"
: "F";
if (!reported.bytes.equals(Buffer.from(expected, "ascii")))
throw new Error(
"Private bridge failure marker does not match the observed exit status.",
);
marker = {
resource: expected === "M" ? "memory" : "file-size",
failure: null,
};
} catch (markerFailure: unknown) {
marker = {
resource: null,
failure:
markerFailure instanceof Error
? markerFailure.message
: String(markerFailure),
};
}
}
if (
cause instanceof OwnedCommandFailure &&
(cause.snapshot?.signal === "SIGXCPU" ||
cause.snapshot?.signal === "SIGXFSZ" ||
((cause.snapshot?.exitCode === PWNTOOLS_FILE_SIZE_FAILURE_EXIT ||
cause.snapshot?.exitCode === PWNTOOLS_MEMORY_FAILURE_EXIT) &&
cause.snapshot.signal === null)) &&
root !== undefined
) {
try {
const reported = await readStableArtifact(
join(root.path, "limits.json"),
4096,
);
limitReport = {
limits: pwntoolsResourceLimitsSchema.parse(
JSON.parse(reported.bytes.toString("utf8")),
),
failure: null,
};
} catch (reportFailure: unknown) {
limitReport = {
limits: null,
failure:
reportFailure instanceof Error
? reportFailure.message
: String(reportFailure),
};
}
}
result = err(
options?.signal?.aborted &&
(cause === options.signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
? new AnalysisCancelledError(OPERATION)
: pwntoolsLayoutFailure(cause, phase, selectedPath, executablePath, {
...(limitReport === undefined ? {} : { limits: limitReport }),
...(marker === undefined ? {} : { marker }),
}),
);
}
if (root !== undefined) {
try {
await root.close();
} catch (cause: unknown) {
return err(
new ProviderCleanupError(
this.identity.id,
[root.path],
{
reason: cause instanceof Error ? cause.message : String(cause),
previous_error: result.ok
? null
: projectAnalysisError(result.error),
...(result.ok
? {
captured_output: {
stdout: result.value.diagnostics.stdout,
stderr: result.value.diagnostics.stderr,
truncated: result.value.diagnostics.truncated,
},
}
: {}),
},
{ operation: OPERATION },
),
);
}
}
return result.ok && options?.signal?.aborted
? err(
new AnalysisCancelledError(OPERATION, {
capturedOutput: {
stdout: result.value.diagnostics.stdout,
stderr: result.value.diagnostics.stderr,
truncated: result.value.diagnostics.truncated,
},
}),
)
: result;
}
}
+19
View File
@@ -0,0 +1,19 @@
/** Verified unchanged upstream profile for the Linux ELF adapter. */
export const PWNTOOLS_PROVIDER_IDENTITY = {
id: "pwntools-elf",
name: "REA pwntools ELF adapter",
version: "pwntools@4.15.0;pyelftools@0.33;unicorn@2.1.2",
} as const;
/** Bridge-reserved status for MemoryError when no structured reply can be written. */
export const PWNTOOLS_MEMORY_FAILURE_EXIT = 75;
/** Bridge-reserved status for an observed EFBIG failure without a complete reply. */
export const PWNTOOLS_FILE_SIZE_FAILURE_EXIT = 76;
/** Complete evidence budgets; address-space is separate from resident memory. */
export const PWNTOOLS_LIMITS = {
inputBytes: 32 * 1024 * 1024,
outputBytes: 64 * 1024 * 1024,
diagnosticBytes: 1024 * 1024,
timeoutMs: 30_000,
addressSpaceBytes: 3 * 1024 * 1024 * 1024,
cpuSeconds: 30,
} as const;
@@ -0,0 +1,32 @@
import { z } from "zod";
import { PWNTOOLS_LIMITS } from "./PwntoolsRelease.js";
/** Actual limits reported by the owned bridge after lowering inherited soft limits. */
export const pwntoolsResourceLimitsSchema = z.strictObject({
address_space_bytes: z
.number()
.int()
.nonnegative()
.max(PWNTOOLS_LIMITS.addressSpaceBytes),
cpu_seconds: z.number().int().nonnegative().max(PWNTOOLS_LIMITS.cpuSeconds),
file_size_bytes: z
.number()
.int()
.nonnegative()
.max(PWNTOOLS_LIMITS.outputBytes),
});
/** A missing or invalid report leaves limits unknown and retains its read failure. */
export interface PwntoolsLimitReport {
readonly limits: z.output<typeof pwntoolsResourceLimitsSchema> | null;
readonly failure: string | null;
}
/** Private failure-branch evidence; a bare launcher exit code is insufficient. */
export interface PwntoolsFailureEvidence {
readonly limits?: PwntoolsLimitReport;
readonly marker?: {
readonly resource: "memory" | "file-size" | null;
readonly failure: string | null;
};
}
+15
View File
@@ -1,3 +1,6 @@
import { registerBinaryDiagnosticsTools } from "./registerBinaryDiagnosticsTools.js";
import { createBinaryLayoutService } from "../composition/binaryDiagnostics.js";
import type { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
import { McpServer } from "@modelcontextprotocol/server";
import { isAbsolute } from "node:path";
@@ -60,6 +63,7 @@ const ACTIVE_TARGET_INSTRUCTIONS =
export interface CreateServerOptions {
readonly logger?: Logger;
readonly binaryLayout?: BinaryLayoutService;
readonly firmwareAnalysis?: FirmwareAnalysisPort;
readonly javascriptRecovery?: JavaScriptRecoveryPort;
readonly webModuleTrace?: WebModuleTraceService;
@@ -88,6 +92,11 @@ const installSessionToolAvailability = (
webModuleResolutionEnabled:
options.webModuleTrace !== undefined ||
isAbsolute(process.env.REA_BROWSER_EXECUTABLE ?? ""),
binaryLayoutEnabled:
options.binaryLayout !== undefined ||
(process.platform === "linux" &&
process.arch === "x64" &&
isAbsolute(process.env.REA_PWNTOOLS_PYTHON ?? "")),
firmwareInspectionEnabled:
options.firmwareAnalysis !== undefined ||
(process.platform === "linux" &&
@@ -190,6 +199,12 @@ export const createServer = (
toolLogger,
recordEvidence,
);
registerBinaryDiagnosticsTools(
server,
options.binaryLayout ?? createBinaryLayoutService(),
toolLogger,
recordEvidence,
);
registerFirmwareTools(
server,
new FirmwareAnalysisService(
@@ -0,0 +1,32 @@
import type { McpServer } from "@modelcontextprotocol/server";
import type { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "../logger.js";
import { logToolExecution } from "./toolLogging.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { toCallToolResult } from "./toolResult.js";
/** Bind offline layout inspection to its named contract and session Evidence owner. */
export const registerBinaryDiagnosticsTools = (
server: McpServer,
service: BinaryLayoutService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
): void => {
const contract = toolContract("inspect_binary_layout");
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 toCallToolResult(result, contract);
const recorded = recordEvidence?.(result.value);
return recorded !== undefined && !recorded.ok
? toCallToolResult(recorded, contract)
: toCallToolResult(result, contract);
},
);
};
+3
View File
@@ -18,6 +18,7 @@ export interface SessionAvailabilityDefaults {
| "androidAnalysisEnabled"
| "javascriptRecoveryEnabled"
| "webModuleResolutionEnabled"
| "binaryLayoutEnabled"
| "firmwareInspectionEnabled"
| "firmwareExtractionEnabled"
>;
@@ -32,6 +33,8 @@ export const sessionAvailabilityPolicy = (
configured ??
(() => ({
processCaptureEnabled: platform !== "win32",
binaryLayoutEnabled:
defaults.optionalFeatures?.binaryLayoutEnabled ?? false,
firmwareInspectionEnabled:
defaults.optionalFeatures?.firmwareInspectionEnabled ?? false,
firmwareExtractionEnabled:
+1 -1
View File
@@ -9,7 +9,7 @@ import type { Result } from "../domain/result.js";
/**
* Serialize an application result as MCP text and structured content.
* Shared error projection preserves actionable local diagnostics while omitting
* raw causes and captured process output.
* raw cause objects; explicitly retained bounded command output stays visible.
*/
export const toCallToolResult = (
result: Result<JsonValue, AnalysisError>,