feat(native): admit raw binaries with caller-supplied architecture and entry (#1868)

* feat(native): admit raw binaries with caller-supplied architecture and entry

* fix(native): honor raw-binary preparation and entry identity

* fix(ghidra): stream raw snapshot attestation with cancellation

* fix(native): preserve and validate raw lifecycle entries

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Matt Van Horn
2026-10-12 00:06:29 +08:00
committed by GitHub
co-authored by morluto
parent d3e83b0899
commit 7c207c7951
57 changed files with 2453 additions and 336 deletions
+103
View File
@@ -0,0 +1,103 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest(
"rejects a headerless image until architecture and entry are supplied",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-raw-cli-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const before = await cli.run({
arguments: ["inspect", path, "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(before.exitCode).not.toBe(0);
expect(JSON.stringify(before.json)).not.toContain("raw-binary");
const missing = await cli.run({
arguments: ["inspect", path, "--target-format", "raw-binary", "--json"],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(missing.exitCode).toBe(1);
expect(missing.json).toMatchObject({
code: "target_unavailable",
details: { reason: expect.stringContaining("architecture") },
});
},
);
cliTest(
"rejects an unaligned AArch64 entry before provider startup",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-raw-cli-alignment-");
const path = join(root, "image.bin");
await writeFile(path, Buffer.from("c0035fd6", "hex"));
const result = await cli.run({
arguments: [
"inspect",
path,
"--target-format",
"raw-binary",
"--architecture",
"arm64",
"--entry-point",
"0x8000001",
"--provider",
"ghidra",
"--json",
],
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "target_unavailable",
details: { reason: expect.stringContaining("must be 4-byte aligned") },
});
},
);
cliTest(
"stops Hopper from claiming a caller-supplied raw-binary image",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-raw-cli-hopper-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const result = await cli.run({
arguments: [
"inspect",
path,
"--target-format",
"raw-binary",
"--architecture",
"arm",
"--entry-point",
"0x8000000",
"--provider",
"hopper",
"--json",
],
environment: {
HOME: root,
XDG_CONFIG_HOME: root,
XDG_CACHE_HOME: root,
},
});
expect(result.exitCode).toBe(1);
expect(JSON.stringify(result.json)).toMatch(/Hopper|ghidra|Ghidra|hopper/i);
expect(JSON.stringify(result.json)).not.toMatch(
/unsupported binary format/i,
);
},
);
@@ -0,0 +1,105 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("raw-binary admission", () => {
it("requires explicit architecture and entry even with a misleading suffix", async () => {
const directory = await createTestTempDirectory("rea-raw-target-");
const path = join(directory, "fixture.js");
const bytes = Buffer.from("1eff2fe1", "hex");
await writeFile(path, bytes);
const target = await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "arm64",
formatHint: "raw-binary",
architecture: "arm",
entryPoint: "0x08000000",
});
expect(target).toMatchObject({
ok: true,
value: {
path,
format: "raw-binary",
kind: "executable",
architecture: "arm",
availableArchitectures: ["arm"],
entryPoint: "0x8000000",
entryPointSource: "0x08000000",
sha256: createHash("sha256").update(bytes).digest("hex"),
},
});
expect(await readFile(path)).toEqual(bytes);
const detected = await parseBinaryTarget(path);
expect(detected.ok && detected.value.format).not.toBe("raw-binary");
});
it("rejects raw-binary without architecture and entry", async () => {
const directory = await createTestTempDirectory("rea-raw-missing-");
const path = join(directory, "fixture.bin");
await writeFile(path, Buffer.from("c3", "hex"));
expect(
await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "x64",
formatHint: "raw-binary",
}),
).toMatchObject({
ok: false,
error: {
_tag: "BinaryTargetError",
reason: expect.stringContaining("architecture"),
},
});
});
it("rejects architecture without format=raw-binary", async () => {
const directory = await createTestTempDirectory("rea-raw-unpaired-");
const path = join(directory, "fixture.bin");
await writeFile(path, Buffer.from("c3", "hex"));
expect(
await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "x64",
architecture: "arm",
entryPoint: "0x8000000",
}),
).toMatchObject({
ok: false,
error: {
_tag: "BinaryTargetError",
reason: expect.stringContaining("format=raw-binary"),
},
});
});
it("rejects an empty image", async () => {
const directory = await createTestTempDirectory("rea-raw-empty-");
const path = join(directory, "fixture.bin");
await writeFile(path, Buffer.alloc(0));
expect(
await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "x64",
formatHint: "raw-binary",
architecture: "x86",
entryPoint: "0x1000",
}),
).toMatchObject({ ok: false, error: { _tag: "BinaryTargetError" } });
});
it("rejects a contradictory target kind", async () => {
const directory = await createTestTempDirectory("rea-raw-kind-");
const path = join(directory, "fixture.bin");
await writeFile(path, Buffer.from("c3", "hex"));
expect(
await parseBinaryTarget(path, {
cwd: directory,
hostArchitecture: "x64",
targetKind: "database",
formatHint: "raw-binary",
architecture: "x86",
entryPoint: "0x1000",
}),
).toMatchObject({ ok: false, error: { _tag: "BinaryTargetError" } });
});
});
+219
View File
@@ -0,0 +1,219 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { Ajv2020 } from "ajv/dist/2020.js";
import { expect, it, onTestFinished } from "vitest";
import { z } from "zod";
import { createServer } from "../../../src/server/createServer.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import type { AnalysisProvider } from "../../../src/application/AnalysisProvider.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { ok } from "../../../src/domain/result.js";
import { observed } from "../../fixtures/analysisExecution.js";
import {
createCacheProvider,
createTestBinarySession,
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { silentLogger } from "../../../src/logger.js";
import type { CallToolResult } from "@modelcontextprotocol/server";
const connect = async (
provider: AnalysisProvider = createCacheProvider([]),
) => {
const session = createTestBinarySession(provider);
const server = createServer(
{ kind: "session", session },
{ logger: silentLogger },
);
const client = new Client({ name: "raw-binary-mcp", 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);
return { client, session };
};
const structured = (result: CallToolResult): Record<string, unknown> => {
if (
typeof result.structuredContent !== "object" ||
result.structuredContent === null
)
throw new Error("missing structured result");
return z.record(z.string(), z.unknown()).parse(result.structuredContent);
};
it("opens a headerless image when architecture and entry are supplied", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const { client } = await connect();
const opened = await client.callTool({
name: "open_binary",
arguments: {
path,
format: "raw-binary",
architecture: "arm",
entry_point: "0x08000000",
},
});
expect(opened.isError).not.toBe(true);
expect(structured(opened).result).toMatchObject({
path,
format: "raw-binary",
kind: "executable",
architecture: "arm",
entry_point: "0x8000000",
});
});
it("rejects an unaligned AArch64 entry before selecting or starting a provider", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-alignment-");
const path = join(root, "image.bin");
await writeFile(path, Buffer.from("c0035fd6", "hex"));
const { client, session } = await connect({
...createCacheProvider([]),
resolveAnalysisProfile: () => {
throw new Error("unaligned input must not select a provider");
},
createClient: () => {
throw new Error("unaligned input must not launch a provider");
},
});
const opened = await client.callTool({
name: "open_binary",
arguments: {
path,
format: "raw-binary",
architecture: "arm64",
entry_point: "0x8000001",
},
});
expect(opened.isError).toBe(true);
expect(JSON.stringify(opened.content)).toContain("must be 4-byte aligned");
expect(session.activeTarget()).toBeUndefined();
});
it("rejects raw-binary open requests that omit architecture", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-missing-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const { client } = await connect();
const opened = await client.callTool({
name: "open_binary",
arguments: { path, format: "raw-binary" },
});
expect(opened.isError).toBe(true);
});
it("reuses a canonical raw entry and replaces the session when the entry changes", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-reopen-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from("1eff2fe1", "hex"));
const fixture = createCacheProvider([]);
const resolved: string[] = [];
const created: string[] = [];
const closed: string[] = [];
const { client, session } = await connect({
...fixture,
resolveAnalysisProfile: (target) => {
if (target.format !== "raw-binary")
throw new Error("expected raw binary");
resolved.push(target.entryPoint);
return Promise.resolve(
ok({
profile: createAnalysisProfile(
{ ...fixture.identity(), version: "1" },
{
entry_point: target.entryPoint,
},
),
}),
);
},
createClient: (target) => {
if (target.format !== "raw-binary")
throw new Error("expected raw binary");
created.push(target.entryPoint);
return {
execute: (operation) => {
if (operation !== "health" && operation !== "address_name")
throw new Error(`unexpected fixture operation: ${operation}`);
return Promise.resolve(observed(target.entryPoint));
},
close: () => {
closed.push(target.entryPoint);
return Promise.resolve(ok(null));
},
};
},
});
const tools = (await client.listTools()).tools;
const validateLifecycle = (
name: "open_binary" | "binary_session",
response: CallToolResult,
) => {
const tool = tools.find((candidate) => candidate.name === name);
if (tool?.outputSchema === undefined)
throw new Error(`missing ${name} output schema`);
const schema = z.record(z.string(), z.unknown()).parse(tool.outputSchema);
const validate = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(schema);
expect(
validate(response.structuredContent),
JSON.stringify(validate.errors),
).toBe(true);
const parsed = toolContract(name).outputSchema.parse(
response.structuredContent,
);
const target = z.record(z.string(), z.unknown()).parse(parsed.result);
const { entry_point: _entry, ...missingEntry } = target;
expect(validate({ ...structured(response), result: missingEntry })).toBe(
false,
);
return target;
};
for (const entryPoint of ["0x08000000", "0x8000000", "0x09000000"]) {
const opened = await client.callTool({
name: "open_binary",
arguments: {
path,
format: "raw-binary",
architecture: "arm",
entry_point: entryPoint,
},
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const canonical = `0x${BigInt(entryPoint).toString(16)}`;
expect(validateLifecycle("open_binary", opened).entry_point).toBe(
canonical,
);
const status = await client.callTool({
name: "binary_session",
arguments: {},
});
expect(status.isError, JSON.stringify(status)).not.toBe(true);
expect(validateLifecycle("binary_session", status).entry_point).toBe(
canonical,
);
const result = await client.callTool({
name: "address_name",
arguments: { address: entryPoint },
});
expect(result.isError, JSON.stringify(result)).not.toBe(true);
expect(structured(result).normalized_result).toBe(canonical);
}
expect(session.analysisProfile()?.parameters.entry_point).toBe("0x9000000");
expect(resolved).toEqual(["0x8000000", "0x9000000"]);
expect(created).toEqual(["0x8000000", "0x9000000"]);
expect(closed).toEqual(["0x8000000"]);
});
@@ -12,6 +12,7 @@ import type { ProgressUpdate } from "../../../../src/application/ProgressReporte
import { ok } from "../../../../src/domain/result.js";
import { GhidraClient } from "../../../../src/ghidra/GhidraClient.js";
import { OwnedFileHandle } from "../../../../src/filesystem/OwnedFileHandle.js";
import { GHIDRA_PROCESS_DIAGNOSTIC_BYTES } from "../../../../src/ghidra/GhidraDiagnostics.js";
import { GhidraHeadlessLauncher } from "../../../../src/ghidra/GhidraLauncher.js";
import type { GhidraDiagnostic } from "../../../../src/ghidra/GhidraClientTypes.js";
@@ -122,12 +123,14 @@ const clientFor = (
readonly transport?: GhidraTransportKind;
readonly runId?: string;
readonly logger?: Logger;
readonly targetPath?: string;
readonly targetSha256?: string;
} = {},
): GhidraClient => {
const client = new GhidraClient({
launcher,
targetPath: fixturePath,
targetSha256: TARGET_SHA256,
targetPath: options.targetPath ?? fixturePath,
targetSha256: options.targetSha256 ?? TARGET_SHA256,
transport: options.transport ?? HOST_TRANSPORT,
providerVersion: PROVIDER_VERSION,
profileDigest: PROFILE_DIGEST,
@@ -223,6 +226,80 @@ it("keeps one shared startup despite a failed progress sink and stops reports af
});
describe("GhidraClient captured source snapshot", () => {
it("retains a snapshot descriptor whose close failed until session cleanup succeeds", async () => {
const client = clientFor(new FixtureLauncher());
const started = await client.start();
if (!started.ok) throw started.error;
const close = vi
.spyOn(OwnedFileHandle.prototype, "close")
.mockRejectedValueOnce(new Error("snapshot descriptor close failed"));
try {
await expect(client.hashTargetSnapshot()).resolves.toMatchObject({
ok: false,
error: { kind: "protocol" },
});
const owner = close.mock.contexts[0];
expect(owner).toBeInstanceOf(OwnedFileHandle);
const closed = await client.close();
if (!closed.ok) throw closed.error;
expect(
close.mock.contexts.filter((context) => context === owner),
).toHaveLength(2);
} finally {
close.mockRestore();
}
});
it("hashes complete private snapshots with bounded chunks and abortable reads", async () => {
const root = await createTestTempDirectory("rea-ghidra-hash-");
const source = join(root, "firmware.bin");
const bytes = Buffer.alloc(512 * 1024 + 3, 0xa5);
const sha256 = createHash("sha256").update(bytes).digest("hex");
await writeFile(source, bytes);
const client = clientFor(new FixtureLauncher(), {
targetPath: source,
targetSha256: sha256,
});
await expect(client.hashTargetSnapshot()).resolves.toMatchObject({
ok: false,
error: { kind: "protocol" },
});
const started = await client.start();
if (!started.ok) throw started.error;
// Observe the admitted private snapshot even if the original path changes.
await writeFile(source, "changed original");
const allocate = Buffer.allocUnsafe;
const allocations = vi.spyOn(Buffer, "allocUnsafe");
try {
const identity = await client.hashTargetSnapshot();
if (!identity.ok) throw identity.error;
expect(identity.value).toEqual({ sha256, bytes: bytes.length });
expect(allocations.mock.calls.length).toBeGreaterThan(1);
expect(
Math.max(...allocations.mock.calls.map(([size]) => size)),
).toBeLessThan(bytes.length);
const controller = new AbortController();
allocations.mockImplementationOnce((size) => {
controller.abort();
return allocate(size);
});
await expect(
client.hashTargetSnapshot(controller.signal),
).resolves.toMatchObject({ ok: false, error: { kind: "cancelled" } });
} finally {
allocations.mockRestore();
}
await expect(client.hashTargetSnapshot()).resolves.toMatchObject({
ok: true,
value: { sha256, bytes: bytes.length },
});
await client.close();
await expect(client.hashTargetSnapshot()).resolves.toMatchObject({
ok: false,
error: { kind: "protocol" },
});
});
it("exposes the immutable import snapshot only during the live session", async () => {
const client = clientFor(new FixtureLauncher());
await expect(client.readTargetSnapshot()).resolves.toMatchObject({
@@ -113,6 +113,39 @@ describe("Ghidra COM loader", () => {
});
});
describe("Ghidra raw-binary loader", () => {
it("loads caller-supplied architecture and entry before auto-analysis", () => {
const arguments_ = ghidraHeadlessArguments({
projectRoot: "/tmp/project",
targetPath: "/tmp/ecu.bin",
bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java",
descriptorPath: "/tmp/session.json",
ghidraLogPath: "/tmp/ghidra.log",
scriptLogPath: "/tmp/script.log",
rawBinary: {
languageId: "ARM:LE:32:v7",
compilerSpecId: "default",
baseAddr: "0x8000000",
},
});
expectOptions(arguments_, [
["-loader", "BinaryLoader"],
["-loader-baseAddr", "0x8000000"],
["-processor", "ARM:LE:32:v7"],
["-cspec", "default"],
]);
const prepare = arguments_.indexOf("-preScript");
expect(arguments_[prepare + 1]).toBe(
join("/package/bridge", "ReaGhidraPrepareRaw.java"),
);
expect(arguments_[prepare + 2]).toBe("ARM:LE:32:v7");
expect(arguments_[prepare + 3]).toBe("0x8000000");
expect(prepare).toBeLessThan(arguments_.indexOf("-postScript"));
expect(arguments_).toContain("-readOnly");
expect(arguments_).toContain("-deleteProject");
});
});
describe("Ghidra headless launcher", () => {
it("forces the admitted real-mode language and loader for DOS MZ", () => {
const arguments_ = ghidraHeadlessArguments({
@@ -208,6 +241,20 @@ describe("Ghidra configured import language and seeds", () => {
).toThrow(/cannot be combined with a DOS import/u);
});
it("never combines a configured language with a raw-binary import", () => {
expect(() =>
ghidraHeadlessArguments({
...base,
languageOverride: { languageId: "x86:LE:32:default" },
rawBinary: {
languageId: "ARM:LE:32:v7",
compilerSpecId: "default",
baseAddr: "0x8000000",
},
}),
).toThrow(/cannot be combined with a raw-binary import/u);
});
it.each(["darwin", "win32"] as const)(
"applies seeds after loader preparation and before analysis scripts on %s",
(platform) => {
@@ -31,6 +31,27 @@ describe("Hopper analysis profiles", () => {
});
});
it("does not map caller-supplied raw binaries onto a Hopper loader", () => {
expect(
hopperLoaderArgsForTarget({
path: "/tmp/ecu.bin",
sha256: "a".repeat(64),
kind: "executable",
format: "raw-binary",
architecture: "arm",
availableArchitectures: ["arm"],
entryPoint: "0x8000000",
entryPointSource: "0x8000000",
}),
).toMatchObject({
ok: false,
error: {
_tag: "ProviderAdapterError",
operation: "resolve_analysis_profile",
},
});
});
it.each([
[target("elf", "x86_64"), ["-l", "ELF", "--intel-64"]],
[target("pe", "x86"), ["-l", "WinPE", "--intel-32"]],