chore: sync main after artifact ownership audit

This commit is contained in:
morluto
2026-10-13 12:56:07 +08:00
69 changed files with 4082 additions and 28 deletions
+1 -1
View File
@@ -481,7 +481,7 @@ const workflowAvailabilityFor = ({
remediation: "Run process capture on a supported Linux or macOS host.",
};
if (kind === "application") return { reason: "available", remediation: null };
if (kind === "flutter-provider")
if (kind === "pcap-provider" || kind === "flutter-provider")
return { reason: "available", remediation: null };
const electron = electronProviderAvailability(name, kind, policy);
if (electron !== null) return electron;
+23
View File
@@ -0,0 +1,23 @@
import type {
AnalysisExecution,
ExecutionOptions,
ProviderAvailability,
} from "../AnalysisProvider.js";
import type { PcapRequest } from "../../domain/pcap/pcapAnalysis.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Result } from "../../domain/result.js";
/**
* Packet-capture analysis boundary over caller-supplied tshark/capinfos.
* Implementation details belong to the provider adapter.
*/
export interface PcapAnalysisPort {
/** Probe both tools without reading any capture file. */
inspectAvailability(signal?: AbortSignal): Promise<ProviderAvailability>;
/** Retry cleanup of retained owned commands and capture snapshots. */
close(): Promise<void>;
execute(
request: PcapRequest,
options?: ExecutionOptions,
): Promise<Result<AnalysisExecution, AnalysisError>>;
}
@@ -0,0 +1,36 @@
import type { PcapAnalysisPort } from "./PcapAnalysisPort.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import {
pcapRequestSchema,
type PcapOperation,
} from "../../domain/pcap/pcapAnalysis.js";
import {
AnalysisCancelledError,
AnalysisInputError,
} from "../../domain/analysisErrorCore.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import { createPcapEvidence } from "../../domain/pcap/pcapEvidence.js";
import { err, ok, type Result } from "../../domain/result.js";
/** Shared CLI/MCP admission, execution, and Evidence composition for pcap. */
export class PcapAnalysisService {
constructor(readonly provider: PcapAnalysisPort) {}
/** Run one caller-selected pcap request and retain capture identity inline. */
async execute(
operation: PcapOperation,
input: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
const request = pcapRequestSchema.safeParse({ operation, input });
if (!request.success)
return err(new AnalysisInputError(operation, { cause: request.error }));
const executed = await this.provider.execute(request.data, options);
if (!executed.ok) return executed;
const execution = executed.value;
return ok(createPcapEvidence(request.data, execution));
}
}
+2
View File
@@ -24,6 +24,7 @@ import { registerManagedCommands } from "./cli/managedCommands.js";
import { registerFirmwareCommands } from "./cli/firmwareCommands.js";
import { registerAndroidCommands } from "./cli/androidCommands.js";
import { registerApktoolCommands } from "./cli/apktoolCommands.js";
import { registerPcapCommands } from "./cli/pcapCommands.js";
import { registerFlutterCommands } from "./cli/flutterCommands.js";
import { registerJebCommands } from "./cli/jebCommands.js";
import { registerAdbCommands } from "./cli/adbCommands.js";
@@ -105,6 +106,7 @@ export const createCli = (
registerManagedCommands(cli, logger, analysis.runProviderAnalysis);
registerAndroidCommands(cli, logger, environment);
registerApktoolCommands(cli, logger, environment);
registerPcapCommands(cli, logger, environment);
registerFlutterCommands(cli, logger);
registerJebCommands(cli, logger, environment);
registerAdbCommands(cli, logger, environment);
+69
View File
@@ -0,0 +1,69 @@
import { z } from "incur";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { PcapAnalysisService } from "../application/pcap/PcapAnalysisService.js";
import type { PcapAnalysisPort } from "../application/pcap/PcapAnalysisPort.js";
import { createPcapAnalysisProvider } from "../composition/pcap.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { PcapOperation } from "../domain/pcap/pcapAnalysis.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
/** Expose the same explicit pcap requests through one-shot CLI commands. */
export const registerPcapCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<Record<string, string | undefined>>,
provider: PcapAnalysisPort = createPcapAnalysisProvider(environment),
): void => {
const service = new PcapAnalysisService(provider);
const execute = (name: string, operation: PcapOperation, input: unknown) =>
withCommandCancellation((signal) =>
logCliCommand(logger, name, async () => {
const result = await service.execute(operation, input, { signal });
try {
await provider.close();
} catch (cause) {
if (cause instanceof AnalysisError) {
if (result.ok) cause.retainPartialObservation(result.value);
return projectAnalysisError(
result.ok
? cause
: analysisErrorWithCleanupFailure(
result.error,
cause,
operation,
),
);
}
throw cause;
}
return result.ok ? result.value : projectAnalysisError(result.error);
}),
);
cli.command(CLI_COMMANDS.inspectPcapClient, {
description:
"Inspect the caller-selected tshark and capinfos binaries without reading a capture",
args: z.object({}),
run: () =>
execute(CLI_COMMANDS.inspectPcapClient, "inspect_pcap_client", {}),
});
cli.command(CLI_COMMANDS.inspectPcapCapture, {
description:
"Inspect one pcap/pcapng capture: endpoints, DNS, TLS SNI, and protocol distribution",
args: z.object({
path: z
.string()
.min(1)
.describe("Local pcap or pcapng capture file to inspect"),
}),
run: ({ args }) =>
execute(CLI_COMMANDS.inspectPcapCapture, "inspect_pcap_capture", {
path: args.path,
}),
});
};
+2
View File
@@ -55,6 +55,8 @@ export const CLI_COMMANDS = Object.freeze({
inspectFirmwareRegions: "inspect-firmware-regions",
extractFirmware: "extract-firmware",
inspectAndroidPackage: "inspect-android-package",
inspectPcapClient: "inspect-pcap-client",
inspectPcapCapture: "inspect-pcap-capture",
identifyFlutterBuild: "identify-flutter-build",
inspectDartAot: "inspect-dart-aot",
inspectApktoolClient: "inspect-apktool-client",
+7
View File
@@ -0,0 +1,7 @@
import type { PcapAnalysisPort } from "../application/pcap/PcapAnalysisPort.js";
import { PcapProvider } from "../pcap/PcapProvider.js";
/** Construct one pcap provider bound to the caller-selected tools. */
export const createPcapAnalysisProvider = (
environment: Readonly<Record<string, string | undefined>> = process.env,
): PcapAnalysisPort => new PcapProvider({ environment });
File diff suppressed because one or more lines are too long
+46
View File
@@ -0,0 +1,46 @@
import {
pcapInputSchemas,
pcapResultSchemas,
} from "../../domain/pcap/pcapAnalysis.js";
import type { ToolContract } from "../toolContractTypes.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
import { toolContractMetadata } from "../toolEffects.js";
import {
analysisDetailSchema,
analysisDetailOutputSchemaOf,
} from "../analysisDetail.js";
import { pcapCaptureSummaryViewResultSchema } from "../../domain/analysisView/analysisView.js";
/** Packet-capture analysis served by caller-supplied tshark and capinfos. */
export const PCAP_TOOL_CONTRACTS = [
{
name: "inspect_pcap_client",
...toolContractMetadata("inspect_pcap_client"),
description:
"Inspect the caller-selected tshark and capinfos binaries: selected commands, selection sources, and versions. Both tools must be usable. Reads no capture file. REA never installs the Wireshark suite; select binaries with REA_TSHARK_COMMAND and REA_CAPINFOS_COMMAND (absolute) or from PATH.",
kind: "pcap-provider",
inputSchema: pcapInputSchemas.inspect_pcap_client,
outputSchema: evidenceResultOf(pcapResultSchemas.inspect_pcap_client),
examples: [{ title: "Check the analysis tools", input: {} }],
},
{
name: "inspect_pcap_capture",
...toolContractMetadata("inspect_pcap_capture"),
description:
"Request detail summary for capture identity/counts, then page retained facts with inspect_analysis_view kind pcap. Default detail complete preserves inline delivery. Inspect one saved pcap or pcapng capture through an owned snapshot: metadata, exact packet count, SHA-256, IPv4/IPv6 address counts, DNS questions and address values from the same single-question response, TLS SNI, protocol distribution and HTTP URIs. All derived inventories are retained within declared resource budgets; unknown DNS attribution and excluded credentials remain explicit. Linux requires util-linux prlimit; Windows uses owned Job Objects. Requires caller-supplied capinfos and tshark; REA never captures traffic.",
kind: "pcap-provider",
inputSchema: pcapInputSchemas.inspect_pcap_capture.extend({
detail: analysisDetailSchema,
}),
outputSchema: analysisDetailOutputSchemaOf(
pcapResultSchemas.inspect_pcap_capture,
pcapCaptureSummaryViewResultSchema,
),
examples: [
{
title: "Inspect a capture file",
input: { path: "/captures/session.pcap" },
},
],
},
] as const satisfies readonly ToolContract[];
+1
View File
@@ -33,6 +33,7 @@ export const TOOL_KINDS = [
"browser-provider",
"electron-provider",
"runtime-provider",
"pcap-provider",
"application",
"session",
] as const;
+2
View File
@@ -12,6 +12,7 @@ import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
import { APKTOOL_TOOL_CONTRACTS } from "./apktool/apktoolToolContracts.js";
import { PCAP_TOOL_CONTRACTS } from "./pcap/pcapToolContracts.js";
import { FLUTTER_TOOL_CONTRACTS } from "./flutter/flutterToolContracts.js";
import { JEB_TOOL_CONTRACTS } from "./jeb/jebToolContracts.js";
import { ADB_TOOL_CONTRACTS } from "./adb/adbToolContracts.js";
@@ -46,6 +47,7 @@ export const TOOL_CONTRACTS = [
...MANAGED_TOOL_CONTRACTS,
...ANDROID_TOOL_CONTRACTS,
...APKTOOL_TOOL_CONTRACTS,
...PCAP_TOOL_CONTRACTS,
...FLUTTER_TOOL_CONTRACTS,
...JEB_TOOL_CONTRACTS,
...ADB_TOOL_CONTRACTS,
+2
View File
@@ -44,6 +44,8 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
search_android_classes: "states it does not execute the APK",
inspect_apktool_client:
"inspects the operator-selected apktool launcher; never installs it",
inspect_pcap_client:
"probes the operator-selected tshark and capinfos; never installs them",
inspect_jeb_client: "talks to a caller-started JEB; never launches it",
open_jeb_project: "the engine analyzes the file; REA does not execute it",
inspect_adb_client:
+10
View File
@@ -182,6 +182,16 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
launchesProcess: true,
writesFilesystem: true,
}),
inspect_pcap_client: effects({
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
}),
inspect_pcap_capture: effects({
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
}),
identify_flutter_build: effects({
mutatesSession: true,
writesFilesystem: true,
+28
View File
@@ -62,6 +62,12 @@ import {
captureSummarySchema,
} from "./webNetworkCaptureView.js";
import type { WebNetworkApiSurfaceAccumulator } from "./WebNetworkApiSurfaceAccumulator.js";
import {
pcapViewRequestSchema,
pcapViewPageSchema,
pcapSummarySchema,
projectPcapCaptureView,
} from "./pcapCaptureView.js";
import {
qlogViewRequestSchema,
qlogViewPageSchema,
@@ -196,6 +202,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
apiSurfaceViewSchema,
captureViewRequestSchema,
qlogViewRequestSchema,
pcapViewRequestSchema,
dartAotViewRequestSchema,
]);
@@ -312,6 +319,7 @@ const viewResultBase = {
"inspect_managed_artifact",
"inspect_web_network_capture",
"inspect_android_package",
"inspect_pcap_capture",
"inspect_dart_aot",
]),
parent_digest: digestSchema,
@@ -384,6 +392,12 @@ export const androidPackageSummaryViewResultSchema = z.strictObject({
summary: androidPackageSummarySchema,
});
export const pcapCaptureSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_pcap_capture"),
summary: pcapSummarySchema,
});
/** Exact snapshot and pool-coverage carrier for selected AOT delivery. */
export const dartAotSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
@@ -415,6 +429,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
managedSummarySchema,
captureSummarySchema,
androidPackageSummarySchema,
pcapSummarySchema,
dartAotSummarySchema,
]),
}),
@@ -433,6 +448,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
...viewResultBase,
parent_operation: z.literal("inspect_web_network_capture"),
}),
z.strictObject({
kind: z.literal("pcap"),
view: pcapViewRequestSchema,
page: pcapViewPageSchema,
source_coverage: z.enum(["complete", "partial"]),
...viewResultBase,
parent_operation: z.literal("inspect_pcap_capture"),
}),
z.strictObject({
kind: z.literal("facet"),
view: facetViewSchema,
@@ -562,6 +585,7 @@ export type UnsignedAnalysisView =
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "qlog" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "pcap" }>, "view_digest">
| Omit<
Extract<AnalysisViewResult, { readonly kind: "capture" }>,
"view_digest"
@@ -686,6 +710,10 @@ export const projectAnalysisView = (
const projected = projectWebNetworkCaptureView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_pcap_capture") {
const projected = projectPcapCaptureView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_binary_layout") {
const layout = binaryLayoutSchema.safeParse(parent.normalizedResult);
if (!layout.success)
+327
View File
@@ -0,0 +1,327 @@
import { z } from "zod";
import { pcapResultSchemas } from "../pcap/pcapAnalysis.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
const captureSchema = pcapResultSchemas.inspect_pcap_capture;
const fields = captureSchema.shape;
const pageShape = {
kind: z.literal("pcap"),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
};
export const pcapViewRequestSchema = z.discriminatedUnion("facet", [
z.strictObject({
...pageShape,
facet: z.enum([
"endpoints",
"dns-queries",
"tls-sni",
"protocols",
"http-uris",
"unattributed-addresses",
]),
}),
z.strictObject({
...pageShape,
facet: z.literal("dns-addresses"),
query: z.string().min(1),
}),
z.strictObject({
...pageShape,
facet: z.literal("diagnostics"),
stream: z.enum(["tshark", "capinfos"]),
}),
]);
export const pcapViewPageSchema = z.discriminatedUnion("facet", [
z.strictObject({ facet: z.literal("endpoints"), items: fields.endpoints }),
z.strictObject({
facet: z.literal("dns-queries"),
items: z.array(
fields.dns_queries.element.omit({ response_addresses: true }).extend({
retained_response_address_count: z.number().int().nonnegative(),
}),
),
}),
z.strictObject({ facet: z.literal("tls-sni"), items: fields.tls_sni_values }),
z.strictObject({
facet: z.literal("protocols"),
items: fields.protocol_distribution,
}),
z.strictObject({
facet: z.literal("http-uris"),
items: fields.http_request_uris,
}),
z.strictObject({
facet: z.literal("unattributed-addresses"),
items: fields.unattributed_dns_addresses,
}),
z.strictObject({
facet: z.literal("dns-addresses"),
items: fields.unattributed_dns_addresses,
}),
z.strictObject({
facet: z.literal("diagnostics"),
text: z.string(),
status: z.enum(["retained", "unknown"]),
}),
]);
export const pcapSummarySchema = captureSchema
.omit({
endpoints: true,
dns_queries: true,
tls_sni_values: true,
protocol_distribution: true,
http_request_uris: true,
unattributed_dns_addresses: true,
diagnostics: true,
})
.extend({
retained_counts: z.strictObject({
endpoints: z.number().int().nonnegative(),
dns_queries: z.number().int().nonnegative(),
tls_sni_values: z.number().int().nonnegative(),
protocol_distribution: z.number().int().nonnegative(),
http_request_uris: z.number().int().nonnegative(),
unattributed_dns_addresses: z.number().int().nonnegative(),
}),
diagnostics_code_units: z
.strictObject({
tshark: z.number().int().nonnegative(),
capinfos: z.number().int().nonnegative(),
})
.nullable(),
});
type Capture = z.output<typeof captureSchema>;
type PcapView = z.output<typeof pcapViewRequestSchema>;
type Page = z.output<typeof pcapViewPageSchema>;
const parseParent = (
parent: AnalysisViewParent,
): Result<Capture, AnalysisError> => {
const parsed = captureSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues,
parent.normalizedResult,
{ cause: parsed.error },
),
);
if (
parent.subject?.local_path !== parsed.data.target.path ||
parent.subject.digest.sha256 !== parsed.data.target.sha256
)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Packet parent subject must identify the report's exact path and SHA-256.",
},
]),
);
return ok(parsed.data);
};
const summarize = ({
endpoints,
dns_queries,
tls_sni_values,
protocol_distribution,
http_request_uris,
unattributed_dns_addresses,
diagnostics,
...metadata
}: Capture) => ({
...metadata,
retained_counts: {
endpoints: endpoints.length,
dns_queries: dns_queries.length,
tls_sni_values: tls_sni_values.length,
protocol_distribution: protocol_distribution.length,
http_request_uris: http_request_uris.length,
unattributed_dns_addresses: unattributed_dns_addresses.length,
},
diagnostics_code_units:
diagnostics === undefined
? null
: {
tshark: diagnostics.tshark_stderr.length,
capinfos: diagnostics.capinfos_stderr.length,
},
});
const selectRows = (
capture: Capture,
view: Exclude<PcapView, { facet: "diagnostics" }>,
): Result<
{ page: Exclude<Page, { facet: "diagnostics" }>; total: number },
AnalysisError
> => {
const slice = <T>(items: readonly T[]) =>
items.slice(view.offset, view.offset + view.limit);
switch (view.facet) {
case "endpoints":
return ok({
page: { facet: view.facet, items: slice(capture.endpoints) },
total: capture.endpoints.length,
});
case "dns-queries":
return ok({
page: {
facet: view.facet,
items: slice(capture.dns_queries).map(
({ response_addresses, ...query }) => ({
...query,
retained_response_address_count: response_addresses.length,
}),
),
},
total: capture.dns_queries.length,
});
case "tls-sni":
return ok({
page: { facet: view.facet, items: slice(capture.tls_sni_values) },
total: capture.tls_sni_values.length,
});
case "protocols":
return ok({
page: {
facet: view.facet,
items: slice(capture.protocol_distribution),
},
total: capture.protocol_distribution.length,
});
case "http-uris":
return ok({
page: { facet: view.facet, items: slice(capture.http_request_uris) },
total: capture.http_request_uris.length,
});
case "unattributed-addresses":
return ok({
page: {
facet: view.facet,
items: slice(capture.unattributed_dns_addresses),
},
total: capture.unattributed_dns_addresses.length,
});
case "dns-addresses": {
const matches = capture.dns_queries.filter(
(query) => query.query === view.query,
);
if (matches.length !== 1)
return err(
analysisViewInputError([
{
path: ["view", "query"],
reason: "invalid_value",
message: "Select one unambiguous exact retained DNS question.",
},
]),
);
return ok({
page: {
facet: view.facet,
items: slice(matches[0]!.response_addresses),
},
total: matches[0]!.response_addresses.length,
});
}
}
};
/** Historical packet facts are paged without reopening the source or rerunning Wireshark. */
export const projectPcapCaptureView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "pcap")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Packet summary parents support summary and pcap fact pages.",
},
]),
);
const parsed = parseParent(parent);
if (!parsed.ok) return parsed;
const capture = parsed.value;
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_pcap_capture" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: capture.target.path, sha256: capture.target.sha256 },
limitations: [
...parent.limitations,
"Page totals count retained rows or UTF-16 diagnostic code units. Exhaustion does not prove whole-network completeness; source coverage and examined counts remain separate.",
],
unknowns: [
"Saved packet observations do not establish process identity, causality, encrypted payload contents or traffic missing from the recording.",
],
};
if (view.kind === "summary")
return ok({
kind: "summary",
view,
...shared,
summary: summarize(capture),
coverage: completeWithinViewCoverage(1, 1),
});
if (view.facet === "diagnostics") {
const value =
view.stream === "tshark"
? capture.diagnostics?.tshark_stderr
: capture.diagnostics?.capinfos_stderr;
const text = value?.slice(view.offset, view.offset + view.limit) ?? "";
return ok({
kind: "pcap",
view,
...shared,
source_coverage: capture.coverage,
page: {
facet: "diagnostics",
text,
status: value === undefined ? "unknown" : "retained",
},
coverage: pageViewCoverage(view.offset, text.length, value?.length ?? 0),
unknowns:
value === undefined
? [
...shared.unknowns,
"The parent did not retain diagnostics; an empty text page does not establish their absence.",
]
: shared.unknowns,
});
}
const selected = selectRows(capture, view);
return selected.ok
? ok({
kind: "pcap",
view,
...shared,
source_coverage: capture.coverage,
page: selected.value.page,
coverage: pageViewCoverage(
view.offset,
selected.value.page.items.length,
selected.value.total,
),
})
: selected;
};
+110
View File
@@ -0,0 +1,110 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
import { digestSchema } from "../digests.js";
/**
* Caller intent for packet-capture analysis through caller-supplied tshark
* and capinfos. REA never installs Wireshark or its tools.
*/
export const pcapInputSchemas = {
inspect_pcap_client: z.strictObject({}),
inspect_pcap_capture: z.strictObject({
path: localPathStringSchema.describe(
"Local pcap or pcapng capture file to inspect",
),
}),
} as const;
/** Supported pcap-backed operations. */
export type PcapOperation = keyof typeof pcapInputSchemas;
/** Validated pcap requests carry their selected operation. */
export type PcapRequest = {
[Name in PcapOperation]: {
operation: Name;
input: z.infer<(typeof pcapInputSchemas)[Name]>;
};
}[PcapOperation];
/** Validate operation and input together so their types remain correlated. */
export const pcapRequestSchema = z.discriminatedUnion("operation", [
z.strictObject({
operation: z.literal("inspect_pcap_client"),
input: pcapInputSchemas.inspect_pcap_client,
}),
z.strictObject({
operation: z.literal("inspect_pcap_capture"),
input: pcapInputSchemas.inspect_pcap_capture,
}),
]);
const client = z.strictObject({
tshark_command: z.string().min(1),
tshark_source: z.enum(["environment", "path"]),
tshark_version: z.string().min(1).nullable(),
capinfos_command: z.string().min(1),
capinfos_source: z.enum(["environment", "path"]),
capinfos_version: z.string().min(1).nullable(),
});
const endpoint = z.strictObject({
address: z.string().min(1),
port: z.number().int().positive().nullable(),
packet_count: z.number().int().positive(),
});
const dnsQuery = z.strictObject({
query: z.string().min(1),
response_addresses: z.array(z.string().min(1)),
response_address_count: z.number().int().nonnegative(),
});
const protocolCount = z.strictObject({
protocol: z.string().min(1),
packet_count: z.number().int().positive(),
});
/** Portable pcap observations with explicit coverage limitations. */
export const pcapResultSchemas = {
inspect_pcap_client: z.strictObject({
client,
}),
inspect_pcap_capture: z.strictObject({
client,
target: z.strictObject({
path: localPathStringSchema,
bytes: z.number().int().nonnegative(),
sha256: digestSchema,
}),
/** File format as capinfos reports it (pcap vs pcapng). */
file_type: z.string().min(1).nullable(),
encapsulation: z.string().min(1).nullable(),
packet_count: z.number().int().nonnegative().nullable(),
capture_start: z.string().nullable(),
capture_end: z.string().nullable(),
capture_duration_seconds: z.number().nonnegative().nullable(),
snapshot_length: z.number().int().positive().nullable(),
/** Distinct endpoints with packet counts, bounded. */
endpoints: z.array(endpoint),
endpoint_count: z.number().int().nonnegative(),
/** DNS queries with resolved addresses, bounded. */
dns_queries: z.array(dnsQuery),
dns_query_count: z.number().int().nonnegative(),
/** TLS Server Name Indication values observed in handshakes. */
tls_sni_values: z.array(z.string().min(1)),
tls_sni_count: z.number().int().nonnegative(),
/** Protocol distribution (frame.protocols column counts). */
protocol_distribution: z.array(protocolCount),
protocol_count: z.number().int().nonnegative(),
/** HTTP request URIs seen on plain-text ports, bounded. */
http_request_uris: z.array(z.string().min(1)),
http_request_uri_count: z.number().int().nonnegative(),
http_uri_redaction_count: z.number().int().nonnegative(),
unattributed_dns_addresses: z.array(z.string().min(1)),
unattributed_dns_address_count: z.number().int().nonnegative(),
unattributed_dns_packet_count: z.number().int().nonnegative(),
coverage: z.enum(["complete", "partial"]),
diagnostics: z
.strictObject({ capinfos_stderr: z.string(), tshark_stderr: z.string() })
.optional(),
}),
} as const;
+34
View File
@@ -0,0 +1,34 @@
import { createEvidence } from "../evidence.js";
import { jsonObjectSchema, type JsonValue } from "../jsonValue.js";
import type { PcapRequest } from "./pcapAnalysis.js";
/** Domain facts needed by both successful and retained partial observations. */
interface PcapObservation {
readonly subject: Parameters<typeof createEvidence>[0] | null;
readonly provider: Parameters<typeof createEvidence>[1];
readonly result: JsonValue;
readonly rawResult: JsonValue | null;
readonly limitations: readonly string[];
readonly locations: NonNullable<
Parameters<typeof createEvidence>[2]["locations"]
>;
}
/** One owner commits packet aggregation provenance and caller intent into Evidence. */
export const createPcapEvidence = (
request: PcapRequest,
observation: PcapObservation,
) =>
createEvidence(observation.subject ?? undefined, observation.provider, {
operation: request.operation,
parameters: jsonObjectSchema.parse(request.input),
result: observation.result,
rawResult: observation.rawResult,
limitations: observation.limitations,
locations: observation.locations,
confidence:
request.operation === "inspect_pcap_capture" ? "derived" : "observed",
...(request.operation === "inspect_pcap_capture"
? { authority: "historical-reference" as const }
: {}),
});
+207
View File
@@ -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,
);
}
};
+170
View File
@@ -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",
});
});
});
+153
View File
@@ -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 },
});
+68
View File
@@ -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 },
);
}
};
+149
View File
@@ -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");
});
+315
View File
@@ -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,
};
};
+493
View File
@@ -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`,
]
: []),
],
};
}
}
+269
View File
@@ -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();
}
}
+4 -2
View File
@@ -74,7 +74,9 @@ const sourceFiles = [
export const SWIFTC_INTERRUPT = "SIGINT";
/** Deadline for the one-shot helper compilation. */
const COMPILER_TIMEOUT_MS = 60_000;
// A fresh Swift SDK cache took 88 seconds on the supported Intel macOS VM.
// Keep compilation bounded independently of short provider version probes.
const COMPILER_TIMEOUT_MS = 120_000;
/** Bound on compiler diagnostics embedded in the inspection failure text. */
const STDERR_EXCERPT_LIMIT = 512;
@@ -253,7 +255,7 @@ export type DarwinProcessReaderCompiler =
export const createDarwinProcessRunTokenReader = (
options: {
readonly compiler?: DarwinProcessReaderCompiler;
/** Deadline for the helper compilation; the default keeps verification fast. */
/** Deadline for helper compilation, independent of provider execution. */
readonly compileTimeoutMs?: number;
/**
* Caller-owned directory holding the compiler's module cache. Unset keeps
+15
View File
@@ -84,6 +84,7 @@ import type { FirmwareAnalysisPort } from "../application/firmware/FirmwareAnaly
import { createFirmwareAnalysisProvider } from "../composition/firmware.js";
import { registerAndroidTools } from "./registerAndroidTools.js";
import { registerApktoolTools } from "./registerApktoolTools.js";
import { registerPcapTools } from "./registerPcapTools.js";
import { registerFlutterTools } from "./registerFlutterTools.js";
import { registerJebTools } from "./registerJebTools.js";
import { registerAdbTools } from "./registerAdbTools.js";
@@ -91,11 +92,14 @@ import { AndroidAnalysisService } from "../application/android/AndroidAnalysisSe
import { JebAnalysisService } from "../application/jeb/JebAnalysisService.js";
import type { AndroidAnalysisPort } from "../application/android/AndroidAnalysisPort.js";
import type { ApktoolResourceAnalysisPort } from "../application/apktool/ApktoolResourceAnalysisPort.js";
import type { PcapAnalysisPort } from "../application/pcap/PcapAnalysisPort.js";
import { PcapAnalysisService } from "../application/pcap/PcapAnalysisService.js";
import { ApktoolResourceAnalysisService } from "../application/apktool/ApktoolResourceAnalysisService.js";
import type { FlutterBuildAnalysisPort } from "../application/flutter/FlutterBuildAnalysisPort.js";
import { FlutterBuildAnalysisService } from "../application/flutter/FlutterBuildAnalysisService.js";
import { createAndroidAnalysisProvider } from "../composition/android.js";
import { createApktoolResourceAnalysisProvider } from "../composition/apktool.js";
import { createPcapAnalysisProvider } from "../composition/pcap.js";
import { createFlutterBuildAnalysisProvider } from "../composition/flutter.js";
import type { JebAnalysisPort } from "../application/jeb/JebAnalysisPort.js";
import { createJebAnalysisProvider } from "../composition/jeb.js";
@@ -146,6 +150,7 @@ export interface CreateServerOptions {
readonly webNetworkCapture?: WebNetworkCaptureService;
readonly androidAnalysis?: AndroidAnalysisPort;
readonly apktoolAnalysis?: ApktoolResourceAnalysisPort;
readonly pcapAnalysis?: PcapAnalysisPort;
readonly flutterAnalysis?: FlutterBuildAnalysisPort;
readonly jebAnalysis?: JebAnalysisPort;
readonly adbDeviceAnalysis?: AdbDeviceAnalysisPort;
@@ -303,6 +308,7 @@ export const createServer = (
);
const android =
options.androidAnalysis ?? createAndroidAnalysisProvider(environment);
const pcap = options.pcapAnalysis ?? createPcapAnalysisProvider(environment);
const flutter =
options.flutterAnalysis ?? createFlutterBuildAnalysisProvider();
const fridaInstrumentation =
@@ -333,6 +339,7 @@ export const createServer = (
jeb.close(),
adbDevice.close(),
flutter.close(),
pcap.close(),
evmInterface.close(),
sqliteDatabase.close(),
binaryLayout.close(),
@@ -438,6 +445,14 @@ export const createServer = (
recordEvidence,
analysisAdmission,
);
registerPcapTools(
server,
new PcapAnalysisService(pcap),
toolLogger,
recordEvidence,
analysisAdmission,
evidenceById,
);
registerFlutterTools(
server,
new FlutterBuildAnalysisService(flutter),
+83
View File
@@ -0,0 +1,83 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { PcapAnalysisService } from "../application/pcap/PcapAnalysisService.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import type { Logger } from "pino";
import {
createContractToolHandler,
createEvidenceToolHandler,
} from "./contractToolHandler.js";
import {
toolRegistrationOptions,
applicationValidatedInputSchema,
} from "./toolRegistrationOptions.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import {
requireAnalysisViewRetention,
summarizeRetainedAnalysis,
} from "../application/analysisView/AnalysisViewService.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { err } from "../domain/result.js";
/** Bind pcap handlers to their exact named contracts through admission. */
export const registerPcapTools = (
server: EvidenceMcpServer,
service: PcapAnalysisService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
evidenceById?: EvidenceLookup,
): void => {
const handler = createContractToolHandler(
server,
service,
logger,
recordEvidence,
withAdmittedAnalysis,
);
const clientContract = toolContract("inspect_pcap_client");
server.registerTool(
clientContract.name,
toolRegistrationOptions(clientContract),
handler(clientContract),
);
const contract = toolContract("inspect_pcap_capture");
const registration = toolRegistrationOptions(contract);
const capture = createEvidenceToolHandler(
server,
async (rawInput, options) => {
const parsed = contract.inputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
contract.name,
parsed.error.issues,
rawInput,
{ cause: parsed.error },
),
);
const { detail, ...input } = parsed.data;
const retention = { recordEvidence, evidenceById };
if (detail === "summary") {
const ready = requireAnalysisViewRetention(contract.name, retention);
if (!ready.ok) return ready;
}
const result = await service.execute(contract.name, input, options);
return detail === "summary" && result.ok
? summarizeRetainedAnalysis(result.value, retention)
: result;
},
logger,
recordEvidence,
withAdmittedAnalysis,
);
server.registerTool(
contract.name,
{
...registration,
inputSchema: applicationValidatedInputSchema(registration.inputSchema),
},
capture(contract),
);
};