feat(pcap): add bounded capture summaries through CLI and MCP
Summarize saved Wireshark4.x captures with enforced native resource limits, serialized admission, stable snapshot verification and retained fact/text pages. Preserve complete inventories within resource budgets and source uncertainty; report cleanup failure with partial Evidence and retained ownership. Verified six recorded corpora /13026 packets with independent Scapy/Python oracles, real CLI/MCP/schema parity,60 SNI names,132 DNS addresses and1000 URIs. Real TShark CI now exercises summary/paging. Actual Windows/Bun Wireshark remains unverified; macOS capture requires a separate enforceable-bound decision. Co-authored-by: 3QL <85309073+3QL@users.noreply.github.com> Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,207 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisProtocolError,
|
||||
AnalysisResourceConstraintError,
|
||||
AnalysisTimeoutError,
|
||||
AnalysisUnsupportedTargetError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import {
|
||||
OwnedCommandFailure,
|
||||
runOwnedCommand,
|
||||
} from "../process/OwnedCommand.js";
|
||||
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
|
||||
import { prepareProcessOwnershipInspection } from "../process/ProcessOwnershipObservation.js";
|
||||
import {
|
||||
isWindowsBatchFile,
|
||||
windowsBatchCommand,
|
||||
WindowsBatchCommandError,
|
||||
} from "../process/WindowsBatchCommand.js";
|
||||
|
||||
export interface PcapCommandLimits {
|
||||
readonly timeoutMs: number;
|
||||
readonly maxOutputBytes: number;
|
||||
}
|
||||
|
||||
/** Owned process execution shared by version probes and capture reads. */
|
||||
export const runPcapCommand = async (options: {
|
||||
readonly operation: string;
|
||||
readonly command: string;
|
||||
readonly arguments: readonly string[];
|
||||
readonly limits: PcapCommandLimits;
|
||||
readonly environment: Readonly<Record<string, string | undefined>>;
|
||||
readonly signal: AbortSignal | undefined;
|
||||
readonly inputPath?: string;
|
||||
readonly nativeBound?: {
|
||||
readonly limiter?: { command: string; arguments: readonly string[] };
|
||||
readonly memoryLimitBytes?: number;
|
||||
};
|
||||
readonly retain: (
|
||||
owner: ProviderProcessSupervisor,
|
||||
resources: readonly string[],
|
||||
) => void;
|
||||
}): Promise<{ stdout: string; stderr: string }> => {
|
||||
const { operation, command, limits, signal } = options;
|
||||
if (signal?.aborted)
|
||||
throw new AnalysisCancelledError(operation, { cause: signal.reason });
|
||||
const hostEnvironment = {
|
||||
...process.env,
|
||||
...options.environment,
|
||||
LC_ALL: "C",
|
||||
LANG: "C",
|
||||
};
|
||||
try {
|
||||
const batch = process.platform === "win32" && isWindowsBatchFile(command);
|
||||
const invocation = batch
|
||||
? windowsBatchCommand({
|
||||
environment: hostEnvironment,
|
||||
batchPath: command,
|
||||
arguments: options.arguments,
|
||||
})
|
||||
: { command, arguments: options.arguments };
|
||||
const boundedInvocation =
|
||||
options.nativeBound?.limiter === undefined
|
||||
? invocation
|
||||
: {
|
||||
command: options.nativeBound.limiter.command,
|
||||
arguments: [
|
||||
...options.nativeBound.limiter.arguments,
|
||||
invocation.command,
|
||||
...invocation.arguments,
|
||||
],
|
||||
};
|
||||
// Native ownership preparation has its own bounded compiler lifecycle;
|
||||
// do not spend the tool's execution deadline rebuilding a cold SDK cache.
|
||||
await prepareProcessOwnershipInspection(signal);
|
||||
const output = await runOwnedCommand(
|
||||
{
|
||||
...boundedInvocation,
|
||||
runId: randomUUID(),
|
||||
hostEnvironment,
|
||||
windowsVerbatimArguments: batch,
|
||||
expectedCommand: null,
|
||||
...(options.nativeBound?.memoryLimitBytes === undefined
|
||||
? {}
|
||||
: { memoryLimitBytes: options.nativeBound.memoryLimitBytes }),
|
||||
},
|
||||
{ timeoutMs: limits.timeoutMs, diagnosticBytes: limits.maxOutputBytes },
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
return { stdout: output.stdout.text, stderr: output.stderr.text };
|
||||
} catch (cause) {
|
||||
if (cause instanceof AnalysisError) throw cause;
|
||||
if (
|
||||
cause instanceof OwnedCommandFailure &&
|
||||
cause.cleanupOwner !== undefined
|
||||
)
|
||||
options.retain(cause.cleanupOwner, cause.resources);
|
||||
const details = {
|
||||
cause,
|
||||
...(cause instanceof OwnedCommandFailure && cause.snapshot !== null
|
||||
? {
|
||||
capturedOutput: {
|
||||
stdout: "",
|
||||
stderr: cause.snapshot.stderr.text,
|
||||
truncated:
|
||||
cause.snapshot.stdout.observedBytes > 0 ||
|
||||
(cause.snapshot.diagnosticTruncated ?? false),
|
||||
exit_code: cause.snapshot.exitCode ?? null,
|
||||
signal: cause.snapshot.signal ?? null,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(cause instanceof OwnedCommandFailure && cause.cleanupFailure !== null
|
||||
? {
|
||||
cleanup: {
|
||||
reason: cause.cleanupFailure,
|
||||
resources: cause.resources,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
if (
|
||||
signal?.aborted ||
|
||||
(cause instanceof OwnedCommandFailure && cause.reason === "cancelled")
|
||||
)
|
||||
throw new AnalysisCancelledError(operation, details);
|
||||
if (
|
||||
cause instanceof OwnedCommandFailure &&
|
||||
cause.snapshot?.memoryLimitReached === true
|
||||
)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
"The owned Windows tool tree reached its enforced committed-memory limit.",
|
||||
{
|
||||
process_memory_limit_bytes:
|
||||
options.nativeBound?.memoryLimitBytes ?? null,
|
||||
},
|
||||
details,
|
||||
);
|
||||
if (
|
||||
cause instanceof OwnedCommandFailure &&
|
||||
(cause.snapshot?.signal === "SIGXCPU" ||
|
||||
cause.snapshot?.signal === "SIGXFSZ")
|
||||
)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
cause.snapshot.signal === "SIGXCPU" ? "cpu" : "file-size",
|
||||
`Producer terminated with ${cause.snapshot.signal}; its exact cause is not independently established.`,
|
||||
null,
|
||||
details,
|
||||
);
|
||||
if (cause instanceof OwnedCommandFailure && cause.reason === "timeout")
|
||||
throw new AnalysisTimeoutError(operation, limits.timeoutMs, details);
|
||||
if (cause instanceof OwnedCommandFailure && cause.reason === "output-limit")
|
||||
throw new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
"Tool output exceeded its complete-output budget",
|
||||
{ max_output_bytes: limits.maxOutputBytes },
|
||||
details,
|
||||
);
|
||||
if (
|
||||
cause instanceof WindowsBatchCommandError ||
|
||||
(cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "ENOENT" || cause.code === "EACCES"))
|
||||
)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"pcap",
|
||||
operation,
|
||||
`Cannot run selected tool ${command}: ${cause.message}`,
|
||||
details,
|
||||
);
|
||||
const diagnostic =
|
||||
cause instanceof OwnedCommandFailure
|
||||
? cause.snapshot?.stderr.text.trim() || cause.message
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: String(cause);
|
||||
if (options.inputPath === undefined)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"pcap",
|
||||
operation,
|
||||
`The selected tool ${command} cannot report its version: ${diagnostic}`,
|
||||
details,
|
||||
);
|
||||
if (
|
||||
options.inputPath !== undefined &&
|
||||
/not a capture file|file.*isn't a capture file|file format.*not supported/iu.test(
|
||||
diagnostic,
|
||||
)
|
||||
)
|
||||
throw new AnalysisUnsupportedTargetError(
|
||||
operation,
|
||||
options.inputPath,
|
||||
diagnostic,
|
||||
details,
|
||||
);
|
||||
throw new AnalysisProtocolError(
|
||||
`Packet capture tool ${command} failed: ${diagnostic}`,
|
||||
details,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,170 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
CAPINFOS_COMMAND_ENV,
|
||||
TSHARK_COMMAND_ENV,
|
||||
resolvePcapTools,
|
||||
} from "./PcapConfiguration.js";
|
||||
import { parseCapinfosOutput, parseTsharkJsonOutput } from "./PcapOutput.js";
|
||||
|
||||
describe("resolvePcapTools", () => {
|
||||
it("prefers absolute environment paths for both tools", () => {
|
||||
expect(
|
||||
resolvePcapTools({
|
||||
[TSHARK_COMMAND_ENV]: "/usr/bin/tshark",
|
||||
[CAPINFOS_COMMAND_ENV]: "/usr/bin/capinfos",
|
||||
}),
|
||||
).toEqual({
|
||||
tshark: { command: "/usr/bin/tshark", source: "environment" },
|
||||
capinfos: { command: "/usr/bin/capinfos", source: "environment" },
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to PATH resolution without the environment keys", () => {
|
||||
expect(resolvePcapTools({})).toEqual({
|
||||
tshark: { command: "tshark", source: "path" },
|
||||
capinfos: { command: "capinfos", source: "path" },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a relative tshark path explicitly", () => {
|
||||
expect(() =>
|
||||
resolvePcapTools({ [TSHARK_COMMAND_ENV]: "bin/tshark" }),
|
||||
).toThrow(/must be an absolute path/u);
|
||||
});
|
||||
|
||||
it("rejects a relative capinfos path explicitly", () => {
|
||||
expect(() =>
|
||||
resolvePcapTools({ [CAPINFOS_COMMAND_ENV]: "capinfos" }),
|
||||
).toThrow(/must be an absolute path/u);
|
||||
});
|
||||
});
|
||||
|
||||
const REAL_CAPINFOS = [
|
||||
"File name: /work/rich-capture.pcap",
|
||||
"File type: Wireshark/tcpdump/... - pcap",
|
||||
"File encapsulation: Linux cooked-mode capture v2",
|
||||
"Packet size limit: file hdr: 262144 bytes",
|
||||
"Number of packets: 50",
|
||||
"File size: 23279 bytes",
|
||||
"Capture duration: 0.373473 seconds",
|
||||
"Earliest packet time: 2026-10-11 14:13:40.608505",
|
||||
"Latest packet time: 2026-10-11 14:13:40.981978",
|
||||
"SHA256: c94f94742b3288b9a979711509ed5eab3028576301f8938319de3c22a6f5c40b",
|
||||
].join("\n");
|
||||
|
||||
describe("parseCapinfosOutput", () => {
|
||||
it("projects metadata from real capinfos output", () => {
|
||||
expect(parseCapinfosOutput(REAL_CAPINFOS)).toEqual({
|
||||
fileType: "Wireshark/tcpdump/... - pcap",
|
||||
encapsulation: "Linux cooked-mode capture v2",
|
||||
packetCount: 50,
|
||||
captureStart: "2026-10-11 14:13:40.608505",
|
||||
captureEnd: "2026-10-11 14:13:40.981978",
|
||||
captureDurationSeconds: 0.373473,
|
||||
snapshotLength: 262144,
|
||||
sha256:
|
||||
"c94f94742b3288b9a979711509ed5eab3028576301f8938319de3c22a6f5c40b",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects empty metadata rather than reporting complete unknown facts", () => {
|
||||
expect(() => parseCapinfosOutput("")).toThrow(/machine-readable/u);
|
||||
});
|
||||
});
|
||||
|
||||
const REAL_TSHARK_JSON = JSON.stringify([
|
||||
{
|
||||
_source: {
|
||||
layers: {
|
||||
"frame.number": ["1"],
|
||||
"frame.protocols": ["sll:ethertype:ip:udp:dns"],
|
||||
"ip.src": ["192.168.1.1"],
|
||||
"ip.dst": ["8.8.8.8"],
|
||||
"dns.qry.name": ["example.com"],
|
||||
"dns.flags.response": ["1"],
|
||||
"dns.a": ["93.184.216.34"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
_source: {
|
||||
layers: {
|
||||
"frame.number": ["2"],
|
||||
"frame.protocols": ["sll:ethertype:ip:tcp:tls"],
|
||||
"ip.src": ["192.168.1.1"],
|
||||
"ip.dst": ["93.184.216.34"],
|
||||
"tls.handshake.extensions_server_name": ["example.com"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
_source: {
|
||||
layers: {
|
||||
"frame.number": ["3"],
|
||||
"frame.protocols": ["sll:ethertype:ip:tcp:http"],
|
||||
"ip.src": ["192.168.1.1"],
|
||||
"ip.dst": ["93.184.216.34"],
|
||||
"http.request.full_uri": ["http://example.com/page"],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
describe("parseTsharkJsonOutput", () => {
|
||||
it("projects endpoints, DNS, TLS SNI, protocols, and HTTP URIs", async () => {
|
||||
const result = await parseTsharkJsonOutput(REAL_TSHARK_JSON);
|
||||
expect(result.endpoints).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ address: "192.168.1.1", port: null, packet_count: 3 },
|
||||
{ address: "8.8.8.8", port: null, packet_count: 1 },
|
||||
{ address: "93.184.216.34", port: null, packet_count: 2 },
|
||||
]),
|
||||
);
|
||||
expect(result.dnsQueries).toEqual([
|
||||
{
|
||||
query: "example.com",
|
||||
response_addresses: ["93.184.216.34"],
|
||||
response_address_count: 1,
|
||||
},
|
||||
]);
|
||||
expect(result.tlsSniValues).toEqual(["example.com"]);
|
||||
expect(result.httpRequestUris).toEqual(["http://example.com/page"]);
|
||||
expect(result.protocolDistribution).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ protocol: "sll:ethertype:ip:udp:dns", packet_count: 1 },
|
||||
{ protocol: "sll:ethertype:ip:tcp:tls", packet_count: 1 },
|
||||
{ protocol: "sll:ethertype:ip:tcp:http", packet_count: 1 },
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("retains every endpoint within the aggregate resource budget", async () => {
|
||||
const packets = Array.from({ length: 10 }, (_, index) => ({
|
||||
_source: {
|
||||
layers: {
|
||||
"frame.number": [String(index + 1)],
|
||||
"frame.protocols": ["ip:tcp"],
|
||||
"ip.src": [`10.0.0.${index}`],
|
||||
"ip.dst": ["10.0.1.1"],
|
||||
},
|
||||
},
|
||||
}));
|
||||
const result = await parseTsharkJsonOutput(JSON.stringify(packets));
|
||||
expect(result.endpoints).toHaveLength(11);
|
||||
expect(result.endpointCount).toBe(11); // 10 src + 1 dst
|
||||
});
|
||||
|
||||
it.each([
|
||||
"",
|
||||
"not json",
|
||||
"{}",
|
||||
"null",
|
||||
"[null]",
|
||||
'[{"_source":{"layers":{"ip.src":[3]}}}]',
|
||||
])("rejects malformed producer output %s", async (text) => {
|
||||
await expect(parseTsharkJsonOutput(text)).rejects.toMatchObject({
|
||||
_tag: "AnalysisProtocolError",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
import type { ProviderAvailability } from "../application/AnalysisProvider.js";
|
||||
import type { ProviderRejectionCode } from "../contracts/providerSelection.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
|
||||
/** Environment keys selecting the caller's tshark and capinfos binaries. */
|
||||
export const TSHARK_COMMAND_ENV = "REA_TSHARK_COMMAND";
|
||||
export const CAPINFOS_COMMAND_ENV = "REA_CAPINFOS_COMMAND";
|
||||
|
||||
/** How each tool was selected for this provider instance. */
|
||||
export interface PcapToolSelection {
|
||||
readonly tshark: { command: string; source: "environment" | "path" };
|
||||
readonly capinfos: { command: string; source: "environment" | "path" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the caller-supplied tshark and capinfos binaries. Each accepts an
|
||||
* absolute environment path or falls back to PATH resolution, mirroring the
|
||||
* mitmdump pattern. REA never installs the Wireshark suite.
|
||||
*/
|
||||
export const resolvePcapTools = (
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
): PcapToolSelection => {
|
||||
const tsharkEnv = environment[TSHARK_COMMAND_ENV];
|
||||
const capinfosEnv = environment[CAPINFOS_COMMAND_ENV];
|
||||
if (
|
||||
tsharkEnv !== undefined &&
|
||||
tsharkEnv.trim() !== "" &&
|
||||
!isAbsolute(tsharkEnv)
|
||||
)
|
||||
throw new PcapConfigurationFailure(
|
||||
"tshark_not_absolute",
|
||||
`${TSHARK_COMMAND_ENV} must be an absolute path to the tshark binary`,
|
||||
{ configured: tsharkEnv },
|
||||
);
|
||||
if (
|
||||
capinfosEnv !== undefined &&
|
||||
capinfosEnv.trim() !== "" &&
|
||||
!isAbsolute(capinfosEnv)
|
||||
)
|
||||
throw new PcapConfigurationFailure(
|
||||
"capinfos_not_absolute",
|
||||
`${CAPINFOS_COMMAND_ENV} must be an absolute path to the capinfos binary`,
|
||||
{ configured: capinfosEnv },
|
||||
);
|
||||
return {
|
||||
tshark: {
|
||||
command:
|
||||
tsharkEnv === undefined || tsharkEnv.trim() === ""
|
||||
? "tshark"
|
||||
: tsharkEnv,
|
||||
source:
|
||||
tsharkEnv === undefined || tsharkEnv.trim() === ""
|
||||
? "path"
|
||||
: "environment",
|
||||
},
|
||||
capinfos: {
|
||||
command:
|
||||
capinfosEnv === undefined || capinfosEnv.trim() === ""
|
||||
? "capinfos"
|
||||
: capinfosEnv,
|
||||
source:
|
||||
capinfosEnv === undefined || capinfosEnv.trim() === ""
|
||||
? "path"
|
||||
: "environment",
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export type PcapConfigurationFailureCode =
|
||||
| "tshark_not_absolute"
|
||||
| "capinfos_not_absolute"
|
||||
| "tshark_missing"
|
||||
| "capinfos_missing"
|
||||
| "tshark_version_unresolved"
|
||||
| "capinfos_version_unresolved"
|
||||
| "tshark_version_unsupported"
|
||||
| "capinfos_version_unsupported";
|
||||
|
||||
export class PcapConfigurationFailure extends Error {
|
||||
constructor(
|
||||
readonly code: PcapConfigurationFailureCode,
|
||||
message: string,
|
||||
readonly diagnostics: Readonly<Record<string, JsonValue>> = {},
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(message, options);
|
||||
}
|
||||
}
|
||||
|
||||
/** Recognize the selected Wireshark tool's version banner. */
|
||||
const parseVersion = (
|
||||
stdout: string,
|
||||
tool: "tshark" | "capinfos",
|
||||
): string | null => {
|
||||
const line = stdout
|
||||
.split(/\r?\n/u)
|
||||
.map((entry) => entry.trim())
|
||||
.find((entry) => entry !== "");
|
||||
const parsed =
|
||||
line === undefined
|
||||
? null
|
||||
: new RegExp(`^${tool} \\(Wireshark\\) (\\d+)\\.\\d+\\.\\d+`, "iu").exec(
|
||||
line,
|
||||
);
|
||||
if (parsed === null || line === undefined) return null;
|
||||
if (parsed[1] !== "4")
|
||||
throw new PcapConfigurationFailure(
|
||||
`${tool}_version_unsupported`,
|
||||
"Packet summary inspection currently requires Wireshark 4.x tools; select an installation with the admitted output profile.",
|
||||
{ version: line },
|
||||
);
|
||||
return line;
|
||||
};
|
||||
|
||||
export interface PcapClientIdentity {
|
||||
readonly tsharkVersion: string | null;
|
||||
readonly capinfosVersion: string | null;
|
||||
}
|
||||
|
||||
/** Probe both tools without reading any capture file. */
|
||||
export const inspectPcapClient = async (
|
||||
selection: PcapToolSelection,
|
||||
probe: (command: string) => Promise<string>,
|
||||
): Promise<PcapClientIdentity> => ({
|
||||
tsharkVersion: parseVersion(await probe(selection.tshark.command), "tshark"),
|
||||
capinfosVersion: parseVersion(
|
||||
await probe(selection.capinfos.command),
|
||||
"capinfos",
|
||||
),
|
||||
});
|
||||
|
||||
/** Availability in the shape shared by every provider. */
|
||||
const rejectionCodeOf = (
|
||||
code: PcapConfigurationFailureCode,
|
||||
): ProviderRejectionCode =>
|
||||
code.includes("missing")
|
||||
? "executable_missing"
|
||||
: code.includes("unsupported")
|
||||
? "unsupported_version"
|
||||
: code.includes("not_absolute")
|
||||
? "not_configured"
|
||||
: "version_unresolved";
|
||||
|
||||
export const pcapConfigurationAvailability = (
|
||||
cause: PcapConfigurationFailure,
|
||||
): ProviderAvailability => ({
|
||||
status: "unavailable",
|
||||
code: rejectionCodeOf(cause.code),
|
||||
reason: cause.message,
|
||||
diagnostics: { ...cause.diagnostics },
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { access, realpath } from "node:fs/promises";
|
||||
import { constants } from "node:fs";
|
||||
import { isAbsolute } from "node:path";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.js";
|
||||
import type { ArtifactAnalysisResources } from "../process/ArtifactAnalysisResources.js";
|
||||
import type { runPcapCommand } from "./PcapCommand.js";
|
||||
|
||||
/** Own native capture admission and the exact enforced resource profile. */
|
||||
export const preparePcapNativeBound = async (
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
resources: ArtifactAnalysisResources,
|
||||
): Promise<{
|
||||
nativeBound: NonNullable<Parameters<typeof runPcapCommand>[0]["nativeBound"]>;
|
||||
limitations: readonly string[];
|
||||
}> => {
|
||||
if (process.platform === "win32") {
|
||||
return {
|
||||
nativeBound: { memoryLimitBytes: 1024 ** 3 },
|
||||
limitations: [
|
||||
"Each owned Windows tool tree has a 1 GiB Job Object committed-memory limit; this is not a machine-wide quota.",
|
||||
],
|
||||
};
|
||||
}
|
||||
if (process.platform !== "linux")
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"pcap",
|
||||
"inspect_pcap_capture",
|
||||
"Packet summaries require an enforceable native memory bound: Linux with util-linux prlimit, or Windows with owned Job Objects. This host's capture boundary remains unsupported.",
|
||||
);
|
||||
const configured =
|
||||
environment.REA_TSHARK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
|
||||
try {
|
||||
if (!isAbsolute(configured))
|
||||
throw new Error("REA_TSHARK_PRLIMIT_COMMAND must be absolute.");
|
||||
const limiter = await realpath(configured);
|
||||
await access(limiter, constants.X_OK);
|
||||
const limits = await resources.readLimits({
|
||||
address_space_bytes: 1024 ** 3,
|
||||
file_bytes: 64 * 1024 ** 2,
|
||||
cpu_seconds: 300,
|
||||
});
|
||||
const nativeBound = {
|
||||
limiter: {
|
||||
command: limiter,
|
||||
arguments: [
|
||||
`--as=${limits.address_space_bytes}:${limits.address_space_bytes}`,
|
||||
`--fsize=${limits.file_bytes}:${limits.file_bytes}`,
|
||||
`--cpu=${limits.cpu_seconds}:${limits.cpu_seconds}`,
|
||||
"--core=0:0",
|
||||
"--",
|
||||
],
|
||||
},
|
||||
};
|
||||
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 (cause instanceof AnalysisError) throw cause;
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"pcap",
|
||||
"inspect_pcap_capture",
|
||||
"Cannot establish the selected Linux resource limiter before processing capture bytes.",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,149 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { parseCapinfosOutput, parseTsharkJsonOutput } from "./PcapOutput.js";
|
||||
|
||||
const capture = (layers: ReadonlyArray<Record<string, string[]>>) =>
|
||||
JSON.stringify(
|
||||
layers.map((fields, index) => ({
|
||||
_source: {
|
||||
layers: {
|
||||
"frame.number": [String(index + 1)],
|
||||
"frame.protocols": ["ip:udp:dns"],
|
||||
...fields,
|
||||
},
|
||||
},
|
||||
})),
|
||||
);
|
||||
|
||||
it("binds interleaved DNS answers to the question in their response packet", async () => {
|
||||
const result = await parseTsharkJsonOutput(
|
||||
capture([
|
||||
{ "dns.qry.name": ["alpha.example"], "dns.flags.response": ["False"] },
|
||||
{ "dns.qry.name": ["beta.example"], "dns.flags.response": ["False"] },
|
||||
{
|
||||
"dns.qry.name": ["alpha.example"],
|
||||
"dns.flags.response": ["True"],
|
||||
"dns.a": ["192.0.2.10"],
|
||||
},
|
||||
{
|
||||
"dns.qry.name": ["beta.example"],
|
||||
"dns.flags.response": ["True"],
|
||||
"dns.a": ["192.0.2.20"],
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(result.dnsQueries).toEqual([
|
||||
{
|
||||
query: "alpha.example",
|
||||
response_addresses: ["192.0.2.10"],
|
||||
response_address_count: 1,
|
||||
},
|
||||
{
|
||||
query: "beta.example",
|
||||
response_addresses: ["192.0.2.20"],
|
||||
response_address_count: 1,
|
||||
},
|
||||
]);
|
||||
expect(result.partial).toBe(false);
|
||||
});
|
||||
|
||||
it("retains unassignable DNS addresses without inventing a query relationship", async () => {
|
||||
const result = await parseTsharkJsonOutput(
|
||||
capture([
|
||||
{
|
||||
"dns.qry.name": ["alpha.example", "beta.example"],
|
||||
"dns.flags.response": ["True"],
|
||||
"dns.a": ["192.0.2.9"],
|
||||
},
|
||||
{ "dns.flags.response": ["True"], "dns.aaaa": ["2001:db8::9"] },
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
result.dnsQueries.every((query) => query.response_addresses.length === 0),
|
||||
).toBe(true);
|
||||
expect(result.unattributedDnsAddresses).toEqual(["192.0.2.9", "2001:db8::9"]);
|
||||
expect(result.unattributedDnsPackets).toBe(2);
|
||||
expect(result.partial).toBe(true);
|
||||
});
|
||||
|
||||
it("counts IPv6 endpoints once per packet and preserves every examined fact", async () => {
|
||||
const packets = Array.from({ length: 51 }, (_, index) => ({
|
||||
"ipv6.src": ["2001:db8::1"],
|
||||
"ipv6.dst": ["2001:db8::1"],
|
||||
"tls.handshake.extensions_server_name": [`host${String(index)}.example`],
|
||||
"frame.protocols": [`ipv6:protocol${String(index)}`],
|
||||
}));
|
||||
const result = await parseTsharkJsonOutput(capture(packets));
|
||||
expect(result.endpoints).toEqual([
|
||||
{ address: "2001:db8::1", port: null, packet_count: 51 },
|
||||
]);
|
||||
expect(result.tlsSniCount).toBe(51);
|
||||
expect(result.tlsSniValues).toHaveLength(51);
|
||||
expect(result.protocolCount).toBe(51);
|
||||
expect(result.protocolDistribution).toHaveLength(51);
|
||||
expect(result.partial).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves all DNS addresses and their exact examined count", async () => {
|
||||
const result = await parseTsharkJsonOutput(
|
||||
capture(
|
||||
Array.from({ length: 101 }, (_, index) => ({
|
||||
"dns.qry.name": ["rotating.example"],
|
||||
"dns.flags.response": ["True"],
|
||||
"dns.a": [`192.0.2.${String(index)}`],
|
||||
})),
|
||||
),
|
||||
);
|
||||
expect(result.dnsQueries[0]?.response_addresses).toHaveLength(101);
|
||||
expect(result.dnsQueries[0]?.response_address_count).toBe(101);
|
||||
expect(result.partial).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts exact machine packet counts and rejects scaled human counts", () => {
|
||||
const prefix =
|
||||
"File type: pcap\nFile encapsulation: Ethernet\nNumber of packets: ";
|
||||
expect(parseCapinfosOutput(`${prefix}20010`).packetCount).toBe(20010);
|
||||
expect(() => parseCapinfosOutput(`${prefix}20 k`)).toThrow(
|
||||
/machine-readable/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("excludes transport credentials without normalizing observed URL bytes", async () => {
|
||||
const result = await parseTsharkJsonOutput(
|
||||
capture([
|
||||
{
|
||||
"http.request.full_uri": [
|
||||
"http://user:password@Example.com/a/../b?token=local-evidence#keep",
|
||||
],
|
||||
},
|
||||
{
|
||||
"http.request.full_uri": [
|
||||
"http://other:secret@Example.com/a/../b?token=local-evidence#keep",
|
||||
],
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(result.httpRequestUris).toEqual([
|
||||
"http://Example.com/a/../b?token=local-evidence#keep",
|
||||
]);
|
||||
expect(result.httpRequestUriCount).toBe(2);
|
||||
expect(result.httpUriRedactionCount).toBe(2);
|
||||
expect(result.partial).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses dense JSON before its expanded graph exceeds the decoding budget", async () => {
|
||||
await expect(
|
||||
parseTsharkJsonOutput(`[${"{},".repeat(600_000)}{}]`),
|
||||
).rejects.toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
});
|
||||
});
|
||||
|
||||
it("permits cancellation while validating and aggregating producer output", async () => {
|
||||
const controller = new AbortController();
|
||||
const result = parseTsharkJsonOutput(
|
||||
capture([{ "ip.src": ["192.0.2.1"] }]),
|
||||
controller.signal,
|
||||
);
|
||||
controller.abort(new Error("stopped"));
|
||||
await expect(result).rejects.toThrow("stopped");
|
||||
});
|
||||
@@ -0,0 +1,315 @@
|
||||
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
|
||||
import {
|
||||
AnalysisProtocolError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { parseRecordedTransportUrl } from "../domain/recordedTransportUrl.js";
|
||||
|
||||
const OPERATION = "inspect_pcap_capture";
|
||||
/** Bounds JSON decoding plus its expanded object graph before JSON.parse. */
|
||||
export const TSHARK_JSON_MAX_BYTES = 8 * 1024 * 1024;
|
||||
const MAX_RETAINED_BYTES = 16 * 1024 * 1024;
|
||||
const MAX_DECODED_BYTES = 128 * 1024 * 1024;
|
||||
|
||||
const protocolFailure = (reason: string): never => {
|
||||
throw new AnalysisProtocolError(`Invalid packet-capture output: ${reason}`);
|
||||
};
|
||||
|
||||
export interface CapinfosMetadata {
|
||||
readonly fileType: string;
|
||||
readonly encapsulation: string;
|
||||
readonly packetCount: number;
|
||||
readonly captureStart: string | null;
|
||||
readonly captureEnd: string | null;
|
||||
readonly captureDurationSeconds: number | null;
|
||||
readonly snapshotLength: number | null;
|
||||
readonly sha256: string | null;
|
||||
}
|
||||
|
||||
/** capinfos -M with a C locale provides exact numbers instead of "20 k". */
|
||||
export const parseCapinfosOutput = (stdout: string): CapinfosMetadata => {
|
||||
const lines = new Map<string, string>();
|
||||
for (const line of stdout.split(/\r?\n/u)) {
|
||||
const at = line.indexOf(":");
|
||||
if (at >= 0 && !/^\s/u.test(line))
|
||||
lines.set(line.slice(0, at), line.slice(at + 1).trim());
|
||||
}
|
||||
const fileType = lines.get("File type");
|
||||
const encapsulation = lines.get("File encapsulation");
|
||||
const countText = lines.get("Number of packets");
|
||||
if (
|
||||
!fileType ||
|
||||
!encapsulation ||
|
||||
countText === undefined ||
|
||||
!/^\d+$/u.test(countText)
|
||||
)
|
||||
return protocolFailure(
|
||||
"capinfos did not provide machine-readable type, encapsulation and packet count",
|
||||
);
|
||||
const packetCount = Number(countText);
|
||||
if (!Number.isSafeInteger(packetCount))
|
||||
return protocolFailure("packet count is not representable");
|
||||
const durationText = lines.get("Capture duration");
|
||||
const duration =
|
||||
durationText === undefined
|
||||
? null
|
||||
: /^(\d+(?:\.\d+)?)(?:\s+seconds?)?$/u.exec(durationText);
|
||||
const snapshot = /^file hdr:\s*(\d+) bytes$/u.exec(
|
||||
lines.get("Packet size limit") ?? "",
|
||||
);
|
||||
const snapshotLength = snapshot === null ? null : Number(snapshot[1]);
|
||||
const sha256 = lines.get("SHA256") ?? null;
|
||||
if (sha256 !== null && !/^[0-9a-f]{64}$/u.test(sha256))
|
||||
return protocolFailure("capinfos SHA256 is malformed");
|
||||
return {
|
||||
fileType,
|
||||
encapsulation,
|
||||
packetCount,
|
||||
captureStart: lines.get("Earliest packet time") ?? null,
|
||||
captureEnd: lines.get("Latest packet time") ?? null,
|
||||
captureDurationSeconds: duration === null ? null : Number(duration[1]),
|
||||
snapshotLength:
|
||||
snapshotLength !== null &&
|
||||
Number.isSafeInteger(snapshotLength) &&
|
||||
snapshotLength > 0
|
||||
? snapshotLength
|
||||
: null,
|
||||
sha256,
|
||||
};
|
||||
};
|
||||
|
||||
export interface TsharkFields {
|
||||
readonly endpoints: { address: string; port: null; packet_count: number }[];
|
||||
readonly endpointCount: number;
|
||||
readonly dnsQueries: {
|
||||
query: string;
|
||||
response_addresses: string[];
|
||||
response_address_count: number;
|
||||
}[];
|
||||
readonly dnsQueryCount: number;
|
||||
readonly tlsSniValues: string[];
|
||||
readonly tlsSniCount: number;
|
||||
readonly protocolDistribution: { protocol: string; packet_count: number }[];
|
||||
readonly protocolCount: number;
|
||||
readonly httpRequestUris: string[];
|
||||
readonly httpRequestUriCount: number;
|
||||
readonly httpUriRedactionCount: number;
|
||||
readonly unattributedDnsAddresses: string[];
|
||||
readonly unattributedDnsAddressCount: number;
|
||||
readonly unattributedDnsPackets: number;
|
||||
readonly packetCount: number;
|
||||
readonly partial: boolean;
|
||||
}
|
||||
|
||||
const object = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
/** Validate the fixed JSON field representation before retaining aggregate facts. */
|
||||
export const parseTsharkJsonOutput = async (
|
||||
stdout: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<TsharkFields> => {
|
||||
signal?.throwIfAborted();
|
||||
if (Buffer.byteLength(stdout) > TSHARK_JSON_MAX_BYTES)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"memory",
|
||||
"tshark JSON exceeds the bounded decoding budget",
|
||||
{ max_json_bytes: TSHARK_JSON_MAX_BYTES },
|
||||
);
|
||||
// The selected-field protocol has five container levels. Reject deeper
|
||||
// graphs before materializing them; quoted brackets are string data.
|
||||
let depth = 0,
|
||||
quoted = false,
|
||||
escaped = false;
|
||||
let decodedBytes = stdout.length * 2;
|
||||
for (let index = 0; index < stdout.length; index += 1) {
|
||||
if (index % 65536 === 0) {
|
||||
await yieldToEventLoop();
|
||||
signal?.throwIfAborted();
|
||||
}
|
||||
const char = stdout[index];
|
||||
if (quoted) {
|
||||
if (escaped) escaped = false;
|
||||
else if (char === "\\") escaped = true;
|
||||
else if (char === '"') quoted = false;
|
||||
} else if (char === '"') {
|
||||
quoted = true;
|
||||
decodedBytes += 64;
|
||||
} else if (char === "{" || char === "[") {
|
||||
decodedBytes += 128;
|
||||
if (++depth > 5) protocolFailure("unexpected JSON nesting");
|
||||
} else if (char === "}" || char === "]") depth -= 1;
|
||||
else if (char === ":" || char === ",") decodedBytes += 128;
|
||||
if (decodedBytes > MAX_DECODED_BYTES)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"memory",
|
||||
"tshark JSON expansion exceeds the decoding budget",
|
||||
{ max_decoded_bytes: MAX_DECODED_BYTES },
|
||||
);
|
||||
}
|
||||
let packets: unknown;
|
||||
try {
|
||||
packets = JSON.parse(stdout) as unknown;
|
||||
} catch (cause) {
|
||||
throw new AnalysisProtocolError("tshark emitted malformed JSON", { cause });
|
||||
}
|
||||
if (!Array.isArray(packets))
|
||||
return protocolFailure("tshark packet root must be an array");
|
||||
const endpoints = new Map<string, number>();
|
||||
const dns = new Map<string, Set<string>>();
|
||||
const sni = new Set<string>();
|
||||
const protocols = new Map<string, number>();
|
||||
const uris = new Set<string>();
|
||||
const observedUris = new Set<string>();
|
||||
let uriRedactions = 0;
|
||||
const unattributed = new Set<string>();
|
||||
let unattributedPackets = 0;
|
||||
let retainedBytes = 0;
|
||||
const charge = (value: string): void => {
|
||||
retainedBytes += 192 + 2 * Buffer.byteLength(value);
|
||||
if (retainedBytes > MAX_RETAINED_BYTES)
|
||||
throw new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"memory",
|
||||
"Packet inventory exceeds the retained-fact budget",
|
||||
{ max_retained_bytes: MAX_RETAINED_BYTES },
|
||||
);
|
||||
};
|
||||
const add = (set: Set<string>, value: string): void => {
|
||||
if (!set.has(value)) {
|
||||
charge(value);
|
||||
set.add(value);
|
||||
}
|
||||
};
|
||||
for (let index = 0; index < packets.length; index += 1) {
|
||||
if (index % 256 === 0) {
|
||||
await yieldToEventLoop();
|
||||
signal?.throwIfAborted();
|
||||
}
|
||||
const packet: unknown = packets[index];
|
||||
if (
|
||||
!object(packet) ||
|
||||
!object(packet._source) ||
|
||||
!object(packet._source.layers)
|
||||
)
|
||||
return protocolFailure(
|
||||
`packet ${String(index + 1)} lacks _source.layers`,
|
||||
);
|
||||
const layers = packet._source.layers;
|
||||
for (const [key, value] of Object.entries(layers))
|
||||
if (
|
||||
!Array.isArray(value) ||
|
||||
!value.every((item) => typeof item === "string")
|
||||
)
|
||||
return protocolFailure(
|
||||
`packet ${String(index + 1)} field ${key} must be an array of strings`,
|
||||
);
|
||||
const field = (name: string): readonly string[] =>
|
||||
(layers[name] as string[] | undefined) ?? [];
|
||||
const frame = field("frame.number");
|
||||
if (
|
||||
frame.length !== 1 ||
|
||||
!/^\d+$/u.test(frame[0]!) ||
|
||||
Number(frame[0]) !== index + 1
|
||||
)
|
||||
return protocolFailure(
|
||||
"frame inventory is missing, duplicated or out of order",
|
||||
);
|
||||
if (
|
||||
field("frame.protocols").length !== 1 ||
|
||||
field("frame.protocols")[0] === ""
|
||||
)
|
||||
return protocolFailure(
|
||||
"packet protocol inventory is missing or ambiguous",
|
||||
);
|
||||
// Count one occurrence per packet even for loopback or nested IP layers.
|
||||
for (const address of new Set([
|
||||
...field("ip.src"),
|
||||
...field("ip.dst"),
|
||||
...field("ipv6.src"),
|
||||
...field("ipv6.dst"),
|
||||
])) {
|
||||
if (address === "") continue;
|
||||
if (!endpoints.has(address)) charge(address);
|
||||
endpoints.set(address, (endpoints.get(address) ?? 0) + 1);
|
||||
}
|
||||
const questions = new Set(
|
||||
field("dns.qry.name").filter((value) => value !== ""),
|
||||
);
|
||||
for (const question of questions)
|
||||
if (!dns.has(question)) {
|
||||
charge(question);
|
||||
dns.set(question, new Set());
|
||||
}
|
||||
const addresses = [...field("dns.a"), ...field("dns.aaaa")].filter(
|
||||
(value) => value !== "",
|
||||
);
|
||||
const response = field("dns.flags.response");
|
||||
if (addresses.length > 0) {
|
||||
if (
|
||||
questions.size === 1 &&
|
||||
response.length > 0 &&
|
||||
response.every((value) => value === "True" || value === "1")
|
||||
) {
|
||||
const values = dns.get(questions.values().next().value!)!;
|
||||
for (const address of addresses) add(values, address);
|
||||
} else {
|
||||
unattributedPackets += 1;
|
||||
for (const address of addresses) add(unattributed, address);
|
||||
}
|
||||
}
|
||||
for (const value of field("tls.handshake.extensions_server_name"))
|
||||
if (value !== "") add(sni, value);
|
||||
for (const value of new Set(field("frame.protocols"))) {
|
||||
if (value === "") continue;
|
||||
if (!protocols.has(value)) charge(value);
|
||||
protocols.set(value, (protocols.get(value) ?? 0) + 1);
|
||||
}
|
||||
for (const value of field("http.request.full_uri")) {
|
||||
if (value === "" || observedUris.has(value)) continue;
|
||||
add(observedUris, value);
|
||||
const { credentials } = parseRecordedTransportUrl(value);
|
||||
if (credentials !== null) uriRedactions += 1;
|
||||
if (credentials === "ambiguous") continue;
|
||||
add(
|
||||
uris,
|
||||
credentials === null
|
||||
? value
|
||||
: value.slice(0, credentials.start) + value.slice(credentials.end),
|
||||
);
|
||||
}
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
return {
|
||||
endpoints: [...endpoints]
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.map(([address, packet_count]) => ({
|
||||
address,
|
||||
port: null,
|
||||
packet_count,
|
||||
})),
|
||||
endpointCount: endpoints.size,
|
||||
dnsQueries: [...dns].map(([query, addresses]) => ({
|
||||
query,
|
||||
response_addresses: [...addresses],
|
||||
response_address_count: addresses.size,
|
||||
})),
|
||||
dnsQueryCount: dns.size,
|
||||
tlsSniValues: [...sni],
|
||||
tlsSniCount: sni.size,
|
||||
protocolDistribution: [...protocols]
|
||||
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
||||
.map(([protocol, packet_count]) => ({ protocol, packet_count })),
|
||||
protocolCount: protocols.size,
|
||||
httpRequestUris: [...uris],
|
||||
httpRequestUriCount: observedUris.size,
|
||||
httpUriRedactionCount: uriRedactions,
|
||||
unattributedDnsAddresses: [...unattributed],
|
||||
unattributedDnsAddressCount: unattributed.size,
|
||||
unattributedDnsPackets: unattributedPackets,
|
||||
packetCount: packets.length,
|
||||
partial: observedUris.size > uris.size || unattributedPackets > 0,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,493 @@
|
||||
import type {
|
||||
ExecutionOptions,
|
||||
ProviderAvailability,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisExecution,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import {
|
||||
pcapResultSchemas,
|
||||
type PcapRequest,
|
||||
type PcapOperation,
|
||||
} from "../domain/pcap/pcapAnalysis.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisProtocolError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ProviderProcessSupervisor } from "../process/ProviderProcess.js";
|
||||
import {
|
||||
PcapConfigurationFailure,
|
||||
inspectPcapClient,
|
||||
resolvePcapTools,
|
||||
pcapConfigurationAvailability,
|
||||
type PcapToolSelection,
|
||||
} from "./PcapConfiguration.js";
|
||||
import {
|
||||
parseCapinfosOutput,
|
||||
parseTsharkJsonOutput,
|
||||
TSHARK_JSON_MAX_BYTES,
|
||||
} from "./PcapOutput.js";
|
||||
import { runPcapCommand, type PcapCommandLimits } from "./PcapCommand.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { createPcapEvidence } from "../domain/pcap/pcapEvidence.js";
|
||||
import { preparePcapNativeBound } from "./PcapNativeBound.js";
|
||||
import { PcapSnapshot } from "./PcapSnapshot.js";
|
||||
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
|
||||
import { ArtifactAnalysisResources } from "../process/ArtifactAnalysisResources.js";
|
||||
import { readLinuxResourceLimits } from "../process/LinuxResourceLimits.js";
|
||||
|
||||
export const PCAP_PROVIDER_IDENTITY = {
|
||||
id: "pcap",
|
||||
name: "Packet capture analysis",
|
||||
version: null,
|
||||
} as const;
|
||||
const FIELDS = [
|
||||
"frame.number",
|
||||
"frame.protocols",
|
||||
"ip.src",
|
||||
"ip.dst",
|
||||
"ipv6.src",
|
||||
"ipv6.dst",
|
||||
"dns.flags.response",
|
||||
"dns.qry.name",
|
||||
"dns.a",
|
||||
"dns.aaaa",
|
||||
"tls.handshake.extensions_server_name",
|
||||
"http.request.full_uri",
|
||||
];
|
||||
|
||||
export interface PcapProviderOptions {
|
||||
readonly environment?: Readonly<Record<string, string | undefined>>;
|
||||
}
|
||||
|
||||
/** Inspect saved captures through bounded, owned tool processes and one stable input copy. */
|
||||
export class PcapProvider {
|
||||
readonly #resources = new ArtifactAnalysisResources(
|
||||
"pcap",
|
||||
"inspect_pcap_capture",
|
||||
readStableArtifact,
|
||||
readLinuxResourceLimits,
|
||||
{
|
||||
message: "A packet summary is already active; retry after it completes.",
|
||||
details: { max_concurrent_inspections: 1 },
|
||||
},
|
||||
);
|
||||
private readonly environment: Readonly<Record<string, string | undefined>>;
|
||||
private readonly snapshots = new Set<PcapSnapshot>();
|
||||
private readonly commands = new Map<
|
||||
ProviderProcessSupervisor,
|
||||
{ snapshot: PcapSnapshot | undefined; resources: readonly string[] }
|
||||
>();
|
||||
|
||||
constructor(options: PcapProviderOptions = {}) {
|
||||
this.environment = options.environment ?? process.env;
|
||||
}
|
||||
|
||||
private run(
|
||||
operation: PcapOperation,
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
limits: PcapCommandLimits,
|
||||
signal: AbortSignal | undefined,
|
||||
snapshot?: PcapSnapshot,
|
||||
inputPath?: string,
|
||||
) {
|
||||
return runPcapCommand({
|
||||
operation,
|
||||
command,
|
||||
arguments: args,
|
||||
limits,
|
||||
signal,
|
||||
environment:
|
||||
snapshot === undefined
|
||||
? this.environment
|
||||
: {
|
||||
...this.environment,
|
||||
WIRESHARK_CONFIG_DIR: snapshot.configurationPath,
|
||||
},
|
||||
...(inputPath === undefined ? {} : { inputPath }),
|
||||
...(inputPath === undefined || this.nativeBound === undefined
|
||||
? {}
|
||||
: { nativeBound: this.nativeBound }),
|
||||
retain: (owner, resources) => {
|
||||
this.commands.set(owner, { snapshot, resources });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private nativeBound: Parameters<typeof runPcapCommand>[0]["nativeBound"];
|
||||
private nativeLimitations: readonly string[] = [];
|
||||
|
||||
private async prepareCaptureBound(): Promise<void> {
|
||||
const prepared = await preparePcapNativeBound(
|
||||
this.environment,
|
||||
this.#resources,
|
||||
);
|
||||
this.nativeBound = prepared.nativeBound;
|
||||
this.nativeLimitations = prepared.limitations;
|
||||
}
|
||||
|
||||
private async client(operation: PcapOperation, signal?: AbortSignal) {
|
||||
const selection = resolvePcapTools(this.environment);
|
||||
const identity = await inspectPcapClient(
|
||||
selection,
|
||||
async (command) =>
|
||||
(
|
||||
await this.run(
|
||||
operation,
|
||||
command,
|
||||
["--version"],
|
||||
{ timeoutMs: 20_000, maxOutputBytes: 64 * 1024 },
|
||||
signal,
|
||||
)
|
||||
).stdout,
|
||||
);
|
||||
for (const [name, version] of [
|
||||
["tshark", identity.tsharkVersion],
|
||||
["capinfos", identity.capinfosVersion],
|
||||
] as const) {
|
||||
if (version === null)
|
||||
throw new PcapConfigurationFailure(
|
||||
`${name}_version_unresolved`,
|
||||
`The selected ${name} command did not report a version. Set REA_${name.toUpperCase()}_COMMAND to its absolute executable path.`,
|
||||
);
|
||||
}
|
||||
return {
|
||||
selection,
|
||||
client: {
|
||||
tshark_command: selection.tshark.command,
|
||||
tshark_source: selection.tshark.source,
|
||||
tshark_version: identity.tsharkVersion,
|
||||
capinfos_command: selection.capinfos.command,
|
||||
capinfos_source: selection.capinfos.source,
|
||||
capinfos_version: identity.capinfosVersion,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async inspectAvailability(
|
||||
signal?: AbortSignal,
|
||||
): Promise<ProviderAvailability> {
|
||||
const result = await this.#resources.run(
|
||||
async () => ok(await this.inspectAvailabilityAdmitted(signal)),
|
||||
signal,
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
return result.value;
|
||||
}
|
||||
|
||||
private async inspectAvailabilityAdmitted(
|
||||
signal?: AbortSignal,
|
||||
): Promise<ProviderAvailability> {
|
||||
try {
|
||||
const { client } = await this.client("inspect_pcap_client", signal);
|
||||
if (process.platform !== "linux" && process.platform !== "win32")
|
||||
return {
|
||||
status: "unavailable",
|
||||
code: "unsupported_host",
|
||||
reason:
|
||||
"No enforceable native memory boundary is available for capture summaries on this host.",
|
||||
diagnostics: client,
|
||||
};
|
||||
await this.prepareCaptureBound();
|
||||
return {
|
||||
status: "available",
|
||||
code: null,
|
||||
reason: null,
|
||||
diagnostics: client,
|
||||
};
|
||||
} catch (cause) {
|
||||
if (signal?.aborted || cause instanceof AnalysisCancelledError)
|
||||
throw new AnalysisCancelledError("inspect_pcap_client", { cause });
|
||||
if (cause instanceof PcapConfigurationFailure)
|
||||
return pcapConfigurationAvailability(cause);
|
||||
return {
|
||||
status: "unavailable",
|
||||
code:
|
||||
cause instanceof AnalysisCapabilityUnavailableError
|
||||
? "executable_missing"
|
||||
: "version_unresolved",
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
diagnostics: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private async discard(
|
||||
snapshot: PcapSnapshot,
|
||||
): Promise<AnalysisError | undefined> {
|
||||
try {
|
||||
if (
|
||||
[...this.commands.values()].some(
|
||||
(command) => command.snapshot === snapshot,
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
"An unreleased command still owns the capture snapshot",
|
||||
);
|
||||
await snapshot.close();
|
||||
this.snapshots.delete(snapshot);
|
||||
return undefined;
|
||||
} catch (cause) {
|
||||
return new ProviderCleanupError(
|
||||
"pcap",
|
||||
[snapshot.path],
|
||||
{ reason: String(cause) },
|
||||
{ operation: "inspect_pcap_capture", cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const failures: unknown[] = [];
|
||||
try {
|
||||
await this.#resources.close();
|
||||
} catch (cause) {
|
||||
failures.push(cause);
|
||||
}
|
||||
for (const owner of this.commands.keys()) {
|
||||
try {
|
||||
const result = await owner.stop();
|
||||
if (result.status === "incomplete") failures.push(result.reason);
|
||||
else if (result.status === "not-owned")
|
||||
failures.push("Command ownership remains unresolved");
|
||||
else this.commands.delete(owner);
|
||||
} catch (cause) {
|
||||
failures.push(cause);
|
||||
}
|
||||
}
|
||||
for (const snapshot of this.snapshots) {
|
||||
const failure = await this.discard(snapshot);
|
||||
if (failure !== undefined) failures.push(failure);
|
||||
}
|
||||
if (failures.length > 0)
|
||||
throw new ProviderCleanupError(
|
||||
"pcap",
|
||||
[...this.snapshots]
|
||||
.map((snapshot) => snapshot.path)
|
||||
.concat(
|
||||
[...this.commands.values()].flatMap((command) => command.resources),
|
||||
),
|
||||
{ reason: "Owned process or snapshot cleanup failed" },
|
||||
{ operation: "pcap.close", cause: new AggregateError(failures) },
|
||||
);
|
||||
}
|
||||
|
||||
async execute(
|
||||
request: PcapRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
return this.#resources.run(
|
||||
() => this.executeAdmitted(request, options),
|
||||
options?.signal,
|
||||
);
|
||||
}
|
||||
|
||||
private async executeAdmitted(
|
||||
request: PcapRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
const signal = options?.signal;
|
||||
let snapshot: PcapSnapshot | undefined;
|
||||
let result: Result<AnalysisExecution, AnalysisError>;
|
||||
try {
|
||||
signal?.throwIfAborted();
|
||||
const { selection, client } = await this.client(
|
||||
request.operation,
|
||||
signal,
|
||||
);
|
||||
const provider = {
|
||||
...PCAP_PROVIDER_IDENTITY,
|
||||
version: client.tshark_version,
|
||||
};
|
||||
if (request.operation === "inspect_pcap_client")
|
||||
result = ok(
|
||||
createAnalysisExecution(
|
||||
pcapResultSchemas.inspect_pcap_client.parse({ client }),
|
||||
provider,
|
||||
),
|
||||
);
|
||||
else {
|
||||
await this.prepareCaptureBound();
|
||||
snapshot = await PcapSnapshot.create();
|
||||
this.snapshots.add(snapshot);
|
||||
const identity = await snapshot.capture(request.input.path, signal);
|
||||
const captured = await this.inspectCapture(
|
||||
selection,
|
||||
snapshot,
|
||||
request.input.path,
|
||||
identity,
|
||||
signal,
|
||||
);
|
||||
const data = pcapResultSchemas.inspect_pcap_capture.parse({
|
||||
client,
|
||||
...captured.result,
|
||||
});
|
||||
result = ok(
|
||||
createAnalysisExecution(data, provider, {
|
||||
subject: {
|
||||
path: request.input.path,
|
||||
format: "file",
|
||||
sha256: identity.sha256,
|
||||
},
|
||||
limitations: captured.limitations,
|
||||
}),
|
||||
);
|
||||
}
|
||||
} catch (cause) {
|
||||
result = err(
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: signal?.aborted
|
||||
? new AnalysisCancelledError(request.operation, { cause })
|
||||
: cause instanceof PcapConfigurationFailure
|
||||
? new AnalysisCapabilityUnavailableError(
|
||||
"pcap",
|
||||
request.operation,
|
||||
cause.message,
|
||||
{ cause },
|
||||
)
|
||||
: new AnalysisProtocolError(
|
||||
`Packet-capture analysis failed: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
if (signal?.aborted && result.ok)
|
||||
result = err(
|
||||
new AnalysisCancelledError(request.operation, {
|
||||
cause: signal.reason,
|
||||
partialObservation: createPcapEvidence(request, result.value),
|
||||
}),
|
||||
);
|
||||
if (snapshot !== undefined) {
|
||||
const cleanup = await this.discard(snapshot);
|
||||
if (signal?.aborted && result.ok)
|
||||
result = err(
|
||||
new AnalysisCancelledError(request.operation, {
|
||||
cause: signal.reason,
|
||||
partialObservation: createPcapEvidence(request, result.value),
|
||||
}),
|
||||
);
|
||||
if (cleanup !== undefined)
|
||||
result = result.ok
|
||||
? err(
|
||||
cleanup.retainPartialObservation(
|
||||
createPcapEvidence(request, result.value),
|
||||
),
|
||||
)
|
||||
: err(
|
||||
analysisErrorWithCleanupFailure(
|
||||
result.error,
|
||||
cleanup,
|
||||
request.operation,
|
||||
),
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private async inspectCapture(
|
||||
selection: PcapToolSelection,
|
||||
snapshot: PcapSnapshot,
|
||||
path: string,
|
||||
identity: { bytes: number; sha256: string },
|
||||
signal: AbortSignal | undefined,
|
||||
) {
|
||||
const info = await this.run(
|
||||
"inspect_pcap_capture",
|
||||
selection.capinfos.command,
|
||||
["-M", "--", snapshot.path],
|
||||
{ timeoutMs: 60_000, maxOutputBytes: 64 * 1024 },
|
||||
signal,
|
||||
snapshot,
|
||||
path,
|
||||
);
|
||||
const metadata = parseCapinfosOutput(info.stdout);
|
||||
if (metadata.sha256 !== null && metadata.sha256 !== identity.sha256)
|
||||
throw new AnalysisProtocolError(
|
||||
"capinfos SHA256 disagrees with the owned capture snapshot",
|
||||
);
|
||||
const dissected = await this.run(
|
||||
"inspect_pcap_capture",
|
||||
selection.tshark.command,
|
||||
[
|
||||
"-n",
|
||||
"-r",
|
||||
snapshot.path,
|
||||
"-T",
|
||||
"json",
|
||||
"--no-duplicate-keys",
|
||||
`--temp-dir=${snapshot.configurationPath}`,
|
||||
...FIELDS.flatMap((field) => ["-e", field]),
|
||||
],
|
||||
{ timeoutMs: 300_000, maxOutputBytes: TSHARK_JSON_MAX_BYTES },
|
||||
signal,
|
||||
snapshot,
|
||||
path,
|
||||
);
|
||||
const fields = await parseTsharkJsonOutput(dissected.stdout, signal);
|
||||
await snapshot.verify(identity, path, signal);
|
||||
if (fields.packetCount !== metadata.packetCount)
|
||||
throw new AnalysisProtocolError(
|
||||
`capinfos counted ${String(metadata.packetCount)} packets but tshark returned ${String(fields.packetCount)}`,
|
||||
);
|
||||
return {
|
||||
result: {
|
||||
target: { path, ...identity },
|
||||
file_type: metadata.fileType,
|
||||
encapsulation: metadata.encapsulation,
|
||||
packet_count: metadata.packetCount,
|
||||
capture_start: metadata.captureStart,
|
||||
capture_end: metadata.captureEnd,
|
||||
capture_duration_seconds: metadata.captureDurationSeconds,
|
||||
diagnostics: {
|
||||
capinfos_stderr: info.stderr,
|
||||
tshark_stderr: dissected.stderr,
|
||||
},
|
||||
snapshot_length: metadata.snapshotLength,
|
||||
endpoints: fields.endpoints,
|
||||
endpoint_count: fields.endpointCount,
|
||||
dns_queries: fields.dnsQueries,
|
||||
dns_query_count: fields.dnsQueryCount,
|
||||
tls_sni_values: fields.tlsSniValues,
|
||||
tls_sni_count: fields.tlsSniCount,
|
||||
protocol_distribution: fields.protocolDistribution,
|
||||
protocol_count: fields.protocolCount,
|
||||
http_request_uris: fields.httpRequestUris,
|
||||
http_request_uri_count: fields.httpRequestUriCount,
|
||||
http_uri_redaction_count: fields.httpUriRedactionCount,
|
||||
unattributed_dns_addresses: fields.unattributedDnsAddresses,
|
||||
unattributed_dns_address_count: fields.unattributedDnsAddressCount,
|
||||
unattributed_dns_packet_count: fields.unattributedDnsPackets,
|
||||
coverage: fields.partial ? "partial" : "complete",
|
||||
},
|
||||
limitations: [
|
||||
...this.nativeLimitations,
|
||||
"Both tools read one owned snapshot; target identity comes from its admitted source descriptor",
|
||||
"DNS address values are associated only with a single question in the same response packet; values may include additional DNS records, not only final resolution answers",
|
||||
"Only bytes present in the saved capture are examined; encryption and capture truncation can hide higher-level fields",
|
||||
...(fields.partial
|
||||
? [
|
||||
"One or more projected categories were capped, credential-bearing URIs were omitted or coalesced, or DNS address attribution remains unresolved; counts retain the examined totals",
|
||||
]
|
||||
: []),
|
||||
...(fields.httpUriRedactionCount > 0
|
||||
? [
|
||||
"HTTP transport credentials were excluded; ambiguous credential spans cause the URI to be omitted",
|
||||
]
|
||||
: []),
|
||||
...(fields.unattributedDnsPackets > 0
|
||||
? [
|
||||
`DNS address attribution was unresolved in ${String(fields.unattributedDnsPackets)} packet(s); unattributed addresses are retained separately`,
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { chmod, open, stat, mkdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisAccessDeniedError,
|
||||
AnalysisArtifactChangedError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisResourceConstraintError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import {
|
||||
openRegularFile,
|
||||
RegularFileAdmissionFailure,
|
||||
sameRegularFileState,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import { PrivateRuntimeRootUnavailableError } from "../process/PrivateRuntimeRootUnavailableError.js";
|
||||
|
||||
const OPERATION = "inspect_pcap_capture";
|
||||
const MAX_CAPTURE_BYTES = 2 * 1024 ** 3;
|
||||
|
||||
/** An owned capture copy and every descriptor needed to release it safely. */
|
||||
export class PcapSnapshot {
|
||||
private readonly handles = new Set<OwnedFileHandle>();
|
||||
readonly path: string;
|
||||
readonly configurationPath: string;
|
||||
private constructor(private readonly root: PrivateRuntimeRoot) {
|
||||
this.path = join(root.path, "capture.pcap");
|
||||
this.configurationPath = join(root.path, "configuration");
|
||||
}
|
||||
|
||||
static async create(): Promise<PcapSnapshot> {
|
||||
try {
|
||||
return new PcapSnapshot(
|
||||
await PrivateRuntimeRoot.create({ prefix: "rea-pcap-" }),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (cause instanceof PrivateRuntimeRootUnavailableError)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"pcap",
|
||||
OPERATION,
|
||||
cause.message,
|
||||
{ cause },
|
||||
);
|
||||
throw new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"file-size",
|
||||
"Cannot allocate the owned capture workspace",
|
||||
null,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private own(handle: OwnedFileHandle): OwnedFileHandle {
|
||||
this.handles.add(handle);
|
||||
return handle;
|
||||
}
|
||||
private async release(handle: OwnedFileHandle): Promise<void> {
|
||||
await handle.close();
|
||||
this.handles.delete(handle);
|
||||
}
|
||||
|
||||
async capture(
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<{ bytes: number; sha256: string }> {
|
||||
const sourceRead = async <T>(read: () => Promise<T>): Promise<T> => {
|
||||
try {
|
||||
return await read();
|
||||
} catch (cause) {
|
||||
if (signal?.aborted)
|
||||
throw new AnalysisCancelledError(OPERATION, { cause });
|
||||
if (cause instanceof AnalysisError) throw cause;
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "EACCES" || cause.code === "EPERM")
|
||||
)
|
||||
throw new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
|
||||
cause,
|
||||
});
|
||||
throw new AnalysisInputError(OPERATION, { cause }, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "invalid_value",
|
||||
message: `Cannot read selected capture ${path}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
},
|
||||
]);
|
||||
}
|
||||
};
|
||||
try {
|
||||
signal?.throwIfAborted();
|
||||
await mkdir(this.configurationPath, { mode: 0o700 });
|
||||
const source = await sourceRead(async () => {
|
||||
try {
|
||||
return this.own(
|
||||
new OwnedFileHandle(
|
||||
await openRegularFile(path, { symlinks: "follow", signal }),
|
||||
),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (cause instanceof RegularFileAdmissionFailure) {
|
||||
this.own(cause.owner);
|
||||
throw cause.cause;
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
});
|
||||
const before = await sourceRead(() =>
|
||||
source.handle.stat({ bigint: true }),
|
||||
);
|
||||
if (before.size > BigInt(MAX_CAPTURE_BYTES))
|
||||
throw new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"file-size",
|
||||
"Capture exceeds the owned-snapshot disk budget",
|
||||
{ max_capture_bytes: MAX_CAPTURE_BYTES },
|
||||
);
|
||||
const destination = this.own(
|
||||
new OwnedFileHandle(await open(this.path, "wx", 0o600)),
|
||||
);
|
||||
const buffer = Buffer.alloc(64 * 1024);
|
||||
const hash = createHash("sha256");
|
||||
let copied = 0;
|
||||
while (copied <= Number(before.size)) {
|
||||
signal?.throwIfAborted();
|
||||
const { bytesRead } = await sourceRead(() =>
|
||||
source.handle.read(
|
||||
buffer,
|
||||
0,
|
||||
Math.min(buffer.length, Number(before.size) - copied + 1),
|
||||
copied,
|
||||
),
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
if (bytesRead === 0) break;
|
||||
copied += bytesRead;
|
||||
if (BigInt(copied) > before.size)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
path,
|
||||
"Capture grew during acquisition",
|
||||
);
|
||||
const chunk = buffer.subarray(0, bytesRead);
|
||||
await destination.handle.writeFile(chunk);
|
||||
hash.update(chunk);
|
||||
}
|
||||
const after = await sourceRead(() =>
|
||||
source.handle.stat({ bigint: true }),
|
||||
);
|
||||
const selected = await stat(path, { bigint: true }).catch(
|
||||
(cause: unknown) => {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause.code === "EACCES" || cause.code === "EPERM")
|
||||
)
|
||||
throw new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
|
||||
cause,
|
||||
});
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
path,
|
||||
"Selected path became unavailable during acquisition",
|
||||
{ cause },
|
||||
);
|
||||
},
|
||||
);
|
||||
if (
|
||||
BigInt(copied) !== before.size ||
|
||||
!sameRegularFileState(before, after) ||
|
||||
!sameRegularFileState(before, selected)
|
||||
)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
path,
|
||||
"Capture identity or contents changed during acquisition",
|
||||
);
|
||||
await this.release(source);
|
||||
await this.release(destination);
|
||||
await chmod(this.path, 0o400);
|
||||
signal?.throwIfAborted();
|
||||
return { bytes: copied, sha256: hash.digest("hex") };
|
||||
} catch (cause) {
|
||||
if (signal?.aborted)
|
||||
throw new AnalysisCancelledError(OPERATION, { cause });
|
||||
if (cause instanceof AnalysisError) throw cause;
|
||||
throw new AnalysisResourceConstraintError(
|
||||
OPERATION,
|
||||
"file-size",
|
||||
"Owned capture snapshot I/O failed",
|
||||
null,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Recheck byte identity after both tools; a read-only mode alone is not proof. */
|
||||
async verify(
|
||||
expected: { bytes: number; sha256: string },
|
||||
selectedPath: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const file = this.own(
|
||||
new OwnedFileHandle(
|
||||
await openRegularFile(this.path, { symlinks: "reject", signal }),
|
||||
),
|
||||
);
|
||||
const before = await file.handle.stat({ bigint: true });
|
||||
const buffer = Buffer.alloc(64 * 1024);
|
||||
const hash = createHash("sha256");
|
||||
let bytes = 0;
|
||||
while (bytes <= expected.bytes) {
|
||||
signal?.throwIfAborted();
|
||||
const read = await file.handle.read(
|
||||
buffer,
|
||||
0,
|
||||
Math.min(buffer.length, expected.bytes - bytes + 1),
|
||||
bytes,
|
||||
);
|
||||
if (read.bytesRead === 0) break;
|
||||
bytes += read.bytesRead;
|
||||
hash.update(buffer.subarray(0, read.bytesRead));
|
||||
}
|
||||
const after = await file.handle.stat({ bigint: true });
|
||||
const selected = await stat(this.path, { bigint: true });
|
||||
if (
|
||||
bytes !== expected.bytes ||
|
||||
hash.digest("hex") !== expected.sha256 ||
|
||||
!sameRegularFileState(before, after) ||
|
||||
!sameRegularFileState(before, selected)
|
||||
)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
selectedPath,
|
||||
"Owned packet snapshot changed during tool analysis.",
|
||||
);
|
||||
await this.release(file);
|
||||
} catch (cause) {
|
||||
if (signal?.aborted)
|
||||
throw new AnalysisCancelledError(OPERATION, { cause });
|
||||
if (cause instanceof RegularFileAdmissionFailure) this.own(cause.owner);
|
||||
if (cause instanceof AnalysisError) throw cause;
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
selectedPath,
|
||||
"Cannot establish the owned packet snapshot's post-analysis identity.",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
const results = await Promise.allSettled(
|
||||
[...this.handles].map((handle) => this.release(handle)),
|
||||
);
|
||||
const failures = results.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason as unknown] : [],
|
||||
);
|
||||
if (failures.length > 0)
|
||||
throw new AggregateError(failures, "Capture descriptor cleanup failed");
|
||||
await this.root.close();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user