feat(captures): inspect recorded packets with bounded TShark delivery (#2318)

Inspect selected fields in existing captures through shared CLI/MCP Evidence.
Page matching frames without changing dissection or two-pass read coverage;
retain failed descriptor/process cleanup ownership and reject excess admission.

Verified with real TShark 4.0.17 and 4.2.2, public Wireshark recordings,
owned HTTP application traffic, real CLI/MCP workflows and schema checks.

Co-authored-by: Olorinm <59321404+Olorinm@users.noreply.github.com>
Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
This commit is contained in:
Ysopwnable
2026-10-12 19:35:35 +00:00
committed by GitHub
co-authored by Olorinm
parent 570c40cde5
commit f611d8ce72
50 changed files with 2850 additions and 0 deletions
+9
View File
@@ -43,6 +43,7 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
type ProviderDescriptor = ProviderCapability;
export type AvailabilityPolicy = {
readonly packetCaptureEnabled?: boolean;
readonly wasmArtifactEnabled?: boolean;
readonly evmInterfaceEnabled?: boolean;
readonly processCaptureEnabled: boolean;
@@ -395,6 +396,14 @@ const workflowAvailabilityFor = ({
remediation:
"On Linux x64, set absolute REA_PWNTOOLS_PYTHON to caller-supplied Python with pwntools 4.15.0. No active binary target is required.",
};
if (name === "inspect_packet_capture")
return policy.packetCaptureEnabled === true
? { reason: "available", remediation: null }
: {
reason: "provider_missing",
remediation:
"On Linux, supply TShark 4.x via absolute REA_TSHARK_COMMAND and util-linux prlimit (REA_TSHARK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
};
if (name === "inspect_wasm_artifact")
return policy.wasmArtifactEnabled === true
? { reason: "available", remediation: null }
@@ -0,0 +1,93 @@
import { isAbsolute } from "node:path";
import type {
AnalysisExecution,
ExecutionOptions,
} from "../AnalysisProvider.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 { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import {
inspectPacketCaptureInputSchema,
packetCaptureSchema,
type InspectPacketCaptureInput,
} from "../../domain/captures/packetCapture.js";
import { err, ok, type Result } from "../../domain/result.js";
export interface PacketCapturePort {
/** Release per-call resources before returning, or retain failed cleanup for close/retry. */
inspect(
input: InspectPacketCaptureInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
close(): Promise<void>;
}
/** One shared validation and Evidence owner for CLI and MCP. */
export class PacketCaptureService {
constructor(readonly provider: PacketCapturePort) {}
close(): Promise<void> {
return this.provider.close();
}
async inspect(
raw: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
const operation = "inspect_packet_capture";
if (options?.signal?.aborted)
return err(new AnalysisCancelledError(operation));
const input = inspectPacketCaptureInputSchema.safeParse(raw);
if (!input.success)
return err(
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
cause: input.error,
}),
);
if (!isAbsolute(input.data.path))
return err(
new AnalysisInputError(operation, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute local path.",
},
]),
);
const decoded = await this.provider.inspect(input.data, options);
if (!decoded.ok) return decoded;
const execution = decoded.value;
const report = packetCaptureSchema.safeParse(execution.result);
if (
!report.success ||
report.data.artifact.path !== input.data.path ||
execution.subject?.path !== input.data.path ||
execution.subject.sha256 !== report.data.artifact.sha256 ||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data)
)
return err(
new AnalysisOutputError(
operation,
"Capture analyzer returned malformed data or changed the selected artifact identity/options.",
),
);
const evidence = createEvidence(execution.subject, execution.provider, {
operation,
parameters: input.data,
result: report.data,
confidence: "observed",
locations: execution.locations,
limitations: execution.limitations,
});
return options?.signal?.aborted
? err(
new AnalysisCancelledError(operation, {
partialObservation: evidence,
}),
)
: ok(evidence);
}
}
+650
View File
@@ -0,0 +1,650 @@
import {
readLinuxResourceLimits,
type LinuxResourceLimits,
} from "../process/LinuxResourceLimits.js";
import { parsePacketOutput } from "./parsePacketOutput.js";
import { randomUUID } from "node:crypto";
import { constants } from "node:fs";
import { access, mkdir, realpath, writeFile } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import {
createAnalysisExecution,
type AnalysisExecution,
type ExecutionOptions,
} from "../application/AnalysisProvider.js";
import type { PacketCapturePort } from "../application/captures/PacketCaptureService.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import {
AnalysisError,
type AnalysisCapturedOutput,
} from "../domain/analysisErrorBase.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisInputError,
AnalysisOutputError,
AnalysisResourceConstraintError,
AnalysisTimeoutError,
} from "../domain/analysisErrorCore.js";
import { createEvidence } from "../domain/evidence.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import {
type InspectPacketCaptureInput,
packetCaptureSchema,
} from "../domain/captures/packetCapture.js";
import { err, ok, type Result } from "../domain/result.js";
import {
runOwnedCommand,
OwnedCommandFailure,
} from "../process/OwnedCommand.js";
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
const OPERATION = "inspect_packet_capture";
export const TSHARK_PROVIDER_IDENTITY = {
id: "tshark-capture",
name: "REA TShark capture adapter",
version: "tshark@4",
} as const;
// Bound the resident input copy and retained text before allocation/collection.
const LIMITS = {
input_bytes: 32 * 1024 * 1024,
output_bytes: 4 * 1024 * 1024,
command_timeout_ms: 30_000,
address_space_bytes: 1024 * 1024 * 1024,
file_bytes: 64 * 1024 * 1024,
cpu_seconds: 30,
} as const;
type Runtime = Pick<PrivateRuntimeRoot, "path" | "close">;
type Launcher = NonNullable<Parameters<typeof runOwnedCommand>[2]>["launcher"];
/** Inspect selected capture files only, retaining cleanup ownership across failures. */
export class TsharkCaptureProvider implements PacketCapturePort {
readonly #artifactResources = new ArtifactResourceScope();
readonly #pending = new Map<Runtime, ProviderProcessSupervisor | undefined>();
#tail: Promise<void> = Promise.resolve();
#busy = false;
#closed = false;
constructor(
readonly environment: Readonly<NodeJS.ProcessEnv> = process.env,
readonly launcher?: Launcher,
readonly createRuntime: () => Promise<Runtime> = () =>
PrivateRuntimeRoot.create({ prefix: "rea-tshark-" }),
readonly platform: NodeJS.Platform = process.platform,
readonly readArtifact: typeof readStableArtifact = readStableArtifact,
readonly readLimits: typeof readLinuxResourceLimits = readLinuxResourceLimits,
) {}
inspect(
input: InspectPacketCaptureInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
if (this.#closed || options?.signal?.aborted)
return Promise.resolve(err(new AnalysisCancelledError(OPERATION)));
if (this.#busy)
return Promise.resolve(
err(
new AnalysisResourceConstraintError(
OPERATION,
"capacity",
"A packet inspection is already active; retry after it completes.",
{ max_concurrent_inspections: 1 },
),
),
);
this.#busy = true;
const work = this.#tail
.then(() =>
this.#artifactResources.run(() => this.#inspect(input, options)),
)
.catch((cause: unknown) =>
err(
this.#failure(
cause,
"artifact",
input.path,
null,
undefined,
undefined,
),
),
)
.finally(() => {
this.#busy = false;
});
this.#tail = work.then(
() => undefined,
() => undefined,
);
return work;
}
close(): Promise<void> {
this.#closed = true;
const work = this.#tail.then(() => this.#closeResources());
this.#tail = work.catch(() => undefined);
return work;
}
async #closeResources(): Promise<void> {
let descriptorFailure: AnalysisError | undefined;
try {
await this.#artifactResources.close();
} catch (cause: unknown) {
descriptorFailure = this.#failure(
cause,
"artifact",
"TShark artifact descriptors",
null,
undefined,
undefined,
);
}
try {
await this.#release();
} catch (cause: unknown) {
if (descriptorFailure !== undefined && cause instanceof AnalysisError)
throw analysisErrorWithCleanupFailure(
descriptorFailure,
cause,
OPERATION,
);
throw cause;
}
if (descriptorFailure !== undefined) throw descriptorFailure;
}
#read(path: string, maximumBytes: number, signal?: AbortSignal) {
return this.readArtifact(
path,
maximumBytes,
signal,
undefined,
this.#artifactResources,
);
}
async #release(): Promise<void> {
for (const [root, owner] of this.#pending) {
try {
if (owner !== undefined) {
const stopped = await owner.stop();
if (stopped.status === "incomplete") throw new Error(stopped.reason);
this.#pending.set(root, undefined);
}
await root.close();
this.#pending.delete(root);
} catch (cause) {
throw new ProviderCleanupError(
TSHARK_PROVIDER_IDENTITY.id,
[root.path],
{ reason: String(cause) },
{ operation: OPERATION, cause },
);
}
}
}
async #inspect(
input: InspectPacketCaptureInput,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>> {
let phase:
| "configuration"
| "artifact"
| "workspace"
| "producer"
| "integrity" = "configuration";
let capturedOutput: AnalysisCapturedOutput | undefined;
let resourcePath = input.path;
let effectiveLimits: LinuxResourceLimits | undefined;
let root: Runtime | undefined;
let result: Result<AnalysisExecution, AnalysisError>;
try {
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
await this.#release();
if (this.platform !== "linux")
throw new Error(
"Packet inspection requires Linux with util-linux prlimit and REA_TSHARK_COMMAND so expanded captures are processed under an enforced address-space limit.",
);
const configured = this.environment.REA_TSHARK_COMMAND ?? "";
if (!isAbsolute(configured))
throw new Error("Supply absolute REA_TSHARK_COMMAND for TShark 4.x.");
const command = await realpath(configured);
await access(command, constants.X_OK);
const tool = await this.#read(command, 64 * 1024 * 1024, options?.signal);
const configuredLimiter =
this.environment.REA_TSHARK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
if (!isAbsolute(configuredLimiter))
throw new Error("REA_TSHARK_PRLIMIT_COMMAND must be absolute.");
const limiter = await realpath(configuredLimiter);
await access(limiter, constants.X_OK);
const limiterIdentity = await this.#read(
limiter,
64 * 1024 * 1024,
options?.signal,
);
effectiveLimits = await this.readLimits(LIMITS, this.#artifactResources);
const limitArguments = [
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
`--cpu=${effectiveLimits.cpu_seconds}:${effectiveLimits.cpu_seconds}`,
"--core=0:0",
"--",
command,
];
phase = "workspace";
root = await this.createRuntime();
this.#pending.set(root, undefined);
const snapshotPath = join(root.path, "capture");
const configurationPath = join(root.path, "configuration");
await mkdir(configurationPath, { mode: 0o700 });
const execute = async (args: readonly string[]) => {
const output = await runOwnedCommand(
{
command: limiter,
arguments: [...limitArguments, ...args],
...(root === undefined ? {} : { cwd: root.path }),
expectedCommand: null,
runId: `rea-tshark-${randomUUID()}`,
hostEnvironment: {
...this.environment,
WIRESHARK_CONFIG_DIR: configurationPath,
},
},
{
timeoutMs: LIMITS.command_timeout_ms,
diagnosticBytes: LIMITS.output_bytes,
acceptNonZeroExit: true,
},
{
...(options?.signal === undefined
? {}
: { signal: options.signal }),
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
},
);
capturedOutput = {
stdout: output.stdout.text,
stderr: output.stderr.text,
truncated: output.diagnosticTruncated ?? false,
exit_code: output.exitCode ?? null,
signal: output.signal ?? null,
};
// Finish bounded integrity checks after output; service handles late cancellation with Evidence.
const previousPhase = phase;
phase = "integrity";
resourcePath = command;
const current = await this.#read(command, 64 * 1024 * 1024);
resourcePath = limiter;
const currentLimiter = await this.#read(limiter, 64 * 1024 * 1024);
if (currentLimiter.sha256 !== limiterIdentity.sha256)
throw new AnalysisArtifactChangedError(
OPERATION,
limiter,
"Configured resource limiter changed during analysis.",
{ capturedOutput },
);
if (current.sha256 !== tool.sha256)
throw new AnalysisArtifactChangedError(
OPERATION,
command,
"Configured TShark executable changed during analysis.",
{ capturedOutput },
);
phase = previousPhase;
resourcePath = input.path;
if (output.exitCode !== 0)
throw new ProviderAdapterError(
TSHARK_PROVIDER_IDENTITY.id,
OPERATION,
{
diagnostics: {
exit_code: output.exitCode ?? null,
stdout: output.stdout.text,
stderr: output.stderr.text,
},
},
);
return output;
};
phase = "configuration";
const version = await execute(["--version"]);
if (
!/^TShark \(Wireshark\) 4\.[0-9]+\.[0-9]+(?:[ .(\r\n]|$)/u.test(
version.stdout.text,
)
)
throw new Error(
"Expected TShark 4.x; inspect the selected installation.",
);
phase = "artifact";
const selected = await this.#read(
input.path,
LIMITS.input_bytes,
options?.signal,
);
phase = "workspace";
await writeFile(snapshotPath, selected.bytes, {
flag: "wx",
mode: 0o400,
});
phase = "producer";
const args = [
"-n",
"-r",
"capture",
"-T",
"json",
"--no-duplicate-keys",
"--temp-dir=.",
...(input.two_pass ? ["-2"] : []),
...(input.packet_limit === null
? []
: ["-c", String(input.packet_limit)]),
...(input.display_filter === null ? [] : ["-Y", input.display_filter]),
...input.decode_as.flatMap((value) => ["-d", value]),
...[...new Set(["frame.number", ...input.fields])].flatMap((field) => [
"-e",
field,
]),
];
const output = await execute(args);
phase = "integrity";
resourcePath = snapshotPath;
if (
(await this.#read(snapshotPath, LIMITS.input_bytes)).sha256 !==
selected.sha256
)
throw new AnalysisArtifactChangedError(
OPERATION,
snapshotPath,
"TShark changed the private capture copy.",
capturedOutput === undefined ? {} : { capturedOutput },
);
phase = "producer";
resourcePath = input.path;
const matchingPackets = parsePacketOutput(
output.stdout.text,
input.fields,
);
const start = Math.min(input.match_offset, matchingPackets.length);
const end =
input.match_limit === null
? matchingPackets.length
: start + Math.min(input.match_limit, matchingPackets.length - start);
const packets = matchingPackets.slice(start, end);
const report = packetCaptureSchema.parse({
artifact: {
path: input.path,
sha256: selected.sha256,
bytes: selected.bytes.length,
},
selection: input,
packets,
output_window: {
matching_packets: matchingPackets.length,
returned_packets: packets.length,
has_more: end < matchingPackets.length,
},
read_scope:
input.packet_limit === null ? "to-eof" : "up-to-input-packet-limit",
configuration: "private-empty-personal-profile",
diagnostics: output.stderr.text,
tool: {
configured_path: configured,
path: command,
sha256: tool.sha256,
version_banner: version.stdout.text,
version_diagnostics: version.stderr.text,
arguments: args,
},
resource_limiter: {
configured_path: configuredLimiter,
path: limiter,
sha256: limiterIdentity.sha256,
arguments: limitArguments,
},
limits: { ...LIMITS, ...effectiveLimits },
hardware_acquisition: "not-performed",
});
result = ok(
createAnalysisExecution(report, TSHARK_PROVIDER_IDENTITY, {
subject: {
path: input.path,
sha256: selected.sha256,
format: "file",
},
locations: [{ kind: "artifact-path", path: input.path }],
limitations: [
"Fields are TShark dissector observations under the selected filter/decode-as/pass settings, not independently verified protocol semantics. Missing fields are absent from the producer output, not known zero or empty values.",
"Packet limits count input packets before display filtering. Filtered results do not establish whole-capture or device traffic absence. Two-pass reassembly cannot recover bytes missing from the recording or beyond the read limit.",
"Repeated field values remain ordered string arrays; raw packet bytes are included only when explicitly selected as a supported field. Export index/score metadata are omitted. All stderr, including warnings on exit zero, is retained.",
"A private empty personal configuration is used. Installed libraries, global configuration and dissector plugins are trusted and not fully fingerprinted. File-only analysis and disabled name resolution do not constitute an OS sandbox.",
"Linux prlimit enforces soft and hard ceilings before execution, preserving stricter inherited limits: at most 1 GiB address space per process, 64 MiB per file, 30 CPU seconds and no core dumps. Effective limits are reported. Resident input is capped at 32 MiB, each command at 30 wall-clock seconds and combined output at 4 MiB. Output overflow fails. These are per-process/per-file limits, not aggregate memory or filesystem quotas; caller-supplied tools and the limiter are trusted.",
],
}),
);
} catch (cause) {
if (
root !== undefined &&
cause instanceof OwnedCommandFailure &&
cause.cleanupOwner !== undefined
)
this.#pending.set(root, cause.cleanupOwner);
result = err(
this.#failure(
cause,
phase,
resourcePath,
root?.path ?? null,
effectiveLimits,
capturedOutput,
),
);
}
try {
await this.#release();
} catch (cause) {
const partialObservation = result.ok
? createEvidence(
result.value.subject ?? undefined,
result.value.provider,
{
operation: OPERATION,
parameters: input,
result: result.value.result,
confidence: "observed",
locations: result.value.locations,
limitations: result.value.limitations,
},
)
: result.error.partialObservation;
return err(
new ProviderCleanupError(
TSHARK_PROVIDER_IDENTITY.id,
[...this.#pending.keys()].map((item) => item.path),
{
reason: String(cause),
previous_error: result.ok
? null
: projectAnalysisError(result.error),
},
{
operation: OPERATION,
cause,
...(partialObservation === undefined ? {} : { partialObservation }),
},
),
);
}
return result;
}
#failure(
cause: unknown,
phase:
| "configuration"
| "artifact"
| "workspace"
| "producer"
| "integrity",
path: string,
workspacePath: string | null,
effectiveLimits: LinuxResourceLimits | undefined,
observedOutput: AnalysisCapturedOutput | undefined,
): AnalysisError {
if (cause instanceof AnalysisError) return cause;
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
return new ProviderCleanupError(
TSHARK_PROVIDER_IDENTITY.id,
cause.cleanup.resources,
{
reason: cause.cleanup.reason,
...(observedOutput === undefined
? {}
: { captured_output: { ...observedOutput } }),
},
{ operation: OPERATION, cause },
);
if (
(cause instanceof Error && cause.name === "AbortError") ||
(cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")
)
return new AnalysisCancelledError(OPERATION, { cause });
const reason = cause instanceof Error ? cause.message : String(cause);
if (cause instanceof OwnedCommandFailure) {
const capturedOutput =
cause.snapshot === null
? undefined
: {
stdout: cause.snapshot.stdout.text,
stderr: cause.snapshot.stderr.text,
truncated: cause.snapshot.diagnosticTruncated ?? false,
exit_code: cause.snapshot.exitCode ?? null,
signal: cause.snapshot.signal ?? null,
};
const detail = {
cause,
...(capturedOutput === undefined ? {} : { capturedOutput }),
};
if (cause.reason === "cancelled")
return new AnalysisCancelledError(OPERATION, detail);
if (cause.reason === "timeout")
return new AnalysisTimeoutError(
OPERATION,
LIMITS.command_timeout_ms,
detail,
);
if (cause.reason === "output-limit")
return new AnalysisResourceConstraintError(
OPERATION,
"memory",
reason,
{ output_bytes: LIMITS.output_bytes },
detail,
);
if (
cause.reason === "process" &&
(cause.snapshot?.signal === "SIGXFSZ" ||
cause.snapshot?.signal === "SIGXCPU")
)
return new AnalysisResourceConstraintError(
OPERATION,
cause.snapshot.signal === "SIGXFSZ" ? "file-size" : "cpu",
`Producer terminated with ${cause.snapshot.signal}; the signal's exact cause is not independently established.`,
effectiveLimits === undefined ? null : { ...effectiveLimits },
detail,
);
return new AnalysisOutputError(OPERATION, reason, detail);
}
if (phase === "workspace") {
const code =
cause instanceof Error &&
"code" in cause &&
typeof cause.code === "string"
? cause.code
: null;
if (code === "ENOSPC" || code === "EDQUOT" || code === "EFBIG")
return new AnalysisResourceConstraintError(
OPERATION,
"file-size",
`Private analysis workspace failed (${code}): ${reason}`,
{ workspace_path: workspacePath, system_code: code },
{ cause },
);
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, OPERATION, {
cause,
userMessage: `Cannot prepare the private analysis workspace: ${reason}`,
diagnostics: {
stage: "workspace",
workspace_path: workspacePath,
system_code: code,
reason,
},
});
}
if (phase === "integrity") {
const detail = {
cause,
...(observedOutput === undefined
? {}
: { capturedOutput: observedOutput }),
};
if (
cause instanceof ArtifactReaderFailure &&
["limit", "integrity", "path"].includes(cause.reason)
)
return new AnalysisArtifactChangedError(
OPERATION,
path,
`Post-run identity verification failed for ${path}: ${reason}`,
detail,
);
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, OPERATION, {
...detail,
diagnostics: { stage: "integrity", resource_path: path, reason },
});
}
if (phase === "configuration")
return new AnalysisCapabilityUnavailableError(
TSHARK_PROVIDER_IDENTITY.id,
OPERATION,
reason,
{
cause,
userMessage: `${reason} On Linux, configure TShark 4.x through REA_TSHARK_COMMAND and util-linux prlimit through REA_TSHARK_PRLIMIT_COMMAND (default /usr/bin/prlimit).`,
},
);
if (
phase === "artifact" &&
cause instanceof ArtifactReaderFailure &&
cause.reason === "limit"
)
return new AnalysisResourceConstraintError(
OPERATION,
"file-size",
reason,
{ input_bytes: LIMITS.input_bytes },
{ cause },
);
if (cause instanceof ArtifactReaderFailure && cause.reason === "integrity")
return new AnalysisArtifactChangedError(OPERATION, path, reason, {
cause,
});
if (
phase === "artifact" &&
cause instanceof Error &&
"code" in cause &&
(cause.code === "EACCES" || cause.code === "EPERM")
)
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
cause,
});
if (phase === "artifact")
return new AnalysisInputError(OPERATION, { cause }, [
{ path: ["path"], reason: "invalid_value", message: reason },
]);
return new AnalysisOutputError(OPERATION, reason, { cause });
}
}
+29
View File
@@ -0,0 +1,29 @@
import { z } from "zod";
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
import { packetFieldsSchema } from "../domain/captures/packetCapture.js";
// _index/_score are TShark export metadata, not captured packet fields.
const producerSchema = z.array(
z.object({ _source: z.object({ layers: packetFieldsSchema }) }),
);
export const parsePacketOutput = (text: string, fields: readonly string[]) => {
const decoded: unknown = JSON.parse(text);
const packets = producerSchema
.parse(decoded)
.map((packet) => packet._source.layers);
const selected = new Set(["frame.number", ...fields]);
let previous = 0n;
for (const packet of packets) {
const frame = BigInt(packet["frame.number"][0]);
if (
frame <= previous ||
Object.keys(packet).some((name) => !selected.has(name))
)
throw new AnalysisOutputError(
"inspect_packet_capture",
"TShark returned unordered frames or unselected fields.",
);
previous = frame;
}
return packets;
};
+2
View File
@@ -1,3 +1,4 @@
import { registerCaptureCommands } from "./cli/captureCommands.js";
import { registerWasmCommands } from "./cli/wasmCommands.js";
import { snapshotEnvironment } from "./process/snapshotEnvironment.js";
import { createDirectAnalysis } from "./composition/directAnalysis.js";
@@ -94,6 +95,7 @@ export const createCli = (
registerCoreAnalysisCommands(cli, logger, analysis.runDirectAnalysis);
registerUtilityCommands(cli, logger, environment, analysis);
registerWasmCommands(cli, logger, environment);
registerCaptureCommands(cli, logger, environment);
registerEvmCommands(cli, logger, environment);
registerGoCommands(cli, logger);
registerSqliteCommands(cli, logger, environment);
+99
View File
@@ -0,0 +1,99 @@
import { z } from "incur";
import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { resolve } from "node:path";
import { createPacketCaptureService } from "../composition/captures.js";
import {
packetCaptureOptionsSchema,
packetCaptureSelectorBudgetIssue,
withinPacketCaptureSelectorBudget,
} from "../domain/captures/packetCapture.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
export const registerCaptureCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<NodeJS.ProcessEnv>,
service: Pick<
PacketCaptureService,
"inspect" | "close"
> = createPacketCaptureService(environment),
): void => {
cli.command(CLI_COMMANDS.inspectPacketCapture, {
description:
"Inspect an existing packet capture with caller-supplied TShark",
args: z.object({ path: z.string().describe("Local packet capture") }),
options: z
.object({
...packetCaptureOptionsSchema.shape,
match_limit: z
.number()
.int()
.positive()
.optional()
.describe("Returned matching frames per page; default 50"),
all_matches: z
.boolean()
.default(false)
.describe(
"Return all remaining matching frames instead of a bounded page",
),
})
.superRefine((options, context) => {
if (options.all_matches && options.match_limit !== undefined)
context.addIssue({
code: "custom",
path: ["all_matches"],
message: "all_matches and match_limit are mutually exclusive",
});
})
.refine(
withinPacketCaptureSelectorBudget,
packetCaptureSelectorBudgetIssue,
),
run: ({ args, options: { all_matches, ...options } }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectPacketCapture, async () => {
const result = await service.inspect(
{
...options,
...(all_matches ? { match_limit: null } : {}),
path: resolve(args.path),
},
{ signal },
);
// A one-shot command must retry retained cleanup before discarding its owner.
try {
await service.close();
} catch (cause) {
const cleanup =
cause instanceof AnalysisError
? cause
: new ProviderCleanupError(
"tshark-capture",
[],
{ reason: String(cause) },
{ cause, operation: "inspect_packet_capture" },
);
if (result.ok) cleanup.retainPartialObservation(result.value);
return projectAnalysisError(
result.ok
? cleanup
: analysisErrorWithCleanupFailure(
result.error,
cleanup,
"inspect_packet_capture",
),
);
}
return result.ok ? result.value : projectAnalysisError(result.error);
}),
),
});
};
+1
View File
@@ -1,5 +1,6 @@
/** Canonical names used by every one-shot CLI command registration. */
export const CLI_COMMANDS = Object.freeze({
inspectPacketCapture: "inspect-packet-capture",
inspectWasmArtifact: "inspect-wasm-artifact",
inspectSqliteDatabase: "inspect-sqlite-database",
inspectEvmInterface: "inspect-evm-interface",
+6
View File
@@ -0,0 +1,6 @@
import { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
import { TsharkCaptureProvider } from "../captures/TsharkCaptureProvider.js";
export const createPacketCaptureService = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
): PacketCaptureService =>
new PacketCaptureService(new TsharkCaptureProvider(environment));
@@ -0,0 +1,31 @@
import {
inspectPacketCaptureInputSchema,
packetCaptureSchema,
} from "../../domain/captures/packetCapture.js";
import type { ToolContract } from "../toolContractTypes.js";
import { toolContractMetadata } from "../toolEffects.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
export const CAPTURE_TOOL_CONTRACTS = [
{
name: "inspect_packet_capture",
...toolContractMetadata("inspect_packet_capture"),
kind: "artifact-provider",
description:
"Inspect caller-selected fields in an existing local packet capture with TShark 4.x. Return 50 matching frames by default, with match_offset/match_limit paging and coverage counts; match_limit:null requests all remaining matches. Preserve repeated values, frame numbers, display filter, decode-as rules and pass mode in inline Evidence with source/tool identity and diagnostics. Optional packet_limit counts input packets before filtering; output paging does not shorten dissection or two-pass reassembly. Requires Linux, util-linux prlimit, and absolute REA_TSHARK_COMMAND. File-only analysis; no live capture or device communication. Missing fields or no matches do not establish absence of device traffic.",
inputSchema: inspectPacketCaptureInputSchema,
outputSchema: evidenceResultOf(packetCaptureSchema),
examples: [
{
title: "Inspect UDP exchanges in a recording",
input: {
path: "/artifacts/device.pcapng",
fields: ["ip.addr", "udp.port", "data.data"],
display_filter: "udp",
decode_as: [],
packet_limit: null,
two_pass: true,
},
},
],
},
] as const satisfies readonly ToolContract[];
+2
View File
@@ -1,3 +1,4 @@
import { CAPTURE_TOOL_CONTRACTS } from "./captures/captureToolContracts.js";
import { WASM_TOOL_CONTRACTS } from "./wasm/wasmToolContracts.js";
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
import { GO_TOOL_CONTRACTS } from "./go/goToolContracts.js";
@@ -39,6 +40,7 @@ export const TOOL_CONTRACTS = [
...GO_TOOL_CONTRACTS,
...WASM_TOOL_CONTRACTS,
...SQLITE_TOOL_CONTRACTS,
...CAPTURE_TOOL_CONTRACTS,
...MANAGED_TOOL_CONTRACTS,
...ANDROID_TOOL_CONTRACTS,
...APKTOOL_TOOL_CONTRACTS,
+5
View File
@@ -59,6 +59,11 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
writesFilesystem: true,
launchesProcess: true,
}),
inspect_packet_capture: effects({
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
}),
inspect_wasm_artifact: effects({
mutatesSession: true,
writesFilesystem: true,
+168
View File
@@ -0,0 +1,168 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
const argument = z
.string()
.min(1)
.max(8192)
.refine((value) => !value.includes("\0"), "NUL is not an argument character");
const captureInputShape = z.strictObject({
path: localPathStringSchema.describe("Absolute local capture path"),
fields: z
.array(argument)
.max(1024)
.min(1)
.describe(
"TShark field names to return, e.g. ip.addr, usb.endpoint_address, btatt.opcode; frame.number is always included",
),
display_filter: argument
.nullable()
.default(null)
.describe(
"Optional Wireshark display filter (-Y), applied within the read limit",
),
decode_as: z
.array(argument)
.max(1024)
.default([])
.describe("Explicit TShark decode-as selections, e.g. tcp.port==8888,http"),
packet_limit: z
.number()
.int()
.positive()
.max(2147483647)
.nullable()
.default(null)
.describe(
"Maximum input packets to read before filtering; omitted scans to EOF within resource limits",
),
two_pass: z
.boolean()
.default(true)
.describe(
"Use two-pass analysis for fields requiring later packets; false requests a single pass",
),
match_offset: z
.number()
.int()
.nonnegative()
.default(0)
.describe("Skip this many matching packets after filtering; default 0"),
match_limit: z
.number()
.int()
.positive()
.nullable()
.default(50)
.describe(
"Return at most this many matching packets after filtering; default 50. Null explicitly returns all remaining matches within producer resource limits.",
),
});
// Bound UTF-8 selector text, terminators, option names and 64-bit argv pointers
// before Set/flatMap expansion. 32 KiB reserves headroom below Linux execve's
// 32-page argv+environment floor; ambient environments can still exhaust it.
export const withinPacketCaptureSelectorBudget = (input: {
fields: readonly string[];
decode_as: readonly string[];
display_filter: string | null;
}): boolean => {
if (input.fields.length > 1024 || input.decode_as.length > 1024) return false;
let bytes = 0;
for (const selections of [input.fields, input.decode_as])
for (const value of selections) {
bytes += Buffer.byteLength(value, "utf8") + 20;
if (bytes > 32768) return false;
}
if (input.display_filter !== null)
bytes += Buffer.byteLength(input.display_filter, "utf8") + 20;
return bytes <= 32768;
};
export const packetCaptureSelectorBudgetIssue = {
message:
"Packet selectors exceed the 32 KiB encoded argument budget; reduce fields, decode-as rules or filter text.",
};
export const inspectPacketCaptureInputSchema = captureInputShape.refine(
withinPacketCaptureSelectorBudget,
packetCaptureSelectorBudgetIssue,
);
export const packetCaptureOptionsSchema = captureInputShape
.omit({ path: true })
.refine(withinPacketCaptureSelectorBudget, packetCaptureSelectorBudgetIssue);
export type InspectPacketCaptureInput = z.infer<
typeof inspectPacketCaptureInputSchema
>;
/** Values remain strings; repeated occurrences remain ordered arrays. */
export const packetFieldsSchema = z
.object({
"frame.number": z.tuple([z.string().regex(/^[1-9][0-9]*$/)]),
})
.catchall(z.array(z.string()));
export const packetCaptureSchema = z
.strictObject({
artifact: z.strictObject({
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
bytes: z.number().int().nonnegative(),
}),
selection: inspectPacketCaptureInputSchema,
packets: z.array(packetFieldsSchema),
output_window: z.strictObject({
matching_packets: z
.number()
.int()
.nonnegative()
.describe(
"Matches in the completed producer output within the indicated input read scope, not total capture packets",
),
returned_packets: z.number().int().nonnegative(),
has_more: z.boolean(),
}),
read_scope: z.enum(["to-eof", "up-to-input-packet-limit"]),
diagnostics: z.string(),
tool: z.strictObject({
configured_path: z.string(),
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
version_banner: z.string(),
version_diagnostics: z.string(),
arguments: z.array(z.string()),
}),
configuration: z.literal("private-empty-personal-profile"),
resource_limiter: z.strictObject({
configured_path: z.string(),
path: z.string(),
sha256: z.string().regex(/^[a-f0-9]{64}$/),
arguments: z.array(z.string()),
}),
limits: z.strictObject({
input_bytes: z.number().int().positive(),
output_bytes: z.number().int().positive(),
command_timeout_ms: z.number().int().positive(),
address_space_bytes: z.number().int().nonnegative(),
file_bytes: z.number().int().nonnegative(),
cpu_seconds: z.number().int().nonnegative(),
}),
hardware_acquisition: z.literal("not-performed"),
})
.superRefine((report, context) => {
const remaining = Math.max(
report.output_window.matching_packets - report.selection.match_offset,
0,
);
const expected =
report.selection.match_limit === null
? remaining
: Math.min(remaining, report.selection.match_limit);
if (
report.packets.length !== expected ||
report.output_window.returned_packets !== expected ||
report.output_window.has_more !== remaining > expected
)
context.addIssue({
code: "custom",
path: ["output_window"],
message:
"Returned packet window must match examined matches and caller-selected offset/limit",
});
});
+43
View File
@@ -0,0 +1,43 @@
import { expect, it } from "vitest";
import { clampLinuxResourceLimits } from "./LinuxResourceLimits.js";
const configured = {
address_space_bytes: 1073741824,
file_bytes: 67108864,
cpu_seconds: 30,
};
const report = (
memory: string,
file = "unlimited unlimited",
cpu = "unlimited unlimited",
) =>
`Limit Soft Limit Hard Limit Units\nMax address space ${memory} bytes\nMax file size ${file} bytes\nMax cpu time ${cpu} seconds\n`;
it("keeps configured ceilings below unlimited or larger inherited limits", () => {
expect(
clampLinuxResourceLimits(configured, report("unlimited unlimited")),
).toEqual(configured);
expect(
clampLinuxResourceLimits(
configured,
report("18446744073709551615 18446744073709551615"),
),
).toEqual(configured);
});
it("preserves stricter soft limits and lower hard ceilings, including zero", () => {
expect(
clampLinuxResourceLimits(
configured,
report("268435456 2147483648", "0 1048576", "10 20"),
),
).toEqual({ address_space_bytes: 268435456, file_bytes: 0, cpu_seconds: 10 });
expect(
clampLinuxResourceLimits(configured, report("268435456 536870912")),
).toMatchObject({ address_space_bytes: 268435456 });
});
it("refuses missing, ambiguous or malformed kernel limits before launch", () => {
for (const value of [
"",
report("invalid unlimited"),
report("unlimited unlimited") + "Max address space 1 2 bytes\n",
])
expect(() => clampLinuxResourceLimits(configured, value)).toThrow();
});
+82
View File
@@ -0,0 +1,82 @@
import { open } from "node:fs/promises";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
/** Per-process ceilings inherited by an owned Linux producer. */
export interface LinuxResourceLimits {
readonly address_space_bytes: number;
readonly file_bytes: number;
readonly cpu_seconds: number;
}
const rows = {
address_space_bytes: "Max address space",
file_bytes: "Max file size",
cpu_seconds: "Max cpu time",
} as const;
/** Never raise either inherited soft policy or hard ceiling. */
export const clampLinuxResourceLimits = (
configured: LinuxResourceLimits,
report: string,
): LinuxResourceLimits => {
const effective = { ...configured };
for (const key of Object.keys(rows) as (keyof LinuxResourceLimits)[]) {
const matches = report
.split("\n")
.filter((line) => line.startsWith(`${rows[key]} `));
const values = matches[0]?.slice(rows[key].length).trim().split(/\s+/u);
if (matches.length !== 1 || values === undefined || values.length !== 3)
throw new Error(`Cannot establish inherited Linux limit: ${rows[key]}`);
let ceiling = BigInt(configured[key]);
for (const token of values.slice(0, 2)) {
if (token === "unlimited") continue;
if (!/^[0-9]+$/u.test(token))
throw new Error(`Invalid inherited Linux limit: ${rows[key]}`);
const value = BigInt(token);
if (value < ceiling) ceiling = value;
}
effective[key] = Number(ceiling);
}
return effective;
};
/** Read the trusted kernel report with a fixed allocation before spawning. */
export const readLinuxResourceLimits = async (
configured: LinuxResourceLimits,
resourceScope?: ArtifactResourceScope,
): Promise<LinuxResourceLimits> => {
const file = await open("/proc/self/limits", "r");
const owner = new OwnedFileHandle(file);
let failure: unknown;
try {
const buffer = Buffer.alloc(16 * 1024);
const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
if (bytesRead === buffer.length)
throw new Error("Inherited Linux limits exceed the report budget.");
return clampLinuxResourceLimits(
configured,
buffer.subarray(0, bytesRead).toString("utf8"),
);
} catch (cause: unknown) {
failure = cause;
throw cause;
} finally {
if (resourceScope === undefined) await file.close();
else {
const cleaned = await resourceScope.release({
kind: "file-handle",
resource: "/proc/self/limits",
handle: owner,
});
if (cleaned.kind === "failed")
throw ArtifactReaderFailure.withCleanup(
failure ?? cleaned.cause,
ArtifactReaderFailure.cleanupObservation(
cleaned.cause,
"/proc/self/limits",
),
);
}
}
};
+17
View File
@@ -1,3 +1,6 @@
import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
import { createPacketCaptureService } from "../composition/captures.js";
import { registerCaptureTools } from "./registerCaptureTools.js";
import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
import { wasmArtifactModule } from "../composition/wasm.js";
import { registerWasmTools } from "./registerWasmTools.js";
@@ -119,6 +122,7 @@ const ACTIVE_TARGET_INSTRUCTIONS =
export interface CreateServerOptions {
readonly environment?: Readonly<NodeJS.ProcessEnv>;
readonly delivery?: ToolResultDelivery;
readonly packetCapture?: PacketCaptureService;
readonly wasmArtifact?: WasmArtifactService;
readonly evmInterface?: EvmInterfaceService;
readonly sqliteDatabase?: SqliteDatabaseService;
@@ -161,6 +165,9 @@ const installSessionToolAvailability = (
const basePolicy = sessionAvailabilityPolicy(options.availabilityPolicy, {
optionalProviderLoadFailures: options.optionalProviderLoadFailures,
optionalFeatures: {
packetCaptureEnabled:
options.packetCapture !== undefined ||
(linux && isAbsolute(environment.REA_TSHARK_COMMAND ?? "")),
wasmArtifactEnabled:
options.wasmArtifact !== undefined ||
isAbsolute(environment.REA_WABT_BIN_DIRECTORY ?? ""),
@@ -292,6 +299,8 @@ export const createServer = (
environment,
options.wasmArtifact,
);
const packetCapture =
options.packetCapture ?? createPacketCaptureService(environment);
const apktool =
options.apktoolAnalysis ??
createApktoolResourceAnalysisProvider(environment);
@@ -304,6 +313,7 @@ export const createServer = (
android.close(),
fridaInstrumentation.closeAll(),
wasmArtifact.close(),
packetCapture.close(),
apktool.close(),
jeb.close(),
adbDevice.close(),
@@ -384,6 +394,13 @@ export const createServer = (
for (const result of results)
if (result.status === "rejected") throw result.reason;
};
registerCaptureTools(
server,
packetCapture,
toolLogger,
recordEvidence,
analysisAdmission,
);
registerConfiguredAnalysisTools(
toolContext,
android,
+31
View File
@@ -0,0 +1,31 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "pino";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import { createEvidenceToolHandler } from "./contractToolHandler.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Bind the named capture contract through shared admission and retained Evidence delivery. */
export const registerCaptureTools = (
server: EvidenceMcpServer,
service: PacketCaptureService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
): void => {
const contract = toolContract("inspect_packet_capture");
const handler = createEvidenceToolHandler(
server,
(input, options) => service.inspect(input, options),
logger,
recordEvidence,
withAdmittedAnalysis,
);
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
handler(contract),
);
};
+3
View File
@@ -8,6 +8,7 @@ export interface SessionAvailabilityDefaults {
| undefined;
readonly optionalFeatures?: Pick<
AvailabilityPolicy,
| "packetCaptureEnabled"
| "wasmArtifactEnabled"
| "evmInterfaceEnabled"
| "browserObservationEnabled"
@@ -32,6 +33,8 @@ export const sessionAvailabilityPolicy = (
const policy =
configured ??
(() => ({
packetCaptureEnabled:
defaults.optionalFeatures?.packetCaptureEnabled ?? false,
wasmArtifactEnabled:
defaults.optionalFeatures?.wasmArtifactEnabled ?? false,
evmInterfaceEnabled: