feat(ghidra): support raw NMOS 6502 analysis (#2079)

* feat(ghidra): admit raw NMOS 6502 analysis

* test(ghidra): require verified POSIX verifier cleanup

* test(ghidra): verify 6502 low-memory raw imports

* docs(skill): document raw NMOS 6502 support

* fix(ghidra): preserve requested Windows raw source paths

* docs(ghidra): include raw 6502 in Windows installation scope

* test(ghidra): verify Windows raw junction rejection through CLI and MCP

* fix(validation): make fixtures portable and preserve explicit Codex home

* fix(ghidra): attest raw mapping state and address space

* fix(ghidra): align diagnostics and regression groups

* fix(ghidra): bind raw attestation to language address space

* chore(ghidra): avoid verifier insertion conflict

* docs(ghidra): align linked raw admission guides

* fix(ghidra): retain 6502 verifier workspace on failure

* test(ghidra): isolate Windows authority doctor fixture

* fix(binary): re-admit Windows raw paths on session reopen

* test(binary): require fresh provider execution after path change

* Constrain 6502 to raw lifecycle and snapshot targets

* Bypass saved reads for unadmitted Windows paths

* Guard direct CLI snapshot replay on Windows paths

* fix(snapshot): gate Windows Ghidra replay on native admission

* fix(snapshot): constrain nested 6502 subjects to raw images

* test: make dyld slice fixtures portable
This commit is contained in:
记得吃中饭
2026-10-13 21:13:01 +08:00
committed by GitHub
parent 352c46aa75
commit 9c14999efd
54 changed files with 1650 additions and 197 deletions
+10 -6
View File
@@ -180,14 +180,17 @@ describe("trace-dylib-resolution CLI", () => {
// A root below a symlinked directory that points outside the bundle.
const outside = await createTestTempDirectory("rea-dylib-outside-");
await writeFiles(outside, { Tool: machoImage({}) });
await symlink(outside, join(app, "Contents/Linked"));
await symlink(outside, join(app, "Contents/Linked"), "dir");
for (const [root, reason, message] of [
["../outside", "invalid_format", "Use a normalized path"],
["Contents/Info.plist", "invalid_value", "is not a Mach-O image"],
[
"Contents/Linked/Tool",
"invalid_value",
"resolves outside the analyzed root",
// Windows link text is outside the POSIX dyld path representation.
process.platform === "win32"
? "is not a regular file in the analyzed root"
: "resolves outside the analyzed root",
],
] as const) {
await expectRootInputError(cli, { app, root, reason, message });
@@ -378,7 +381,8 @@ cliTest(
},
);
describe.skipIf(process.getuid?.() === 0)(
// This permission fixture requires POSIX mode bits and a non-root caller.
describe.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"trace-dylib-resolution permissions",
() => {
cliTest(
@@ -510,6 +514,8 @@ cliTest(
app,
"--root",
"Contents/MacOS/App",
"--architecture",
"arm64e",
"--json",
],
environment: ENVIRONMENT,
@@ -518,9 +524,7 @@ cliTest(
const trace = dylibResolutionResultSchema.parse(
parseEvidence(result.json).normalized_result,
);
expect(
trace.roots.filter(({ architecture }) => architecture === "arm64e"),
).toHaveLength(2);
expect(trace.roots).toHaveLength(2);
const environments = trace.findings
.filter(({ kind }) => kind === "dyld-environment-present")
.map(({ explanation }) =>
+30
View File
@@ -38,6 +38,36 @@ cliTest(
},
);
cliTest(
"rejects a 6502 image crossing the 16-bit boundary before provider startup",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-6502-cli-overflow-");
const path = join(root, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
const result = await cli.run({
arguments: [
"inspect",
path,
"--target-format",
"raw-binary",
"--architecture",
"6502",
"--entry-point",
"0xffff",
"--provider",
"ghidra",
"--json",
],
environment: { HOME: root, XDG_CONFIG_HOME: root, XDG_CACHE_HOME: root },
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { reason: expect.stringContaining("6502 address width") },
});
},
);
cliTest(
"rejects an unaligned AArch64 entry before provider startup",
async ({ cli }) => {
@@ -1,5 +1,5 @@
import { parseConfig } from "../../../src/config/parseConfig.js";
import { writeFile } from "node:fs/promises";
import { symlink, writeFile } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { describe, expect, it, vi } from "vitest";
@@ -14,7 +14,7 @@ import type {
import type { DirectAnalysisDependencies } from "../../../src/application/DirectAnalysisDependencies.js";
import { createAnalysisProfile } from "../../../src/domain/analysisProfile.js";
import { createAnalysisExecution } from "../../../src/application/AnalysisProvider.js";
import { ok } from "../../../src/domain/result.js";
import { err, ok } from "../../../src/domain/result.js";
import {
readAnalysisSnapshot,
writeAnalysisSnapshot,
@@ -40,6 +40,7 @@ import {
} from "../../fixtures/binarySession.js";
import { BinarySession } from "../../../src/application/binary/BinarySession.js";
import { OwnedStagedOutput } from "../../../src/filesystem/OwnedStagedOutput.js";
import { ProviderAdapterError } from "../../../src/domain/providerAdapterError.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import {
CAPABILITIES as GHIDRA_CAPABILITIES,
@@ -396,7 +397,85 @@ describe("snapshot output cleanup lifecycle", () => {
});
});
const verifyWindowsSnapshotAdmission = async (
selectedPath: "direct" | "junction",
): Promise<void> => {
const fixture = await createSnapshotReplayFixture(
"rea-direct-snapshot-junction-",
);
const rawPath = join(dirname(fixture.path), "image.bin");
await writeFile(rawPath, Buffer.from("a92a60", "hex"));
const linked = join(dirname(fixture.path), "linked");
const linkedPath = join(linked, basename(rawPath));
const identity = { ...GHIDRA_PROVIDER_IDENTITY, version: "12.1.4" };
const profile = createAnalysisProfile(identity, {
fixture: true,
});
const baseProvider = fixture.createProvider({
identity,
profile,
supportedOperations: ["search_strings"],
});
let rejectAdmission = false;
const provider: AnalysisProvider = {
...baseProvider,
createClient: (target, profile, context) => {
const client = baseProvider.createClient(target, profile, context);
return {
...client,
execute: (operation, parameters, options) =>
rejectAdmission && operation === "search_strings"
? Promise.resolve(
err(new ProviderAdapterError("ghidra", operation)),
)
: client.execute(operation, parameters, options),
};
},
};
const dependencies = fixture.dependencies(provider);
const arguments_ = { pattern: "fixture", document: "fixture" };
const options = {
snapshotPath: fixture.snapshotPath,
formatHint: "raw-binary" as const,
architecture: "6502" as const,
entryPoint: "0x8001",
};
const first = await runDirectAnalysis(
dependencies,
rawPath,
"search_strings",
arguments_,
options,
);
expect(first).toMatchObject({ operation: "search_strings" });
expect(fixture.starts).toHaveLength(1);
if (selectedPath === "junction")
await symlink(dirname(fixture.path), linked, "junction");
rejectAdmission = true;
const second = await runDirectAnalysis(
dependencies,
selectedPath === "junction" ? linkedPath : rawPath,
"search_strings",
arguments_,
options,
);
expect(second).toMatchObject({ error: "Analysis failed" });
expect(fixture.starts).toHaveLength(2);
expect(
fixture.calls.filter((call) => call === "search_strings"),
).toHaveLength(1);
};
describe("direct analysis composed snapshot replay", () => {
it.skipIf(process.platform !== "win32")(
"does not replay a CLI snapshot through a Windows junction",
() => verifyWindowsSnapshotAdmission("junction"),
);
it.skipIf(process.platform !== "win32")(
"does not replay a CLI snapshot before native admission on a canonical path",
() => verifyWindowsSnapshotAdmission("direct"),
);
it.each([
{
tool: "search_strings",
@@ -516,7 +595,7 @@ describe("Ghidra composed workflow snapshot replay", () => {
{ tool: "inspect_native_api", arguments: { procedure: "0x1000" } },
{ tool: "trace_feature", arguments: { query: "fixture" } },
] as const)(
"persists and replays $tool with production Ghidra capability policies",
"persists $tool with production Ghidra capability policies",
async ({ tool, arguments: parameters }) => {
const fixture = await createSnapshotReplayFixture("rea-ghidra-workflow-");
const profile = createAnalysisProfile(
@@ -554,8 +633,14 @@ describe("Ghidra composed workflow snapshot replay", () => {
{ snapshotPath: fixture.snapshotPath },
);
expect(replay).toEqual(first);
expect(fixture.starts).toHaveLength(1);
expect(fixture.calls).toEqual(initialCalls);
if (process.platform === "win32") {
// The first provider call in a new CLI session admits its source.
expect(fixture.starts).toHaveLength(2);
expect(fixture.calls.length).toBeGreaterThan(initialCalls.length);
} else {
expect(fixture.starts).toHaveLength(1);
expect(fixture.calls).toEqual(initialCalls);
}
},
);
});
@@ -388,7 +388,7 @@ it("produces deterministic ASAR graphs with unpacked native linkage and complete
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await createPackageWithOptions(source, archive, { unpack: "*.node" });
const first = await reconstructJavaScriptArtifact({
input_path: archive,
@@ -487,7 +487,7 @@ it("keeps ASAR analysis usable when unpacked native companion bytes are absent",
await mkdir(source);
await writeJavaScriptArtifactFixture(source);
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await createPackageWithOptions(source, archive, { unpack: "*.node" });
await rm(join(`${archive}.unpacked`, "native", "addon.node"));
const snapshot = await scanArtifactInventory(archive);
@@ -515,7 +515,7 @@ it("recurses into filesystem-backed ASAR containers without losing container-rel
const resources = join(outer, "resources");
await mkdir(resources, { recursive: true });
await createPackageWithOptions(source, join(resources, "app.asar"), {
unpack: "**/*.node",
unpack: "*.node",
});
const result = await reconstructJavaScriptArtifact({
@@ -1,5 +1,11 @@
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import {
mkdir,
readFile,
realpath,
symlink,
writeFile,
} from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -7,6 +13,37 @@ import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("raw-binary admission", () => {
it("preserves the requested raw path for Windows reparse admission", async () => {
const directory = await createTestTempDirectory("rea-raw-linked-");
const actual = join(directory, "actual");
const linked = join(directory, "linked");
await mkdir(actual);
const bytes = Buffer.from("a90160", "hex");
await writeFile(join(actual, "fixture.bin"), bytes);
await symlink(
actual,
linked,
process.platform === "win32" ? "junction" : "dir",
);
const requested = join(linked, "fixture.bin");
const canonical = await realpath(requested);
const target = await parseBinaryTarget("linked/fixture.bin", {
cwd: directory,
formatHint: "raw-binary",
architecture: "6502",
entryPoint: "0x8000",
});
expect(target).toMatchObject({
ok: true,
value: {
path: canonical,
sourcePath: process.platform === "win32" ? requested : canonical,
sha256: createHash("sha256").update(bytes).digest("hex"),
format: "raw-binary",
architecture: "6502",
},
});
});
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");
+208 -23
View File
@@ -1,4 +1,4 @@
import { writeFile } from "node:fs/promises";
import { mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -10,7 +10,8 @@ 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 { ProviderAdapterError } from "../../../src/domain/providerAdapterError.js";
import { err, ok } from "../../../src/domain/result.js";
import { observed } from "../../fixtures/analysisExecution.js";
import {
createCacheProvider,
@@ -18,6 +19,7 @@ import {
} from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { silentLogger } from "../../../src/logger.js";
import { GHIDRA_PROVIDER_IDENTITY } from "../../../src/ghidra/GhidraProviderCapabilities.js";
import type { CallToolResult } from "@modelcontextprotocol/server";
const connect = async (
@@ -50,29 +52,97 @@ const structured = (result: CallToolResult): Record<string, unknown> => {
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: {
const withGhidraFixtureIdentity = (
provider: AnalysisProvider,
): AnalysisProvider => {
const identity = { ...GHIDRA_PROVIDER_IDENTITY, version: "12.1.4" };
const profile = createAnalysisProfile(identity, { fixture: true });
return {
...provider,
identity: () => identity,
capabilities: () =>
provider.capabilities().map((capability) => ({
...capability,
provider: identity,
})),
resolveAnalysisProfile: () => Promise.resolve(ok({ profile })),
createClient: (target, _profile, context) => {
const client = provider.createClient(target, profile, context);
return {
...client,
execute: async (operation, parameters, options) => {
const result = await client.execute(operation, parameters, options);
return result.ok
? ok({
...result.value,
provider: identity,
analysisProfile: profile,
})
: result;
},
};
},
};
};
it("keeps 6502 out of detected lifecycle output contracts", () => {
const schema = toolContract("open_binary").outputSchema;
const result = {
path: "/fixture/image.bin",
kind: "executable",
sha256: "a".repeat(64),
architecture: "6502",
};
expect(
schema.safeParse({ result: { ...result, format: "pe" } }).success,
).toBe(false);
expect(
schema.safeParse({
result: { ...result, format: "raw-binary", entry_point: "0x8001" },
}).success,
).toBe(true);
const validateAdvertised = new Ajv2020({ strict: false }).compile(
z.toJSONSchema(schema),
);
expect(validateAdvertised({ result: { ...result, format: "pe" } })).toBe(
false,
);
expect(
validateAdvertised({
result: { ...result, format: "raw-binary", entry_point: "0x8001" },
}),
).toBe(true);
});
it.each([
["arm", "0x08000000", "0x8000000", "1eff2fe1"],
["6502", "0x008001", "0x8001", "a92a60"],
])(
"opens a headerless %s image when architecture and entry are supplied",
async (architecture, entryPoint, canonical, bytes) => {
const root = await createTestTempDirectory("rea-raw-mcp-");
const path = join(root, "ecu.bin");
await writeFile(path, Buffer.from(bytes, "hex"));
const { client } = await connect();
const opened = await client.callTool({
name: "open_binary",
arguments: {
path,
format: "raw-binary",
architecture,
entry_point: entryPoint,
},
});
expect(opened.isError).not.toBe(true);
expect(structured(opened).result).toMatchObject({
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",
});
});
kind: "executable",
architecture,
entry_point: canonical,
});
},
);
it("rejects an unaligned AArch64 entry before selecting or starting a provider", async () => {
const root = await createTestTempDirectory("rea-raw-mcp-alignment-");
@@ -217,3 +287,118 @@ it("reuses a canonical raw entry and replaces the session when the entry changes
expect(created).toEqual(["0x8000000", "0x9000000"]);
expect(closed).toEqual(["0x8000000"]);
});
it.skipIf(process.platform !== "win32")(
"does not replay a saved read after switching to a Windows junction",
async () => {
const root = await createTestTempDirectory("rea-raw-mcp-linked-reopen-");
const actual = join(root, "actual");
const linked = join(root, "linked");
await mkdir(actual);
const path = join(actual, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
await symlink(actual, linked, "junction");
const created: string[] = [];
const executed: string[] = [];
const fixture = createCacheProvider([]);
const { client } = await connect(
withGhidraFixtureIdentity({
...fixture,
createClient: (target) => {
created.push(target.sourcePath ?? target.path);
return {
execute: (operation) => {
if (operation === "address_name")
executed.push(target.sourcePath ?? target.path);
if (
operation === "address_name" &&
target.sourcePath === join(linked, "image.bin")
)
return Promise.resolve(
err(new ProviderAdapterError("fixture", operation)),
);
return Promise.resolve(
observed(operation === "address_name" ? "entry" : null),
);
},
close: () => Promise.resolve(ok(null)),
};
},
}),
);
const linkedPath = join(linked, "image.bin");
for (const requested of [path, linkedPath]) {
const opened = await client.callTool({
name: "open_binary",
arguments: {
path: requested,
format: "raw-binary",
architecture: "6502",
entry_point: "0x8001",
},
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
const address = await client.callTool({
name: "address_name",
arguments: { address: "0x8001", document: "image.bin" },
});
expect(address.isError === true, JSON.stringify(address)).toBe(
requested === linkedPath,
);
}
expect(created).toEqual([path, linkedPath]);
expect(executed).toEqual([path, linkedPath]);
},
);
it.skipIf(process.platform !== "win32")(
"reuses saved reads after a fixture admits a noncanonical Windows path",
async () => {
const root = await createTestTempDirectory("rea-raw-mcp-admitted-path-");
const actual = join(root, "actual");
const linked = join(root, "linked");
await mkdir(actual);
const path = join(actual, "image.bin");
await writeFile(path, Buffer.from("a92a60", "hex"));
await symlink(actual, linked, "junction");
const calls: string[] = [];
const fixture = createCacheProvider([]);
// This fixture accepts the alias to isolate cache behavior after admission.
// The real Ghidra verifier checks that a junction itself is rejected.
const { client, session } = await connect(
withGhidraFixtureIdentity({
...fixture,
createClient: () => ({
execute: (operation) => {
if (operation === "address_name") calls.push(operation);
return Promise.resolve(
observed(operation === "health" ? null : "entry"),
);
},
close: () => Promise.resolve(ok(null)),
}),
}),
);
const linkedPath = join(linked, "image.bin");
const opened = await client.callTool({
name: "open_binary",
arguments: {
path: linkedPath,
format: "raw-binary",
architecture: "6502",
entry_point: "0x8001",
},
});
expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
expect(session.activeTarget()?.sourcePath).toBe(linkedPath);
expect(session.activeTarget()?.path).toBe(path);
for (const _ of [0, 1]) {
const address = await client.callTool({
name: "address_name",
arguments: { address: "0x8001", document: "image.bin" },
});
expect(address.isError, JSON.stringify(address)).not.toBe(true);
}
expect(calls).toEqual(["address_name"]);
},
);
@@ -135,7 +135,7 @@ it("ignores unavailable members of a nested ASAR but refuses them as active entr
const source = join(root, "bundle");
await mkdir(source);
const archive = join(source, "app.asar");
await createPackageWithOptions(contents, archive, { unpack: "**/*.node" });
await createPackageWithOptions(contents, archive, { unpack: "*.node" });
await rm(join(`${archive}.unpacked`, "native", "addon.node"));
const nestedOutput = join(root, "nested-output");
+9
View File
@@ -0,0 +1,9 @@
FEATURES {
STARTADDRESS: default = $8001;
}
MEMORY {
IMAGE: start = %S, size = $10000 - %S, file = %O;
}
SEGMENTS {
CODE: load = IMAGE, type = ro;
}
+19
View File
@@ -0,0 +1,19 @@
; Source-owned NMOS 6502 fixture: direct call, conditional branch, and arithmetic.
.setcpu "6502"
.segment "CODE"
.export entry, add_three
entry:
lda #7
jsr add_three
cmp #10
bne mismatch
lda #42
rts
mismatch:
lda #0
rts
add_three:
clc
adc #3
rts
@@ -35,6 +35,20 @@ const shellExamples = (content: string): string[] =>
);
describe("onboarding documentation product facts", () => {
it.each([
["docs/native-investigation.md", "raw-binary.md#nmos-6502"],
["docs/ghidra-riscv.md", "raw-binary.md"],
])(
"routes raw admission guidance in %s to the owning guide",
async (path, target) => {
const content = await readFile(resolve(path), "utf8");
const links = [...content.matchAll(/\]\(([^)\s]+)\)/gu)].map(
(match) => match[1],
);
expect(links, path).toContain(target);
},
);
it("keeps the installation MCP example aligned with the package registration command", async () => {
const content = await readFile(resolve("docs/installation.md"), "utf8");
expect(jsonExamples(content)).toContainEqual(
+1 -1
View File
@@ -29,7 +29,7 @@ export const createStrippedAsarAddon = async (
await mkdir(dirname(path), { recursive: true });
await writeFile(path, file.contents);
}
await createPackageWithOptions(source, archive, { unpack: "**/*.node" });
await createPackageWithOptions(source, archive, { unpack: "*.node" });
await writeFile(
join(`${archive}.unpacked`, "node_modules", "btime", "binding.node"),
stripped,