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:
N0zoM1z0
2026-10-06 14:16:04 +00:00
committed by GitHub
parent 8d7071da4c
commit 5a7c769692
58 changed files with 3230 additions and 16 deletions
+229
View File
@@ -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 },
);
}
};
+265
View File
@@ -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("/")}`;
};
+350
View File
@@ -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;
}
}
+115
View File
@@ -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;
}
};
+34
View File
@@ -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;
+148
View File
@@ -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();
});
});
+327
View File
@@ -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),
};
};