Files
reverse-engineering-anything/src/pcap/PcapNativeBound.ts
T
morluto 402ce20b80 fix(session): declare, admit and advertise the open-target prerequisite through one owner (#15356)
* fix(contracts): declare the open-target prerequisite once in availability

Replace the requiresActiveTarget boolean with an "active-target" value of the
availability declaration. 18 contracts that read a required caller path, all
declared standalone or host-restricted or named inventory rules, no longer
claim to need an open target.

* fix(session): admit tools through one session evaluator shared with binary_session

binary_session availability and call-time dispatch now read one admission
evaluator for active-target tools and external mutations. Resource-only
lane refusals and Ghidra or resource-only external-mutation refusals carry
the open_binary or close_binary recovery that binary_session reports,
instead of a generic capability or unreadable-output error. Packet
capture, Wakaru, firmware and mitmproxy refuse an unsupported host before
reading tool configuration.

* fix(mcp): advertise the open-target prerequisite and name open_binary on first contact

Each active-target tool's advertised description ends with one sentence
derived from its availability declaration. When the SDK refuses such a
tool's arguments while the session would also refuse it, the
invalid_request remediation names the session recovery first, read from
the same admission evaluator as binary_session and dispatch.

* fix(mcp): refuse composed workflows as a whole and keep scoped recovery and catalog identity in step

A composed workflow such as batch_decompile now refuses with the
advertised open_binary or close_binary recovery before it runs, instead of
reporting a batch of failed children. Malformed arguments on a connection
that does not advertise session tools lead with the scoped restart
recovery, and catalog digests cover the advertised prerequisite sentence.
The prerequisite test reads union alternatives.
2026-12-01 03:55:48 +00:00

206 lines
8.0 KiB
TypeScript

import { BOUNDED_PRODUCER_LIMITS } from "../domain/producerResourceLimits.js";
import { selectArtifactCommandPath } from "../process/ArtifactCommandPath.js";
import {
pcapCaptureHostSupported,
PCAP_CAPTURE_HOST_REMEDIATION,
PCAP_CAPTURE_UNSUPPORTED_HOST_REASON,
} from "../domain/pcap/pcapAnalysis.js";
import { access, stat } from "node:fs/promises";
import { constants } from "node:fs";
import { basename, isAbsolute } from "node:path";
import {
AnalysisError,
type AnalysisCapturedOutput,
} from "../domain/analysisErrorBase.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
cancelledBy,
} from "../domain/analysisErrorCore.js";
import type { ArtifactAnalysisResources } from "../process/ArtifactAnalysisResources.js";
import { prlimitCeilingArguments } from "../process/LinuxResourceLimits.js";
import type { runPcapCommand } from "./PcapCommand.js";
import type { ArtifactCommandPath } from "../process/ArtifactCommandPath.js";
import { errorMessage } from "../kernel/errorMessage.js";
const PRLIMIT_COMMAND_ENV = "REA_TSHARK_PRLIMIT_COMMAND";
/** Repair for an unusable selected capture limiter; readiness and admission share it. */
export const PCAP_LIMITER_REMEDIATION = `Check that ${PRLIMIT_COMMAND_ENV} (default /usr/bin/prlimit) names an absolute, executable util-linux prlimit.`;
/**
* Capture summaries need this host before anything else: no tool selection
* or setting can make an unsupported host enforce the native bound, so the
* host is checked before tshark is resolved.
*/
export const pcapCaptureHostRefusal = (
platform: NodeJS.Platform,
operation: "inspect_pcap_client" | "inspect_pcap_capture",
): AnalysisCapabilityUnavailableError | undefined =>
pcapCaptureHostSupported(platform)
? undefined
: new AnalysisCapabilityUnavailableError(
"pcap",
operation,
PCAP_CAPTURE_UNSUPPORTED_HOST_REASON,
{
userMessage: PCAP_CAPTURE_UNSUPPORTED_HOST_REASON,
remediationAction: PCAP_CAPTURE_HOST_REMEDIATION,
},
);
/** Which stage an unsuccessful limited capture command's exit belongs to. */
export type PcapLimitedExitStage =
| { readonly stage: "tool" }
| { readonly stage: "tool-launch"; readonly refusal: "missing" | "denied" }
| { readonly stage: "limiter" };
/**
* Attribute an unsuccessful exit of a command run through util-linux prlimit.
* prlimit sets the limits and then replaces itself with the tool (execvp), so
* once that succeeds the exit status and output are the tool's own. Before
* that, prlimit reports its own failure through err(3) on stderr, prefixed
* with its invocation name: a failed exec exits 127 (ENOENT) or 126, any
* other prlimit failure exits 1. Commands run with LC_ALL=C, so the message
* is untranslated.
*/
export const attributePcapLimitedExit = (
limiterInvocationPath: string,
exit: {
readonly exitCode: number | null | undefined;
readonly signal: string | null | undefined;
readonly stderr: string;
},
): PcapLimitedExitStage => {
const prefix = `${basename(limiterInvocationPath)}: `;
// A signal or output without prlimit's own prefix belongs to the tool.
if (
(exit.signal !== null && exit.signal !== undefined) ||
!exit.stderr.startsWith(prefix)
)
return { stage: "tool" };
if (
(exit.exitCode === 126 || exit.exitCode === 127) &&
exit.stderr.startsWith(`${prefix}failed to execute `)
)
return {
stage: "tool-launch",
refusal: exit.exitCode === 127 ? "missing" : "denied",
};
return exit.exitCode === 1 ? { stage: "limiter" } : { stage: "tool" };
};
/** Capture CPU ceiling, in seconds. */
const PCAP_CPU_SECONDS = 300;
/** Own native capture admission and the exact enforced resource profile. */
export const preparePcapNativeBound = async (
platform: NodeJS.Platform,
environment: Readonly<Record<string, string | undefined>>,
resources: ArtifactAnalysisResources,
probe: (
selected: ArtifactCommandPath,
arguments_: string[],
) => Promise<{
readonly stdout: string;
readonly capturedOutput: AnalysisCapturedOutput;
}>,
signal?: AbortSignal,
operation:
| "inspect_pcap_client"
| "inspect_pcap_capture" = "inspect_pcap_capture",
): Promise<{
nativeBound: NonNullable<Parameters<typeof runPcapCommand>[0]["nativeBound"]>;
limitations: readonly string[];
}> => {
if (platform === "win32") {
return {
nativeBound: {
memoryLimitBytes: BOUNDED_PRODUCER_LIMITS.address_space_bytes,
},
limitations: [
"Each owned Windows tool tree has a 1 GiB Job Object committed-memory limit; this is not a machine-wide quota.",
],
};
}
const hostRefusal = pcapCaptureHostRefusal(platform, operation);
if (hostRefusal !== undefined) throw hostRefusal;
const configured = environment[PRLIMIT_COMMAND_ENV] ?? "/usr/bin/prlimit";
let probeFailure: AnalysisError | undefined;
let capturedOutput: AnalysisCapturedOutput | undefined;
try {
if (!isAbsolute(configured))
throw new Error(`${PRLIMIT_COMMAND_ENV} must be absolute.`);
const selection = await selectArtifactCommandPath(configured, signal);
if (!(await stat(selection.resolvedPath)).isFile())
throw new Error("The selected limiter is not a regular file.");
await access(selection.resolvedPath, constants.X_OK);
const readProbe = async (argument: "--version" | "--help") => {
try {
const output = await probe(selection, [argument]);
capturedOutput = output.capturedOutput;
return output.stdout;
} catch (cause) {
if (
(cause instanceof AnalysisCapabilityUnavailableError ||
cause instanceof AnalysisOutputError) &&
!cause.cleanupIncomplete
) {
probeFailure = cause;
throw new Error(
cause instanceof AnalysisOutputError
? `The selected limiter produced unreadable ${argument === "--version" ? "version" : "help"} output.`
: "The selected limiter could not be run.",
{ cause },
);
}
throw cause;
}
};
const version = await readProbe("--version");
const prefix = `${basename(selection.invocationPath)} from util-linux `;
if (
!version.startsWith(prefix) ||
version.slice(prefix.length).trim() === ""
)
throw new Error(
"The selected limiter did not report a util-linux prlimit version.",
);
const help = await readProbe("--help");
for (const flag of ["--as", "--fsize", "--cpu", "--core"]) {
if (!new RegExp(`(?:^|\\s)${flag}(?:[=\\[\\s,]|$)`, "u").test(help))
throw new Error(`The selected limiter does not advertise ${flag}.`);
}
const limits = await resources.readLimits({
address_space_bytes: BOUNDED_PRODUCER_LIMITS.address_space_bytes,
file_bytes: BOUNDED_PRODUCER_LIMITS.file_bytes,
cpu_seconds: PCAP_CPU_SECONDS,
});
const nativeBound = {
limiter: {
command: selection,
arguments: prlimitCeilingArguments(limits),
},
};
const limitations = [
`Linux prlimit preserves stricter inherited ceilings: ${limits.address_space_bytes} bytes of per-process address space, ${limits.file_bytes} bytes per file and ${limits.cpu_seconds} CPU seconds; core dumps are disabled. These are not aggregate machine quotas.`,
];
return { nativeBound, limitations };
} catch (cause) {
if (signal?.aborted === true && !(cause instanceof AnalysisError))
throw cancelledBy(operation, signal);
if (cause instanceof AnalysisError) throw cause;
const reason =
"Cannot establish the selected Linux resource limiter before processing capture bytes.";
throw new AnalysisCapabilityUnavailableError("pcap", operation, reason, {
cause,
capturedOutput: probeFailure?.capturedOutput ?? capturedOutput,
diagnostics: {
...probeFailure?.diagnostics,
configuration_key: PRLIMIT_COMMAND_ENV,
configured,
},
userMessage: `${reason} (${errorMessage(cause)}) ${PCAP_LIMITER_REMEDIATION}`,
remediationAction: PCAP_LIMITER_REMEDIATION,
});
}
};