* feat(native): admit bounded MIPS ELF analysis through Ghidra Retain MIPS ELF identity and interpretation through Evidence and snapshots. Keep provider admission bounded to ELF32 ET_EXEC o32 MIPS32r2, without implicitly widening Hopper, IDA or Windows P0 coverage. Add source-owned fixtures and an optional real-provider verifier; real Ghidra verification remains pending in this contribution environment. Refs #718 * fix(ghidra): bound MIPS floating-point mode admission Reject explicit EF_MIPS_FP64 and EF_MIPS_NAN2008 declarations until their semantics have a real-provider verification lane. Add PSP PRX/Allegrex, o64/EABI and floating-point-mode refusal regressions. Document that the header gate is not a full .MIPS.abiflags check and advance the profile lane identity to invalidate older interpretation bindings. Validation: 24 standalone checks against the transpiled production profile module passed; the two new flag cases failed before this change. Clang 17 and LLD compiled the source-owned fixture for both endian targets. The complete Vitest/typecheck suite and real Ghidra verification remain pending. Refs morluto/rea#718; PSP support remains follow-up morluto/rea#1330. * fix(native): validate MIPS ABI records before Ghidra admission Read bounded ELF32 PT_MIPS_ABIFLAGS and SHT_MIPS_ABIFLAGS records through the already-open target handle. Preserve declared ABI fields, reject conflicting/duplicate/truncated records, and keep missing records unknown. Wire inspection into target resolution before provider selection. Require compatible declarations for the deliberately narrow Ghidra lane and bind all ABI fields into profile identity (v3) for snapshot invalidation. Clang 17 produced eight source-owned fixtures spanning both byte orders and FPXX/FP32/FP64/soft-float modes with identical ELF header flags. The new reader and policy distinguish them. 24 focused regression test bodies passed after TypeScript transpilation using node:test in place of Vitest; strict isolated TypeScript checking of the reader and target/result types passed. These are limited checks, not full Vitest/project typechecking or real-Ghidra verification, which remain pending. Advances morluto/rea#718. PSP/Allegrex remains morluto/rea#1330 follow-up. * fix(native): repair MIPS integration boundaries and test resolver behavior Keep ELF targets out of Hopper Mach-O preparation and scope existing PE fixture types correctly. Move ABI tests into the filesystem boundary lane, use shared cleanup, add resolver regressions, apply the pinned formatter, and register the real MIPS verifier through the existing package-command pattern. Validated with repository-pinned Node/npm, check:ci, actual focused Vitest, discovery and docs:check. Real Ghidra conformance remains pending. * fix(test): honor caller-selected JDK in real MIPS verification * test(native): strengthen MIPS Ghidra conformance Cross-check the source-owned fixture with bounded GNU readelf inspection, compare production ELF/ABI interpretation and independent symbol addresses, and verify effective Ghidra language/compiler identity through existing public operations. Add a source-owned fixed-encoding probe for immediate and conditional branch checks plus global/string byte assertions. Add 16 assertion/producer-boundary regression cases without widening production admission, changing provider contracts, or introducing proprietary dependencies. Local focused suite: 99 passed, one existing root-permission test skipped. Typecheck, lint/module boundaries, formatting and 700-file discovery pass; full hosted checks and real Ghidra verification remain pending for this checkpoint. * fix(ghidra): preserve native-tool architecture checks after MIPS integration The conflict-free upstream merge failed TypeScript compilation because includes on the union of MIPS-only and other architecture arrays requires never. Use equality-based membership without casts or changing accepted native hosts. Extend the existing native-decompiler rejection table with a MIPS executable at a Linux x64 tool path; retain upstream FAT and unknown-header behavior. Hosted verification follows this commit; no success is claimed yet. --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
988 lines
32 KiB
TypeScript
988 lines
32 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { execFile } from "node:child_process";
|
|
// Fake-backed provider coverage; real Ghidra verification lives in
|
|
// `npm run verify:ghidra` and its focused variants.
|
|
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { promisify } from "node:util";
|
|
import { describe, expect, it } from "vitest";
|
|
import { fixtureDosLoadImage } from "./GhidraLoadImage.fixture.js";
|
|
import { jsonValueSchema } from "../domain/jsonValue.js";
|
|
|
|
import { parseConfig } from "../config/parseConfig.js";
|
|
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
|
import { parseExecutableHeader } from "../domain/binaryTarget.js";
|
|
import { GhidraProvider } from "./GhidraProvider.js";
|
|
import type { GhidraProviderClientFactory } from "./GhidraProviderClient.js";
|
|
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
|
|
import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js";
|
|
import { err, ok } from "../domain/result.js";
|
|
import { GhidraSessionError } from "./GhidraSessionError.js";
|
|
import { silentLogger } from "../logger.js";
|
|
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
|
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
|
import { ProviderStartupDeadline } from "../process/ProviderDeadline.js";
|
|
|
|
const INSTALL = "/opt/ghidra_12.1.4_PUBLIC";
|
|
const installationHost = (): GhidraInstallationHost => ({
|
|
platform: "linux",
|
|
architecture: "x64",
|
|
readText: () => "application.version=12.1.4\n",
|
|
executable: () => true,
|
|
probeJava: () => ({
|
|
version: "21.0.11",
|
|
major: 21,
|
|
home: "/usr/lib/jvm/jdk-21",
|
|
bits: 64,
|
|
runtime: "jdk",
|
|
}),
|
|
});
|
|
|
|
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,
|
|
clientFactory,
|
|
);
|
|
};
|
|
|
|
describe("Ghidra provider", () => {
|
|
it("commits DOS loader and real-mode language while retaining the CPU family", async () => {
|
|
const ghidra = provider();
|
|
const target: BinaryTarget = {
|
|
path: "/tmp/legacy.exe",
|
|
sha256: "a".repeat(64),
|
|
kind: "executable",
|
|
format: "dos-mz",
|
|
architecture: "x86",
|
|
availableArchitectures: ["x86"],
|
|
};
|
|
expect(ghidra.inspectTargetSupport(target).status).toBe("supported");
|
|
const resolved = await ghidra.resolveAnalysisProfile(target);
|
|
expect(resolved.ok && resolved.value).toMatchObject({
|
|
profile: {
|
|
parameters: {
|
|
target_format: "dos-mz",
|
|
architecture: "x86",
|
|
loader: "MzLoader",
|
|
language_id: "x86:LE:16:Real Mode",
|
|
compiler_spec_id: "default",
|
|
load_segment: "0x1000",
|
|
address_coordinates: "linear-byte-offset",
|
|
},
|
|
},
|
|
});
|
|
const windows = provider({ ...installationHost(), platform: "win32" });
|
|
expect(windows.inspectTargetSupport(target).status).toBe("unsupported");
|
|
});
|
|
it("discovers the exact installation once without launching Ghidra", () => {
|
|
let probeCount = 0;
|
|
const host: GhidraInstallationHost = {
|
|
...installationHost(),
|
|
probeJava: () => {
|
|
probeCount += 1;
|
|
return {
|
|
version: "21.0.11",
|
|
major: 21,
|
|
home: "/usr/lib/jvm/jdk-21",
|
|
bits: 64,
|
|
runtime: "jdk",
|
|
};
|
|
},
|
|
};
|
|
const ghidra = provider(host);
|
|
|
|
expect(ghidra.capabilities()).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({
|
|
operation: "list_procedures",
|
|
effects: expect.objectContaining({
|
|
mutatesArtifact: false,
|
|
mayShowUi: false,
|
|
mayWriteFilesystem: true,
|
|
}),
|
|
}),
|
|
expect.objectContaining({
|
|
operation: "analyze_function",
|
|
limitations: expect.arrayContaining([
|
|
expect.stringContaining(
|
|
"unresolved targetless flows remain unknown",
|
|
),
|
|
]),
|
|
}),
|
|
]),
|
|
);
|
|
expect(ghidra.inspectAvailability()).toMatchObject({
|
|
status: "available",
|
|
diagnostics: {
|
|
install_dir: INSTALL,
|
|
provider_version: "12.1.4",
|
|
java_version: "21.0.11",
|
|
},
|
|
});
|
|
expect(ghidra.inspectAvailability()).toMatchObject({ status: "available" });
|
|
expect(probeCount).toBe(1);
|
|
});
|
|
|
|
it("separates target kind, format, and concrete architecture", () => {
|
|
const ghidra = provider();
|
|
expect(
|
|
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
|
|
).toMatchObject({
|
|
status: "supported",
|
|
});
|
|
expect(
|
|
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
|
|
).toMatchObject({
|
|
status: "supported",
|
|
});
|
|
expect(
|
|
ghidra.inspectTargetSupport({
|
|
path: "/tmp/fixture.asar",
|
|
sha256: "a".repeat(64),
|
|
kind: "archive",
|
|
format: "asar",
|
|
}),
|
|
).toMatchObject({
|
|
status: "unsupported",
|
|
code: "target_kind_unsupported",
|
|
});
|
|
expect(
|
|
ghidra.inspectTargetSupport({
|
|
path: "/tmp/fixture.js",
|
|
sha256: "a".repeat(64),
|
|
kind: "artifact",
|
|
format: "javascript",
|
|
}),
|
|
).toMatchObject({
|
|
status: "unsupported",
|
|
code: "target_kind_unsupported",
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("Ghidra Mach-O slice support", () => {
|
|
it("refuses universal targets whose selected slice cannot be enforced", () => {
|
|
const ghidra = provider();
|
|
const universal: BinaryTarget = {
|
|
path: "/tmp/fixture",
|
|
sha256: "a".repeat(64),
|
|
kind: "executable",
|
|
format: "mach-o",
|
|
architecture: "arm64",
|
|
availableArchitectures: ["x86_64", "arm64"],
|
|
};
|
|
|
|
expect(ghidra.inspectTargetSupport(universal)).toMatchObject({
|
|
status: "unsupported",
|
|
code: "architecture_unsupported",
|
|
reason: expect.stringContaining("universal Mach-O"),
|
|
diagnostics: {
|
|
architecture: "arm64",
|
|
available_architectures: ["x86_64", "arm64"],
|
|
},
|
|
});
|
|
expect(
|
|
ghidra.inspectTargetSupport(executableTarget("mach-o", "arm64")),
|
|
).toMatchObject({ status: "supported" });
|
|
});
|
|
});
|
|
|
|
describe("Ghidra platform support", () => {
|
|
it("commits the PE role and managed classification to profile identity", async () => {
|
|
const ghidra = provider({ ...installationHost(), platform: "win32" });
|
|
const application = peTarget("x86_64");
|
|
const library = {
|
|
...application,
|
|
executableRole: "shared-library",
|
|
} as const;
|
|
const digests = new Set<string>();
|
|
for (const target of [
|
|
application,
|
|
library,
|
|
{ ...library, managed: true },
|
|
]) {
|
|
const resolved = await ghidra.resolveAnalysisProfile(target);
|
|
if (!resolved.ok) throw resolved.error;
|
|
const profile = resolved.value.profile;
|
|
if (profile === null) throw new Error("Expected a PE analysis profile");
|
|
expect(profile.parameters).toMatchObject({
|
|
executable_role: target.executableRole,
|
|
managed: target.managed,
|
|
});
|
|
digests.add(profile.digest);
|
|
}
|
|
expect(digests.size).toBe(3);
|
|
});
|
|
|
|
it("keeps Windows annotation mutation unavailable independently of native controls", () => {
|
|
const ghidra = provider({ ...installationHost(), platform: "win32" });
|
|
expect(
|
|
ghidra
|
|
.capabilities()
|
|
.find(({ operation }) => operation === "annotate_native_function"),
|
|
).toMatchObject({
|
|
available: false,
|
|
reason: "Windows Ghidra P0 does not admit database mutation.",
|
|
availabilityCode: "unsupported_host",
|
|
});
|
|
});
|
|
|
|
it("keeps Windows P0 unavailable until native isolation authority exists", () => {
|
|
const ghidra = provider({ ...installationHost(), platform: "win32" });
|
|
const nativeApplication = peTarget("x86_64");
|
|
|
|
for (const architecture of ["x86", "x86_64"] as const)
|
|
expect(ghidra.inspectTargetSupport(peTarget(architecture))).toMatchObject(
|
|
{
|
|
status: "supported",
|
|
diagnostics: {
|
|
host_platform: "win32",
|
|
architecture,
|
|
executable_role: "application",
|
|
managed: false,
|
|
},
|
|
},
|
|
);
|
|
expect(ghidra.inspectAvailability()).toMatchObject({
|
|
status: "unavailable",
|
|
code: "unsupported_host",
|
|
reason: expect.stringContaining(
|
|
"Windows native controls are unavailable",
|
|
),
|
|
diagnostics: {
|
|
windows_security: {
|
|
job_object_process_ownership: expect.objectContaining({
|
|
available: false,
|
|
proof: "not-proven",
|
|
}),
|
|
private_runtime_dacl: expect.objectContaining({
|
|
available: false,
|
|
proof: "not-proven",
|
|
}),
|
|
reparse_safe_path_admission: expect.objectContaining({
|
|
available: false,
|
|
proof: "not-proven",
|
|
}),
|
|
},
|
|
},
|
|
});
|
|
expect(ghidra.capabilities()).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({
|
|
operation: "list_procedures",
|
|
available: false,
|
|
availabilityCode: "unsupported_host",
|
|
limitations: expect.arrayContaining([
|
|
expect.stringContaining(
|
|
"matching packaged Windows x64 native addon",
|
|
),
|
|
expect.stringContaining(
|
|
"private DACLs, and Job Object ownership automatically",
|
|
),
|
|
]),
|
|
}),
|
|
]),
|
|
);
|
|
expect(
|
|
ghidra.inspectTargetSupport({
|
|
...nativeApplication,
|
|
executableRole: "non-executable",
|
|
}),
|
|
).toMatchObject({
|
|
status: "unsupported",
|
|
code: "target_role_unsupported",
|
|
});
|
|
expect(
|
|
ghidra.inspectTargetSupport({ ...nativeApplication, managed: true }),
|
|
).toMatchObject({
|
|
status: "unsupported",
|
|
code: "managed_target_unsupported",
|
|
});
|
|
expect(
|
|
ghidra.inspectTargetSupport(executableTarget("elf", "x86_64")),
|
|
).toMatchObject({
|
|
status: "unsupported",
|
|
code: "target_format_unsupported",
|
|
});
|
|
expect(
|
|
ghidra.inspectTargetSupport(executableTarget("pe", "arm64")),
|
|
).toMatchObject({
|
|
status: "unsupported",
|
|
code: "architecture_unsupported",
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("Ghidra Windows PE fixture admission", () => {
|
|
it("admits generated PE32 and PE32+ DLLs and applications while preserving native-only Windows admission", async () => {
|
|
const root = fileURLToPath(new URL("../../", import.meta.url));
|
|
await promisify(execFile)(process.execPath, [
|
|
join(root, "scripts/create-ghidra-windows-fixture.mjs"),
|
|
]);
|
|
const ghidra = provider({ ...installationHost(), platform: "win32" });
|
|
for (const architecture of ["x86", "x86_64"] as const) {
|
|
for (const dll of [false, true]) {
|
|
const path = join(
|
|
root,
|
|
"build/fixtures",
|
|
`rea-ghidra-windows${architecture === "x86" ? "-x86" : ""}.${dll ? "dll" : "exe"}`,
|
|
);
|
|
const bytes = await readFile(path);
|
|
const metadata = parseExecutableHeader(bytes, "x64");
|
|
const role = dll ? "shared-library" : "application";
|
|
expect(metadata).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
format: "pe",
|
|
architecture,
|
|
executableRole: role,
|
|
managed: false,
|
|
},
|
|
});
|
|
if (!metadata.ok) throw new Error(metadata.error);
|
|
if (metadata.value.format !== "pe")
|
|
throw new Error("Expected a PE fixture");
|
|
const target: BinaryTarget = {
|
|
path,
|
|
sha256: createHash("sha256").update(bytes).digest("hex"),
|
|
kind: "executable",
|
|
...metadata.value,
|
|
};
|
|
expect(ghidra.inspectTargetSupport(target).status).toBe("supported");
|
|
for (const [candidate, code] of [
|
|
[
|
|
{ ...target, executableRole: "non-executable" },
|
|
"target_role_unsupported",
|
|
],
|
|
[{ ...target, managed: true }, "managed_target_unsupported"],
|
|
[{ ...target, architecture: "arm64" }, "architecture_unsupported"],
|
|
] as const) {
|
|
expect(ghidra.inspectTargetSupport(candidate)).toMatchObject({
|
|
status: "unsupported",
|
|
code,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("Ghidra startup configuration", () => {
|
|
it("carries supplied startup settings through configuration, the provider, the timer and timeout diagnostics", async () => {
|
|
const target = executableTarget("elf", "x86_64");
|
|
for (const [raw, expected] of [
|
|
[undefined, 330_000],
|
|
["900000", 900_000],
|
|
["1260000", 1_260_000],
|
|
["2147483647", 2_147_483_647],
|
|
] as const) {
|
|
const config = parseConfig({
|
|
GHIDRA_INSTALL_DIR: INSTALL,
|
|
...(raw === undefined ? {} : { REA_GHIDRA_STARTUP_TIMEOUT_MS: raw }),
|
|
});
|
|
if (!config.ok) throw config.error;
|
|
let timeout: number | undefined;
|
|
const ghidra = new GhidraProvider(
|
|
config.value,
|
|
silentLogger,
|
|
{},
|
|
installationHost(),
|
|
(options) => {
|
|
timeout = options.startupTimeoutMs;
|
|
return {
|
|
start: () =>
|
|
Promise.resolve(
|
|
err(
|
|
new GhidraSessionError(
|
|
"timeout",
|
|
"Startup deadline elapsed",
|
|
{},
|
|
),
|
|
),
|
|
),
|
|
callTool: () => Promise.resolve(ok([])),
|
|
close: () => Promise.resolve(ok(null)),
|
|
};
|
|
},
|
|
);
|
|
const profile = await ghidra.resolveAnalysisProfile(target);
|
|
if (!profile.ok) throw profile.error;
|
|
if (profile.value.profile === null)
|
|
throw new Error("Expected a bound profile");
|
|
const client = ghidra.createClient(target, profile.value.profile);
|
|
try {
|
|
const failure = await client.execute("health", {});
|
|
expect(timeout, String(raw)).toBe(expected);
|
|
expect(failure).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisTimeoutError", timeoutMs: expected },
|
|
});
|
|
if (timeout === undefined)
|
|
throw new Error("Provider omitted startup deadline");
|
|
const deadline = new ProviderStartupDeadline(timeout);
|
|
try {
|
|
expect(await deadline.wait(20)).toBe("elapsed");
|
|
expect(deadline.signal.aborted).toBe(false);
|
|
} finally {
|
|
deadline.dispose();
|
|
}
|
|
} finally {
|
|
await client.close();
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("Ghidra client projection", () => {
|
|
it("commits exact provider, isolation, and resource semantics", async () => {
|
|
const toolCalls: Array<{
|
|
readonly operation: string;
|
|
readonly input: unknown;
|
|
readonly options: unknown;
|
|
}> = [];
|
|
let startCount = 0;
|
|
const factoryOptions: unknown[] = [];
|
|
const callTool: ReturnType<GhidraProviderClientFactory>["callTool"] = (
|
|
operation,
|
|
input,
|
|
options,
|
|
) => {
|
|
toolCalls.push({ operation, input, options });
|
|
return Promise.resolve(
|
|
ok([
|
|
{
|
|
address: "0x1000",
|
|
value: "fixture_main",
|
|
procedure: {
|
|
external: false,
|
|
thunk: false,
|
|
thunk_target: null,
|
|
},
|
|
},
|
|
]),
|
|
);
|
|
};
|
|
const clientFactory: GhidraProviderClientFactory = (options) => {
|
|
factoryOptions.push(options);
|
|
return {
|
|
start: () => {
|
|
startCount += 1;
|
|
return Promise.resolve(ok(sessionInfo()));
|
|
},
|
|
callTool,
|
|
close: () => Promise.resolve(ok(null)),
|
|
};
|
|
};
|
|
const ghidra = provider(installationHost(), clientFactory);
|
|
const resolved = await ghidra.resolveAnalysisProfile(
|
|
executableTarget("elf", "x86_64"),
|
|
);
|
|
|
|
if (!resolved.ok) throw resolved.error;
|
|
if (resolved.value.profile === null)
|
|
throw new Error("Expected a bound Ghidra profile");
|
|
expect(resolved.value.profile).toMatchObject({
|
|
provider: { id: "ghidra", name: "Ghidra", version: "12.1.4" },
|
|
parameters: {
|
|
import_mode: "ephemeral-source-immutable",
|
|
annotation_policy: "atomic-function-entry-metadata-v1",
|
|
analyzer_preset: "ghidra-default",
|
|
},
|
|
});
|
|
expect(resolved.value.profile.parameters).toMatchObject({
|
|
language_id: "auto-from-header",
|
|
compiler_spec_id: "auto-default",
|
|
});
|
|
|
|
const result = await ghidra
|
|
.createClient(executableTarget("elf", "x86_64"), resolved.value.profile, {
|
|
runId: "11111111-1111-4111-8111-111111111111",
|
|
})
|
|
.execute("list_procedures", {});
|
|
expect(factoryOptions).toEqual([
|
|
expect.objectContaining({
|
|
runId: "11111111-1111-4111-8111-111111111111",
|
|
platform: "linux",
|
|
}),
|
|
]);
|
|
expect(toolCalls).toEqual([
|
|
{
|
|
operation: "list_procedures",
|
|
input: { document: null },
|
|
options: {},
|
|
},
|
|
]);
|
|
expect(result).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
provider: {
|
|
id: "ghidra",
|
|
name: "Ghidra",
|
|
version: "12.1.4",
|
|
},
|
|
analysisProfile: resolved.value.profile,
|
|
result: [{ address: "0x1000", value: "fixture_main" }],
|
|
rawResult: [{ procedure: { external: false, thunk: false } }],
|
|
},
|
|
});
|
|
expect(startCount).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe("Ghidra result projection", () => {
|
|
const createElfClient = async (ghidra: GhidraProvider) => {
|
|
const target = executableTarget("elf", "x86_64");
|
|
const resolved = await ghidra.resolveAnalysisProfile(target);
|
|
if (!resolved.ok) throw resolved.error;
|
|
if (resolved.value.profile === null)
|
|
throw new Error("Expected a bound Ghidra profile");
|
|
return ghidra.createClient(target, resolved.value.profile);
|
|
};
|
|
|
|
it("rejects malformed inventory output before Evidence creation", async () => {
|
|
const ghidra = provider(installationHost(), () => ({
|
|
start: () => Promise.resolve(ok(sessionInfo())),
|
|
callTool: () => Promise.resolve(ok({ items: "not-an-inventory" })),
|
|
close: () => Promise.resolve(ok(null)),
|
|
}));
|
|
const client = await createElfClient(ghidra);
|
|
await expect(client.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(ok(null)),
|
|
}));
|
|
const client = await createElfClient(ghidra);
|
|
await expect(
|
|
client.execute("list_procedures", {}),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { _tag: tag },
|
|
});
|
|
},
|
|
);
|
|
|
|
it("preserves the rejected name constraint and function address", async () => {
|
|
const message =
|
|
"Invalid function name at 0x10100: Symbol name contains invalid characters";
|
|
const ghidra = provider(installationHost(), () => ({
|
|
start: () => Promise.resolve(ok(sessionInfo())),
|
|
callTool: () =>
|
|
Promise.resolve(
|
|
err(
|
|
new GhidraSessionError(
|
|
"remote",
|
|
message,
|
|
{},
|
|
{ remoteCode: "invalid_function_name" },
|
|
),
|
|
),
|
|
),
|
|
close: () => Promise.resolve(ok(null)),
|
|
}));
|
|
const client = await createElfClient(ghidra);
|
|
await expect(
|
|
client.execute("annotate_native_function", {
|
|
procedure: "0x10100",
|
|
name: "bad name",
|
|
}),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "AnalysisInputError",
|
|
issues: [{ path: ["name"], reason: "invalid_value", message }],
|
|
},
|
|
});
|
|
});
|
|
|
|
it("projects remote decompile cancellation as a provider-neutral interruption", async () => {
|
|
const code = "decompile_cancelled";
|
|
const tag = "AnalysisCancelledError";
|
|
const ghidra = provider(installationHost(), () => ({
|
|
start: () => Promise.resolve(ok(sessionInfo())),
|
|
callTool: () =>
|
|
Promise.resolve(
|
|
err(
|
|
new GhidraSessionError(
|
|
"remote",
|
|
"Fixture decompiler interruption",
|
|
{ remote_code: code },
|
|
{ remoteCode: code },
|
|
),
|
|
),
|
|
),
|
|
close: () => Promise.resolve(ok(null)),
|
|
}));
|
|
const client = await createElfClient(ghidra);
|
|
const result = await client.execute("procedure_pseudo_code", {
|
|
procedure: "main",
|
|
});
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: tag },
|
|
});
|
|
});
|
|
|
|
it("returns cancellation before profile work", async () => {
|
|
const controller = new AbortController();
|
|
controller.abort();
|
|
await expect(
|
|
provider().resolveAnalysisProfile(executableTarget("elf", "x86_64"), {
|
|
signal: controller.signal,
|
|
}),
|
|
).resolves.toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisCancelledError", operation: "open_binary" },
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("Ghidra measured load-image projection", () => {
|
|
it.each([
|
|
"verified",
|
|
"mismatch",
|
|
"changed-snapshot",
|
|
"unsupported",
|
|
"missing-snapshot",
|
|
] as const)(
|
|
"preserves %s state and producing observations",
|
|
async (state) => {
|
|
const fixture = fixtureDosLoadImage();
|
|
if (state === "mismatch") fixture.observation.entry_points = ["0x10001"];
|
|
if (state === "changed-snapshot") fixture.bytes[0] = 0;
|
|
const factory: GhidraProviderClientFactory = () => ({
|
|
start: () => Promise.resolve(ok(sessionInfo())),
|
|
callTool: () =>
|
|
Promise.resolve(ok(jsonValueSchema.parse(fixture.observation))),
|
|
close: () => Promise.resolve(ok(null)),
|
|
...(state === "missing-snapshot"
|
|
? {}
|
|
: {
|
|
readTargetSnapshot: () => Promise.resolve(ok(fixture.bytes)),
|
|
}),
|
|
});
|
|
const ghidra = provider(installationHost(), factory);
|
|
const target: BinaryTarget = {
|
|
path: "/tmp/source-owned-fixture.exe",
|
|
sha256: fixture.sha256,
|
|
kind: "executable",
|
|
format: state === "unsupported" ? "elf" : "dos-mz",
|
|
architecture: "x86",
|
|
availableArchitectures: ["x86"],
|
|
};
|
|
const profile = await ghidra.resolveAnalysisProfile(target);
|
|
if (!profile.ok || profile.value.profile === null)
|
|
throw new Error("Expected admitted profile");
|
|
const result = await ghidra
|
|
.createClient(target, profile.value.profile)
|
|
.execute("inspect_native_load_image", {});
|
|
if (state === "changed-snapshot" || state === "missing-snapshot") {
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "ProviderAdapterError",
|
|
diagnostics: { reason: expect.stringContaining("snapshot") },
|
|
},
|
|
});
|
|
} else {
|
|
expect(result).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
result: { status: state, observations: fixture.observation },
|
|
rawResult: fixture.observation,
|
|
analysisProfile: profile.value.profile,
|
|
},
|
|
});
|
|
}
|
|
},
|
|
);
|
|
});
|
|
|
|
const sessionInfo = () => ({
|
|
name: "REA Ghidra bridge" as const,
|
|
run_id: "11111111-1111-4111-8111-111111111111",
|
|
profile_digest: "a".repeat(64),
|
|
provider: { id: "ghidra" as const, version: "12.1.4" },
|
|
read_only: false 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",
|
|
sha256: "a".repeat(64),
|
|
},
|
|
});
|
|
|
|
const executableTarget = (
|
|
format: "mach-o" | "elf" | "pe",
|
|
architecture: Extract<BinaryTarget, { format: "pe" }>["architecture"],
|
|
): BinaryTarget =>
|
|
format === "pe"
|
|
? peTarget(architecture)
|
|
: {
|
|
path: "/tmp/fixture",
|
|
sha256: "a".repeat(64),
|
|
kind: "executable",
|
|
format,
|
|
architecture,
|
|
availableArchitectures: [architecture],
|
|
};
|
|
|
|
const peTarget = (
|
|
architecture: Extract<BinaryTarget, { format: "pe" }>["architecture"],
|
|
): Extract<BinaryTarget, { format: "pe" }> => ({
|
|
path: "/tmp/fixture",
|
|
sha256: "a".repeat(64),
|
|
kind: "executable",
|
|
format: "pe",
|
|
architecture,
|
|
availableArchitectures: [architecture],
|
|
executableRole: "application",
|
|
managed: false,
|
|
});
|
|
|
|
describe("Ghidra extension failures", () => {
|
|
it.each(["unsupported", "failed", "malformed"] as const)(
|
|
"preserves %s recovery diagnostics and closes without restarting",
|
|
async (status) => {
|
|
const directory = await mkdtemp(
|
|
join(tmpdir(), "rea-provider-extension-"),
|
|
);
|
|
try {
|
|
const jar = join(directory, "addon.jar");
|
|
await writeFile(jar, Buffer.from([0x50, 0x4b, 3, 4]));
|
|
const config = parseConfig({
|
|
GHIDRA_INSTALL_DIR: INSTALL,
|
|
REA_GHIDRA_NATIVEAOT_JAR: jar,
|
|
});
|
|
if (!config.ok) throw config.error;
|
|
let starts = 0,
|
|
calls = 0,
|
|
closes = 0;
|
|
const ghidra = new GhidraProvider(
|
|
config.value,
|
|
silentLogger,
|
|
{},
|
|
installationHost(),
|
|
() => ({
|
|
start: () => {
|
|
starts++;
|
|
return Promise.resolve(
|
|
ok({
|
|
...sessionInfo(),
|
|
analysis_extensions: [
|
|
{
|
|
id: "nativeaot",
|
|
sha256:
|
|
status === "malformed"
|
|
? "0".repeat(64)
|
|
: createHash("sha256")
|
|
.update(Buffer.from([0x50, 0x4b, 3, 4]))
|
|
.digest("hex"),
|
|
status: status === "malformed" ? "failed" : status,
|
|
reason:
|
|
"directory-discovery: Unsupported layout at 0x401000",
|
|
result: {
|
|
id: "nativeaot",
|
|
integration_api: 1,
|
|
source_revision:
|
|
"effeb734fc570c32650f88b159608979dc7b423e",
|
|
source_revision_authority: "build-reported-unattested",
|
|
status: status === "malformed" ? "failed" : status,
|
|
reason:
|
|
"directory-discovery: Unsupported layout at 0x401000",
|
|
method_tables: 0,
|
|
diagnostics: ["exact producer diagnostic"],
|
|
},
|
|
},
|
|
],
|
|
}),
|
|
);
|
|
},
|
|
callTool: () => {
|
|
calls++;
|
|
return Promise.resolve(ok(null));
|
|
},
|
|
close: () => {
|
|
closes++;
|
|
return Promise.resolve(ok(null));
|
|
},
|
|
}),
|
|
);
|
|
const target = executableTarget("elf", "x86_64");
|
|
const resolved = await ghidra.resolveAnalysisProfile(target);
|
|
if (!resolved.ok || resolved.value.profile === null)
|
|
throw new Error("expected extension profile");
|
|
const client = ghidra.createClient(target, resolved.value.profile);
|
|
const failed = await client.execute("health", {});
|
|
expect(failed.ok).toBe(false);
|
|
if (!failed.ok) {
|
|
expect(failed.error._tag).toBe(
|
|
status === "unsupported"
|
|
? "AnalysisCapabilityUnavailableError"
|
|
: "ProviderAdapterError",
|
|
);
|
|
expect(JSON.stringify(failed.error)).toContain(
|
|
status === "malformed"
|
|
? "identity mismatch"
|
|
: "Unsupported layout at 0x401000",
|
|
);
|
|
}
|
|
expect(await client.execute("list_procedures", {})).toEqual(failed);
|
|
expect({ starts, calls, closes }).toEqual({
|
|
starts: 1,
|
|
calls: 0,
|
|
closes: 1,
|
|
});
|
|
} finally {
|
|
await rm(directory, { recursive: true, force: true });
|
|
}
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("compatible Ghidra builds", () => {
|
|
it("accepts the build and reports that it is unverified", async () => {
|
|
const ghidra = provider(
|
|
{
|
|
...installationHost(),
|
|
readText: () =>
|
|
"application.version=12.1.2\napplication.java.min=21\napplication.java.max=\n",
|
|
probeJava: () => ({
|
|
version: "27",
|
|
major: 27,
|
|
home: "/usr/lib/jvm/java-27-openjdk",
|
|
bits: 64,
|
|
runtime: "jdk",
|
|
}),
|
|
},
|
|
() => ({
|
|
start: () =>
|
|
Promise.resolve(
|
|
ok({
|
|
...sessionInfo(),
|
|
provider: { id: "ghidra", version: "12.1.2" },
|
|
}),
|
|
),
|
|
callTool: () =>
|
|
Promise.resolve(
|
|
ok([
|
|
{
|
|
address: "0x1000",
|
|
value: "fixture_main",
|
|
procedure: {
|
|
external: false,
|
|
thunk: false,
|
|
thunk_target: null,
|
|
},
|
|
},
|
|
]),
|
|
),
|
|
close: () => Promise.resolve(ok(null)),
|
|
}),
|
|
);
|
|
const resolved = await ghidra.resolveAnalysisProfile(
|
|
executableTarget("elf", "x86_64"),
|
|
);
|
|
if (!resolved.ok || resolved.value.profile === null)
|
|
throw new Error("expected a compatible Ghidra profile");
|
|
const client = ghidra.createClient(
|
|
executableTarget("elf", "x86_64"),
|
|
resolved.value.profile,
|
|
);
|
|
const health = await client.execute("health", {});
|
|
const procedures = await client.execute("list_procedures", {});
|
|
expect(ghidra.inspectAvailability()).toMatchObject({
|
|
status: "available",
|
|
diagnostics: { provider_version: "12.1.2", java_version: "27" },
|
|
});
|
|
expect(health.ok && health.value.provider.version).toBe("12.1.2");
|
|
const unverified = expect.stringContaining("12.1.2");
|
|
expect(health.ok && health.value.limitations).toEqual(
|
|
expect.arrayContaining([unverified]),
|
|
);
|
|
expect(procedures.ok && procedures.value.limitations).toEqual(
|
|
expect.arrayContaining([unverified]),
|
|
);
|
|
expect(procedures.ok && procedures.value.provider.version).toBe("12.1.2");
|
|
});
|
|
});
|
|
|
|
it("projects Ghidra startup failure and its incomplete cleanup together", async () => {
|
|
const cleanup = new ProviderCleanupError("ghidra", ["owned-ghidra-process"], {
|
|
reason: "process cleanup unconfirmed",
|
|
});
|
|
const ghidra = provider(installationHost(), () => ({
|
|
start: async () =>
|
|
err(
|
|
new GhidraSessionError(
|
|
"timeout",
|
|
"Ghidra startup deadline elapsed",
|
|
{ failure_kind: "timeout" },
|
|
{ timeoutMs: 250, cleanupFailure: cleanup },
|
|
),
|
|
),
|
|
callTool: async () => ok(null),
|
|
close: async () => err(cleanup),
|
|
}));
|
|
const target = executableTarget("elf", "x86_64");
|
|
const profile = await ghidra.resolveAnalysisProfile(target);
|
|
if (!profile.ok || profile.value.profile === null)
|
|
throw new Error("Expected Ghidra analysis profile");
|
|
const result = await ghidra
|
|
.createClient(target, profile.value.profile)
|
|
.execute("health", {});
|
|
expect(result.ok).toBe(false);
|
|
if (!result.ok)
|
|
expect(projectAnalysisError(result.error)).toMatchObject({
|
|
code: "cleanup_incomplete",
|
|
details: {
|
|
resources: ["owned-ghidra-process"],
|
|
diagnostics: {
|
|
primary_error: {
|
|
code: "provider_timeout",
|
|
details: { timeout_ms: 250 },
|
|
},
|
|
cleanup_error: { code: "cleanup_incomplete" },
|
|
},
|
|
},
|
|
});
|
|
});
|