feat(ghidra): implement read-only inventory operations
This commit is contained in:
@@ -8,6 +8,11 @@ their Mach-O symbols and strings with native command-line tools.
|
||||
Only source files are versioned. Generated binaries, generated large-fixture
|
||||
source, debug information, and manifests must remain under `build/`.
|
||||
|
||||
`ghidra/inventory.c` is also compiled into temporary Linux ELF debug and
|
||||
stripped variants by `npm run verify:ghidra`. It fixes local functions, external
|
||||
`puts` linkage, defined strings, and writable/executable memory needed to prove
|
||||
the read-only Ghidra inventory contracts without committing a binary.
|
||||
|
||||
The C fixture fixes a known call chain and strings. The version pair fixes an
|
||||
added symbol, changed string, and changed call relationship. The generated
|
||||
large fixture contains 1,205 uniquely named functions and strings so provider
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#include <stdio.h>
|
||||
|
||||
volatile int rea_ghidra_inventory_global = 7;
|
||||
|
||||
__attribute__((noinline, used)) int rea_ghidra_inventory_leaf(int value) {
|
||||
puts("REA_GHIDRA_LEAF_VALUE");
|
||||
return value + rea_ghidra_inventory_global;
|
||||
}
|
||||
|
||||
__attribute__((noinline, used)) int rea_ghidra_inventory_entry(void) {
|
||||
puts("REA_GHIDRA_INVENTORY_ENTRY");
|
||||
return rea_ghidra_inventory_leaf(35);
|
||||
}
|
||||
|
||||
int main(void) { return rea_ghidra_inventory_entry() == 42 ? 0 : 1; }
|
||||
Vendored
+135
-2
@@ -89,6 +89,26 @@ else {
|
||||
} else socket.write(response);
|
||||
continue;
|
||||
}
|
||||
if (mode === "remote_error" && request.method === "list_procedures") {
|
||||
socket.write(
|
||||
`${JSON.stringify({
|
||||
id: request.id,
|
||||
ok: false,
|
||||
error: {
|
||||
code: "not_found",
|
||||
message: "Unknown Ghidra procedure name",
|
||||
},
|
||||
})}\n`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const inventory = inventoryResult(request.method);
|
||||
if (inventory !== undefined) {
|
||||
socket.write(
|
||||
`${JSON.stringify({ id: request.id, ok: true, result: inventory })}\n`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (request.method === "shutdown") {
|
||||
socket.end(
|
||||
`${JSON.stringify({
|
||||
@@ -112,17 +132,130 @@ const sessionInfo = ({
|
||||
timedOut,
|
||||
}) => ({
|
||||
name: "REA Ghidra bridge",
|
||||
bridge_version: 1,
|
||||
bridge_version: 2,
|
||||
run_id: sessionRunId,
|
||||
profile_digest: digest,
|
||||
provider: { id: "ghidra", version },
|
||||
read_only: true,
|
||||
analysis_complete: !timedOut,
|
||||
analysis_timed_out: timedOut,
|
||||
capabilities: ["ping", "shutdown"],
|
||||
capabilities: [
|
||||
"ping",
|
||||
"shutdown",
|
||||
"address_name",
|
||||
"list_documents",
|
||||
"list_names",
|
||||
"list_procedures",
|
||||
"list_segments",
|
||||
"list_strings",
|
||||
"procedure_address",
|
||||
"resolve_containing_procedure",
|
||||
"search_procedures",
|
||||
"search_strings",
|
||||
],
|
||||
target: {
|
||||
name: "fixture",
|
||||
language_id: "x86:LE:64:default",
|
||||
compiler_spec_id: "gcc",
|
||||
image_base: "0x1000",
|
||||
default_address_space: "ram",
|
||||
},
|
||||
});
|
||||
|
||||
const inventoryResult = (method) => {
|
||||
const page = (items) => ({
|
||||
items,
|
||||
offset: 0,
|
||||
limit: method.startsWith("search_") ? 100 : 500,
|
||||
total: items.length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
switch (method) {
|
||||
case "address_name":
|
||||
return "fixture_main";
|
||||
case "list_documents":
|
||||
return ["fixture"];
|
||||
case "list_names":
|
||||
return page([
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: false,
|
||||
type: "function",
|
||||
source: "analysis",
|
||||
},
|
||||
},
|
||||
]);
|
||||
case "list_procedures":
|
||||
return page([
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: { external: false, thunk: false, thunk_target: null },
|
||||
},
|
||||
]);
|
||||
case "list_segments":
|
||||
return [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x1000",
|
||||
end: "0x1100",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x1000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
];
|
||||
case "list_strings":
|
||||
return page([
|
||||
{
|
||||
address: "0x2000",
|
||||
value: "fixture value",
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "present_or_not_required",
|
||||
byte_length: 14,
|
||||
},
|
||||
},
|
||||
]);
|
||||
case "procedure_address":
|
||||
return "0x1000";
|
||||
case "resolve_containing_procedure":
|
||||
return {
|
||||
query_address: "0x1001",
|
||||
found: true,
|
||||
procedure: { address: "0x1000", name: "fixture_main" },
|
||||
};
|
||||
case "search_procedures":
|
||||
return page([
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
},
|
||||
]);
|
||||
case "search_strings":
|
||||
return page([
|
||||
{
|
||||
address: "0x2000",
|
||||
value: "fixture value",
|
||||
value_truncated: false,
|
||||
},
|
||||
]);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
GhidraLaunchSession,
|
||||
GhidraLauncher,
|
||||
} from "../src/ghidra/GhidraLauncher.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../src/ghidra/GhidraSessionValues.js";
|
||||
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("./fixtures/fakeGhidra.mjs", import.meta.url),
|
||||
@@ -31,6 +32,7 @@ type FixtureMode =
|
||||
| "oversized_whitespace"
|
||||
| "future_id"
|
||||
| "analysis_timeout"
|
||||
| "remote_error"
|
||||
| "hang_after_start"
|
||||
| "silent"
|
||||
| "exit";
|
||||
@@ -114,12 +116,63 @@ describe("GhidraClient", () => {
|
||||
read_only: true,
|
||||
analysis_complete: true,
|
||||
analysis_timed_out: false,
|
||||
capabilities: ["ping", "shutdown"],
|
||||
capabilities: GHIDRA_SESSION_CAPABILITIES,
|
||||
target: {
|
||||
image_base: "0x1000",
|
||||
default_address_space: "ram",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(Buffer.byteLength(launcher.socketPaths[0] ?? "")).toBeLessThan(108);
|
||||
});
|
||||
|
||||
it("correlates an admitted inventory request after startup", async () => {
|
||||
const client = clientFor(new FixtureLauncher());
|
||||
|
||||
await expect(
|
||||
client.callTool("list_procedures", {
|
||||
document: null,
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
items: [
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
procedure: { external: false, thunk: false },
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
has_more: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves an authenticated operation failure code and diagnostics", async () => {
|
||||
const client = clientFor(new FixtureLauncher("remote_error"));
|
||||
|
||||
const result = await client.callTool("list_procedures", {
|
||||
document: null,
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "remote",
|
||||
remoteCode: "not_found",
|
||||
diagnostics: {
|
||||
remote_code: "not_found",
|
||||
remote_message: "Unknown Ghidra procedure name",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["wrong_identity", "protocol"],
|
||||
["malformed", "protocol"],
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
GHIDRA_INVENTORY_OPERATIONS,
|
||||
isGhidraInventoryOperation,
|
||||
parseGhidraInventoryInput,
|
||||
parseGhidraInventoryResult,
|
||||
type GhidraInventoryOperation,
|
||||
} from "../src/ghidra/GhidraInventoryValues.js";
|
||||
import type { JsonValue } from "../src/domain/jsonValue.js";
|
||||
|
||||
describe("Ghidra inventory boundary values", () => {
|
||||
it("defaults bounded provider inputs without accepting undeclared fields", () => {
|
||||
expect(parseGhidraInventoryInput("list_procedures", {})).toEqual({
|
||||
ok: true,
|
||||
value: { document: null, offset: 0, limit: 100 },
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("search_strings", { pattern: "needle" }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
pattern: "needle",
|
||||
mode: "literal",
|
||||
case_sensitive: false,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
document: null,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("list_documents", { extra: true }),
|
||||
).toMatchObject({ ok: false, error: { _tag: "AnalysisInputError" } });
|
||||
expect(parseGhidraInventoryInput("address_name", {})).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
expect(
|
||||
parseGhidraInventoryInput("procedure_address", {
|
||||
procedure: "x".repeat(4097),
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the admitted operation set closed", () => {
|
||||
expect(GHIDRA_INVENTORY_OPERATIONS).toHaveLength(10);
|
||||
expect(isGhidraInventoryOperation("list_names")).toBe(true);
|
||||
expect(isGhidraInventoryOperation("goto_address")).toBe(false);
|
||||
expect(isGhidraInventoryOperation("set_comment")).toBe(false);
|
||||
});
|
||||
|
||||
it("parses primary, dynamic, and external symbol facts", () => {
|
||||
const items = [
|
||||
{
|
||||
address: "EXTERNAL:0x1",
|
||||
value: "libc::puts",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: false,
|
||||
external: true,
|
||||
type: "function",
|
||||
source: "imported",
|
||||
},
|
||||
},
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "LAB_00401000",
|
||||
value_truncated: false,
|
||||
symbol: {
|
||||
primary: true,
|
||||
dynamic: true,
|
||||
external: false,
|
||||
type: "label",
|
||||
source: "default",
|
||||
},
|
||||
},
|
||||
] satisfies readonly JsonValue[];
|
||||
expect(parseGhidraInventoryResult("list_names", page(items))).toEqual({
|
||||
ok: true,
|
||||
value: page(items),
|
||||
});
|
||||
});
|
||||
|
||||
it("parses thunk, string-layout, and memory-permission observations", () => {
|
||||
expect(
|
||||
parseGhidraInventoryResult(
|
||||
"list_procedures",
|
||||
page([
|
||||
{
|
||||
address: "0x401020",
|
||||
value: "puts",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: true,
|
||||
thunk_target: "EXTERNAL:0x1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraInventoryResult(
|
||||
"list_strings",
|
||||
page([
|
||||
{
|
||||
address: "0x402000",
|
||||
value: "fixture",
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "missing",
|
||||
byte_length: 7,
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
parseGhidraInventoryResult("list_segments", [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x401000",
|
||||
end: "0x402000",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x400000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
]),
|
||||
).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it.each(malformedOutputs())(
|
||||
"rejects malformed %s output",
|
||||
(_name, operation, value) => {
|
||||
expect(parseGhidraInventoryResult(operation, value)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
function malformedOutputs(): Array<
|
||||
[string, GhidraInventoryOperation, JsonValue]
|
||||
> {
|
||||
return [
|
||||
[
|
||||
"non-canonical address",
|
||||
"list_procedures",
|
||||
page([
|
||||
{
|
||||
address: "00401000",
|
||||
value: "main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
]),
|
||||
],
|
||||
[
|
||||
"missing external metadata",
|
||||
"list_names",
|
||||
page([{ address: "0x401000", value: "main", value_truncated: false }]),
|
||||
],
|
||||
[
|
||||
"contradictory continuation",
|
||||
"search_strings",
|
||||
{
|
||||
...page([]),
|
||||
total: 1,
|
||||
has_more: false,
|
||||
next_offset: null,
|
||||
},
|
||||
],
|
||||
[
|
||||
"non-advancing continuation",
|
||||
"list_procedures",
|
||||
{
|
||||
...page([]),
|
||||
total: 1,
|
||||
has_more: true,
|
||||
next_offset: 0,
|
||||
},
|
||||
],
|
||||
[
|
||||
"items beyond exact total",
|
||||
"list_procedures",
|
||||
{ ...page([procedureItem()]), total: 0 },
|
||||
],
|
||||
["provider limit", "search_procedures", { ...page([]), limit: 101 }],
|
||||
["multiple programs", "list_documents", ["first", "second"]],
|
||||
];
|
||||
}
|
||||
|
||||
function procedureItem(): JsonValue {
|
||||
return {
|
||||
address: "0x401000",
|
||||
value: "main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function page(items: readonly JsonValue[]) {
|
||||
return {
|
||||
items: [...items],
|
||||
offset: 0,
|
||||
limit: 500,
|
||||
total: items.length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BinarySession } from "../src/application/BinarySession.js";
|
||||
import { EnhancedTools } from "../src/application/EnhancedTools.js";
|
||||
import { AnalysisProviderRegistry } from "../src/application/AnalysisProviderRegistry.js";
|
||||
import { SessionProviderRouter } from "../src/application/SessionProviderRouter.js";
|
||||
import { parseConfig } from "../src/config.js";
|
||||
import { parseEvidence } from "../src/domain/evidence.js";
|
||||
import type { JsonValue } from "../src/domain/jsonValue.js";
|
||||
import { ok } from "../src/domain/result.js";
|
||||
import type { GhidraInstallationHost } from "../src/ghidra/GhidraInstallation.js";
|
||||
import type { GhidraInventoryOperation } from "../src/ghidra/GhidraInventoryValues.js";
|
||||
import {
|
||||
GhidraProvider,
|
||||
type GhidraProviderClientFactory,
|
||||
} from "../src/ghidra/GhidraProvider.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../src/ghidra/GhidraSessionValues.js";
|
||||
import { silentLogger } from "../src/logger.js";
|
||||
import { createServer } from "../src/server/createServer.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
|
||||
describe("Ghidra MCP and shared CLI composition", () => {
|
||||
it("preserves provider evidence, composed parity, and capability routing", async () => {
|
||||
const calls: GhidraInventoryOperation[] = [];
|
||||
const factory: GhidraProviderClientFactory = (options) => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo(options.profileDigest))),
|
||||
callTool: (operation, input) => {
|
||||
calls.push(operation);
|
||||
return Promise.resolve(ok(resultFor(operation, input)));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
|
||||
if (!config.ok) throw config.error;
|
||||
const provider = new GhidraProvider(
|
||||
config.value,
|
||||
silentLogger,
|
||||
installationHost(),
|
||||
factory,
|
||||
);
|
||||
const session = new BinarySession(
|
||||
SessionProviderRouter.selectable(
|
||||
new AnalysisProviderRegistry([provider]),
|
||||
[],
|
||||
),
|
||||
);
|
||||
const server = createServer(session, session, { logger: silentLogger });
|
||||
const mcp = new Client({ name: "ghidra-parity", version: "1.0.0" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await mcp.connect(clientTransport);
|
||||
const opened = await mcp.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: process.execPath },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
|
||||
const listed = parseEvidence(
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "list_procedures",
|
||||
arguments: {},
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
expect(listed).toMatchObject({
|
||||
operation: "list_procedures",
|
||||
provider: { id: "ghidra", name: "Ghidra", version: "12.1.2" },
|
||||
analysis_profile: {
|
||||
provider: { id: "ghidra", version: "12.1.2" },
|
||||
parameters: {
|
||||
import_mode: "ephemeral-read-only",
|
||||
analyzer_preset: "ghidra-default",
|
||||
},
|
||||
},
|
||||
normalized_result: {
|
||||
items: [
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
total: 1,
|
||||
},
|
||||
raw_result: {
|
||||
items: [{ value_truncated: false }],
|
||||
},
|
||||
});
|
||||
|
||||
const mcpOverview = parseEvidence(
|
||||
(
|
||||
await mcp.callTool({
|
||||
name: "binary_overview",
|
||||
arguments: { detail: "detailed", limit: 5 },
|
||||
})
|
||||
).structuredContent,
|
||||
);
|
||||
const directOverview = await new EnhancedTools(session).execute(
|
||||
"binary_overview",
|
||||
{ detail: "detailed", limit: 5 },
|
||||
);
|
||||
expect(directOverview.ok).toBe(true);
|
||||
if (!directOverview.ok) return;
|
||||
expect(mcpOverview.normalized_result).toEqual(directOverview.value);
|
||||
expect(mcpOverview).toMatchObject({
|
||||
provider: { id: "rea-workflow" },
|
||||
confidence: "derived",
|
||||
normalized_result: {
|
||||
document: "fixture",
|
||||
segment_count: 1,
|
||||
procedure_count: 1,
|
||||
string_count: 2,
|
||||
segments: [{ name: ".text", length: 256 }],
|
||||
},
|
||||
});
|
||||
|
||||
const unsupported = await mcp.callTool({
|
||||
name: "set_comment",
|
||||
arguments: { address: "0x401000", comment: "not allowed" },
|
||||
});
|
||||
expect(unsupported.isError).toBe(true);
|
||||
expect(unsupported.structuredContent).toMatchObject({
|
||||
error: { code: "capability_unavailable" },
|
||||
});
|
||||
expect(calls).not.toContain("set_comment");
|
||||
|
||||
const status = await mcp.callTool({
|
||||
name: "binary_session",
|
||||
arguments: {},
|
||||
});
|
||||
expect(status.structuredContent).toMatchObject({
|
||||
result: {
|
||||
open: true,
|
||||
analysis_provider_binding: {
|
||||
provider: { id: "ghidra", version: "12.1.2" },
|
||||
},
|
||||
tool_availability: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "binary_overview",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({ name: "swift_classes", available: true }),
|
||||
expect.objectContaining({
|
||||
name: "get_objc_classes",
|
||||
available: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "batch_decompile",
|
||||
available: false,
|
||||
reason: "provider_missing",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
name: "trace_feature",
|
||||
available: false,
|
||||
reason: "provider_missing",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([mcp.close(), server.close()]);
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const installationHost = (): GhidraInstallationHost => ({
|
||||
readText: () => "application.version=12.1.2\n",
|
||||
executable: () => true,
|
||||
probeJava: () => ({
|
||||
version: "21.0.11",
|
||||
major: 21,
|
||||
home: "/usr/lib/jvm/jdk-21",
|
||||
bits: 64,
|
||||
jdk: true,
|
||||
}),
|
||||
});
|
||||
|
||||
const sessionInfo = (profileDigest: string) => ({
|
||||
name: "REA Ghidra bridge" as const,
|
||||
bridge_version: 2 as const,
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
profile_digest: profileDigest,
|
||||
provider: { id: "ghidra" as const, version: "12.1.2" },
|
||||
read_only: true as const,
|
||||
analysis_complete: true,
|
||||
analysis_timed_out: false,
|
||||
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
|
||||
target: {
|
||||
name: "fixture",
|
||||
language_id: "x86:LE:64:default",
|
||||
compiler_spec_id: "gcc",
|
||||
image_base: "0x400000",
|
||||
default_address_space: "ram",
|
||||
},
|
||||
});
|
||||
|
||||
const resultFor = (
|
||||
operation: GhidraInventoryOperation,
|
||||
input: Readonly<Record<string, JsonValue>>,
|
||||
): JsonValue => {
|
||||
const limit = typeof input.limit === "number" ? input.limit : 100;
|
||||
switch (operation) {
|
||||
case "list_documents":
|
||||
return ["fixture"];
|
||||
case "list_procedures":
|
||||
return page(
|
||||
[
|
||||
{
|
||||
address: "0x401000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
limit,
|
||||
);
|
||||
case "list_strings":
|
||||
return page(
|
||||
[
|
||||
stringItem("0x402000", "inventory fixture"),
|
||||
stringItem("0x402020", "external fixture"),
|
||||
],
|
||||
limit,
|
||||
);
|
||||
case "list_segments":
|
||||
return [
|
||||
{
|
||||
name: ".text",
|
||||
start: "0x401000",
|
||||
end: "0x401100",
|
||||
readable: true,
|
||||
writable: false,
|
||||
executable: true,
|
||||
permissions: { available: true, source: "ghidra-memory-block" },
|
||||
provenance: "ghidra-memory-block",
|
||||
address_space: "ram",
|
||||
image_base: "0x400000",
|
||||
initialized: true,
|
||||
overlay: false,
|
||||
sections: [],
|
||||
},
|
||||
];
|
||||
case "list_names":
|
||||
case "search_procedures":
|
||||
case "search_strings":
|
||||
return page([], limit);
|
||||
case "address_name":
|
||||
return "fixture_main";
|
||||
case "procedure_address":
|
||||
return "0x401000";
|
||||
case "resolve_containing_procedure":
|
||||
return {
|
||||
query_address: "0x401001",
|
||||
found: true,
|
||||
procedure: { address: "0x401000", name: "fixture_main" },
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const page = (items: readonly JsonValue[], limit: number): JsonValue => ({
|
||||
items: [...items],
|
||||
offset: 0,
|
||||
limit,
|
||||
total: items.length,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
});
|
||||
|
||||
const stringItem = (address: string, value: string): JsonValue => ({
|
||||
address,
|
||||
value,
|
||||
value_truncated: false,
|
||||
string: {
|
||||
encoding: "UTF-8",
|
||||
termination: "present_or_not_required",
|
||||
byte_length: value.length + 1,
|
||||
},
|
||||
});
|
||||
@@ -6,8 +6,12 @@ import {
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
GhidraProvider,
|
||||
type GhidraProviderClientFactory,
|
||||
} from "../src/ghidra/GhidraProvider.js";
|
||||
import type { GhidraInstallationHost } from "../src/ghidra/GhidraInstallation.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../src/ghidra/GhidraSessionValues.js";
|
||||
import { err, ok } from "../src/domain/result.js";
|
||||
import { GhidraSessionError } from "../src/ghidra/GhidraSessionError.js";
|
||||
import { silentLogger } from "../src/logger.js";
|
||||
|
||||
const INSTALL = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
@@ -23,10 +27,13 @@ const installationHost = (): GhidraInstallationHost => ({
|
||||
}),
|
||||
});
|
||||
|
||||
const provider = (host = installationHost()): GhidraProvider => {
|
||||
const provider = (
|
||||
host = installationHost(),
|
||||
clientFactory?: GhidraProviderClientFactory,
|
||||
): GhidraProvider => {
|
||||
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL });
|
||||
if (!config.ok) throw config.error;
|
||||
return new GhidraProvider(config.value, silentLogger, host);
|
||||
return new GhidraProvider(config.value, silentLogger, host, clientFactory);
|
||||
};
|
||||
|
||||
describe("Ghidra provider", () => {
|
||||
@@ -36,9 +43,29 @@ describe("Ghidra provider", () => {
|
||||
const ghidra = provider(host);
|
||||
|
||||
expect(ghidra.identity()).toEqual(GHIDRA_PROVIDER_IDENTITY);
|
||||
expect(ghidra.capabilities()).toBe(GHIDRA_PROVIDER_TOOL_CONTRACTS);
|
||||
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toEqual([]);
|
||||
expect(ghidra.capabilities().map(({ operation }) => operation)).toEqual(
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
expect(GHIDRA_PROVIDER_TOOL_CONTRACTS).toHaveLength(10);
|
||||
expect(Object.isFrozen(ghidra.capabilities())).toBe(true);
|
||||
expect(ghidra.capabilities()).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "list_procedures",
|
||||
pagination: "offset",
|
||||
effects: expect.objectContaining({
|
||||
mutatesArtifact: false,
|
||||
mayShowUi: false,
|
||||
mayWriteFilesystem: true,
|
||||
}),
|
||||
limits: {
|
||||
maxResults: 500,
|
||||
maxPayloadBytes: 1024 * 1024,
|
||||
timeoutMs: 10_000,
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({
|
||||
status: "available",
|
||||
diagnostics: {
|
||||
@@ -86,7 +113,33 @@ describe("Ghidra provider", () => {
|
||||
});
|
||||
|
||||
it("commits exact provider, isolation, and resource semantics", async () => {
|
||||
const ghidra = provider();
|
||||
const callTool = vi.fn().mockResolvedValue(
|
||||
ok({
|
||||
items: [
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
value_truncated: false,
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: 1,
|
||||
next_offset: null,
|
||||
has_more: false,
|
||||
}),
|
||||
);
|
||||
const start = vi.fn().mockResolvedValue(ok(sessionInfo()));
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start,
|
||||
callTool,
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
@@ -112,15 +165,92 @@ describe("Ghidra provider", () => {
|
||||
const result = await ghidra
|
||||
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
|
||||
.execute("list_procedures", {});
|
||||
expect(callTool).toHaveBeenCalledWith(
|
||||
"list_procedures",
|
||||
{ document: null, offset: 0, limit: 100 },
|
||||
{},
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
providerId: "ghidra",
|
||||
ok: true,
|
||||
value: {
|
||||
provider: {
|
||||
id: "ghidra",
|
||||
name: "Ghidra",
|
||||
version: "12.1.2",
|
||||
},
|
||||
analysisProfile: resolved.value.profile,
|
||||
result: {
|
||||
items: [{ address: "0x1000", value: "fixture_main" }],
|
||||
total: 1,
|
||||
},
|
||||
rawResult: {
|
||||
items: [{ procedure: { external: false, thunk: false } }],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(start).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects malformed inventory output before Evidence creation", async () => {
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () => Promise.resolve(ok({ items: "not-a-page" })),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
|
||||
await expect(
|
||||
ghidra
|
||||
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile)
|
||||
.execute("list_procedures", {}),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisOutputError" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["invalid_request", "AnalysisInputError"],
|
||||
["not_found", "AnalysisInputError"],
|
||||
["ambiguous", "AnalysisInputError"],
|
||||
["method_unavailable", "AnalysisCapabilityUnavailableError"],
|
||||
] as const)(
|
||||
"projects remote %s without losing its typed meaning",
|
||||
async (code, tag) => {
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: () =>
|
||||
Promise.resolve(
|
||||
err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
"Fixture remote failure",
|
||||
{ remote_code: code },
|
||||
{ remoteCode: code },
|
||||
),
|
||||
),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null) return;
|
||||
|
||||
await expect(
|
||||
ghidra
|
||||
.createClient(
|
||||
executableTarget("elf", "x86_64"),
|
||||
resolved.value.profile,
|
||||
)
|
||||
.execute("list_procedures", {}),
|
||||
).resolves.toMatchObject({ ok: false, error: { _tag: tag } });
|
||||
},
|
||||
);
|
||||
|
||||
it("returns cancellation before profile work", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
@@ -135,6 +265,25 @@ describe("Ghidra provider", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const sessionInfo = () => ({
|
||||
name: "REA Ghidra bridge" as const,
|
||||
bridge_version: 2 as const,
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
profile_digest: "a".repeat(64),
|
||||
provider: { id: "ghidra" as const, version: "12.1.2" },
|
||||
read_only: true as const,
|
||||
analysis_complete: true,
|
||||
analysis_timed_out: false,
|
||||
capabilities: [...GHIDRA_SESSION_CAPABILITIES],
|
||||
target: {
|
||||
name: "fixture",
|
||||
language_id: "x86:LE:64:default",
|
||||
compiler_spec_id: "gcc",
|
||||
image_base: "0x1000",
|
||||
default_address_space: "ram",
|
||||
},
|
||||
});
|
||||
|
||||
const executableTarget = (
|
||||
format: BinaryTarget["format"],
|
||||
architecture?: NonNullable<BinaryTarget["architecture"]>,
|
||||
|
||||
@@ -19,7 +19,10 @@ import {
|
||||
HOPPER_PROVIDER_IDENTITY,
|
||||
HOPPER_PROVIDER_TOOL_CONTRACTS,
|
||||
} from "../src/hopper/HopperProvider.js";
|
||||
import { GHIDRA_PROVIDER_IDENTITY } from "../src/ghidra/GhidraProvider.js";
|
||||
import {
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
GHIDRA_PROVIDER_TOOL_CONTRACTS,
|
||||
} from "../src/ghidra/GhidraProvider.js";
|
||||
import { NATIVE_MACOS_PROVIDER_IDENTITY } from "../src/native/NativeMacOSProvider.js";
|
||||
import {
|
||||
assertDocumentationFacts,
|
||||
@@ -74,7 +77,7 @@ describe("canonical product catalog", () => {
|
||||
expect(
|
||||
catalog.providers.find(({ id }) => id === GHIDRA_PROVIDER_IDENTITY.id)
|
||||
?.capabilities,
|
||||
).toEqual([]);
|
||||
).toEqual(GHIDRA_PROVIDER_TOOL_CONTRACTS.map(({ name }) => name).sort());
|
||||
expect(
|
||||
z.toJSONSchema(analysisSnapshotSchema).properties?.snapshot_version,
|
||||
).toMatchObject({
|
||||
|
||||
@@ -7,6 +7,7 @@ import { describe, expect, it } from "vitest";
|
||||
import { parseConfig } from "../src/config.js";
|
||||
import { HopperProvider } from "../src/hopper/HopperProvider.js";
|
||||
import { GhidraProvider } from "../src/ghidra/GhidraProvider.js";
|
||||
import { GHIDRA_INVENTORY_OPERATIONS } from "../src/ghidra/GhidraInventoryValues.js";
|
||||
import { silentLogger } from "../src/logger.js";
|
||||
|
||||
const sourceRoot = new URL("../src/", import.meta.url);
|
||||
@@ -37,7 +38,7 @@ describe("provider-neutral architecture", () => {
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
|
||||
it("publishes no speculative Ghidra binary capabilities", () => {
|
||||
it("publishes only admitted immutable Ghidra inventory capabilities", () => {
|
||||
const config = parseConfig({});
|
||||
expect(config.ok).toBe(true);
|
||||
if (!config.ok) return;
|
||||
@@ -46,8 +47,28 @@ describe("provider-neutral architecture", () => {
|
||||
executable: () => false,
|
||||
probeJava: () => undefined,
|
||||
});
|
||||
expect(provider.capabilities()).toEqual([]);
|
||||
expect(Object.isFrozen(provider.capabilities())).toBe(true);
|
||||
const capabilities = provider.capabilities();
|
||||
expect(capabilities.map(({ operation }) => operation).sort()).toEqual(
|
||||
[...GHIDRA_INVENTORY_OPERATIONS].sort(),
|
||||
);
|
||||
expect(Object.isFrozen(capabilities)).toBe(true);
|
||||
for (const descriptor of capabilities) {
|
||||
expect(descriptor).toMatchObject({
|
||||
available: true,
|
||||
reason: null,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
});
|
||||
expect(Object.isFrozen(descriptor)).toBe(true);
|
||||
expect(Object.isFrozen(descriptor.effects)).toBe(true);
|
||||
expect(Object.isFrozen(descriptor.limits)).toBe(true);
|
||||
expect(Object.isFrozen(descriptor.limitations)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("publishes deterministic immutable Hopper capability descriptors", () => {
|
||||
|
||||
Reference in New Issue
Block a user