feat(firmware): integrate Binwalk and Unblob analysis
* feat(firmware): integrate Binwalk and Unblob analysis * fix(firmware): verify published files and namespace source references * test(firmware): isolate extractor dependency failure from process cleanup * fix(firmware): retain actionable report and cleanup diagnostics * test: assert retained batch output failure diagnostics
This commit is contained in:
@@ -55,6 +55,27 @@ const entry = (
|
||||
};
|
||||
|
||||
describe("capability inventory: provider status", () => {
|
||||
it("reports firmware inspection and extraction prerequisites independently", () => {
|
||||
const policy = {
|
||||
processCaptureEnabled: true,
|
||||
firmwareInspectionEnabled: true,
|
||||
};
|
||||
expect(entry("inspect_firmware_regions", status(), policy)).toMatchObject({
|
||||
available: true,
|
||||
surface: "firmware-provider",
|
||||
});
|
||||
expect(entry("extract_firmware", status(), policy)).toMatchObject({
|
||||
available: false,
|
||||
reason: "provider_missing",
|
||||
remediation: expect.stringContaining("REA_UNBLOB_COMMAND"),
|
||||
});
|
||||
expect(
|
||||
entry("extract_firmware", status(), {
|
||||
processCaptureEnabled: true,
|
||||
firmwareExtractionEnabled: true,
|
||||
}),
|
||||
).toMatchObject({ available: true });
|
||||
});
|
||||
it("keeps Android APK operations target-free and reports their explicit engine prerequisite", () => {
|
||||
expect(
|
||||
entry("inspect_android_package", status(), {
|
||||
|
||||
@@ -28,6 +28,8 @@ type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
|
||||
type ProviderDescriptor = ProviderCapability;
|
||||
export type AvailabilityPolicy = {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly firmwareInspectionEnabled?: boolean;
|
||||
readonly firmwareExtractionEnabled?: boolean;
|
||||
readonly androidAnalysisEnabled?: boolean;
|
||||
readonly browserObservationEnabled?: boolean;
|
||||
readonly browserScenarioEnabled?: boolean;
|
||||
@@ -206,6 +208,19 @@ const workflowAvailabilityFor = ({
|
||||
kind,
|
||||
policy,
|
||||
}: AvailabilityContext): Availability | null => {
|
||||
if (kind === "firmware-provider") {
|
||||
const enabled =
|
||||
name === "inspect_firmware_regions"
|
||||
? policy.firmwareInspectionEnabled
|
||||
: policy.firmwareExtractionEnabled;
|
||||
return enabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"On Linux, provide an absolute REA_BINWALK_COMMAND (Binwalk 3.1.0) or REA_UNBLOB_COMMAND (Unblob 26.6.4) path and util-linux prlimit. Extraction also requires the selected format’s external extractor.",
|
||||
};
|
||||
}
|
||||
if (kind === "android-provider")
|
||||
return policy.androidAnalysisEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
ExecutionOptions,
|
||||
} from "./AnalysisProvider.js";
|
||||
import type { FirmwareRequest } from "../domain/firmwareAnalysis.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
|
||||
/** File-oriented firmware engines; executable admission remains a separate operation. */
|
||||
export interface FirmwareAnalysisPort {
|
||||
execute(
|
||||
request: FirmwareRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import type { FirmwareAnalysisPort } from "./FirmwareAnalysisPort.js";
|
||||
import {
|
||||
firmwareRequestSchema,
|
||||
type FirmwareOperation,
|
||||
} from "../domain/firmwareAnalysis.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Shared CLI/MCP validation and Evidence composition for arbitrary firmware files. */
|
||||
export class FirmwareAnalysisService {
|
||||
constructor(readonly provider: FirmwareAnalysisPort) {}
|
||||
|
||||
/** Execute an explicit inspection or extraction and preserve its producing identity. */
|
||||
async execute(
|
||||
operation: FirmwareOperation,
|
||||
input: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
if (options?.signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const parsed = firmwareRequestSchema.safeParse({ operation, input });
|
||||
if (!parsed.success)
|
||||
return err(new AnalysisInputError(operation, { cause: parsed.error }));
|
||||
const executed = await this.provider.execute(parsed.data, options);
|
||||
if (!executed.ok) return executed;
|
||||
const execution = executed.value;
|
||||
if (execution.subject === null)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Firmware execution did not bind its source artifact",
|
||||
),
|
||||
);
|
||||
return ok(
|
||||
createEvidence(execution.subject, execution.provider, {
|
||||
operation,
|
||||
parameters: jsonObjectSchema.parse(parsed.data.input),
|
||||
result: execution.result,
|
||||
rawResult: execution.rawResult,
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
confidence: "observed",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { registerCoreAnalysisCommands } from "./cli/coreAnalysisCommands.js";
|
||||
import { registerUtilityCommands } from "./cli/utilityCommands.js";
|
||||
import { registerArtifactCommands } from "./cli/artifactCommands.js";
|
||||
import { registerManagedCommands } from "./cli/managedCommands.js";
|
||||
import { registerFirmwareCommands } from "./cli/firmwareCommands.js";
|
||||
import { registerAndroidCommands } from "./cli/androidCommands.js";
|
||||
import { registerEvidenceCommands } from "./cliEvidenceCommands.js";
|
||||
import { registerProcessCommands } from "./cli/processCommands.js";
|
||||
@@ -49,6 +50,7 @@ export const createCli = (
|
||||
registerArtifactCommands(cli, logger);
|
||||
registerManagedCommands(cli, logger);
|
||||
registerAndroidCommands(cli, logger, environment);
|
||||
registerFirmwareCommands(cli, logger, environment);
|
||||
registerEvidenceCommands(cli, logger);
|
||||
registerProcessCommands(cli, logger, environment);
|
||||
registerBrowserCommands(cli, logger);
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { z } from "incur";
|
||||
import { FirmwareAnalysisService } from "../application/FirmwareAnalysisService.js";
|
||||
import { FirmwareProvider } from "../firmware/FirmwareProvider.js";
|
||||
import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { FirmwareOperation } from "../domain/firmwareAnalysis.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { withCommandCancellation } from "./commandCancellation.js";
|
||||
|
||||
/** One-shot firmware CLI commands backed by the same workflows as MCP. */
|
||||
export const registerFirmwareCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
): void => {
|
||||
const service = new FirmwareAnalysisService(
|
||||
new FirmwareProvider(environment),
|
||||
);
|
||||
const execute = (
|
||||
name: string,
|
||||
operation: FirmwareOperation,
|
||||
input: unknown,
|
||||
) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, name, async () => {
|
||||
const result = await service.execute(operation, input, { signal });
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
);
|
||||
const path = z.string().describe("Local firmware path; never executed");
|
||||
cli.command(CLI_COMMANDS.inspectFirmwareRegions, {
|
||||
description:
|
||||
"Inspect firmware signature candidates without extracting them",
|
||||
args: z.object({ path }),
|
||||
run: ({ args }) =>
|
||||
execute(
|
||||
CLI_COMMANDS.inspectFirmwareRegions,
|
||||
"inspect_firmware_regions",
|
||||
args,
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.extractFirmware, {
|
||||
description:
|
||||
"Extract selected firmware bytes and return verified files and provenance",
|
||||
args: z.object({
|
||||
path,
|
||||
outputDirectory: z
|
||||
.string()
|
||||
.describe("Absolute absent output directory; parent must exist"),
|
||||
}),
|
||||
options: z.object({
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.optional()
|
||||
.describe("Selected byte offset; requires length"),
|
||||
length: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.optional()
|
||||
.describe("Selected byte length; requires offset"),
|
||||
maxDepth: z
|
||||
.number()
|
||||
.int()
|
||||
.optional()
|
||||
.describe("Extraction depth, 1–10; default 3"),
|
||||
maxOutputBytes: z
|
||||
.number()
|
||||
.int()
|
||||
.optional()
|
||||
.describe("Staging byte budget; default 256 MiB, maximum 512 MiB"),
|
||||
maxOutputFiles: z
|
||||
.number()
|
||||
.int()
|
||||
.optional()
|
||||
.describe("Staging entry budget; default 10000"),
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
execute(CLI_COMMANDS.extractFirmware, "extract_firmware", {
|
||||
path: args.path,
|
||||
output_directory: args.outputDirectory,
|
||||
...(options.offset === undefined && options.length === undefined
|
||||
? {}
|
||||
: { range: { offset: options.offset, length: options.length } }),
|
||||
...(options.maxDepth === undefined
|
||||
? {}
|
||||
: { max_depth: options.maxDepth }),
|
||||
...(options.maxOutputBytes === undefined
|
||||
? {}
|
||||
: { max_output_bytes: options.maxOutputBytes }),
|
||||
...(options.maxOutputFiles === undefined
|
||||
? {}
|
||||
: { max_output_files: options.maxOutputFiles }),
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -32,6 +32,8 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
resolveNativeCallTargets: "resolve-native-call-targets",
|
||||
inspectAssetCatalog: "inspect-asset-catalog",
|
||||
inspectManagedArtifact: "inspect-managed-artifact",
|
||||
inspectFirmwareRegions: "inspect-firmware-regions",
|
||||
extractFirmware: "extract-firmware",
|
||||
inspectAndroidPackage: "inspect-android-package",
|
||||
searchAndroidClasses: "search-android-classes",
|
||||
inspectAndroidClass: "inspect-android-class",
|
||||
|
||||
@@ -8,6 +8,7 @@ import { OFFICIAL_TOOL_CONTRACTS } from "./officialToolContracts.js";
|
||||
import { SESSION_TOOL_CONTRACTS } from "./sessionToolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { FIRMWARE_TOOL_CONTRACTS } from "./firmwareToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./androidToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
@@ -75,6 +76,7 @@ describe("tool contract surface", () => {
|
||||
...NATIVE_TOOL_CONTRACTS,
|
||||
...ARTIFACT_TOOL_CONTRACTS,
|
||||
...ANDROID_TOOL_CONTRACTS,
|
||||
...FIRMWARE_TOOL_CONTRACTS,
|
||||
...MANAGED_TOOL_CONTRACTS,
|
||||
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
...BROWSER_TOOL_CONTRACTS,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
firmwareInputSchemas,
|
||||
firmwareResultSchemas,
|
||||
} from "../domain/firmwareAnalysis.js";
|
||||
import type { ToolContract } from "./toolContractTypes.js";
|
||||
import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
|
||||
/** Explicit local firmware observations and extraction, backed by caller-supplied tools. */
|
||||
export const FIRMWARE_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_firmware_regions",
|
||||
...toolContractMetadata("inspect_firmware_regions"),
|
||||
kind: "firmware-provider",
|
||||
description:
|
||||
"Inspect signature candidates in a local firmware file with Binwalk 3.1.0. Returns offsets, reported lengths, descriptions and raw confidence values. Length validation and runtime addresses remain unknown. No extraction or target execution. Linux, caller-supplied tool and util-linux prlimit required; 128 MiB input limit, one worker and 120-second deadline.",
|
||||
inputSchema: firmwareInputSchemas.inspect_firmware_regions,
|
||||
outputSchema: evidenceResultOf(
|
||||
firmwareResultSchemas.inspect_firmware_regions,
|
||||
),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect firmware regions",
|
||||
input: { path: "/tmp/firmware.bin" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "extract_firmware",
|
||||
...toolContractMetadata("extract_firmware"),
|
||||
kind: "firmware-provider",
|
||||
description:
|
||||
"Extract caller-selected firmware bytes with Unblob 26.6.4 into an absent output directory. Returns verified child paths/digests, task derivations, unknown chunks and extraction diagnostics inline. Preserves the default sandbox; publishes regular files only. Linux, caller-supplied tool, format-specific extractors and util-linux prlimit required. No mounts or extracted-code execution. Select a returned native file with open_binary for Ghidra analysis; decompressed offsets are not original-file addresses.",
|
||||
inputSchema: firmwareInputSchemas.extract_firmware,
|
||||
outputSchema: evidenceResultOf(firmwareResultSchemas.extract_firmware),
|
||||
examples: [
|
||||
{
|
||||
title: "Extract selected firmware",
|
||||
input: {
|
||||
path: "/tmp/firmware.bin",
|
||||
output_directory: "/tmp/firmware-output",
|
||||
range: { offset: 64, length: 4096 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -25,6 +25,7 @@ export const TOOL_KINDS = [
|
||||
"artifact-provider",
|
||||
"managed-provider",
|
||||
"android-provider",
|
||||
"firmware-provider",
|
||||
"browser-provider",
|
||||
"electron-provider",
|
||||
"runtime-provider",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { SESSION_TOOL_CONTRACTS } from "./sessionToolContracts.js";
|
||||
import { TOOL_CONTRACTS } from "./toolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { FIRMWARE_TOOL_CONTRACTS } from "./firmwareToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./androidToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
@@ -21,6 +22,7 @@ const GROUPS = {
|
||||
artifact: ARTIFACT_TOOL_CONTRACTS,
|
||||
managed: MANAGED_TOOL_CONTRACTS,
|
||||
android: ANDROID_TOOL_CONTRACTS,
|
||||
firmware: FIRMWARE_TOOL_CONTRACTS,
|
||||
managed_workflow: MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
browser_provider: BROWSER_PROVIDER_TOOL_CONTRACTS,
|
||||
electron: ELECTRON_TOOL_CONTRACTS,
|
||||
@@ -93,6 +95,8 @@ const PUBLISHED_TOOL_NAME_FLOOR = [
|
||||
"inspect_electron_page",
|
||||
"inspect_macho",
|
||||
"inspect_managed_artifact",
|
||||
"inspect_firmware_regions",
|
||||
"extract_firmware",
|
||||
"inspect_android_package",
|
||||
"search_android_classes",
|
||||
"inspect_android_class",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { FIRMWARE_TOOL_CONTRACTS } from "./firmwareToolContracts.js";
|
||||
import { ANDROID_TOOL_CONTRACTS } from "./androidToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { BROWSER_PROVIDER_TOOL_CONTRACTS } from "./browserProviderToolContracts.js";
|
||||
@@ -21,6 +22,7 @@ export const TOOL_CONTRACTS = [
|
||||
...ARTIFACT_TOOL_CONTRACTS,
|
||||
...MANAGED_TOOL_CONTRACTS,
|
||||
...ANDROID_TOOL_CONTRACTS,
|
||||
...FIRMWARE_TOOL_CONTRACTS,
|
||||
...MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
...BROWSER_PROVIDER_TOOL_CONTRACTS,
|
||||
...ELECTRON_TOOL_CONTRACTS,
|
||||
|
||||
@@ -41,6 +41,17 @@ const sessionEvidence = effects({ mutatesSession: true });
|
||||
|
||||
/** Explicit effect audit for every public tool. */
|
||||
export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
inspect_firmware_regions: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
extract_firmware: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
idempotent: false,
|
||||
}),
|
||||
inspect_android_package: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "./analysisErrorCore.js";
|
||||
import { ArtifactOperationError } from "./artifactOperationError.js";
|
||||
import { BinaryTargetError } from "./configurationErrors.js";
|
||||
@@ -160,6 +161,23 @@ describe("analysis error projection: provider failures", () => {
|
||||
});
|
||||
|
||||
describe("analysis error projection: caller contract", () => {
|
||||
it("preserves the reported output constraint without exposing its internal cause", () => {
|
||||
const projected = projectAnalysisError(
|
||||
new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
"Report exceeded the declared byte budget",
|
||||
{ cause: new Error("private internal cause") },
|
||||
),
|
||||
);
|
||||
expect(projected).toMatchObject({
|
||||
code: "unreadable_output",
|
||||
details: {
|
||||
operation: "extract_firmware",
|
||||
reason: "Report exceeded the declared byte budget",
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(projected)).not.toContain("private internal cause");
|
||||
});
|
||||
it("maps representative failures without exposing causes", () => {
|
||||
const secretCause = new Error("secret-token");
|
||||
const projected = [
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisTimeoutError,
|
||||
} from "./analysisErrorCore.js";
|
||||
import { ArtifactOperationError } from "./artifactOperationError.js";
|
||||
@@ -176,6 +177,8 @@ const errorDetails = (
|
||||
const requestErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof AnalysisOutputError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
if (error instanceof AnalysisInputError && error.issues.length > 0)
|
||||
return {
|
||||
operation: error.operation,
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { z } from "zod";
|
||||
import { digestSchema } from "./digests.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
const bytes = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
||||
const range = z.strictObject({ offset: bytes, length: bytes.positive() });
|
||||
const target = {
|
||||
path: z.string().min(1).describe("Local firmware file; never executed"),
|
||||
};
|
||||
|
||||
/** Explicit firmware inspection and extraction intent, independent of engines. */
|
||||
export const firmwareInputSchemas = {
|
||||
inspect_firmware_regions: z.strictObject(target),
|
||||
extract_firmware: z.strictObject({
|
||||
...target,
|
||||
output_directory: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Absolute, absent output directory; parent must exist"),
|
||||
range: range
|
||||
.optional()
|
||||
.describe("Explicit file-byte interval; omit to extract the whole file"),
|
||||
max_depth: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(10)
|
||||
.default(3)
|
||||
.describe("Extraction depth; reaching it yields partial analysis"),
|
||||
max_output_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(512 * 1024 * 1024)
|
||||
.default(256 * 1024 * 1024)
|
||||
.describe(
|
||||
"Staging file-byte budget, checked during extraction; transient overshoot is possible",
|
||||
),
|
||||
max_output_files: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(100_000)
|
||||
.default(10_000)
|
||||
.describe("Staging entry budget, including directories and links"),
|
||||
}),
|
||||
} as const;
|
||||
|
||||
/** Supported firmware operations. */
|
||||
export type FirmwareOperation = keyof typeof firmwareInputSchemas;
|
||||
/** Correlated, validated firmware request. */
|
||||
export type FirmwareRequest = {
|
||||
[Name in FirmwareOperation]: {
|
||||
operation: Name;
|
||||
input: z.infer<(typeof firmwareInputSchemas)[Name]>;
|
||||
};
|
||||
}[FirmwareOperation];
|
||||
/** Validate the operation with its exact input contract. */
|
||||
export const firmwareRequestSchema = z.discriminatedUnion("operation", [
|
||||
z.strictObject({
|
||||
operation: z.literal("inspect_firmware_regions"),
|
||||
input: firmwareInputSchemas.inspect_firmware_regions,
|
||||
}),
|
||||
z.strictObject({
|
||||
operation: z.literal("extract_firmware"),
|
||||
input: firmwareInputSchemas.extract_firmware,
|
||||
}),
|
||||
]);
|
||||
|
||||
const engine = z.strictObject({
|
||||
name: z.string(),
|
||||
version: z.string(),
|
||||
executable_path: z.string(),
|
||||
executable_sha256: digestSchema,
|
||||
source_revision: z.null(),
|
||||
worker_count: z.literal(1),
|
||||
});
|
||||
const selection = z.strictObject({ ...range.shape, sha256: digestSchema });
|
||||
const chunk = z.strictObject({
|
||||
input_path: z.string(),
|
||||
provider_id: z.string(),
|
||||
range,
|
||||
handler: z.string().nullable(),
|
||||
encrypted: z.boolean().nullable(),
|
||||
root_file_range: range.nullable(),
|
||||
});
|
||||
|
||||
/** Portable results retain reported boundaries, unknowns and extraction lineage. */
|
||||
export const firmwareResultSchemas = {
|
||||
inspect_firmware_regions: z.strictObject({
|
||||
engine,
|
||||
input_size: bytes,
|
||||
regions: z.array(
|
||||
z.strictObject({
|
||||
provider_id: z.string(),
|
||||
offset: bytes,
|
||||
reported_size: bytes,
|
||||
signature: z.string(),
|
||||
description: z.string(),
|
||||
reported_confidence: z.number().int().min(0).max(255),
|
||||
size_basis: z.literal("provider_reported_validation_unknown"),
|
||||
}),
|
||||
),
|
||||
coverage: z.literal("signature_scan"),
|
||||
}),
|
||||
extract_firmware: z.strictObject({
|
||||
engine,
|
||||
selection,
|
||||
output_directory: z.string(),
|
||||
coverage: z.enum(["complete", "partial"]),
|
||||
files: z.array(
|
||||
z.strictObject({
|
||||
relative_path: z.string(),
|
||||
path: z.string(),
|
||||
size: bytes,
|
||||
sha256: digestSchema,
|
||||
reported_sha256: digestSchema.nullable(),
|
||||
mime_type: z.string().nullable(),
|
||||
analysis_depth: bytes.nullable(),
|
||||
runtime_address: z.null(),
|
||||
original_file_range: z.null(),
|
||||
}),
|
||||
),
|
||||
unpublished_entries: z.array(
|
||||
z.strictObject({
|
||||
relative_path: z.string(),
|
||||
kind: z.enum(["symlink", "special"]),
|
||||
link_target: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
chunks: z.array(chunk),
|
||||
derivations: z.array(
|
||||
z.strictObject({
|
||||
parent_path: z.string(),
|
||||
child_path: z.string(),
|
||||
provider_blob_id: z.string(),
|
||||
handler: z.string().nullable(),
|
||||
parent_file_range: range.nullable(),
|
||||
}),
|
||||
),
|
||||
depth_limited_paths: z.array(z.string()),
|
||||
diagnostics: z.array(jsonValueSchema),
|
||||
published_bytes: bytes,
|
||||
}),
|
||||
} as const;
|
||||
@@ -0,0 +1,229 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { access, realpath } from "node:fs/promises";
|
||||
import { constants } from "node:fs";
|
||||
import { isAbsolute } from "node:path";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisCancelledError,
|
||||
AnalysisTimeoutError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import {
|
||||
spawnOwnedProviderProcess,
|
||||
ProviderProcessSupervisor,
|
||||
type OwnedProviderProcessSpawnOptions,
|
||||
type SpawnedOwnedProviderProcess,
|
||||
} from "../process/ProviderProcess.js";
|
||||
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
|
||||
import { FIRMWARE_LIMITS } from "./FirmwareRelease.js";
|
||||
import {
|
||||
hashFirmwareFile,
|
||||
inventoryFirmwareOutput,
|
||||
readFirmwareReport,
|
||||
} from "./FirmwareFiles.js";
|
||||
|
||||
/** Injectable owned launcher for production protocol and lifecycle tests. */
|
||||
export type FirmwareLauncher = (
|
||||
options: OwnedProviderProcessSpawnOptions,
|
||||
) => Promise<SpawnedOwnedProviderProcess>;
|
||||
|
||||
/** Resolve explicitly supplied executable paths; never install or search for engines. */
|
||||
export const resolveFirmwareCommand = async (
|
||||
environment: Readonly<Record<string, string | undefined>>,
|
||||
engine: "binwalk" | "unblob",
|
||||
operation: string,
|
||||
) => {
|
||||
const variable =
|
||||
engine === "binwalk" ? "REA_BINWALK_COMMAND" : "REA_UNBLOB_COMMAND";
|
||||
const configured = environment[variable];
|
||||
if (
|
||||
process.platform !== "linux" ||
|
||||
configured === undefined ||
|
||||
!isAbsolute(configured)
|
||||
)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
engine,
|
||||
operation,
|
||||
`This integration requires Linux and an absolute ${variable} path to the caller-supplied tool`,
|
||||
);
|
||||
const command = await realpath(configured).catch((cause: unknown) => {
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
engine,
|
||||
operation,
|
||||
`${variable} is unavailable: ${cause instanceof Error ? cause.message : String(cause)}`,
|
||||
);
|
||||
});
|
||||
await access(command, constants.X_OK);
|
||||
const limiter =
|
||||
environment.REA_FIRMWARE_PRLIMIT_COMMAND ?? "/usr/bin/prlimit";
|
||||
if (!isAbsolute(limiter))
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
engine,
|
||||
operation,
|
||||
"REA_FIRMWARE_PRLIMIT_COMMAND must be absolute",
|
||||
);
|
||||
await access(limiter, constants.X_OK).catch(() => {
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
engine,
|
||||
operation,
|
||||
`Resource limiter unavailable: ${limiter}; provide util-linux prlimit`,
|
||||
);
|
||||
});
|
||||
return { command, limiter, sha256: await hashFirmwareFile(command) };
|
||||
};
|
||||
|
||||
/** Execute one bounded provider command and verify its owned descendants have stopped. */
|
||||
export const runFirmwareCommand = async (context: {
|
||||
engine: string;
|
||||
operation: string;
|
||||
command: string;
|
||||
limiter: string;
|
||||
args: readonly string[];
|
||||
cwd: string;
|
||||
environment: Readonly<Record<string, string | undefined>>;
|
||||
signal: AbortSignal;
|
||||
launcher?: FirmwareLauncher;
|
||||
outputBudget?: { root: string; bytes: number; entries: number };
|
||||
acceptReportedExtractionFailure?: boolean;
|
||||
}) => {
|
||||
const { engine, operation, signal } = context;
|
||||
signal.throwIfAborted();
|
||||
const runId = `rea-firmware-${randomUUID()}`;
|
||||
const spawned = await (context.launcher ?? spawnOwnedProviderProcess)({
|
||||
command: context.limiter,
|
||||
arguments: [
|
||||
`--as=${FIRMWARE_LIMITS.addressSpaceBytes}`,
|
||||
`--fsize=${context.outputBudget?.bytes ?? FIRMWARE_LIMITS.reportBytes}`,
|
||||
"--core=0",
|
||||
"--cpu=120",
|
||||
"--",
|
||||
context.command,
|
||||
...context.args,
|
||||
],
|
||||
expectedCommand: null,
|
||||
runId,
|
||||
cwd: context.cwd,
|
||||
hostEnvironment: context.environment,
|
||||
env: {
|
||||
TMPDIR: context.cwd,
|
||||
OMP_NUM_THREADS: "1",
|
||||
OPENBLAS_NUM_THREADS: "1",
|
||||
RAYON_NUM_THREADS: "1",
|
||||
NO_COLOR: "1",
|
||||
},
|
||||
});
|
||||
const supervisor = new ProviderProcessSupervisor({
|
||||
...spawned,
|
||||
ownsProcessLifetime: true,
|
||||
cleanup:
|
||||
spawned.cleanup ?? (() => cleanupOwnedProcessGroup(spawned.ownership)),
|
||||
});
|
||||
let failure: unknown;
|
||||
try {
|
||||
const deadline = Date.now() + FIRMWARE_LIMITS.timeoutMs;
|
||||
while (!(await supervisor.waitForExit(100))) {
|
||||
if (signal.aborted) throw new AnalysisCancelledError(operation);
|
||||
if (Date.now() >= deadline)
|
||||
throw new AnalysisTimeoutError(operation, FIRMWARE_LIMITS.timeoutMs);
|
||||
if (context.outputBudget !== undefined)
|
||||
await inventoryFirmwareOutput(
|
||||
context.outputBudget.root,
|
||||
context.outputBudget.bytes,
|
||||
context.outputBudget.entries,
|
||||
operation,
|
||||
signal,
|
||||
);
|
||||
}
|
||||
if (signal.aborted) throw new AnalysisCancelledError(operation);
|
||||
} catch (cause: unknown) {
|
||||
failure = cause;
|
||||
}
|
||||
const stopped = await supervisor.stop();
|
||||
const snapshot = supervisor.snapshot();
|
||||
supervisor.dispose();
|
||||
if (stopped.status === "incomplete")
|
||||
throw new ProviderCleanupError(engine, [runId, context.cwd], {
|
||||
reason: stopped.reason,
|
||||
leader_pid: spawned.ownership.leaderPid,
|
||||
process_group_id: spawned.ownership.processGroupId,
|
||||
exit_code: snapshot.exitCode ?? null,
|
||||
signal: snapshot.signal ?? null,
|
||||
stdout: snapshot.stdout.text,
|
||||
stderr: snapshot.stderr.text,
|
||||
stdout_bytes: snapshot.stdout.bytes,
|
||||
stderr_bytes: snapshot.stderr.bytes,
|
||||
previous_error: failure instanceof Error ? failure.message : null,
|
||||
});
|
||||
if (failure !== undefined) throw failure;
|
||||
if (
|
||||
snapshot.exitCode !== 0 &&
|
||||
!(
|
||||
context.acceptReportedExtractionFailure === true &&
|
||||
snapshot.exitCode === 1
|
||||
)
|
||||
)
|
||||
throw new ProviderAdapterError(engine, operation, {
|
||||
diagnostics: {
|
||||
reason:
|
||||
"Tool failed; inspect exit status and stderr for format, dependency, sandbox or resource-limit failures",
|
||||
exit_code: snapshot.exitCode ?? null,
|
||||
signal: snapshot.signal ?? null,
|
||||
stdout: snapshot.stdout.text,
|
||||
stderr: snapshot.stderr.text,
|
||||
stdout_bytes: snapshot.stdout.bytes,
|
||||
stderr_bytes: snapshot.stderr.bytes,
|
||||
},
|
||||
});
|
||||
return {
|
||||
stdout: snapshot.stdout,
|
||||
stderr: snapshot.stderr,
|
||||
exit_code: snapshot.exitCode,
|
||||
signal: snapshot.signal ?? null,
|
||||
command: context.command,
|
||||
args: [...context.args],
|
||||
resource_limiter: context.limiter,
|
||||
};
|
||||
};
|
||||
|
||||
/** Preserve tool failure diagnostics when an accepted exit 1 has no usable report. */
|
||||
export const readFirmwareCommandReport = async (context: {
|
||||
path: string;
|
||||
engine: string;
|
||||
operation: string;
|
||||
execution: Awaited<ReturnType<typeof runFirmwareCommand>>;
|
||||
}): Promise<unknown> => {
|
||||
try {
|
||||
return await readFirmwareReport(context.path, context.operation);
|
||||
} catch (cause: unknown) {
|
||||
if (context.execution.exit_code === 1)
|
||||
throw new ProviderAdapterError(context.engine, context.operation, {
|
||||
cause,
|
||||
diagnostics: {
|
||||
reason:
|
||||
"Tool exited 1 without a usable analysis report; inspect stderr for startup, sandbox or dependency failures",
|
||||
report_failure:
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
exit_code: 1,
|
||||
signal: context.execution.signal,
|
||||
stdout: context.execution.stdout.text,
|
||||
stderr: context.execution.stderr.text,
|
||||
stdout_bytes: context.execution.stdout.bytes,
|
||||
stderr_bytes: context.execution.stderr.bytes,
|
||||
},
|
||||
});
|
||||
const diagnostics = `stdout (${context.execution.stdout.bytes} bytes): ${context.execution.stdout.text}; stderr (${context.execution.stderr.bytes} bytes): ${context.execution.stderr.text}`;
|
||||
if (cause instanceof AnalysisOutputError)
|
||||
throw new AnalysisOutputError(
|
||||
context.operation,
|
||||
`${cause.reason}; ${diagnostics}`,
|
||||
{ cause },
|
||||
);
|
||||
throw new AnalysisOutputError(
|
||||
context.operation,
|
||||
`Tool did not produce the expected complete report: ${context.path}; ${diagnostics}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,265 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants, createReadStream, createWriteStream } from "node:fs";
|
||||
import {
|
||||
chmod,
|
||||
lstat,
|
||||
open,
|
||||
readdir,
|
||||
readlink,
|
||||
realpath,
|
||||
} from "node:fs/promises";
|
||||
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { Transform } from "node:stream";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import type { FirmwareRequest } from "../domain/firmwareAnalysis.js";
|
||||
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
|
||||
import { FIRMWARE_LIMITS } from "./FirmwareRelease.js";
|
||||
|
||||
/** One regular file or unpublished filesystem entry in a private extraction. */
|
||||
export interface FirmwareEntry {
|
||||
readonly relativePath: string;
|
||||
readonly path: string;
|
||||
readonly size: number;
|
||||
readonly kind: "file" | "symlink" | "special";
|
||||
readonly linkTarget: string | null;
|
||||
}
|
||||
|
||||
/** Hash a regular tool or extracted file without retaining its bytes in memory. */
|
||||
export const hashFirmwareFile = async (
|
||||
path: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> => {
|
||||
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
const hash = createHash("sha256");
|
||||
try {
|
||||
if (!(await handle.stat()).isFile())
|
||||
throw new Error(`Not a regular file: ${path}`);
|
||||
for await (const chunk of handle.createReadStream({ autoClose: false })) {
|
||||
signal?.throwIfAborted();
|
||||
hash.update(chunk);
|
||||
}
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
return hash.digest("hex");
|
||||
};
|
||||
|
||||
/** Copy and identify the exact bytes consumed by firmware providers. */
|
||||
export const snapshotFirmware = async (
|
||||
request: FirmwareRequest,
|
||||
root: string,
|
||||
signal: AbortSignal,
|
||||
) => {
|
||||
const sourcePath = resolve(request.input.path);
|
||||
const source = await realpath(sourcePath);
|
||||
const handle = await open(source, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
const fullPath = join(root, "firmware.bin");
|
||||
const hash = createHash("sha256");
|
||||
let size = 0;
|
||||
try {
|
||||
const stat = await handle.stat();
|
||||
if (
|
||||
!stat.isFile() ||
|
||||
stat.size === 0 ||
|
||||
stat.size > FIRMWARE_LIMITS.inputBytes
|
||||
)
|
||||
throw new AnalysisInputError(request.operation, undefined, [
|
||||
{
|
||||
path: ["path"],
|
||||
reason: "out_of_range",
|
||||
message: `Firmware must be a nonempty regular file no larger than ${FIRMWARE_LIMITS.inputBytes} bytes`,
|
||||
},
|
||||
]);
|
||||
const meter = new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
size += chunk.length;
|
||||
if (size > FIRMWARE_LIMITS.inputBytes) {
|
||||
callback(new Error("Firmware grew beyond the input byte budget"));
|
||||
return;
|
||||
}
|
||||
hash.update(chunk);
|
||||
callback(null, chunk);
|
||||
},
|
||||
});
|
||||
await pipeline(
|
||||
handle.createReadStream({ autoClose: false }),
|
||||
meter,
|
||||
createWriteStream(fullPath, { flags: "wx", mode: 0o600 }),
|
||||
{ signal },
|
||||
);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
await chmod(fullPath, 0o400);
|
||||
const sha256 = hash.digest("hex");
|
||||
const selected =
|
||||
request.operation === "extract_firmware" ? request.input.range : undefined;
|
||||
const offset = selected?.offset ?? 0;
|
||||
const length = selected?.length ?? size;
|
||||
if (length === 0 || offset > size || length > size - offset)
|
||||
throw new AnalysisInputError(request.operation, undefined, [
|
||||
{
|
||||
path: ["range"],
|
||||
reason: "out_of_range",
|
||||
message: `Selected range must be within the ${size}-byte firmware file`,
|
||||
},
|
||||
]);
|
||||
let inputPath = fullPath;
|
||||
if (selected !== undefined) {
|
||||
inputPath = join(root, "selected.bin");
|
||||
await pipeline(
|
||||
createReadStream(fullPath, { start: offset, end: offset + length - 1 }),
|
||||
createWriteStream(inputPath, { flags: "wx", mode: 0o600 }),
|
||||
{ signal },
|
||||
);
|
||||
await chmod(inputPath, 0o400);
|
||||
}
|
||||
return {
|
||||
subject: { path: sourcePath, sha256, format: "file" as const },
|
||||
size,
|
||||
inputPath,
|
||||
selection: {
|
||||
offset,
|
||||
length,
|
||||
sha256:
|
||||
selected === undefined
|
||||
? sha256
|
||||
: await hashFirmwareFile(inputPath, signal),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Read a complete bounded report; oversized data is never reported as complete. */
|
||||
export const readFirmwareReport = async (
|
||||
path: string,
|
||||
operation: string,
|
||||
): Promise<unknown> => {
|
||||
const handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
||||
try {
|
||||
if (!(await handle.stat()).isFile())
|
||||
throw new AnalysisOutputError(operation, "Report is not a regular file");
|
||||
const bytes = await readBoundedFileBytes(
|
||||
handle,
|
||||
FIRMWARE_LIMITS.reportBytes,
|
||||
);
|
||||
if (bytes === undefined)
|
||||
throw new AnalysisOutputError(
|
||||
operation,
|
||||
`Report exceeded ${FIRMWARE_LIMITS.reportBytes} bytes`,
|
||||
);
|
||||
try {
|
||||
const value: unknown = JSON.parse(bytes.toString("utf8"));
|
||||
return value;
|
||||
} catch (cause: unknown) {
|
||||
throw new AnalysisOutputError(
|
||||
operation,
|
||||
"Tool report is not valid complete JSON",
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** Inventory private output without following links, enforcing aggregate staging budgets. */
|
||||
export const inventoryFirmwareOutput = async (
|
||||
root: string,
|
||||
maxBytes: number,
|
||||
maxEntries: number,
|
||||
operation: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<FirmwareEntry[]> => {
|
||||
const entries: FirmwareEntry[] = [];
|
||||
const pending = [root];
|
||||
let bytes = 0;
|
||||
let count = 0;
|
||||
while (pending.length > 0) {
|
||||
if (signal?.aborted === true) throw new AnalysisCancelledError(operation);
|
||||
const directory = pending.pop();
|
||||
if (directory === undefined) break;
|
||||
const directoryStat = await lstat(directory).catch((cause: unknown) => {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (
|
||||
directoryStat === undefined ||
|
||||
!directoryStat.isDirectory() ||
|
||||
directoryStat.isSymbolicLink()
|
||||
)
|
||||
continue;
|
||||
const names = await readdir(directory).catch((cause: unknown) => {
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT")
|
||||
return [];
|
||||
throw cause;
|
||||
});
|
||||
for (const name of names.sort()) {
|
||||
count++;
|
||||
if (count > maxEntries)
|
||||
throw new AnalysisOutputError(
|
||||
operation,
|
||||
`Staging entry budget exceeded (${maxEntries})`,
|
||||
);
|
||||
const path = join(directory, name);
|
||||
const stat = await lstat(path).catch((cause: unknown) => {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
cause.code === "ENOENT"
|
||||
)
|
||||
return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (stat === undefined) continue;
|
||||
if (stat.isDirectory()) {
|
||||
pending.push(path);
|
||||
continue;
|
||||
}
|
||||
if (stat.isFile()) bytes += stat.size;
|
||||
if (bytes > maxBytes)
|
||||
throw new AnalysisOutputError(
|
||||
operation,
|
||||
`Staging byte budget exceeded (${maxBytes})`,
|
||||
);
|
||||
entries.push({
|
||||
path,
|
||||
relativePath: relative(root, path).split(sep).join("/"),
|
||||
size: stat.size,
|
||||
kind: stat.isSymbolicLink()
|
||||
? "symlink"
|
||||
: stat.isFile()
|
||||
? "file"
|
||||
: "special",
|
||||
linkTarget: stat.isSymbolicLink() ? await readlink(path) : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
return entries.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
|
||||
};
|
||||
|
||||
/** Bind producer paths to the selected input or private extraction tree. */
|
||||
export const firmwareLogicalPath = (
|
||||
path: string,
|
||||
inputPath: string,
|
||||
outputRoot: string,
|
||||
): string => {
|
||||
if (path === inputPath) return "$input";
|
||||
const rel = relative(outputRoot, path);
|
||||
if (
|
||||
!isAbsolute(path) ||
|
||||
rel === ".." ||
|
||||
rel.startsWith(`..${sep}`) ||
|
||||
isAbsolute(rel)
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`Provider reported a path outside its owned output: ${path}`,
|
||||
);
|
||||
return rel === "" ? "$output" : `$output/${rel.split(sep).join("/")}`;
|
||||
};
|
||||
@@ -0,0 +1,350 @@
|
||||
import { join, isAbsolute } from "node:path";
|
||||
import { z } from "zod";
|
||||
import type { FirmwareAnalysisPort } from "../application/FirmwareAnalysisPort.js";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type ExecutionOptions,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import {
|
||||
firmwareResultSchemas,
|
||||
type FirmwareRequest,
|
||||
} from "../domain/firmwareAnalysis.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisOutputError,
|
||||
AnalysisTimeoutError,
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import { publishFirmwareExtraction } from "./FirmwarePublication.js";
|
||||
import {
|
||||
FIRMWARE_LIMITS,
|
||||
FIRMWARE_RELEASES,
|
||||
BINWALK_PROVIDER_IDENTITY,
|
||||
UNBLOB_PROVIDER_IDENTITY,
|
||||
} from "./FirmwareRelease.js";
|
||||
import {
|
||||
resolveFirmwareCommand,
|
||||
runFirmwareCommand,
|
||||
readFirmwareCommandReport,
|
||||
type FirmwareLauncher,
|
||||
} from "./FirmwareCommand.js";
|
||||
import { inventoryFirmwareOutput, snapshotFirmware } from "./FirmwareFiles.js";
|
||||
import {
|
||||
normalizeBinwalkReport,
|
||||
normalizeUnblobReport,
|
||||
} from "./FirmwareReports.js";
|
||||
|
||||
type Outcome = Awaited<ReturnType<FirmwareAnalysisPort["execute"]>>;
|
||||
const waitForPredecessor = (
|
||||
predecessor: Promise<void>,
|
||||
operation: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const abort = () => reject(new AnalysisCancelledError(operation));
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
if (signal?.aborted === true) abort();
|
||||
void predecessor.then(() => {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
const limitations = [
|
||||
"Signature matches and reported sizes do not establish partition validity, encryption or runtime mappings. Binwalk may infer unknown lengths before emitting its report.",
|
||||
"Only Linux is supported by this integration. One worker, inherited per-process address-space/file-size/CPU limits and a deadline constrain execution; staging byte and entry budgets are polled and may transiently overshoot. Limits are not aggregate process-memory or filesystem quotas.",
|
||||
"Unblob's default sandbox and skip rules remain enabled. Missing external extractors, unknown chunks, encrypted chunks and depth limits yield partial coverage. Extracted code is never executed; only regular files are published, without executable permission bits.",
|
||||
"The actual launcher executable is hashed. Interpreter, shared libraries and installed Python package dependencies are not independently attested; source revision remains unknown for caller-supplied builds.",
|
||||
] as const;
|
||||
|
||||
/** Queued bring-your-own firmware adapters with private snapshots and owned cleanup. */
|
||||
export class FirmwareProvider implements FirmwareAnalysisPort {
|
||||
#tail: Promise<void> = Promise.resolve();
|
||||
#cleanupFailure: AnalysisError | undefined;
|
||||
constructor(
|
||||
readonly environment: Readonly<
|
||||
Record<string, string | undefined>
|
||||
> = process.env,
|
||||
readonly launcher?: FirmwareLauncher,
|
||||
) {}
|
||||
|
||||
/** Inspect regions or explicitly extract selected bytes without changing the source. */
|
||||
async execute(
|
||||
request: FirmwareRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Outcome> {
|
||||
const predecessor = this.#tail;
|
||||
let release = () => {};
|
||||
this.#tail = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
// Cancel the caller promptly without letting a later request bypass its predecessor.
|
||||
try {
|
||||
await waitForPredecessor(predecessor, request.operation, options?.signal);
|
||||
} catch (cause: unknown) {
|
||||
void predecessor.then(release);
|
||||
return err(
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new AnalysisCancelledError(request.operation),
|
||||
);
|
||||
}
|
||||
try {
|
||||
return await this.#execute(request, options);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
async #execute(
|
||||
request: FirmwareRequest,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Outcome> {
|
||||
let root: PrivateRuntimeRoot | undefined;
|
||||
const engineName =
|
||||
request.operation === "inspect_firmware_regions" ? "binwalk" : "unblob";
|
||||
const deadline = AbortSignal.timeout(FIRMWARE_LIMITS.timeoutMs);
|
||||
const signal =
|
||||
options?.signal === undefined
|
||||
? deadline
|
||||
: AbortSignal.any([options.signal, deadline]);
|
||||
let outcome: Outcome;
|
||||
try {
|
||||
if (this.#cleanupFailure !== undefined) return err(this.#cleanupFailure);
|
||||
if (signal.aborted) throw new AnalysisCancelledError(request.operation);
|
||||
const command = await resolveFirmwareCommand(
|
||||
this.environment,
|
||||
engineName,
|
||||
request.operation,
|
||||
);
|
||||
root = await PrivateRuntimeRoot.create({ prefix: "rea-firmware-" });
|
||||
const target = await snapshotFirmware(request, root.path, signal);
|
||||
const run = (
|
||||
args: readonly string[],
|
||||
outputBudget?: { root: string; bytes: number; entries: number },
|
||||
) =>
|
||||
runFirmwareCommand({
|
||||
engine: engineName,
|
||||
operation: request.operation,
|
||||
...command,
|
||||
args,
|
||||
cwd: root?.path ?? "",
|
||||
environment: this.environment,
|
||||
signal,
|
||||
...(this.launcher === undefined ? {} : { launcher: this.launcher }),
|
||||
...(outputBudget === undefined
|
||||
? {}
|
||||
: { outputBudget, acceptReportedExtractionFailure: true }),
|
||||
});
|
||||
const versionRun = await run(["--version"]);
|
||||
const version = versionRun.stdout.text.trim();
|
||||
const expected = FIRMWARE_RELEASES[engineName].version;
|
||||
if (
|
||||
versionRun.stdout.bytes > 1024 ||
|
||||
(engineName === "binwalk"
|
||||
? version !== `binwalk ${expected}`
|
||||
: version !== expected)
|
||||
)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
engineName,
|
||||
request.operation,
|
||||
`Unsupported tool version ${version}; this adapter is verified against ${expected}`,
|
||||
);
|
||||
const engine = {
|
||||
name: engineName,
|
||||
version: expected,
|
||||
executable_path: command.command,
|
||||
executable_sha256: command.sha256,
|
||||
source_revision: null,
|
||||
worker_count: 1 as const,
|
||||
};
|
||||
const reportPath = join(root.path, "report.json");
|
||||
let result: unknown;
|
||||
let raw: unknown;
|
||||
if (request.operation === "inspect_firmware_regions") {
|
||||
const processRun = await run([
|
||||
"--quiet",
|
||||
"--search-all",
|
||||
"--threads",
|
||||
"1",
|
||||
"--log",
|
||||
reportPath,
|
||||
target.inputPath,
|
||||
]);
|
||||
const report = await readFirmwareCommandReport({
|
||||
path: reportPath,
|
||||
engine: engineName,
|
||||
operation: request.operation,
|
||||
execution: processRun,
|
||||
});
|
||||
result = firmwareResultSchemas.inspect_firmware_regions.parse({
|
||||
engine,
|
||||
input_size: target.size,
|
||||
regions: normalizeBinwalkReport(
|
||||
report,
|
||||
target.inputPath,
|
||||
target.size,
|
||||
),
|
||||
coverage: "signature_scan",
|
||||
});
|
||||
raw = { report, execution: processRun, version_execution: versionRun };
|
||||
} else {
|
||||
if (!isAbsolute(request.input.output_directory))
|
||||
throw new AnalysisInputError(request.operation, undefined, [
|
||||
{
|
||||
path: ["output_directory"],
|
||||
reason: "invalid_format",
|
||||
message: "Extraction output directory must be absolute",
|
||||
},
|
||||
]);
|
||||
const outputRoot = join(root.path, "extracted");
|
||||
const processRun = await run(
|
||||
[
|
||||
"--process-num",
|
||||
"1",
|
||||
"--depth",
|
||||
String(request.input.max_depth),
|
||||
"--randomness-depth",
|
||||
"0",
|
||||
"--report",
|
||||
reportPath,
|
||||
"--log",
|
||||
join(root.path, "unblob.log"),
|
||||
"--extract-dir",
|
||||
outputRoot,
|
||||
target.inputPath,
|
||||
],
|
||||
{
|
||||
root: outputRoot,
|
||||
bytes: request.input.max_output_bytes,
|
||||
entries: request.input.max_output_files,
|
||||
},
|
||||
);
|
||||
const report = await readFirmwareCommandReport({
|
||||
path: reportPath,
|
||||
engine: engineName,
|
||||
operation: request.operation,
|
||||
execution: processRun,
|
||||
});
|
||||
const normalized = normalizeUnblobReport(report, {
|
||||
inputPath: target.inputPath,
|
||||
outputRoot,
|
||||
...target.selection,
|
||||
maxDepth: request.input.max_depth,
|
||||
});
|
||||
if (processRun.exit_code === 1 && normalized.diagnostics.length === 0)
|
||||
throw new AnalysisOutputError(
|
||||
request.operation,
|
||||
"Unblob failed without a reported extraction diagnostic",
|
||||
);
|
||||
const entries = await inventoryFirmwareOutput(
|
||||
outputRoot,
|
||||
request.input.max_output_bytes,
|
||||
request.input.max_output_files,
|
||||
request.operation,
|
||||
signal,
|
||||
);
|
||||
result = await publishFirmwareExtraction({
|
||||
outputDirectory: request.input.output_directory,
|
||||
entries,
|
||||
normalized,
|
||||
selection: target.selection,
|
||||
engine,
|
||||
signal,
|
||||
});
|
||||
raw = { report, execution: processRun, version_execution: versionRun };
|
||||
}
|
||||
outcome = ok(
|
||||
createAnalysisExecution(
|
||||
result,
|
||||
engineName === "binwalk"
|
||||
? BINWALK_PROVIDER_IDENTITY
|
||||
: UNBLOB_PROVIDER_IDENTITY,
|
||||
{
|
||||
subject: target.subject,
|
||||
rawResult: raw,
|
||||
limitations,
|
||||
locations: [
|
||||
{
|
||||
kind: "file-offset-range",
|
||||
start: target.selection.offset,
|
||||
end: target.selection.offset + target.selection.length,
|
||||
},
|
||||
],
|
||||
},
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
outcome = err(
|
||||
cause instanceof ProviderCleanupError
|
||||
? cause
|
||||
: options?.signal?.aborted === true
|
||||
? new AnalysisCancelledError(request.operation)
|
||||
: deadline.aborted
|
||||
? new AnalysisTimeoutError(
|
||||
request.operation,
|
||||
FIRMWARE_LIMITS.timeoutMs,
|
||||
)
|
||||
: cause instanceof AnalysisError
|
||||
? cause
|
||||
: cause instanceof z.ZodError
|
||||
? new AnalysisOutputError(
|
||||
request.operation,
|
||||
"Tool report violated the pinned producer protocol",
|
||||
{ cause },
|
||||
)
|
||||
: new ProviderAdapterError(engineName, request.operation, {
|
||||
cause,
|
||||
diagnostics: {
|
||||
reason:
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: String(cause),
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (!outcome.ok && outcome.error.cleanupIncomplete) {
|
||||
this.#cleanupFailure =
|
||||
root === undefined ||
|
||||
outcome.error.cleanupResources.includes(root.path)
|
||||
? outcome.error
|
||||
: new ProviderCleanupError(
|
||||
engineName,
|
||||
[...outcome.error.cleanupResources, root.path],
|
||||
outcome.error instanceof ProviderAdapterError
|
||||
? (outcome.error.diagnostics ?? {
|
||||
reason: outcome.error.message,
|
||||
})
|
||||
: { reason: outcome.error.message },
|
||||
{ cause: outcome.error },
|
||||
);
|
||||
}
|
||||
}
|
||||
// Never remove a workspace while process ownership remains uncertain.
|
||||
if (this.#cleanupFailure !== undefined) return err(this.#cleanupFailure);
|
||||
try {
|
||||
await root?.close();
|
||||
} catch (cause: unknown) {
|
||||
this.#cleanupFailure = new ProviderCleanupError(
|
||||
engineName,
|
||||
[
|
||||
root?.path ?? "unknown",
|
||||
...(outcome.ok && request.operation === "extract_firmware"
|
||||
? [request.input.output_directory]
|
||||
: []),
|
||||
],
|
||||
{
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
previous_result: outcome.ok ? outcome.value.result : null,
|
||||
},
|
||||
);
|
||||
return err(this.#cleanupFailure);
|
||||
}
|
||||
return outcome;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { createReadStream } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { z } from "zod";
|
||||
import { SafeOutputTree } from "../artifacts/SafeOutputTree.js";
|
||||
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { firmwareResultSchemas } from "../domain/firmwareAnalysis.js";
|
||||
import { hashFirmwareFile, type FirmwareEntry } from "./FirmwareFiles.js";
|
||||
import type { normalizeUnblobReport } from "./FirmwareReports.js";
|
||||
|
||||
/** Publish verified regular files, preserving links as metadata and rolling back failed writes. */
|
||||
export const publishFirmwareExtraction = async (context: {
|
||||
outputDirectory: string;
|
||||
entries: readonly FirmwareEntry[];
|
||||
normalized: ReturnType<typeof normalizeUnblobReport>;
|
||||
selection: { offset: number; length: number; sha256: string };
|
||||
engine: z.infer<typeof firmwareResultSchemas.extract_firmware>["engine"];
|
||||
signal: AbortSignal;
|
||||
}) => {
|
||||
let tree: SafeOutputTree | undefined;
|
||||
try {
|
||||
const materialized = new Set(
|
||||
context.entries
|
||||
.filter((entry) => entry.kind === "file")
|
||||
.map((entry) => `$output/${entry.relativePath}`),
|
||||
);
|
||||
for (const path of context.normalized.files.keys()) {
|
||||
if (path !== "$input" && !materialized.has(path))
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`Reported regular file is absent from materialized output: ${path}`,
|
||||
);
|
||||
}
|
||||
const files = [];
|
||||
const unpublished = [];
|
||||
tree = await SafeOutputTree.create(context.outputDirectory);
|
||||
for (const entry of context.entries) {
|
||||
if (entry.kind !== "file") {
|
||||
unpublished.push({
|
||||
relative_path: entry.relativePath,
|
||||
kind: entry.kind,
|
||||
link_target: entry.linkTarget,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const logicalPath = `$output/${entry.relativePath}`;
|
||||
const reported = context.normalized.files.get(logicalPath);
|
||||
const sha256 = await hashFirmwareFile(entry.path, context.signal);
|
||||
if (
|
||||
(reported?.sha256 !== null &&
|
||||
reported?.sha256 !== undefined &&
|
||||
reported.sha256 !== sha256) ||
|
||||
(context.normalized.sizes.has(logicalPath) &&
|
||||
context.normalized.sizes.get(logicalPath) !== entry.size)
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`Extracted bytes disagree with provider report: ${entry.relativePath}`,
|
||||
);
|
||||
await tree.write(
|
||||
entry.relativePath,
|
||||
createReadStream(entry.path),
|
||||
sha256,
|
||||
context.signal,
|
||||
);
|
||||
files.push({
|
||||
relative_path: entry.relativePath,
|
||||
path: join(tree.outputRoot, entry.relativePath),
|
||||
size: entry.size,
|
||||
sha256,
|
||||
reported_sha256: reported?.sha256 ?? null,
|
||||
mime_type: reported?.mimeType ?? null,
|
||||
analysis_depth: reported?.depth ?? null,
|
||||
runtime_address: null,
|
||||
original_file_range: null,
|
||||
});
|
||||
}
|
||||
const result = firmwareResultSchemas.extract_firmware.parse({
|
||||
engine: context.engine,
|
||||
selection: context.selection,
|
||||
output_directory: tree.outputRoot,
|
||||
coverage:
|
||||
unpublished.length > 0 ? "partial" : context.normalized.coverage,
|
||||
files,
|
||||
unpublished_entries: unpublished,
|
||||
chunks: context.normalized.chunks,
|
||||
derivations: context.normalized.derivations,
|
||||
depth_limited_paths: context.normalized.depth_limited_paths,
|
||||
diagnostics: context.normalized.diagnostics,
|
||||
published_bytes: files.reduce((sum, file) => sum + file.size, 0),
|
||||
});
|
||||
context.signal.throwIfAborted();
|
||||
await tree.commit();
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
try {
|
||||
await tree?.rollback();
|
||||
} catch (cleanupCause: unknown) {
|
||||
throw new ProviderCleanupError(
|
||||
"unblob",
|
||||
[context.outputDirectory],
|
||||
{
|
||||
reason:
|
||||
cleanupCause instanceof Error
|
||||
? cleanupCause.message
|
||||
: String(cleanupCause),
|
||||
previous_error:
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
{ cause: cleanupCause },
|
||||
);
|
||||
}
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
/** Audited upstream sources; installed tool bytes are fingerprinted separately. */
|
||||
export const FIRMWARE_RELEASES = {
|
||||
binwalk: {
|
||||
version: "3.1.0",
|
||||
revision: "4fdab3d464d97b68e0af9088df3f9e2e1545b21c",
|
||||
repository: "https://github.com/ReFirmLabs/binwalk",
|
||||
},
|
||||
unblob: {
|
||||
version: "26.6.4",
|
||||
revision: "1fcc7a0a584a70a96c31f5a276c20944d199a089",
|
||||
repository: "https://github.com/onekey-sec/unblob",
|
||||
},
|
||||
} as const;
|
||||
|
||||
/** Catalog identities; Evidence uses the version observed from the executed tool. */
|
||||
export const BINWALK_PROVIDER_IDENTITY = {
|
||||
id: "binwalk",
|
||||
name: "Binwalk",
|
||||
version: FIRMWARE_RELEASES.binwalk.version,
|
||||
} as const;
|
||||
/** Catalog identity for explicit firmware extraction. */
|
||||
export const UNBLOB_PROVIDER_IDENTITY = {
|
||||
id: "unblob",
|
||||
name: "Unblob",
|
||||
version: FIRMWARE_RELEASES.unblob.version,
|
||||
} as const;
|
||||
|
||||
/** Resource policy for this Linux integration, not a claim of aggregate containment. */
|
||||
export const FIRMWARE_LIMITS = {
|
||||
inputBytes: 128 * 1024 * 1024,
|
||||
reportBytes: 8 * 1024 * 1024,
|
||||
addressSpaceBytes: 1024 * 1024 * 1024,
|
||||
timeoutMs: 120_000,
|
||||
} as const;
|
||||
@@ -0,0 +1,148 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
normalizeBinwalkReport,
|
||||
normalizeUnblobReport,
|
||||
} from "./FirmwareReports.js";
|
||||
|
||||
const context = {
|
||||
inputPath: "/private/input.bin",
|
||||
outputRoot: "/private/output",
|
||||
sha256: "a".repeat(64),
|
||||
length: 20,
|
||||
offset: 64,
|
||||
maxDepth: 3,
|
||||
};
|
||||
const root = () => ({
|
||||
task: {
|
||||
path: context.inputPath,
|
||||
depth: 0,
|
||||
blob_id: "",
|
||||
is_multi_file: false,
|
||||
},
|
||||
reports: [
|
||||
{
|
||||
__typename__: "StatReport",
|
||||
path: context.inputPath,
|
||||
size: 20,
|
||||
is_file: true,
|
||||
is_dir: false,
|
||||
is_link: false,
|
||||
link_target: null,
|
||||
},
|
||||
{ __typename__: "HashReport", sha256: context.sha256 },
|
||||
{
|
||||
__typename__: "UnknownChunkReport",
|
||||
id: "unknown",
|
||||
start_offset: 0,
|
||||
end_offset: 20,
|
||||
size: 20,
|
||||
randomness: null,
|
||||
},
|
||||
],
|
||||
subtasks: [],
|
||||
});
|
||||
|
||||
describe("firmware producer boundaries", () => {
|
||||
it("retains unknown chunks and their selected original-file range", () => {
|
||||
const normalized = normalizeUnblobReport([root()], context);
|
||||
expect(normalized.coverage).toBe("partial");
|
||||
expect(normalized.chunks[0]).toMatchObject({
|
||||
handler: null,
|
||||
range: { offset: 0, length: 20 },
|
||||
root_file_range: { offset: 64, length: 20 },
|
||||
});
|
||||
});
|
||||
it("preserves unfamiliar report types as explicit diagnostics", () => {
|
||||
const record = root();
|
||||
const normalized = normalizeUnblobReport(
|
||||
[
|
||||
{
|
||||
...record,
|
||||
reports: [
|
||||
...record.reports,
|
||||
{ __typename__: "FutureError", reason: "new producer facet" },
|
||||
],
|
||||
},
|
||||
],
|
||||
context,
|
||||
);
|
||||
expect(normalized.diagnostics).toEqual([
|
||||
{
|
||||
input_path: "$input",
|
||||
report: { __typename__: "FutureError", reason: "new producer facet" },
|
||||
},
|
||||
]);
|
||||
expect(normalized.coverage).toBe("partial");
|
||||
});
|
||||
it("rejects unknown tasks outside the owned output and disconnected task graphs", () => {
|
||||
const record = root();
|
||||
for (const path of [
|
||||
"/private/output/../escaped",
|
||||
"/private/output/unconnected",
|
||||
]) {
|
||||
const child = { ...record, task: { ...record.task, path, depth: 1 } };
|
||||
expect(() => normalizeUnblobReport([record, child], context)).toThrow();
|
||||
}
|
||||
});
|
||||
it("rejects absent root identity, inconsistent chunk bounds and duplicate tasks", () => {
|
||||
const record = root();
|
||||
expect(() => normalizeUnblobReport([], context)).toThrow("exactly one");
|
||||
expect(() =>
|
||||
normalizeUnblobReport(
|
||||
[
|
||||
{
|
||||
...record,
|
||||
reports: record.reports.filter(
|
||||
(report) => report.__typename__ !== "HashReport",
|
||||
),
|
||||
},
|
||||
],
|
||||
context,
|
||||
),
|
||||
).toThrow("hash");
|
||||
expect(() =>
|
||||
normalizeUnblobReport(
|
||||
[
|
||||
{
|
||||
...record,
|
||||
reports: [
|
||||
...record.reports,
|
||||
{
|
||||
__typename__: "UnknownChunkReport",
|
||||
id: "bad",
|
||||
start_offset: 10,
|
||||
end_offset: 21,
|
||||
size: 11,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
context,
|
||||
),
|
||||
).toThrow("bounds");
|
||||
expect(() => normalizeUnblobReport([record, record], context)).toThrow(
|
||||
"exactly one",
|
||||
);
|
||||
});
|
||||
it("rejects empty, combined and extracting Binwalk reports", () => {
|
||||
const record = {
|
||||
Analysis: { file_path: context.inputPath, file_map: [], extractions: {} },
|
||||
};
|
||||
expect(normalizeBinwalkReport([record], context.inputPath, 20)).toEqual([]);
|
||||
for (const report of [
|
||||
[],
|
||||
[record, record],
|
||||
[
|
||||
{
|
||||
Analysis: {
|
||||
...record.Analysis,
|
||||
extractions: { hit: { status: "success" } },
|
||||
},
|
||||
},
|
||||
],
|
||||
])
|
||||
expect(() =>
|
||||
normalizeBinwalkReport(report, context.inputPath, 20),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,327 @@
|
||||
import { z } from "zod";
|
||||
import { AnalysisOutputError } from "../domain/analysisErrorCore.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { digestSchema } from "../domain/digests.js";
|
||||
import { firmwareLogicalPath } from "./FirmwareFiles.js";
|
||||
|
||||
const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
||||
const signature = z.object({
|
||||
id: z.string().min(1),
|
||||
offset: integer,
|
||||
size: integer,
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
confidence: z.number().int().min(0).max(255),
|
||||
always_display: z.boolean(),
|
||||
extraction_declined: z.boolean(),
|
||||
});
|
||||
const scan = z.array(
|
||||
z.object({
|
||||
Analysis: z.object({
|
||||
file_path: z.string(),
|
||||
file_map: z.array(signature),
|
||||
extractions: z.record(z.string(), jsonValueSchema),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const report = z.object({ __typename__: z.string() }).catchall(jsonValueSchema);
|
||||
const task = z.object({
|
||||
path: z.string(),
|
||||
depth: integer,
|
||||
blob_id: z.string(),
|
||||
is_multi_file: z.boolean(),
|
||||
});
|
||||
const extraction = z.array(
|
||||
z.object({ task, reports: z.array(report), subtasks: z.array(task) }),
|
||||
);
|
||||
const stat = z.object({
|
||||
__typename__: z.literal("StatReport"),
|
||||
path: z.string(),
|
||||
size: integer,
|
||||
is_dir: z.boolean(),
|
||||
is_file: z.boolean(),
|
||||
is_link: z.boolean(),
|
||||
link_target: z.string().nullable(),
|
||||
});
|
||||
const hashes = z.object({ sha256: digestSchema });
|
||||
const region = z.object({
|
||||
id: z.string(),
|
||||
start_offset: integer,
|
||||
end_offset: integer,
|
||||
size: integer,
|
||||
});
|
||||
const known = new Set([
|
||||
"StatReport",
|
||||
"HashReport",
|
||||
"FileMagicReport",
|
||||
"RandomnessReport",
|
||||
"ChunkReport",
|
||||
"UnknownChunkReport",
|
||||
"CarveDirectoryReport",
|
||||
"MultiFileReport",
|
||||
]);
|
||||
|
||||
/** Interpret the pinned Binwalk report without inventing validated region lengths. */
|
||||
export const normalizeBinwalkReport = (
|
||||
raw: unknown,
|
||||
inputPath: string,
|
||||
size: number,
|
||||
) => {
|
||||
const records = scan.parse(raw);
|
||||
const analysis = records[0]?.Analysis;
|
||||
if (
|
||||
records.length !== 1 ||
|
||||
analysis?.file_path !== inputPath ||
|
||||
Object.keys(analysis.extractions).length !== 0
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
"inspect_firmware_regions",
|
||||
"Expected one inspection-only report for the selected immutable input",
|
||||
);
|
||||
return analysis.file_map.map((hit) => {
|
||||
if (hit.offset >= size || hit.size > size - hit.offset)
|
||||
throw new AnalysisOutputError(
|
||||
"inspect_firmware_regions",
|
||||
"Reported region lies outside the selected file",
|
||||
);
|
||||
return {
|
||||
provider_id: hit.id,
|
||||
offset: hit.offset,
|
||||
reported_size: hit.size,
|
||||
signature: hit.name,
|
||||
description: hit.description,
|
||||
reported_confidence: hit.confidence,
|
||||
size_basis: "provider_reported_validation_unknown" as const,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
/** Normalize Unblob's unordered task graph, retaining unknown and failed analyses. */
|
||||
export const normalizeUnblobReport = (
|
||||
raw: unknown,
|
||||
context: {
|
||||
inputPath: string;
|
||||
outputRoot: string;
|
||||
sha256: string;
|
||||
length: number;
|
||||
offset: number;
|
||||
maxDepth: number;
|
||||
},
|
||||
) => {
|
||||
const records = extraction.parse(raw);
|
||||
const logical = (path: string) =>
|
||||
firmwareLogicalPath(path, context.inputPath, context.outputRoot);
|
||||
const roots = records.filter(
|
||||
({ task: item }) => item.path === context.inputPath && item.depth === 0,
|
||||
);
|
||||
if (roots.length !== 1)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
"Expected exactly one selected input task",
|
||||
);
|
||||
const rootHash = roots[0]?.reports.find(
|
||||
(r) => r.__typename__ === "HashReport",
|
||||
);
|
||||
if (
|
||||
rootHash === undefined ||
|
||||
hashes.parse(rootHash).sha256 !== context.sha256
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
"Unblob input hash disagrees with selected snapshot",
|
||||
);
|
||||
const files = new Map<
|
||||
string,
|
||||
{ sha256: string | null; mimeType: string | null; depth: number }
|
||||
>();
|
||||
const sizes = new Map<string, number>();
|
||||
const depths: string[] = [];
|
||||
const diagnostics: JsonValue[] = [];
|
||||
const chunks: {
|
||||
input_path: string;
|
||||
provider_id: string;
|
||||
range: { offset: number; length: number };
|
||||
handler: string | null;
|
||||
encrypted: boolean | null;
|
||||
root_file_range: { offset: number; length: number } | null;
|
||||
}[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const record of records) {
|
||||
const path = logical(record.task.path);
|
||||
if (seen.has(path))
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`Duplicate analysis task: ${path}`,
|
||||
);
|
||||
seen.add(path);
|
||||
if (record.task.depth >= context.maxDepth) depths.push(path);
|
||||
const metadata = record.reports.find(
|
||||
(r) => r.__typename__ === "StatReport",
|
||||
);
|
||||
if (metadata === undefined)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`Missing StatReport: ${path}`,
|
||||
);
|
||||
const parsedStat = stat.parse(metadata);
|
||||
if (parsedStat.path !== record.task.path)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`StatReport is bound to another task: ${path}`,
|
||||
);
|
||||
if (path === "$input" && parsedStat.size !== context.length)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
"Unblob input size disagrees with selected snapshot",
|
||||
);
|
||||
if (
|
||||
path === "$input" &&
|
||||
(!parsedStat.is_file || parsedStat.is_link || parsedStat.is_dir)
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
"Selected input was not reported as a regular file",
|
||||
);
|
||||
sizes.set(path, parsedStat.size);
|
||||
const hash = record.reports.find((r) => r.__typename__ === "HashReport");
|
||||
const magic = record.reports.find(
|
||||
(r) => r.__typename__ === "FileMagicReport",
|
||||
);
|
||||
if (parsedStat.is_file && !parsedStat.is_link)
|
||||
files.set(path, {
|
||||
sha256: hash === undefined ? null : hashes.parse(hash).sha256,
|
||||
mimeType:
|
||||
magic === undefined
|
||||
? null
|
||||
: z.object({ mime_type: z.string() }).parse(magic).mime_type,
|
||||
depth: record.task.depth,
|
||||
});
|
||||
for (const item of record.reports) {
|
||||
if (!known.has(item.__typename__))
|
||||
diagnostics.push(
|
||||
jsonValueSchema.parse({ input_path: path, report: item }),
|
||||
);
|
||||
if (
|
||||
item.__typename__ === "ChunkReport" ||
|
||||
item.__typename__ === "UnknownChunkReport"
|
||||
) {
|
||||
const parsed = region.parse(item);
|
||||
if (
|
||||
parsed.end_offset <= parsed.start_offset ||
|
||||
parsed.end_offset > parsedStat.size ||
|
||||
parsed.size !== parsed.end_offset - parsed.start_offset
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`Invalid chunk bounds for ${path}`,
|
||||
);
|
||||
const detail =
|
||||
item.__typename__ === "ChunkReport"
|
||||
? z
|
||||
.object({
|
||||
handler_name: z.string(),
|
||||
is_encrypted: z.boolean(),
|
||||
extraction_reports: z.array(jsonValueSchema),
|
||||
})
|
||||
.parse(item)
|
||||
: null;
|
||||
if (detail !== null)
|
||||
for (const problem of detail.extraction_reports)
|
||||
diagnostics.push({ input_path: path, report: problem });
|
||||
chunks.push({
|
||||
input_path: path,
|
||||
provider_id: parsed.id,
|
||||
range: { offset: parsed.start_offset, length: parsed.size },
|
||||
handler: detail?.handler_name ?? null,
|
||||
encrypted: detail?.is_encrypted ?? null,
|
||||
root_file_range:
|
||||
path === "$input"
|
||||
? {
|
||||
offset: context.offset + parsed.start_offset,
|
||||
length: parsed.size,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const recordsByPath = new Map(
|
||||
records.map((record) => [record.task.path, record.task]),
|
||||
);
|
||||
const chunksByOrigin = new Map<string, (typeof chunks)[number]>();
|
||||
for (const item of chunks) {
|
||||
const key = JSON.stringify([item.input_path, item.provider_id]);
|
||||
if (chunksByOrigin.has(key))
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`Duplicate chunk identity in ${item.input_path}`,
|
||||
);
|
||||
chunksByOrigin.set(key, item);
|
||||
}
|
||||
const derivations = records.flatMap((record) =>
|
||||
record.subtasks.map((child) => {
|
||||
const parentPath = logical(record.task.path);
|
||||
const childPath = logical(child.path);
|
||||
if (!seen.has(childPath))
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`Missing child task: ${childPath}`,
|
||||
);
|
||||
const reportedChild = recordsByPath.get(child.path);
|
||||
if (
|
||||
reportedChild?.depth !== child.depth ||
|
||||
reportedChild.blob_id !== child.blob_id ||
|
||||
reportedChild.is_multi_file !== child.is_multi_file
|
||||
)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
`Child task identity disagrees with its analysis: ${childPath}`,
|
||||
);
|
||||
const origin = chunksByOrigin.get(
|
||||
JSON.stringify([parentPath, child.blob_id]),
|
||||
);
|
||||
return {
|
||||
parent_path: parentPath,
|
||||
child_path: childPath,
|
||||
provider_blob_id: child.blob_id,
|
||||
handler: origin?.handler ?? null,
|
||||
parent_file_range: origin?.range ?? null,
|
||||
};
|
||||
}),
|
||||
);
|
||||
const reachable = new Set(["$input"]);
|
||||
const pending = ["$input"];
|
||||
const childrenByParent = new Map<string, string[]>();
|
||||
for (const edge of derivations) {
|
||||
const children = childrenByParent.get(edge.parent_path) ?? [];
|
||||
children.push(edge.child_path);
|
||||
childrenByParent.set(edge.parent_path, children);
|
||||
}
|
||||
while (pending.length > 0) {
|
||||
const parent = pending.pop();
|
||||
for (const child of childrenByParent.get(parent ?? "") ?? []) {
|
||||
if (reachable.has(child)) continue;
|
||||
reachable.add(child);
|
||||
pending.push(child);
|
||||
}
|
||||
}
|
||||
if (reachable.size !== seen.size)
|
||||
throw new AnalysisOutputError(
|
||||
"extract_firmware",
|
||||
"Report contains tasks disconnected from the selected input",
|
||||
);
|
||||
return {
|
||||
files,
|
||||
sizes,
|
||||
chunks,
|
||||
derivations,
|
||||
depth_limited_paths: depths.sort(),
|
||||
diagnostics,
|
||||
coverage:
|
||||
depths.length > 0 ||
|
||||
diagnostics.length > 0 ||
|
||||
chunks.some((c) => c.handler === null || c.encrypted === true)
|
||||
? ("partial" as const)
|
||||
: ("complete" as const),
|
||||
};
|
||||
};
|
||||
File diff suppressed because one or more lines are too long
@@ -18,6 +18,10 @@ import { registerElectronTools } from "./registerElectronTools.js";
|
||||
import { registerEnhancedTools } from "./registerEnhancedTools.js";
|
||||
import { registerJavaScriptRuntimeObservationTools } from "./registerJavaScriptRuntimeObservationTools.js";
|
||||
import { registerManagedTools } from "./registerManagedTools.js";
|
||||
import { registerFirmwareTools } from "./registerFirmwareTools.js";
|
||||
import { FirmwareAnalysisService } from "../application/FirmwareAnalysisService.js";
|
||||
import type { FirmwareAnalysisPort } from "../application/FirmwareAnalysisPort.js";
|
||||
import { FirmwareProvider } from "../firmware/FirmwareProvider.js";
|
||||
import { registerAndroidTools } from "./registerAndroidTools.js";
|
||||
import { AndroidAnalysisService } from "../application/AndroidAnalysisService.js";
|
||||
import type { AndroidAnalysisPort } from "../application/AndroidAnalysisPort.js";
|
||||
@@ -38,6 +42,7 @@ const ACTIVE_TARGET_INSTRUCTIONS =
|
||||
|
||||
export interface CreateServerOptions {
|
||||
readonly logger?: Logger;
|
||||
readonly firmwareAnalysis?: FirmwareAnalysisPort;
|
||||
readonly androidAnalysis?: AndroidAnalysisPort;
|
||||
readonly browserObservation?: BrowserObservationPort;
|
||||
readonly browserScenarioCapture?: BrowserScenarioCapturePort;
|
||||
@@ -55,6 +60,14 @@ const installSessionToolAvailability = (
|
||||
if (session === undefined) return undefined;
|
||||
const policy = sessionAvailabilityPolicy(options.availabilityPolicy, {
|
||||
optionalFeatures: {
|
||||
firmwareInspectionEnabled:
|
||||
options.firmwareAnalysis !== undefined ||
|
||||
(process.platform === "linux" &&
|
||||
isAbsolute(process.env.REA_BINWALK_COMMAND ?? "")),
|
||||
firmwareExtractionEnabled:
|
||||
options.firmwareAnalysis !== undefined ||
|
||||
(process.platform === "linux" &&
|
||||
isAbsolute(process.env.REA_UNBLOB_COMMAND ?? "")),
|
||||
androidAnalysisEnabled:
|
||||
options.androidAnalysis !== undefined ||
|
||||
((process.platform === "linux" || process.platform === "darwin") &&
|
||||
@@ -127,6 +140,14 @@ export const createServer = (
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
);
|
||||
registerFirmwareTools(
|
||||
server,
|
||||
new FirmwareAnalysisService(
|
||||
options.firmwareAnalysis ?? new FirmwareProvider(),
|
||||
),
|
||||
toolLogger,
|
||||
recordEvidence,
|
||||
);
|
||||
registerObservationTools(toolContext);
|
||||
registerGuidedPrompts(server, analysis, session);
|
||||
if (session !== undefined) {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
import type { FirmwareAnalysisService } from "../application/FirmwareAnalysisService.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import type { FirmwareOperation } from "../domain/firmwareAnalysis.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
|
||||
/** Bind firmware handlers to their exact named schemas. */
|
||||
export const registerFirmwareTools = (
|
||||
server: McpServer,
|
||||
service: FirmwareAnalysisService,
|
||||
logger: Logger,
|
||||
recordEvidence?: BinarySessionPort["recordEvidence"],
|
||||
): void => {
|
||||
const handler =
|
||||
(contract: ToolContract<FirmwareOperation>) =>
|
||||
async (input: unknown, context: ServerContext) => {
|
||||
const result = await logToolExecution(logger, contract.name, () =>
|
||||
service.execute(contract.name, input, {
|
||||
signal: context.mcpReq.signal,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, contract);
|
||||
const recorded = recordEvidence?.(result.value);
|
||||
return recorded !== undefined && !recorded.ok
|
||||
? toCallToolResult(recorded, contract)
|
||||
: toCallToolResult(result, contract);
|
||||
};
|
||||
const inspect = toolContract("inspect_firmware_regions");
|
||||
server.registerTool(
|
||||
inspect.name,
|
||||
toolRegistrationOptions(inspect),
|
||||
handler(inspect),
|
||||
);
|
||||
const extract = toolContract("extract_firmware");
|
||||
server.registerTool(
|
||||
extract.name,
|
||||
toolRegistrationOptions(extract),
|
||||
handler(extract),
|
||||
);
|
||||
};
|
||||
@@ -12,6 +12,8 @@ export interface SessionAvailabilityDefaults {
|
||||
| "electronAutomationEnabled"
|
||||
| "v8InspectorObservationEnabled"
|
||||
| "androidAnalysisEnabled"
|
||||
| "firmwareInspectionEnabled"
|
||||
| "firmwareExtractionEnabled"
|
||||
>;
|
||||
}
|
||||
|
||||
@@ -23,6 +25,10 @@ export const sessionAvailabilityPolicy = (
|
||||
configured ??
|
||||
(() => ({
|
||||
processCaptureEnabled: platform !== "win32",
|
||||
firmwareInspectionEnabled:
|
||||
defaults.optionalFeatures?.firmwareInspectionEnabled ?? false,
|
||||
firmwareExtractionEnabled:
|
||||
defaults.optionalFeatures?.firmwareExtractionEnabled ?? false,
|
||||
androidAnalysisEnabled:
|
||||
defaults.optionalFeatures?.androidAnalysisEnabled ?? false,
|
||||
browserObservationEnabled:
|
||||
|
||||
Reference in New Issue
Block a user