feat(native): search analyzed memory for masked byte patterns (#2341)
* feat(native): search analyzed memory for masked byte patterns The diff adds search_bytes to the CLI, the shared MCP contract, Ghidra inventory, and the headless bridge, and advertises the same operation on Hopper as unavailable until that provider is verified. Patterns are hexadecimal byte pairs with optional ?? wildcards and an optional equal-length bit mask; the TypeScript boundary and the bridge both require a nonempty pattern, equal lengths, and at least one constrained bit. Ghidra walks initialized blocks in address order within inclusive bounds, keeps overlapping matches inside a single block, and returns each hit with its segment, unique source file offset, and containing procedure, continuing through a cursor bound to the target, profile, pattern, mask, and bounds. Each page reports the inclusive ranges examined and the skipped uninitialized blocks; cancellation returns a typed error and discards the active Ghidra database. address_to_file_offset now uses the same unique-offset helper, which rejects a mapping that is missing, ambiguous, or larger than a safe integer. * fix(native): limit unbounded byte search to loaded memory Without start or end, search_bytes walked every Ghidra block, including non-loaded file parts such as .symtab and overlay blocks, which the docs call out of scope. Unbounded searches now skip those blocks and list them in searched.skipped_not_loaded; explicit bounds in their address space still search them. Document that a match must end at or before end. * fix(native): preserve implicit address spaces in range consumers * fix(native): reject present malformed byte search state --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
co-authored by
Matt Van Horn
morluto
parent
70611713e1
commit
2a78763e20
@@ -5,9 +5,277 @@ import { join } from "node:path";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { nativeAotPeFixture } from "../../fixtures/nativeaotPe.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
import { ghidraFunctionIdentity } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import { connectGhidraMcp, sessionEvidence } from "./ghidraMcpHarness.js";
|
||||
import {
|
||||
connectGhidraMcp,
|
||||
ghidraInstallationHost,
|
||||
sessionEvidence,
|
||||
} from "./ghidraMcpHarness.js";
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { GhidraClient } from "../../../src/ghidra/GhidraClient.js";
|
||||
import { GhidraProvider } from "../../../src/ghidra/GhidraProvider.js";
|
||||
import { parseConfig } from "../../../src/config/parseConfig.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
|
||||
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { waitForExit } from "../../support/process/processFixture.js";
|
||||
import { GhidraSessionError } from "../../../src/ghidra/GhidraSessionError.js";
|
||||
|
||||
it("retains byte-search coverage and rejects malformed pages before creating Evidence", async () => {
|
||||
const page = {
|
||||
matches: [
|
||||
{
|
||||
address: "0x401000",
|
||||
segment: ".text",
|
||||
file_offset: null,
|
||||
procedure: null,
|
||||
},
|
||||
],
|
||||
searched: {
|
||||
blocks: [
|
||||
{ segment: ".text", start: "0x401000", end: "0x40100f", bytes: 16 },
|
||||
],
|
||||
bytes: 16,
|
||||
skipped_uninitialized: [
|
||||
{ segment: ".bss", start: "0x402000", end: "0x40200f", bytes: 16 },
|
||||
],
|
||||
skipped_not_loaded: [
|
||||
{ segment: ".symtab", start: "0x0", end: "0x17f", bytes: 384 },
|
||||
],
|
||||
},
|
||||
complete: false,
|
||||
next_cursor: "continuation",
|
||||
};
|
||||
let output = jsonValueSchema.parse(page);
|
||||
const harness = await connectGhidraMcp("byte-search-projection", () =>
|
||||
Promise.resolve(ok(output)),
|
||||
);
|
||||
try {
|
||||
const first = await harness.mcp.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: { pattern: "48 ??", limit: 1 },
|
||||
});
|
||||
expect(first.isError).not.toBe(true);
|
||||
expect(
|
||||
sessionEvidence(harness.session, first.structuredContent)
|
||||
.normalized_result,
|
||||
).toEqual(page);
|
||||
output = jsonValueSchema.parse({
|
||||
...page,
|
||||
matches: [],
|
||||
complete: true,
|
||||
next_cursor: null,
|
||||
});
|
||||
const last = await harness.mcp.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: { pattern: "48 ??", cursor: "continuation" },
|
||||
});
|
||||
expect(last.isError).not.toBe(true);
|
||||
expect(
|
||||
sessionEvidence(harness.session, last.structuredContent)
|
||||
.normalized_result,
|
||||
).toEqual(output);
|
||||
output = jsonValueSchema.parse({ ...page, complete: true });
|
||||
const malformed = await harness.mcp.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: { pattern: "49 ??" },
|
||||
});
|
||||
expect(parseMcpToolError(malformed)).toMatchObject({
|
||||
error: { code: "unreadable_output" },
|
||||
});
|
||||
for (const block of [
|
||||
{ segment: ".text", start: "0x1000", end: "0x1009", bytes: 1 },
|
||||
{ segment: ".text", start: "0x1009", end: "0x1000", bytes: 1 },
|
||||
{ segment: ".text", start: "overlay:0x1000", end: "0x1000", bytes: 1 },
|
||||
{ segment: ".text", start: "invalid", end: "0x1000", bytes: 1 },
|
||||
]) {
|
||||
output = jsonValueSchema.parse({
|
||||
...page,
|
||||
searched: { ...page.searched, blocks: [block], bytes: block.bytes },
|
||||
});
|
||||
const invalidCoverage = await harness.mcp.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: { pattern: "48 ??" },
|
||||
});
|
||||
expect(parseMcpToolError(invalidCoverage)).toMatchObject({
|
||||
error: { code: "unreadable_output" },
|
||||
});
|
||||
expect(invalidCoverage.structuredContent).toBeUndefined();
|
||||
}
|
||||
const calls = harness.calls.length;
|
||||
for (const args of [{ pattern: "??" }, { pattern: "48", mask: "ffff" }]) {
|
||||
const invalid = await harness.mcp.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: args,
|
||||
});
|
||||
expect(invalid.isError).toBe(true);
|
||||
expect(JSON.stringify(invalid.content)).toContain(
|
||||
"Input validation error",
|
||||
);
|
||||
}
|
||||
expect(harness.calls).toHaveLength(calls);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("projects cancelled byte searches as typed failures without successful partial Evidence", async () => {
|
||||
const harness = await connectGhidraMcp("byte-search-cancelled", () =>
|
||||
Promise.resolve(
|
||||
err(new GhidraSessionError("cancelled", "Search cancelled")),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const reply = await harness.mcp.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: { pattern: "48 8b" },
|
||||
});
|
||||
expect(reply.isError).toBe(true);
|
||||
expect(parseMcpToolError(reply)).toMatchObject({
|
||||
error: { code: "cancelled" },
|
||||
});
|
||||
expect(reply.structuredContent).toBeUndefined();
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("searches bytes through MCP and the socket bridge with pagination and skipped coverage", async () => {
|
||||
const config = parseConfig({ GHIDRA_INSTALL_DIR: "/fixture/ghidra" });
|
||||
if (!config.ok) throw config.error;
|
||||
const provider = new GhidraProvider(
|
||||
config.value,
|
||||
silentLogger,
|
||||
{},
|
||||
ghidraInstallationHost(),
|
||||
(options) =>
|
||||
new GhidraClient({
|
||||
...options,
|
||||
platform: process.platform,
|
||||
startupTimeoutMs: 5000,
|
||||
launcher: {
|
||||
launch: async (launch) => {
|
||||
const projectRoot = join(launch.runtimeRoot, "project");
|
||||
await mkdir(projectRoot);
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
fileURLToPath(
|
||||
new URL("../../fixtures/fakeGhidra.mjs", import.meta.url),
|
||||
),
|
||||
],
|
||||
{
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
REA_GHIDRA_FIXTURE_CONFIG: JSON.stringify({
|
||||
endpointPath: launch.endpointPath,
|
||||
token: launch.token,
|
||||
runId: launch.runId,
|
||||
providerVersion: launch.providerVersion,
|
||||
profileDigest: launch.profileDigest,
|
||||
targetSha256: launch.targetSha256,
|
||||
transport: launch.transport,
|
||||
}),
|
||||
},
|
||||
},
|
||||
);
|
||||
return ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true as const,
|
||||
projectRoot,
|
||||
ghidraLogPath: join(launch.runtimeRoot, "ghidra.log"),
|
||||
scriptLogPath: join(launch.runtimeRoot, "script.log"),
|
||||
cleanup: async () => {
|
||||
const signaled =
|
||||
child.exitCode === null && child.signalCode === null;
|
||||
if (signaled) child.kill("SIGTERM");
|
||||
return (await waitForExit(child, 2000))
|
||||
? { cleaned: true as const, signaled }
|
||||
: { cleaned: false as const, reason: "Fixture did not exit" };
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const session = composeBinarySession(
|
||||
new AnalysisProviderRegistry([provider]),
|
||||
);
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ logger: silentLogger },
|
||||
);
|
||||
const client = new Client({ name: "byte-search", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: process.execPath },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const first = await client.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: { pattern: "48 8b ?? ?? 89", limit: 1 },
|
||||
});
|
||||
expect(first.isError, JSON.stringify(first)).not.toBe(true);
|
||||
const firstEvidence = sessionEvidence(session, first.structuredContent);
|
||||
expect(firstEvidence.normalized_result).toMatchObject({
|
||||
matches: [
|
||||
{
|
||||
address: "0x1000",
|
||||
segment: ".text",
|
||||
file_offset: 0,
|
||||
procedure: { name: "fixture_main" },
|
||||
},
|
||||
],
|
||||
searched: {
|
||||
bytes: 10,
|
||||
skipped_uninitialized: [{ segment: ".bss", bytes: 16 }],
|
||||
},
|
||||
complete: false,
|
||||
next_cursor: "fixture-second-page",
|
||||
});
|
||||
const second = await client.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: {
|
||||
pattern: "48 8b ?? ?? 89",
|
||||
limit: 1,
|
||||
cursor: "fixture-second-page",
|
||||
},
|
||||
});
|
||||
expect(second.isError).not.toBe(true);
|
||||
expect(
|
||||
sessionEvidence(session, second.structuredContent).normalized_result,
|
||||
).toMatchObject({
|
||||
matches: [{ address: "0x1005", file_offset: 5 }],
|
||||
complete: true,
|
||||
next_cursor: null,
|
||||
});
|
||||
const invalid = await client.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: { pattern: "??" },
|
||||
});
|
||||
expect(invalid.isError).toBe(true);
|
||||
expect(JSON.stringify(invalid.content)).toContain(
|
||||
"Pattern must constrain at least one bit",
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
const closed = await session.close();
|
||||
if (!closed.ok) throw closed.error;
|
||||
}
|
||||
});
|
||||
|
||||
it("retains missing PDB coverage in empty PE name-search Evidence and snapshot replay", async () => {
|
||||
const root = await createTestTempDirectory("rea-pdb-evidence-");
|
||||
|
||||
@@ -54,7 +54,7 @@ export const connectGhidraMcp = async (
|
||||
config.value,
|
||||
silentLogger,
|
||||
{},
|
||||
installationHost(),
|
||||
ghidraInstallationHost(),
|
||||
factory,
|
||||
);
|
||||
const session = composeBinarySession(
|
||||
@@ -100,7 +100,7 @@ export const sessionEvidence = (session: BinarySession, value: unknown) => {
|
||||
return evidence;
|
||||
};
|
||||
|
||||
const installationHost = (): GhidraInstallationHost => ({
|
||||
export const ghidraInstallationHost = (): GhidraInstallationHost => ({
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
readText: () => "application.version=12.1.4\napplication.java.min=21\n",
|
||||
|
||||
@@ -43,7 +43,23 @@ describe("official operation arguments", () => {
|
||||
const execute: AnalysisOperationPort["execute"] = (name, parameters) => {
|
||||
calls.push({ name, parameters });
|
||||
return Promise.resolve(
|
||||
observed(name === "search_strings" ? [] : "int main() {}"),
|
||||
observed(
|
||||
name === "search_bytes"
|
||||
? {
|
||||
matches: [],
|
||||
searched: {
|
||||
blocks: [],
|
||||
bytes: 0,
|
||||
skipped_uninitialized: [],
|
||||
skipped_not_loaded: [],
|
||||
},
|
||||
complete: true,
|
||||
next_cursor: null,
|
||||
}
|
||||
: name === "search_strings"
|
||||
? []
|
||||
: "int main() {}",
|
||||
),
|
||||
);
|
||||
};
|
||||
const createSession = () =>
|
||||
@@ -59,6 +75,7 @@ describe("official operation arguments", () => {
|
||||
const client = await connect({ execute });
|
||||
for (const [name, mcpParameters, cliParameters] of [
|
||||
["procedure_pseudo_code", { procedure: "main" }, { procedure: "main" }],
|
||||
["search_bytes", { pattern: "48 ??" }, { pattern: "48 ??", limit: 100 }],
|
||||
[
|
||||
"search_strings",
|
||||
{ pattern: "entry" },
|
||||
@@ -93,6 +110,11 @@ describe("official operation arguments", () => {
|
||||
["list_procedures", { document: null }],
|
||||
["procedure_pseudo_code", { procedure: "main", document: 3 }],
|
||||
["search_strings", { pattern: "entry", case_sensitive: null }],
|
||||
["search_bytes", { pattern: "??" }],
|
||||
["search_bytes", { pattern: "48 8B", mask: "ff" }],
|
||||
["search_bytes", { pattern: "4?" }],
|
||||
["search_bytes", { pattern: "48", limit: 1001 }],
|
||||
["search_bytes", { pattern: "48", cursor: null }],
|
||||
] as const) {
|
||||
const result = await client.callTool({ name, arguments: parameters });
|
||||
expect(result.isError).toBe(true);
|
||||
|
||||
@@ -10,6 +10,12 @@ import { err } from "../../../src/domain/result.js";
|
||||
import { observed as ok } from "../../fixtures/analysisExecution.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { HopperProvider } from "../../../src/hopper/HopperProvider.js";
|
||||
import { parseConfig } from "../../../src/config/parseConfig.js";
|
||||
import { silentLogger } from "../../../src/logger.js";
|
||||
import { composeBinarySession } from "../../../src/application/binary/BinarySessionComposition.js";
|
||||
import { AnalysisProviderRegistry } from "../../../src/application/binary/AnalysisProviderRegistry.js";
|
||||
import { createBinarySessionTargets } from "../../fixtures/binarySession.js";
|
||||
|
||||
interface Invocation {
|
||||
readonly name: string;
|
||||
@@ -18,6 +24,67 @@ interface Invocation {
|
||||
|
||||
const resources: Array<{ close(): Promise<void> }> = [];
|
||||
|
||||
it("returns typed Hopper byte-search unavailability without launching the provider", async () => {
|
||||
const [target] = await createBinarySessionTargets();
|
||||
const config = parseConfig({ HOPPER_LAUNCHER_PATH: process.execPath });
|
||||
if (!config.ok) throw config.error;
|
||||
const provider = new HopperProvider(config.value, silentLogger, {}, "linux");
|
||||
const session = composeBinarySession(
|
||||
new AnalysisProviderRegistry([provider]),
|
||||
);
|
||||
const server = createServer(
|
||||
{ kind: "session", session },
|
||||
{ logger: silentLogger },
|
||||
);
|
||||
const client = new Client({
|
||||
name: "hopper-byte-search-unavailable",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: target },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const result = await client.callTool({
|
||||
name: "search_bytes",
|
||||
arguments: { pattern: "48 8b" },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "capability_unavailable",
|
||||
details: { provider_id: "hopper", operation: "search_bytes" },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
const closed = await session.close();
|
||||
if (!closed.ok) throw closed.error;
|
||||
}
|
||||
});
|
||||
|
||||
it("advertises strict masked-byte arguments and bounded pages", () => {
|
||||
const contract = OFFICIAL_TOOL_CONTRACTS.find(
|
||||
({ name }) => name === "search_bytes",
|
||||
);
|
||||
expect(
|
||||
contract?.inputSchema.parse({ pattern: "48 8B ?? ?? 89" }),
|
||||
).toMatchObject({ limit: 100 });
|
||||
expect(
|
||||
contract?.inputSchema.safeParse({ pattern: "48", ignored: true }).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
contract?.inputSchema.safeParse({ pattern: "48", mask: "f0", limit: 1000 })
|
||||
.success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
describe("read_bytes contract", () => {
|
||||
it("accepts lengths above the former arbitrary ceiling and rejects zero", () => {
|
||||
const contract = OFFICIAL_TOOL_CONTRACTS.find(
|
||||
|
||||
Vendored
+37
-2
@@ -121,7 +121,7 @@ const handleRequest = (socket, server, request, state) => {
|
||||
? [stringItem("0x2000", "fixture 雪🦊")]
|
||||
: request.method === "list_strings" && state.mode === "oversized_result"
|
||||
? [stringItem("0x2000", "x".repeat(64 * 1024 * 1024 + 1))]
|
||||
: inventoryResultFor(request.method);
|
||||
: inventoryResultFor(request.method, request.params);
|
||||
if (inventory !== undefined) {
|
||||
const response = `${JSON.stringify({ id: request.id, ok: true, result: inventory })}\n`;
|
||||
if (state.mode === "fragmented") {
|
||||
@@ -228,6 +228,7 @@ const sessionInfo = ({
|
||||
"shutdown",
|
||||
"inspect_native_load_image",
|
||||
"read_bytes",
|
||||
"search_bytes",
|
||||
"address_to_file_offset",
|
||||
"address_name",
|
||||
"list_documents",
|
||||
@@ -273,8 +274,42 @@ const sessionInfo = ({
|
||||
},
|
||||
});
|
||||
|
||||
const inventoryResultFor = (method) => {
|
||||
const inventoryResultFor = (method, params) => {
|
||||
switch (method) {
|
||||
case "search_bytes": {
|
||||
const continued = params.cursor === "fixture-second-page";
|
||||
const paged = params.limit === 1 && !continued;
|
||||
const addresses = continued
|
||||
? ["0x1005"]
|
||||
: paged
|
||||
? ["0x1000"]
|
||||
: ["0x1000", "0x1005"];
|
||||
return {
|
||||
matches: addresses.map((address) => ({
|
||||
address,
|
||||
segment: ".text",
|
||||
file_offset: address === "0x1000" ? 0 : 5,
|
||||
procedure: { address: "0x1000", name: "fixture_main" },
|
||||
})),
|
||||
searched: {
|
||||
blocks: [
|
||||
{
|
||||
segment: ".text",
|
||||
start: continued ? "0x1005" : "0x1000",
|
||||
end: "0x1009",
|
||||
bytes: continued ? 5 : 10,
|
||||
},
|
||||
],
|
||||
bytes: continued ? 5 : 10,
|
||||
skipped_uninitialized: [
|
||||
{ segment: ".bss", start: "0x2000", end: "0x200f", bytes: 16 },
|
||||
],
|
||||
skipped_not_loaded: [],
|
||||
},
|
||||
complete: !paged,
|
||||
next_cursor: paged ? "fixture-second-page" : null,
|
||||
};
|
||||
}
|
||||
case "address_name":
|
||||
return "fixture_main";
|
||||
case "list_documents":
|
||||
|
||||
Reference in New Issue
Block a user