chore: merge main into feat/signature-posture

This commit is contained in:
morluto
2026-10-08 16:59:55 +08:00
85 changed files with 5854 additions and 1121 deletions
+232
View File
@@ -0,0 +1,232 @@
import { access, mkdir, stat, writeFile } from "node:fs/promises";
import { constants } from "node:fs";
import { randomUUID } from "node:crypto";
import { isAbsolute, join } from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import type { AnalysisCapturedOutput } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import {
recordedCrashDebuggerSchema,
type RecordedCrash,
} from "../../domain/native/recordedCrash.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import { runOwnedCommand } from "../../process/OwnedCommand.js";
import {
capturedPwntoolsOutput,
pwntoolsDecoderFailure,
} from "../pwntools/PwntoolsFailures.js";
import { PWNTOOLS_LIMITS } from "../pwntools/PwntoolsRelease.js";
import { readPwntoolsFailureEvidence } from "../pwntools/PwntoolsResourceLimits.js";
import type { PwntoolsLauncher } from "../pwntools/PwntoolsDecoder.js";
const OPERATION = "inspect_recorded_crash";
const replySchema = z.discriminatedUnion("ok", [
z.strictObject({ ok: z.literal(true), value: recordedCrashDebuggerSchema }),
z.strictObject({
ok: z.literal(false),
reason: z.enum([
"unavailable",
"unsupported",
"decoder",
"format",
"output-limit",
]),
message: z.string(),
}),
]);
/** Add mapping candidates from an owned core-only debugger, using the existing snapshot. */
export const inspectPwndbgCore = async ({
environment,
rootPath,
diagnostics,
options,
launcher,
}: {
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly rootPath: string;
readonly diagnostics: AnalysisCapturedOutput;
readonly options: ExecutionOptions | undefined;
readonly launcher?: PwntoolsLauncher;
}): Promise<RecordedCrash["debugger"]> => {
const gdb = environment.REA_PWNDBG_GDB ?? "/usr/bin/gdb";
const entry = environment.REA_PWNDBG_GDBINIT ?? "";
const venv = environment.REA_PWNDBG_VENV_PATH ?? "";
const unavailable = (message: string, cause?: unknown) =>
new AnalysisCapabilityUnavailableError("pwndbg-core", OPERATION, message, {
...(cause === undefined ? {} : { cause }),
userMessage: message,
capturedOutput: diagnostics,
});
for (const [key, path, kind] of [
["REA_PWNDBG_GDB", gdb, "file"],
["REA_PWNDBG_GDBINIT", entry, "file"],
["REA_PWNDBG_VENV_PATH", venv, "directory"],
] as const) {
try {
if (!isAbsolute(path))
throw new Error("Expected an absolute caller-supplied path.");
await access(
path,
key === "REA_PWNDBG_GDB" ? constants.X_OK : constants.R_OK,
);
const information = await stat(path);
if (kind === "file" ? !information.isFile() : !information.isDirectory())
throw new Error(`Expected a ${kind}.`);
} catch (cause: unknown) {
throw unavailable(
`${key} is unavailable at ${path}: ${cause instanceof Error ? cause.message : String(cause)}. Configure the requested core-only context, or omit include_debugger_context for basic recorded evidence.`,
cause,
);
}
}
const stage = join(rootPath, "debugger");
await mkdir(stage, { mode: 0o700 });
const requestPath = join(stage, "request.json");
const replyPath = join(stage, "reply.json");
await writeFile(
requestPath,
JSON.stringify({
snapshot_path: join(rootPath, "object.snapshot"),
reply_path: replyPath,
gdb,
gdbinit: entry,
venv,
}),
{ flag: "wx", mode: 0o600 },
);
let output: AnalysisCapturedOutput | undefined;
try {
options?.signal?.throwIfAborted();
const execution = await runOwnedCommand(
{
command: environment.REA_PWNTOOLS_PYTHON ?? "",
arguments: [
"-I",
fileURLToPath(
new URL("../../../bridge/pwndbg/launch.py", import.meta.url),
),
join(stage, "resource.failure"),
requestPath,
],
cwd: stage,
runId: `rea-recorded-core-debugger-${randomUUID()}`,
hostEnvironment: {
...environment,
PWNDBG_NO_AUTOUPDATE: "1",
PWNDBG_VENV_PATH: venv,
PWNLIB_NOTERM: "1",
TERM: "dumb",
HOME: stage,
XDG_CACHE_HOME: join(stage, "cache"),
XDG_CONFIG_HOME: join(stage, "config"),
PYTHONNOUSERSITE: "1",
OPENBLAS_NUM_THREADS: "1",
OMP_NUM_THREADS: "1",
},
},
{
timeoutMs: PWNTOOLS_LIMITS.timeoutMs,
diagnosticBytes: PWNTOOLS_LIMITS.diagnosticBytes,
},
{
...(options?.signal === undefined ? {} : { signal: options.signal }),
...(launcher === undefined ? {} : { launcher }),
},
);
output = capturedPwntoolsOutput(execution);
let reply: z.output<typeof replySchema>;
try {
const raw = await readStableArtifact(
replyPath,
PWNTOOLS_LIMITS.outputBytes,
options?.signal,
);
reply = replySchema.parse(JSON.parse(raw.bytes.toString("utf8")));
} catch (cause: unknown) {
if (options?.signal?.aborted)
throw new AnalysisCancelledError(OPERATION, {
capturedOutput: recordedCrashStageOutput(diagnostics, output),
});
throw new AnalysisOutputError(
OPERATION,
`Core-only debugger reply failed: ${cause instanceof Error ? cause.message : String(cause)}`,
{
cause,
capturedOutput: recordedCrashStageOutput(diagnostics, output),
},
);
}
if (!reply.ok) {
if (reply.reason === "unavailable" || reply.reason === "unsupported")
throw new AnalysisCapabilityUnavailableError(
"pwndbg-core",
OPERATION,
reply.message,
{
userMessage: reply.message,
capturedOutput: recordedCrashStageOutput(diagnostics, output),
},
);
if (reply.reason === "format" || reply.reason === "output-limit")
throw new AnalysisOutputError(OPERATION, reply.message, {
capturedOutput: recordedCrashStageOutput(diagnostics, output),
});
throw new ProviderAdapterError("pwndbg-core", OPERATION, {
diagnostics: {
stage: "debugger",
reason: reply.message,
captured_output: { ...recordedCrashStageOutput(diagnostics, output) },
},
});
}
if (reply.value.status !== "available")
throw new AnalysisOutputError(
OPERATION,
"Requested debugger context returned no core evidence.",
{ capturedOutput: recordedCrashStageOutput(diagnostics, output) },
);
return { ...reply.value, diagnostics: output };
} catch (cause: unknown) {
if (
options?.signal?.aborted &&
(cause === options.signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
)
throw new AnalysisCancelledError(OPERATION, {
capturedOutput: recordedCrashStageOutput(diagnostics, output),
});
throw pwntoolsDecoderFailure(
cause,
"debugger",
gdb,
environment.REA_PWNTOOLS_PYTHON ?? "",
await readPwntoolsFailureEvidence(cause, stage),
{
operation: OPERATION,
providerId: "pwndbg-core",
precedingOutput: diagnostics,
},
);
}
};
/** Preserve both stages' exact text and their independently observed truncation state. */
export const recordedCrashStageOutput = (
basic: AnalysisCapturedOutput,
debuggerOutput?: AnalysisCapturedOutput,
): AnalysisCapturedOutput =>
debuggerOutput === undefined
? basic
: {
stdout: `[core decoder]\n${basic.stdout}\n[debugger]\n${debuggerOutput.stdout}`,
stderr: `[core decoder]\n${basic.stderr}\n[debugger]\n${debuggerOutput.stderr}`,
truncated: basic.truncated || debuggerOutput.truncated,
};
+333
View File
@@ -0,0 +1,333 @@
import {
pwntoolsDecoderFailure,
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 { ProviderIdentity } from "../../application/AnalysisProvider.js";
import type { AnalysisCapturedOutput } from "../../domain/analysisErrorBase.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisUnsupportedTargetError,
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 { runOwnedCommand } from "../../process/OwnedCommand.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
import {
pwntoolsResourceLimitsSchema,
readPwntoolsFailureEvidence,
} from "./PwntoolsResourceLimits.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import {
PWNTOOLS_PROVIDER_IDENTITY,
PWNTOOLS_LIMITS,
} from "./PwntoolsRelease.js";
/** Owned launcher seam shared by the offline pwntools artifact adapters. */
export type PwntoolsLauncher = NonNullable<
Parameters<typeof runOwnedCommand>[2]
>["launcher"];
interface DecoderReport {
readonly diagnostics: AnalysisCapturedOutput;
}
/** Adapter-selected semantics around a shared owned pwntools process boundary. */
export interface PwntoolsDecoderProfile<
Input extends { readonly path: string },
Payload,
Report extends DecoderReport,
> {
readonly identity: ProviderIdentity;
readonly operation: string;
readonly bridge: URL;
readonly payloadSchema: z.ZodType<Payload>;
readonly project: (context: {
readonly input: Input;
readonly payload: Payload;
readonly snapshot: { readonly bytes: Buffer; readonly sha256: string };
readonly rootPath: string;
readonly diagnostics: AnalysisCapturedOutput;
readonly options: ExecutionOptions | undefined;
}) => Report | Promise<Report>;
}
/** Thin owned-process adapter; all ELF parsing and heuristics come from unchanged upstream code. */
export class PwntoolsDecoder<
Input extends { readonly path: string },
Payload,
Report extends DecoderReport,
> {
readonly identity: ProviderIdentity;
constructor(
readonly profile: PwntoolsDecoderProfile<Input, Payload, Report>,
readonly environment: Readonly<NodeJS.ProcessEnv>,
readonly launcher?: PwntoolsLauncher,
readonly createRuntime: () => Promise<
Pick<PrivateRuntimeRoot, "path" | "close">
> = () => PrivateRuntimeRoot.create({ prefix: "rea-artifact-decoder-" }),
) {
this.identity = profile.identity;
}
/** Snapshot one explicit artifact and return complete static observations without launching the selected object as a host process. */
async inspect(
input: Input,
options?: ExecutionOptions,
): Promise<Result<Report, AnalysisError>> {
const OPERATION = this.profile.operation;
const context = { operation: OPERATION, providerId: this.identity.id };
const replySchema = z.discriminatedUnion("ok", [
z.strictObject({
ok: z.literal(true),
profile: z.literal(PWNTOOLS_PROVIDER_IDENTITY.version),
value: this.profile.payloadSchema,
}),
z.strictObject({
ok: z.literal(false),
reason: z.enum([
"format",
"unsupported",
"unsupported-target",
"unavailable",
"resource-limit",
"output-limit",
"decoder",
]),
message: z.string(),
reported_limits: pwntoolsResourceLimitsSchema.nullable().optional(),
}),
]);
let root: Pick<PrivateRuntimeRoot, "path" | "close"> | undefined;
let result: Result<Report, 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 initial real-verified pwntools artifact profile 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,
undefined,
undefined,
context,
);
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,
undefined,
undefined,
context,
);
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(this.profile.bridge),
join(root.path, "resource.failure"),
requestPath,
],
cwd: root.path,
runId: `rea-artifact-decoder-${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 pwntools 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 === "unsupported-target")
throw new AnalysisUnsupportedTargetError(
OPERATION,
input.path,
reply.message,
{ capturedOutput },
);
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,
context,
);
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 },
},
});
}
result = ok(
await this.profile.project({
input,
payload: reply.value,
snapshot,
rootPath: root.path,
diagnostics: capturedOutput,
options,
}),
);
} catch (cause: unknown) {
const evidence = await readPwntoolsFailureEvidence(cause, root?.path);
result = err(
options?.signal?.aborted &&
(cause === options.signal.reason ||
(cause instanceof Error && cause.name === "AbortError"))
? new AnalysisCancelledError(OPERATION)
: pwntoolsDecoderFailure(
cause,
phase,
selectedPath,
executablePath,
evidence,
context,
),
);
}
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;
}
}
+75 -28
View File
@@ -25,33 +25,58 @@ import {
PWNTOOLS_FILE_SIZE_FAILURE_EXIT,
} from "./PwntoolsRelease.js";
const OPERATION = "inspect_binary_layout";
/** Operation identity supplied by each adapter sharing the pwntools boundary. */
export interface PwntoolsFailureContext {
readonly operation: string;
readonly providerId: string;
readonly precedingOutput?: AnalysisCapturedOutput;
}
const DEFAULT_CONTEXT = {
operation: "inspect_binary_layout",
providerId: PWNTOOLS_PROVIDER_IDENTITY.id,
};
/** Keep read, engine, output and owned-lifecycle failure reasons distinct. */
export const pwntoolsLayoutFailure = (
export const pwntoolsDecoderFailure = (
cause: unknown,
phase: string,
path: string,
executablePath = path,
failureEvidence: PwntoolsFailureEvidence = {},
context: PwntoolsFailureContext = DEFAULT_CONTEXT,
): AnalysisError => {
const limitReport = failureEvidence.limits;
if (cause instanceof AnalysisError) return cause;
if (cause instanceof OwnedCommandFailure) {
const outputOptions =
const currentOutput =
cause.snapshot === null
? undefined
: { capturedOutput: capturedPwntoolsOutput(cause.snapshot) };
: capturedPwntoolsOutput(cause.snapshot);
const combinedOutput =
context.precedingOutput === undefined
? currentOutput
: currentOutput === undefined
? context.precedingOutput
: {
stdout: `[core decoder]\n${context.precedingOutput.stdout}\n[debugger]\n${currentOutput.stdout}`,
stderr: `[core decoder]\n${context.precedingOutput.stderr}\n[debugger]\n${currentOutput.stderr}`,
truncated:
context.precedingOutput.truncated || currentOutput.truncated,
};
const outputOptions =
combinedOutput === undefined
? undefined
: { capturedOutput: combinedOutput };
if (cause.cleanupFailure !== null)
return new ProviderCleanupError(
PWNTOOLS_PROVIDER_IDENTITY.id,
context.providerId,
cause.resources,
{
reason: cause.cleanupFailure,
...(cause.snapshot === null
...(combinedOutput === undefined
? {}
: {
captured_output: { ...capturedPwntoolsOutput(cause.snapshot) },
captured_output: { ...combinedOutput },
}),
previous_error: {
failure_kind: cause.reason,
@@ -62,18 +87,22 @@ export const pwntoolsLayoutFailure = (
stderr: cause.snapshot?.stderr.text ?? null,
},
},
{ operation: OPERATION, cause },
{ operation: context.operation, cause },
);
if (cause.reason === "cancelled")
return new AnalysisCancelledError(OPERATION, outputOptions);
return new AnalysisCancelledError(context.operation, outputOptions);
if (cause.reason === "timeout")
return new AnalysisTimeoutError(
OPERATION,
context.operation,
PWNTOOLS_LIMITS.timeoutMs,
outputOptions,
);
if (cause.reason === "output-limit")
return new AnalysisOutputError(OPERATION, cause.message, outputOptions);
return new AnalysisOutputError(
context.operation,
cause.message,
outputOptions,
);
if (
cause.reason === "process" &&
(cause.snapshot?.signal === "SIGXFSZ" ||
@@ -82,7 +111,7 @@ export const pwntoolsLayoutFailure = (
cause.snapshot.signal === null))
)
return new AnalysisResourceConstraintError(
OPERATION,
context.operation,
"file-size",
(cause.snapshot.signal === "SIGXFSZ"
? "Owned Python terminated with SIGXFSZ; the exact signal cause is unknown."
@@ -95,7 +124,7 @@ export const pwntoolsLayoutFailure = (
);
if (cause.reason === "process" && cause.snapshot?.signal === "SIGXCPU")
return new AnalysisResourceConstraintError(
OPERATION,
context.operation,
"cpu",
"Owned Python terminated with SIGXCPU; the exact signal cause is unknown." +
(limitReport?.failure === null || limitReport === undefined
@@ -111,7 +140,7 @@ export const pwntoolsLayoutFailure = (
cause.snapshot.signal === null
)
return new AnalysisResourceConstraintError(
OPERATION,
context.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
@@ -132,20 +161,27 @@ export const pwntoolsLayoutFailure = (
`Selected Python could not launch (${String(cause.code)}): ${executablePath}. Check the configured executable, its interpreter and host execute access.`,
executablePath,
String(cause.code),
undefined,
context,
);
if (cause instanceof ArtifactReaderFailure) {
if (cause.reason === "integrity")
return new AnalysisArtifactChangedError(OPERATION, path, cause.message, {
cause,
});
return new AnalysisArtifactChangedError(
context.operation,
path,
cause.message,
{
cause,
},
);
if (cause.reason === "cancelled")
return new AnalysisCancelledError(OPERATION);
return new AnalysisCancelledError(context.operation);
if (
cause.reason === "limit" ||
cause.reason === "path" ||
cause.reason === "format"
)
return new AnalysisInputError(OPERATION, { cause }, [
return new AnalysisInputError(context.operation, { cause }, [
{
path: ["path"],
reason: cause.reason === "limit" ? "out_of_range" : "invalid_format",
@@ -159,19 +195,26 @@ export const pwntoolsLayoutFailure = (
`Selected Python executable is unavailable (${String(cause.code)}): ${path}. Check the caller-selected path and execute access.`,
path,
String(cause.code),
undefined,
context,
);
if (
phase === "artifact-read" &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
cause,
});
return new AnalysisAccessDeniedError(
context.operation,
path,
cause.code,
{
cause,
},
);
if (
phase === "artifact-read" &&
(cause.code === "ENOENT" || cause.code === "ENOTDIR")
)
return new AnalysisInputError(OPERATION, { cause }, [
return new AnalysisInputError(context.operation, { cause }, [
{
path: ["path"],
reason: "invalid_value",
@@ -179,11 +222,14 @@ export const pwntoolsLayoutFailure = (
},
]);
}
return new ProviderAdapterError(PWNTOOLS_PROVIDER_IDENTITY.id, OPERATION, {
return new ProviderAdapterError(context.providerId, context.operation, {
cause,
diagnostics: {
phase,
path,
...(context.precedingOutput === undefined
? {}
: { preceding_output: { ...context.precedingOutput } }),
reason: cause instanceof Error ? cause.message : String(cause),
...(failureEvidence.marker === undefined
? {}
@@ -214,16 +260,17 @@ export const pwntoolsUnavailable = (
path: string,
systemCode?: string,
capturedOutput?: AnalysisCapturedOutput,
context: PwntoolsFailureContext = DEFAULT_CONTEXT,
): ProviderSelectionError =>
new ProviderSelectionError({
...(capturedOutput === undefined ? {} : { capturedOutput }),
operation: OPERATION,
operation: context.operation,
reason: "provider_unavailable",
requestedProviderId: PWNTOOLS_PROVIDER_IDENTITY.id,
candidateIds: [PWNTOOLS_PROVIDER_IDENTITY.id],
requestedProviderId: context.providerId,
candidateIds: [context.providerId],
rejections: [
{
providerId: PWNTOOLS_PROVIDER_IDENTITY.id,
providerId: context.providerId,
code: "provider_unavailable",
reason,
diagnostics: {
+58 -365
View File
@@ -1,381 +1,74 @@
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 { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { PwntoolsDecoder, type PwntoolsLauncher } from "./PwntoolsDecoder.js";
import { PWNTOOLS_PROVIDER_IDENTITY } from "./PwntoolsRelease.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";
import type { BinaryLayoutPort } from "../../application/binaryDiagnostics/BinaryLayoutPort.js";
import type { z } from "zod";
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;
/** ELF-specific projection around the shared owned pwntools decoder boundary. */
export class PwntoolsLayoutProvider
extends PwntoolsDecoder<
InspectBinaryLayoutInput,
z.output<typeof binaryLayoutPayloadSchema>,
BinaryLayout
>
implements BinaryLayoutPort
{
constructor(
readonly environment: Readonly<NodeJS.ProcessEnv>,
readonly launcher?: Launcher,
readonly createRuntime: () => Promise<
environment: Readonly<NodeJS.ProcessEnv>,
launcher?: PwntoolsLauncher,
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,
) {
super(
{
identity: PWNTOOLS_PROVIDER_IDENTITY,
operation: "inspect_binary_layout",
bridge: new URL("../../../bridge/pwntools/layout.py", import.meta.url),
payloadSchema: binaryLayoutPayloadSchema,
project: ({ input, payload, snapshot, diagnostics }) => {
const value = binaryLayoutSchema.safeParse({
...payload,
artifact: {
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
]);
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,
diagnostics,
});
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.",
if (!value.success)
throw new AnalysisOutputError(
"inspect_binary_layout",
`ELF reply contains invalid source ranges or value meanings: ${value.error.issues[0]?.message ?? "schema mismatch"}`,
{ capturedOutput: diagnostics },
);
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;
for (const table of value.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(
"inspect_binary_layout",
"Reported packed relocation bytes differ from the selected snapshot at their original file range.",
{ capturedOutput: diagnostics },
);
}
return value.data;
},
},
environment,
launcher,
createRuntime,
);
}
}
@@ -0,0 +1,144 @@
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import {
recordedCrashPayloadSchema,
recordedCrashSchema,
type InspectRecordedCrashInput,
type RecordedCrash,
} from "../../domain/native/recordedCrash.js";
import type { RecordedCrashPort } from "../../application/binaryDiagnostics/RecordedCrashPort.js";
import { PrivateRuntimeRoot } from "../../process/PrivateRuntimeRoot.js";
import { PwntoolsDecoder, type PwntoolsLauncher } from "./PwntoolsDecoder.js";
import { PWNTOOLS_PROVIDER_IDENTITY } from "./PwntoolsRelease.js";
import { validateRecordedCrashSources } from "./RecordedCrashSourceBindings.js";
import { validateRecordedCrashStructure } from "./RecordedCrashStructureBindings.js";
import {
inspectPwndbgCore,
recordedCrashStageOutput,
} from "../pwndbg/PwndbgCoreContext.js";
import type { z } from "zod";
/** Preserve every recorded thread while optionally enriching the same owned snapshot. */
export class PwntoolsRecordedCrashProvider
extends PwntoolsDecoder<
InspectRecordedCrashInput,
z.output<typeof recordedCrashPayloadSchema>,
RecordedCrash
>
implements RecordedCrashPort
{
constructor(
environment: Readonly<NodeJS.ProcessEnv>,
launcher?: PwntoolsLauncher,
createRuntime: () => Promise<
Pick<PrivateRuntimeRoot, "path" | "close">
> = () => PrivateRuntimeRoot.create({ prefix: "rea-recorded-crash-" }),
) {
super(
{
identity: PWNTOOLS_PROVIDER_IDENTITY,
operation: "inspect_recorded_crash",
bridge: new URL(
"../../../bridge/pwntools/recorded_crash.py",
import.meta.url,
),
payloadSchema: recordedCrashPayloadSchema,
project: async ({
input,
payload,
snapshot,
rootPath,
diagnostics,
options,
}) => {
const validate = (debuggerContext: RecordedCrash["debugger"]) =>
recordedCrashSchema.safeParse({
...payload,
artifact: {
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
debugger: debuggerContext,
decoder_diagnostics: diagnostics,
diagnostics:
debuggerContext.status === "available"
? recordedCrashStageOutput(
diagnostics,
debuggerContext.diagnostics,
)
: diagnostics,
});
const checked = validate({ status: "not-requested" });
if (!checked.success)
throw new AnalysisOutputError(
"inspect_recorded_crash",
`Recorded core reply is invalid: ${checked.error.issues[0]?.message ?? "schema mismatch"}`,
{ capturedOutput: diagnostics },
);
const value = checked.data;
validateRecordedCrashStructure(value, snapshot.bytes, diagnostics);
const checkBytes = (
raw: string,
range: { readonly offset: string; readonly bytes: string },
) => {
const start = Number(BigInt(range.offset));
const length = Number(BigInt(range.bytes));
if (
!Buffer.from(raw, "base64").equals(
snapshot.bytes.subarray(start, start + length),
)
)
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported raw note bytes differ from the selected snapshot.",
{ capturedOutput: diagnostics },
);
};
for (const note of value.notes) {
checkBytes(note.owner_bytes_base64, note.owner_location);
checkBytes(note.descriptor_bytes_base64, note.descriptor_location);
}
for (const padding of value.note_padding)
checkBytes(padding.bytes_base64, padding.location);
validateRecordedCrashSources(value, snapshot.bytes, diagnostics);
for (const thread of value.threads)
for (const register of thread.registers) {
const start = Number(BigInt(register.location.offset));
if (
snapshot.bytes.readBigUInt64LE(start) !== BigInt(register.value)
)
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported register value differs from its recorded source bytes.",
{ capturedOutput: diagnostics },
);
}
if (!input.include_debugger_context) return value;
const context = await inspectPwndbgCore({
environment,
rootPath,
diagnostics,
options,
...(launcher === undefined ? {} : { launcher }),
});
const enriched = validate(context);
if (!enriched.success)
throw new AnalysisOutputError(
"inspect_recorded_crash",
`Recorded debugger context is invalid: ${enriched.error.issues[0]?.message ?? "schema mismatch"}`,
{
capturedOutput:
context.status === "available"
? recordedCrashStageOutput(diagnostics, context.diagnostics)
: diagnostics,
},
);
return enriched.data;
},
},
environment,
launcher,
createRuntime,
);
}
}
@@ -1,3 +1,10 @@
import { join } from "node:path";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import { OwnedCommandFailure } from "../../process/OwnedCommand.js";
import {
PWNTOOLS_MEMORY_FAILURE_EXIT,
PWNTOOLS_FILE_SIZE_FAILURE_EXIT,
} from "./PwntoolsRelease.js";
import { z } from "zod";
import { PWNTOOLS_LIMITS } from "./PwntoolsRelease.js";
@@ -30,3 +37,78 @@ export interface PwntoolsFailureEvidence {
readonly failure: string | null;
};
}
/** Read only bounded owned reports; unverified reserved statuses stay unclassified. */
export const readPwntoolsFailureEvidence = async (
cause: unknown,
rootPath?: string,
): Promise<PwntoolsFailureEvidence> => {
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) &&
rootPath !== undefined
) {
try {
const reported = await readStableArtifact(
join(rootPath, "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)) &&
rootPath !== undefined
) {
try {
const reported = await readStableArtifact(
join(rootPath, "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),
};
}
}
return {
...(limitReport === undefined ? {} : { limits: limitReport }),
...(marker === undefined ? {} : { marker }),
};
};
@@ -0,0 +1,68 @@
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import {
RECORDED_LINUX_AMD64_REGISTERS,
type RecordedCrash,
} from "../../domain/native/recordedCrash.js";
const registerOffsets = new Map<string, number>(
RECORDED_LINUX_AMD64_REGISTERS.map((name, index) => [name, 112 + index * 8]),
);
/** Bind interpreted values and register identities to Linux amd64 source bytes. */
export function validateRecordedCrashSources(
report: RecordedCrash,
snapshot: Buffer,
diagnostics: RecordedCrash["decoder_diagnostics"],
): void {
const fail = () => {
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported PID or signal value differs from its recorded Linux amd64 source bytes.",
{ capturedOutput: diagnostics },
);
};
const descriptor = (noteIndex: number, minimumBytes: number): Buffer => {
const note = report.notes[noteIndex];
if (note === undefined) return fail();
const start = Number(BigInt(note.descriptor_location.offset));
const length = Number(BigInt(note.descriptor_location.bytes));
if (length < minimumBytes) return fail();
return snapshot.subarray(start, start + length);
};
// Fixed offsets independently checked against unchanged pwntools 4.15.0
// elf_prstatus_amd64 / elf_siginfo_64; this is the sole supported note ABI.
for (const thread of report.threads) {
const bytes = descriptor(thread.note_index, 336);
if (
thread.historical_pid !== bytes.readInt32LE(32) ||
thread.recorded_current_signal !== bytes.readInt16LE(12)
)
fail();
const note = report.notes[thread.note_index];
if (note === undefined) return fail();
for (const register of thread.registers) {
const offset = registerOffsets.get(register.name);
if (
offset === undefined ||
BigInt(register.location.offset) !==
BigInt(note.descriptor_location.offset) + BigInt(offset)
)
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported register source does not match its Linux amd64 register identity.",
{ capturedOutput: diagnostics },
);
}
}
for (const signal of report.signals) {
const bytes = descriptor(signal.note_index, 32);
if (
signal.number !== bytes.readInt32LE(0) ||
signal.errno !== bytes.readInt32LE(4) ||
signal.code !== bytes.readInt32LE(8) ||
(signal.fault_address !== null &&
BigInt(signal.fault_address) !== bytes.readBigUInt64LE(16))
)
fail();
}
}
@@ -0,0 +1,133 @@
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import type { RecordedCrash } from "../../domain/native/recordedCrash.js";
// Exact amd64/core enum projections in the pinned pyelftools 0.33 profile.
const segmentKinds = new Map([
[0, "PT_NULL"],
[1, "PT_LOAD"],
[2, "PT_DYNAMIC"],
[3, "PT_INTERP"],
[4, "PT_NOTE"],
[5, "PT_SHLIB"],
[6, "PT_PHDR"],
[7, "PT_TLS"],
[0x60000000, "PT_LOOS"],
[0x6fffffff, "PT_HIOS"],
[0x6474e550, "PT_GNU_EH_FRAME"],
[0x6474e551, "PT_GNU_STACK"],
[0x6474e552, "PT_GNU_RELRO"],
[0x6474e553, "PT_GNU_PROPERTY"],
]);
const noteKinds = new Map([
[1, "NT_PRSTATUS"],
[2, "NT_FPREGSET"],
[3, "NT_PRPSINFO"],
[4, "NT_TASKSTRUCT"],
[6, "NT_AUXV"],
[0x53494749, "NT_SIGINFO"],
[0x46494c45, "NT_FILE"],
]);
const matchesKind = (
raw: number,
reported: string | number,
kinds: ReadonlyMap<number, string>,
): boolean => {
const known = kinds.get(raw);
return typeof reported === "string"
? reported === known
: known === undefined && reported === raw;
};
const segmentMatches = (
segment: RecordedCrash["segments"][number],
raw: Buffer,
): boolean => {
const type = raw.readUInt32LE(0);
return (
matchesKind(type, segment.type, segmentKinds) &&
BigInt(segment.flags) === BigInt(raw.readUInt32LE(4)) &&
segment.file_backing ===
(type === 0 || raw.readBigUInt64LE(32) === 0n ? "none" : "file") &&
(
[
[segment.offset, 8],
[segment.virtual_address, 16],
[segment.physical_address, 24],
[segment.file_size, 32],
[segment.memory_size, 40],
[segment.alignment, 48],
] as const
).every(
([field, relative]) => BigInt(field) === raw.readBigUInt64LE(relative),
)
);
};
/** Bind coverage-bearing ELF and note headers to the same snapshot as their payloads. */
export function validateRecordedCrashStructure(
report: RecordedCrash,
snapshot: Buffer,
diagnostics: RecordedCrash["decoder_diagnostics"],
): void {
const fail = () => {
throw new AnalysisOutputError(
"inspect_recorded_crash",
"Reported core structure differs from its original ELF/note headers.",
{ capturedOutput: diagnostics },
);
};
const bytesAt = (offset: bigint, bytes: number): Buffer => {
if (offset < 0n || offset > BigInt(snapshot.length - bytes)) return fail();
return snapshot.subarray(Number(offset), Number(offset) + bytes);
};
const header = bytesAt(0n, 64);
if (
!header
.subarray(0, 6)
.equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2, 1])) ||
![0, 3].includes(header[7] ?? -1) ||
header[8] !== 0 ||
header.readUInt16LE(16) !== 4 ||
header.readUInt16LE(18) !== 62
)
fail();
const table = header.readBigUInt64LE(32);
const entryBytes = header.readUInt16LE(54);
let count = header.readUInt16LE(56);
if (count === 0xffff) {
if (header.readUInt16LE(58) < 64) return fail();
count = bytesAt(header.readBigUInt64LE(40), 64).readUInt32LE(44);
}
if (count !== report.segments.length || (count > 0 && entryBytes < 56))
fail();
for (const segment of report.segments) {
const offset = table + BigInt(segment.index) * BigInt(entryBytes);
if (
BigInt(segment.header_location.offset) !== offset ||
BigInt(segment.header_location.bytes) !== BigInt(entryBytes)
)
fail();
const raw = bytesAt(offset, entryBytes);
if (!segmentMatches(segment, raw)) fail();
}
for (const note of report.notes) {
const raw = bytesAt(BigInt(note.location.offset), 12);
if (
BigInt(note.owner_location.bytes) !== BigInt(raw.readUInt32LE(0)) ||
BigInt(note.descriptor_location.bytes) !== BigInt(raw.readUInt32LE(4)) ||
!matchesKind(raw.readUInt32LE(8), note.type, noteKinds)
)
fail();
const owner = bytesAt(
BigInt(note.owner_location.offset),
raw.readUInt32LE(0),
);
const terminator = owner.indexOf(0);
const display =
owner.length === 0
? null
: owner.subarray(0, terminator).toString("utf8");
if ((owner.length > 0 && terminator < 0) || note.owner_display !== display)
fail();
}
}