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
@@ -22,6 +22,10 @@ import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "../../../src/brow
import { V8_INSPECTOR_PROVIDER_IDENTITY } from "../../../src/browser/V8InspectorProvider.js";
import { CLI_COMMAND_NAMES } from "../../../src/cliCommandNames.js";
import { createCli } from "../../../src/cli.js";
import {
BINWALK_PROVIDER_IDENTITY,
UNBLOB_PROVIDER_IDENTITY,
} from "../../../src/firmware/FirmwareRelease.js";
import { JADX_PROVIDER_IDENTITY } from "../../../src/android/JadxRelease.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
import {
@@ -73,6 +77,8 @@ describe("canonical product catalog", () => {
[
HOPPER_PROVIDER_IDENTITY,
JADX_PROVIDER_IDENTITY,
BINWALK_PROVIDER_IDENTITY,
UNBLOB_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_IDENTITY,
NATIVE_MACOS_PROVIDER_IDENTITY,
ARTIFACT_GRAPH_PROVIDER,
@@ -0,0 +1,343 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { expect, it as test } from "vitest";
import {
firmwareFixture,
assertFirmwareCleanup,
} from "../../fixtures/firmware/provider.js";
import { firmwareResultSchemas } from "../../../src/domain/firmwareAnalysis.js";
import { FirmwareAnalysisService } from "../../../src/application/FirmwareAnalysisService.js";
import { FirmwareProvider } from "../../../src/firmware/FirmwareProvider.js";
import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { toCallToolResult } from "../../../src/server/toolResult.js";
const it = test.skipIf(process.platform !== "linux");
it("binds region observations to exact bytes and preserves provider-reported uncertainty", async () => {
const fixture = await firmwareFixture();
const result = await fixture.service.execute("inspect_firmware_regions", {
path: fixture.path,
});
if (!result.ok) throw result.error;
const normalized = firmwareResultSchemas.inspect_firmware_regions.parse(
result.value.normalized_result,
);
expect(normalized.regions[0]).toMatchObject({
offset: 2,
reported_size: 4,
size_basis: "provider_reported_validation_unknown",
});
expect(result.value.subject?.local_path).toBe(fixture.path);
expect(result.value.subject?.format).toBe("file");
expect(result.value.raw_result).toMatchObject({
report: [{ Analysis: { file_map: [{ id: "hit" }] } }],
});
expect(fixture.launches[1]?.args).toEqual(
expect.arrayContaining(["--as=1073741824", "--threads", "1"]),
);
await assertFirmwareCleanup(fixture.launches);
});
it.each(["wrong-input", "bounds"])(
"rejects a mismatched or out-of-bounds inspection: %s",
async (mode) => {
const fixture = await firmwareFixture(mode);
const result = await fixture.service.execute("inspect_firmware_regions", {
path: fixture.path,
});
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
await assertFirmwareCleanup(fixture.launches);
},
);
it("extracts a selected interval with verified file identity and parent-byte lineage", async () => {
const fixture = await firmwareFixture();
const result = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: fixture.output,
range: { offset: 2, length: 4 },
});
if (!result.ok) throw result.error;
const normalized = firmwareResultSchemas.extract_firmware.parse(
result.value.normalized_result,
);
expect(normalized.selection).toMatchObject({ offset: 2, length: 4 });
expect(normalized.files[0]).toMatchObject({
relative_path: "rootfs/config",
size: 14,
original_file_range: null,
runtime_address: null,
});
expect(normalized.chunks[0]?.root_file_range).toEqual({
offset: 2,
length: 4,
});
expect(normalized.derivations[0]).toMatchObject({
parent_path: "$input",
child_path: "$output/rootfs/config",
handler: "gzip",
parent_file_range: { offset: 0, length: 4 },
});
expect(await readFile(normalized.files[0]?.path ?? "", "utf8")).toBe(
"firmware=true\n",
);
expect(fixture.launches[1]?.args).toEqual(
expect.arrayContaining(["--process-num", "1", "--randomness-depth", "0"]),
);
expect(fixture.launches[1]?.args).not.toContain("--no-sandbox");
await assertFirmwareCleanup(fixture.launches);
});
it.each(["depth", "dependency", "link"])(
"reports partial extraction for %s without losing inline results",
async (mode) => {
const fixture = await firmwareFixture(mode);
const result = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: fixture.output,
});
if (!result.ok) throw result.error;
const normalized = firmwareResultSchemas.extract_firmware.parse(
result.value.normalized_result,
);
expect(normalized.coverage).toBe("partial");
expect(normalized.files).toHaveLength(1);
if (mode === "depth")
expect(normalized.depth_limited_paths).toEqual(["$output/rootfs/config"]);
if (mode === "dependency")
expect(normalized.diagnostics).toEqual([
{
input_path: "$input",
report: {
__typename__: "ExtractorDependencyNotFoundReport",
severity: "ERROR",
dependencies: ["sasquatch"],
},
},
]);
if (mode === "link") {
expect(normalized.unpublished_entries).toEqual([
{
relative_path: "escape",
kind: "symlink",
link_target: "/etc/passwd",
},
]);
await expect(access(`${fixture.output}/escape`)).rejects.toMatchObject({
code: "ENOENT",
});
}
await assertFirmwareCleanup(fixture.launches);
},
);
it("distinguishes a real output file named $input from the selected original", async () => {
const fixture = await firmwareFixture("reserved-name");
const outcome = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: fixture.output,
});
if (!outcome.ok) throw outcome.error;
const result = firmwareResultSchemas.extract_firmware.parse(
outcome.value.normalized_result,
);
expect(result.files[0]?.relative_path).toBe("$input");
expect(result.derivations[0]).toMatchObject({
parent_path: "$input",
child_path: "$output/$input",
});
expect(await readFile(`${fixture.output}/$input`, "utf8")).toBe(
"firmware=true\n",
);
await assertFirmwareCleanup(fixture.launches);
});
it.each(["hash", "malformed", "budget", "missing-file"])(
"rejects invalid or over-budget extraction and rolls back output: %s",
async (mode) => {
const fixture = await firmwareFixture(mode);
const result = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: fixture.output,
...(mode === "budget" ? { max_output_bytes: 1000 } : {}),
});
expect(result.ok).toBe(false);
await expect(access(fixture.output)).rejects.toMatchObject({
code: "ENOENT",
});
await assertFirmwareCleanup(fixture.launches);
},
);
it("preserves existing output and rejects invalid intervals before invoking extraction", async () => {
const fixture = await firmwareFixture();
await mkdir(fixture.output);
await writeFile(`${fixture.output}/existing`, "keep");
const existing = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: fixture.output,
});
expect(existing.ok).toBe(false);
expect(await readFile(`${fixture.output}/existing`, "utf8")).toBe("keep");
const previous = fixture.launches.length;
const invalid = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: fixture.output,
range: { offset: 100, length: 1 },
});
expect(invalid).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
expect(fixture.launches).toHaveLength(previous);
await assertFirmwareCleanup(fixture.launches);
});
it("retains startup stderr when Unblob exits 1 without a report", async () => {
const fixture = await firmwareFixture("startup");
const result = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: fixture.output,
});
if (result.ok) throw new Error("Expected startup failure");
const details = {
diagnostics: {
stderr: expect.stringContaining("Landlock sandbox is not available"),
exit_code: 1,
},
};
expect(projectAnalysisError(result.error)).toMatchObject({ details });
expect(
toCallToolResult(result, toolContract("extract_firmware"))
.structuredContent,
).toMatchObject({ error: { details } });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
diagnostics: {
exit_code: 1,
stderr: expect.stringContaining("Landlock sandbox is not available"),
report_failure: expect.stringContaining("ENOENT"),
},
},
});
await expect(access(fixture.output)).rejects.toMatchObject({
code: "ENOENT",
});
await assertFirmwareCleanup(fixture.launches);
});
it("distinguishes a successful process with missing output from startup failure", async () => {
const fixture = await firmwareFixture("missing-report");
const result = await fixture.service.execute("extract_firmware", {
path: fixture.path,
output_directory: fixture.output,
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
reason: expect.stringContaining("expected complete report"),
},
});
if (result.ok) throw new Error("Expected missing-output failure");
expect(projectAnalysisError(result.error)).toMatchObject({
details: { reason: expect.stringContaining("Producer forgot its report") },
});
await assertFirmwareCleanup(fixture.launches);
});
it("cancels an owned active process and permits the next queued operation", async () => {
const fixture = await firmwareFixture("stall");
const controller = new AbortController();
const pending = fixture.service.execute(
"inspect_firmware_regions",
{ path: fixture.path },
{ signal: controller.signal },
);
await expect.poll(() => fixture.launches.length).toBe(2);
controller.abort();
expect(await pending).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
const cancelled = await fixture.service.execute(
"inspect_firmware_regions",
{ path: fixture.path },
{ signal: AbortSignal.abort() },
);
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(fixture.launches).toHaveLength(2);
await assertFirmwareCleanup(fixture.launches);
});
it("cancels a waiting request promptly while keeping later launches behind the active operation", async () => {
const fixture = await firmwareFixture("stall");
const activeController = new AbortController();
const active = fixture.service.execute(
"inspect_firmware_regions",
{ path: fixture.path },
{ signal: activeController.signal },
);
await expect.poll(() => fixture.launches.length).toBe(2);
const queuedController = new AbortController();
const queued = fixture.service.execute(
"inspect_firmware_regions",
{ path: fixture.path },
{ signal: queuedController.signal },
);
queuedController.abort();
expect(await queued).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(fixture.launches).toHaveLength(2);
activeController.abort();
expect((await active).ok).toBe(false);
await assertFirmwareCleanup(fixture.launches);
});
it("retains an uncertain workspace and blocks new launches after cleanup failure", async () => {
const fixture = await firmwareFixture("cleanup-failure");
const first = await fixture.service.execute("inspect_firmware_regions", {
path: fixture.path,
});
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
const workspace = fixture.launches[0]?.cwd;
expect(workspace).toBeDefined();
if (workspace !== undefined) await access(workspace);
const next = await fixture.service.execute("inspect_firmware_regions", {
path: fixture.path,
});
expect(next).toMatchObject({ ok: false, error: { cleanupIncomplete: true } });
expect(fixture.launches).toHaveLength(1);
});
it("rejects absent or unsupported engines without installing anything", async () => {
const missing = await new FirmwareAnalysisService(
new FirmwareProvider({}),
).execute("inspect_firmware_regions", { path: "/tmp/unused" });
expect(missing).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
const fixture = await firmwareFixture("version");
const result = await fixture.service.execute("inspect_firmware_regions", {
path: fixture.path,
});
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCapabilityUnavailableError" },
});
await assertFirmwareCleanup(fixture.launches);
});
@@ -94,6 +94,7 @@ describe("enhanced MCP tools", () => {
error: {
code: "unreadable_output",
category: "execution_failure",
details: { operation: "decompile", reason: "failed" },
message:
"Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.",
retryable: false,
+55
View File
@@ -0,0 +1,55 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { expect, it as test, onTestFinished } from "vitest";
import { FIRMWARE_TOOL_CONTRACTS } from "../../../src/contracts/firmwareToolContracts.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import {
firmwareFixture,
assertFirmwareCleanup,
} from "../../fixtures/firmware/provider.js";
const it = test.skipIf(process.platform !== "linux");
it("executes named firmware contracts with inline Evidence and no native binary admission", async () => {
const fixture = await firmwareFixture();
const session = createTestBinarySession(() => {
throw new Error("Firmware inspection must not acquire a native provider");
});
const server = createServer(session, session, {
firmwareAnalysis: fixture.provider,
});
const client = new Client({ name: "firmware-regression", version: "1" });
onTestFinished(async () => {
await client.close();
await server.close();
await session.close();
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
await server.connect(serverTransport);
await client.connect(clientTransport);
const advertised = await client.listTools();
for (const contract of FIRMWARE_TOOL_CONTRACTS) {
expect(
advertised.tools.find((tool) => tool.name === contract.name)?.annotations,
).toMatchObject(contract.annotations);
const response = await client.callTool({
name: contract.name,
arguments: {
path: fixture.path,
...(contract.name === "extract_firmware"
? { output_directory: fixture.output }
: {}),
},
});
expect(response.isError, JSON.stringify(response)).not.toBe(true);
const result = contract.outputSchema.parse(response.structuredContent);
const evidence = parseEvidence(result.evidence);
expect(result.result).toEqual(evidence.normalized_result);
expect(result.evidence_id).toBe(evidence.evidence_id);
expect(evidence.operation).toBe(contract.name);
expect(evidence.raw_result).not.toBeNull();
}
await assertFirmwareCleanup(fixture.launches);
});
+129
View File
@@ -0,0 +1,129 @@
import { createHash } from "node:crypto";
import { mkdir, readFile, writeFile, symlink } from "node:fs/promises";
import { join } from "node:path";
const args = process.argv.slice(2);
const mode = process.env.REA_FIRMWARE_FIXTURE_MODE;
const engine = process.env.REA_FIRMWARE_FIXTURE_ENGINE;
if (args.includes("--version")) {
console.log(
mode === "version"
? "unsupported"
: engine === "binwalk"
? "binwalk 3.1.0"
: "26.6.4",
);
} else if (mode === "stall") {
setInterval(() => {}, 1000);
} else if (mode === "startup") {
console.error("Landlock sandbox is not available on this fixture host");
process.exitCode = 1;
} else if (mode === "missing-report") {
console.error("Producer forgot its report");
} else {
const input = args.at(-1);
const bytes = await readFile(input);
const sha256 = createHash("sha256").update(bytes).digest("hex");
const reportPath =
args[args.indexOf(engine === "binwalk" ? "--log" : "--report") + 1];
if (engine === "binwalk") {
await writeFile(
reportPath,
JSON.stringify([
{
Analysis: {
file_path: mode === "wrong-input" ? "/tmp/another.bin" : input,
file_map: [
{
id: "hit",
offset: 2,
size: mode === "bounds" ? bytes.length : 4,
name: "gzip",
confidence: 250,
description: "fixture signature",
always_display: false,
extraction_declined: false,
},
],
extractions: {},
},
},
]),
);
} else {
const output = args[args.indexOf("--extract-dir") + 1];
await mkdir(output, { recursive: true });
const child =
mode === "reserved-name"
? join(output, "$input")
: join(output, "rootfs", "config");
await mkdir(join(output, "rootfs"));
const content = Buffer.from("firmware=true\n");
if (mode !== "missing-file")
await writeFile(child, mode === "budget" ? Buffer.alloc(10000) : content);
if (mode === "link") await symlink("/etc/passwd", join(output, "escape"));
const childHash = createHash("sha256").update(content).digest("hex");
const depth =
mode === "depth" ? Number(args[args.indexOf("--depth") + 1]) : 1;
const stat = (path, size) => ({
__typename__: "StatReport",
path,
size,
is_file: true,
is_dir: false,
is_link: false,
link_target: null,
});
const task = (path, level, id) => ({
path,
depth: level,
blob_id: id,
is_multi_file: false,
});
const hash = (value) => ({ __typename__: "HashReport", sha256: value });
const childTask = task(child, depth, "gzip-id");
const records = [
{
task: childTask,
reports: [
stat(child, content.length),
...(mode === "depth"
? []
: [hash(mode === "hash" ? "a".repeat(64) : childHash)]),
],
subtasks: [],
},
{
task: task(input, 0, ""),
reports: [
stat(input, bytes.length),
hash(sha256),
{
__typename__: "ChunkReport",
id: "gzip-id",
start_offset: 0,
end_offset: bytes.length,
size: bytes.length,
handler_name: "gzip",
is_encrypted: false,
extraction_reports:
mode === "dependency"
? [
{
__typename__: "ExtractorDependencyNotFoundReport",
severity: "ERROR",
dependencies: ["sasquatch"],
},
]
: [],
},
],
subtasks: [childTask],
},
];
await writeFile(
reportPath,
mode === "malformed" ? "[" : JSON.stringify(records),
);
if (mode === "dependency") process.exitCode = 1;
}
}
+94
View File
@@ -0,0 +1,94 @@
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { access, rm, writeFile } from "node:fs/promises";
import { expect, onTestFinished } from "vitest";
import { FirmwareProvider } from "../../../src/firmware/FirmwareProvider.js";
import { FirmwareAnalysisService } from "../../../src/application/FirmwareAnalysisService.js";
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
import { createTestTempDirectory } from "../temporaryDirectory.js";
/** Exercise real subprocess ownership with synthetic pinned producer representations. */
export const firmwareFixture = async (mode = "normal") => {
const root = await createTestTempDirectory("rea-firmware-test-");
const path = join(root, "input.bin");
await writeFile(path, Buffer.from("fixture-input-data"));
onTestFinished(() => rm(root, { recursive: true, force: true }));
const launches: {
cwd: string | undefined;
pid: number | undefined;
args: readonly string[];
}[] = [];
const provider = new FirmwareProvider(
{
...process.env,
REA_BINWALK_COMMAND: "/usr/bin/true",
REA_UNBLOB_COMMAND: process.execPath,
},
async (options) => {
const start = options.arguments.indexOf("--") + 2;
const args = options.arguments.slice(start);
const engine =
options.arguments[start - 1]?.endsWith("/true") === true
? "binwalk"
: "unblob";
const spawned = await spawnOwnedProviderProcess({
...options,
command: process.execPath,
expectedCommand: process.execPath,
arguments: [
fileURLToPath(new URL("./producer.mjs", import.meta.url)),
...args,
],
env: {
...options.env,
REA_FIRMWARE_FIXTURE_MODE: mode,
REA_FIRMWARE_FIXTURE_ENGINE: engine,
},
});
launches.push({
cwd: options.cwd,
pid: spawned.process.pid,
args: options.arguments,
});
if (mode === "cleanup-failure") {
onTestFinished(async () => {
if (options.cwd !== undefined)
await rm(options.cwd, { recursive: true, force: true });
});
return {
...spawned,
cleanup: async () => ({
cleaned: false,
reason: "injected ownership failure",
}),
};
}
return spawned;
},
);
return {
provider,
service: new FirmwareAnalysisService(provider),
path,
output: join(root, "output"),
root,
launches,
};
};
/** Verify only the acquired process groups and private runtime directories. */
export const assertFirmwareCleanup = async (
launches: Awaited<ReturnType<typeof firmwareFixture>>["launches"],
): Promise<void> => {
for (const launch of launches) {
const pid = launch.pid;
if (pid !== undefined)
expect(() => process.kill(-pid, 0)).toThrowError(
expect.objectContaining({ code: "ESRCH" }),
);
if (launch.cwd !== undefined)
await expect(access(launch.cwd)).rejects.toMatchObject({
code: "ENOENT",
});
}
};