feat(ghidra): integrate optional NativeAOT metadata recovery (#748)
* feat(ghidra): integrate optional NativeAOT metadata recovery * fix(ghidra): bind extension snapshots to configured artifacts * test(ghidra): verify lazy NativeAOT startup failures * fix(ghidra): preserve NativeAOT failure reasons and coverage * fix(ghidra): preserve NativeAOT x64 calling conventions * test(ghidra): guard recovered NativeAOT method conventions * fix(ghidra): reject blocking extension file inputs * fix(ghidra): diagnose incompatible NativeAOT extension classes * test(ghidra): verify real extension initialization failures * fix(ghidra): keep extension descriptor fields optional
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import { AnalysisCapabilityUnavailableError } from "../../domain/analysisErrorCore.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
||||
import { jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
import {
|
||||
validateGhidraExtensionResults,
|
||||
type GhidraExtension,
|
||||
type GhidraExtensionResult,
|
||||
} from "./GhidraExtensions.js";
|
||||
|
||||
/** Preserve unsupported recovery separately from malformed or failed producers. */
|
||||
export const ghidraExtensionFailure = (
|
||||
extensions: readonly GhidraExtension[],
|
||||
results: readonly GhidraExtensionResult[],
|
||||
operation: string,
|
||||
): AnalysisError | undefined => {
|
||||
const reports = results;
|
||||
const invalid = validateGhidraExtensionResults(extensions, reports);
|
||||
const failed = reports.find(
|
||||
(value) => value.status === "unsupported" || value.status === "failed",
|
||||
);
|
||||
if (invalid === null && failed === undefined) return undefined;
|
||||
return invalid === null && failed?.status === "unsupported"
|
||||
? new AnalysisCapabilityUnavailableError(
|
||||
"ghidra",
|
||||
operation,
|
||||
`${failed.id}: ${failed.reason}. Omit REA_GHIDRA_NATIVEAOT_JAR to continue ordinary native analysis.`,
|
||||
)
|
||||
: new ProviderAdapterError("ghidra", operation, {
|
||||
diagnostics: {
|
||||
reason: invalid ?? failed?.reason ?? "Ghidra extension failed",
|
||||
analysis_extensions: jsonValueSchema.parse(reports),
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,414 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { constants } from "node:fs";
|
||||
import { promisify } from "node:util";
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { parseConfig } from "../../config.js";
|
||||
import type { BinaryTarget } from "../../domain/binaryTarget.js";
|
||||
import {
|
||||
ghidraExtensionSchema,
|
||||
resolveGhidraExtensions,
|
||||
snapshotGhidraExtensions,
|
||||
validateGhidraExtensionResults,
|
||||
validateGhidraExtensionProfile,
|
||||
type GhidraExtensionResult,
|
||||
} from "./GhidraExtensions.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
const root = async () => {
|
||||
const path = await mkdtemp(join(tmpdir(), "rea-extension-test-"));
|
||||
roots.push(path);
|
||||
return path;
|
||||
};
|
||||
const target: BinaryTarget = {
|
||||
path: "/tmp/native",
|
||||
kind: "executable",
|
||||
format: "elf",
|
||||
architecture: "x86_64",
|
||||
availableArchitectures: ["x86_64"],
|
||||
sha256: "a".repeat(64),
|
||||
};
|
||||
const config = (path?: string) => {
|
||||
const parsed = parseConfig(
|
||||
path === undefined ? {} : { REA_GHIDRA_NATIVEAOT_JAR: path },
|
||||
);
|
||||
if (!parsed.ok) throw parsed.error;
|
||||
return parsed.value;
|
||||
};
|
||||
const artifact = async () => {
|
||||
const directory = await root();
|
||||
const path = join(directory, "fixture.jar");
|
||||
const bytes = Buffer.from([0x50, 0x4b, 3, 4, 0, 1, 2, 3]);
|
||||
await writeFile(path, bytes);
|
||||
const resolved = await resolveGhidraExtensions(config(path), target, "linux");
|
||||
if (!resolved.ok || resolved.value[0] === undefined)
|
||||
throw new Error("expected fixture artifact");
|
||||
return { extension: resolved.value[0], bytes, path };
|
||||
};
|
||||
const result = (sha256: string): GhidraExtensionResult => ({
|
||||
id: "nativeaot",
|
||||
sha256,
|
||||
status: "not_applicable",
|
||||
reason: "No matching directory",
|
||||
result: {
|
||||
id: "nativeaot",
|
||||
integration_api: 1,
|
||||
source_revision: "effeb734fc570c32650f88b159608979dc7b423e",
|
||||
source_revision_authority: "build-reported-unattested",
|
||||
status: "not_applicable",
|
||||
reason: "No matching directory",
|
||||
method_tables: 0,
|
||||
diagnostics: [],
|
||||
},
|
||||
});
|
||||
|
||||
describe("optional Ghidra extension boundary", () => {
|
||||
it("keeps ordinary profiles free of unconfigured extensions", async () => {
|
||||
expect(await resolveGhidraExtensions(config(), target, "linux")).toEqual({
|
||||
ok: true,
|
||||
value: [],
|
||||
});
|
||||
});
|
||||
it("validates configuration paths rather than ignoring an unsupported value", () => {
|
||||
expect(parseConfig({ REA_GHIDRA_NATIVEAOT_JAR: "relative.jar" }).ok).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
it("commits the actual regular artifact bytes and caller path", async () => {
|
||||
const { extension, bytes, path } = await artifact();
|
||||
expect(extension).toMatchObject({
|
||||
configured_path: path,
|
||||
path,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
integration_api: 1,
|
||||
});
|
||||
});
|
||||
it("snapshots identical bytes exclusively into the private runtime", async () => {
|
||||
const { extension, bytes } = await artifact();
|
||||
const runtime = await root();
|
||||
const snapshots = await snapshotGhidraExtensions([extension], runtime);
|
||||
expect(snapshots[0]?.path).toBe(join(runtime, "extensions/nativeaot.jar"));
|
||||
expect(await readFile(join(runtime, "extensions/nativeaot.jar"))).toEqual(
|
||||
bytes,
|
||||
);
|
||||
await expect(
|
||||
snapshotGhidraExtensions([extension], runtime),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
it("rejects artifact changes after the profile commitment", async () => {
|
||||
const { extension, path } = await artifact();
|
||||
await writeFile(path, Buffer.from([0x50, 0x4b, 3, 4, 9, 9, 9, 9]));
|
||||
await expect(
|
||||
snapshotGhidraExtensions([extension], await root()),
|
||||
).rejects.toThrow("digest differs");
|
||||
});
|
||||
it("rejects nonexistent, empty and non-JAR artifacts with useful reasons", async () => {
|
||||
const directory = await root();
|
||||
for (const bytes of [Buffer.alloc(0), Buffer.from("invalid jar")]) {
|
||||
const path = join(directory, "invalid.jar");
|
||||
await writeFile(path, bytes);
|
||||
const resolved = await resolveGhidraExtensions(
|
||||
config(path),
|
||||
target,
|
||||
"linux",
|
||||
);
|
||||
expect(resolved.ok).toBe(false);
|
||||
if (!resolved.ok)
|
||||
expect(resolved.error).toMatchObject({
|
||||
diagnostics: { path, extension: "nativeaot" },
|
||||
});
|
||||
}
|
||||
expect(
|
||||
(
|
||||
await resolveGhidraExtensions(
|
||||
config(join(directory, "absent.jar")),
|
||||
target,
|
||||
"linux",
|
||||
)
|
||||
).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
it("rejects unsupported hosts and target architectures before opening files", async () => {
|
||||
expect(
|
||||
(await resolveGhidraExtensions(config("/absent.jar"), target, "win32"))
|
||||
.ok,
|
||||
).toBe(false);
|
||||
expect(
|
||||
(
|
||||
await resolveGhidraExtensions(
|
||||
config("/absent.jar"),
|
||||
{
|
||||
...target,
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["arm64"],
|
||||
},
|
||||
"linux",
|
||||
)
|
||||
).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects a FIFO without requiring another process to open its writer",
|
||||
async () => {
|
||||
const path = join(await root(), "not-a-jar.fifo");
|
||||
await promisify(execFile)("mkfifo", [path]);
|
||||
let writerRequired = false;
|
||||
let rescueTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
// Release a broken blocking-open implementation so regression failures
|
||||
// do not strand a libuv filesystem worker. Success needs no FIFO peer.
|
||||
const rescue = new Promise<void>((resolve) => {
|
||||
rescueTimer = setTimeout(() => {
|
||||
writerRequired = true;
|
||||
void open(path, constants.O_WRONLY | constants.O_NONBLOCK)
|
||||
.then((file) => file.close())
|
||||
.then(resolve, () => resolve());
|
||||
}, 1000);
|
||||
});
|
||||
try {
|
||||
const resolved = await resolveGhidraExtensions(
|
||||
config(path),
|
||||
target,
|
||||
"linux",
|
||||
);
|
||||
expect(resolved.ok).toBe(false);
|
||||
if (!resolved.ok)
|
||||
expect(resolved.error).toMatchObject({
|
||||
diagnostics: { reason: expect.stringContaining("regular JAR") },
|
||||
});
|
||||
expect(writerRequired).toBe(false);
|
||||
} finally {
|
||||
clearTimeout(rescueTimer);
|
||||
if (writerRequired) await rescue;
|
||||
}
|
||||
},
|
||||
);
|
||||
it("honors cancellation before artifact I/O", async () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const resolved = await resolveGhidraExtensions(
|
||||
config("/absent.jar"),
|
||||
target,
|
||||
"linux",
|
||||
controller.signal,
|
||||
);
|
||||
expect(resolved.ok).toBe(false);
|
||||
if (!resolved.ok)
|
||||
expect(resolved.error._tag).toBe("AnalysisCancelledError");
|
||||
});
|
||||
it("refuses traversal identities in an imported extension profile", () => {
|
||||
expect(
|
||||
ghidraExtensionSchema.safeParse({
|
||||
id: "../escape",
|
||||
path: "/fixture.jar",
|
||||
configured_path: "/fixture.jar",
|
||||
sha256: "a".repeat(64),
|
||||
integration_api: 1,
|
||||
entry_class: "ignored",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra extension profile and producer validation", () => {
|
||||
it("requires exact inventory, artifact digest and consistent producer status", async () => {
|
||||
const { extension } = await artifact();
|
||||
const valid = result(extension.sha256);
|
||||
expect(validateGhidraExtensionResults([extension], [valid])).toBeNull();
|
||||
expect(validateGhidraExtensionResults([extension], [])).not.toBeNull();
|
||||
expect(validateGhidraExtensionResults([], [valid])).not.toBeNull();
|
||||
expect(
|
||||
validateGhidraExtensionResults([extension], [valid, valid]),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
validateGhidraExtensionResults(
|
||||
[extension],
|
||||
[{ ...valid, sha256: "b".repeat(64) }],
|
||||
),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
validateGhidraExtensionResults(
|
||||
[extension],
|
||||
[{ ...valid, status: "complete" }],
|
||||
),
|
||||
).not.toBeNull();
|
||||
});
|
||||
it("requires matching explicit configuration for imported executable profiles", async () => {
|
||||
const { extension, path } = await artifact();
|
||||
expect(
|
||||
validateGhidraExtensionProfile(
|
||||
[extension],
|
||||
config(path),
|
||||
target,
|
||||
"linux",
|
||||
),
|
||||
).toBeNull();
|
||||
expect(
|
||||
validateGhidraExtensionProfile([extension], config(), target, "linux"),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
validateGhidraExtensionProfile(
|
||||
[extension],
|
||||
config(path),
|
||||
target,
|
||||
"darwin",
|
||||
),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
validateGhidraExtensionProfile(
|
||||
[{ ...extension, entry_class: "arbitrary.Code" }],
|
||||
config(path),
|
||||
target,
|
||||
"linux",
|
||||
),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
validateGhidraExtensionProfile(
|
||||
[{ ...extension, configured_path: "/another.jar" }],
|
||||
config(path),
|
||||
target,
|
||||
"linux",
|
||||
),
|
||||
).not.toBeNull();
|
||||
});
|
||||
it("does not classify PE/CLI or ReadyToRun as NativeAOT", async () => {
|
||||
const resolved = await resolveGhidraExtensions(
|
||||
config("/absent.jar"),
|
||||
{ ...target, format: "pe", managed: true, executableRole: "application" },
|
||||
"linux",
|
||||
);
|
||||
expect(resolved.ok).toBe(false);
|
||||
if (!resolved.ok)
|
||||
expect(resolved.error).toMatchObject({
|
||||
diagnostics: {
|
||||
reason: expect.stringContaining("inspect_managed_artifact"),
|
||||
},
|
||||
});
|
||||
});
|
||||
it("does not substitute another artifact under an unchanged configured path", async () => {
|
||||
const first = await artifact();
|
||||
const second = await artifact();
|
||||
await expect(
|
||||
snapshotGhidraExtensions(
|
||||
[{ ...second.extension, configured_path: first.path }],
|
||||
await root(),
|
||||
),
|
||||
).rejects.toThrow("resolved path differs");
|
||||
});
|
||||
it("rejects unregistered descriptors before snapshot filesystem writes", async () => {
|
||||
const { extension } = await artifact();
|
||||
const runtime = await root();
|
||||
await expect(
|
||||
snapshotGhidraExtensions([{ ...extension, id: "unknown" }], runtime),
|
||||
).rejects.toThrow("Unregistered");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra extension recovery coverage", () => {
|
||||
it("validates positive recovery, measured partial coverage and distinct table identities", async () => {
|
||||
const { extension } = await artifact();
|
||||
const baseline = result(extension.sha256);
|
||||
const positive: GhidraExtensionResult = {
|
||||
...baseline,
|
||||
status: "complete",
|
||||
reason: null,
|
||||
result: {
|
||||
...baseline.result,
|
||||
status: "complete",
|
||||
reason: null,
|
||||
method_tables: 1,
|
||||
header_address: "0x401000",
|
||||
discovery: "signature-heuristic",
|
||||
format_major: 9,
|
||||
format_minor: 1,
|
||||
types: [
|
||||
{
|
||||
address: "0x402000",
|
||||
type: "/NativeAOT/MethodTables/Class_00402000_MT",
|
||||
},
|
||||
],
|
||||
derived_memory: {
|
||||
address: "0x402000",
|
||||
size_bytes: 64,
|
||||
sha256: "a".repeat(64),
|
||||
file_offset: null,
|
||||
},
|
||||
coverage: {
|
||||
frozen_object_candidates: 1,
|
||||
frozen_objects_annotated: 1,
|
||||
basis: "rehydrated-pointer-candidates-and-committed-instance-types",
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(validateGhidraExtensionResults([extension], [positive])).toBeNull();
|
||||
const incomplete = {
|
||||
...positive,
|
||||
result: {
|
||||
...positive.result,
|
||||
coverage: {
|
||||
frozen_object_candidates: 2,
|
||||
frozen_objects_annotated: 1,
|
||||
basis: "rehydrated-pointer-candidates-and-committed-instance-types",
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(
|
||||
validateGhidraExtensionResults([extension], [incomplete]),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
validateGhidraExtensionResults(
|
||||
[extension],
|
||||
[
|
||||
{
|
||||
...incomplete,
|
||||
status: "partial",
|
||||
result: { ...incomplete.result, status: "partial" },
|
||||
},
|
||||
],
|
||||
),
|
||||
).toBeNull();
|
||||
expect(
|
||||
validateGhidraExtensionResults(
|
||||
[extension],
|
||||
[{ ...positive, result: { ...positive.result, discovery: null } }],
|
||||
),
|
||||
).not.toBeNull();
|
||||
});
|
||||
it("preserves real loader failures without requiring a successful analyzer report", async () => {
|
||||
const { extension } = await artifact();
|
||||
const reason = "Extension loading/analysis failed: ClassNotFoundException";
|
||||
expect(
|
||||
validateGhidraExtensionResults(
|
||||
[extension],
|
||||
[
|
||||
{
|
||||
id: "nativeaot",
|
||||
sha256: extension.sha256,
|
||||
status: "failed",
|
||||
reason,
|
||||
result: { loader_failure: reason },
|
||||
},
|
||||
],
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
it("does not accept complete recovery without format and byte identities", async () => {
|
||||
const { extension } = await artifact();
|
||||
const incomplete = result(extension.sha256);
|
||||
incomplete.result.status = "complete";
|
||||
incomplete.result.reason = null;
|
||||
expect(
|
||||
validateGhidraExtensionResults(
|
||||
[extension],
|
||||
[{ ...incomplete, status: "complete", reason: null }],
|
||||
),
|
||||
).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { constants } from "node:fs";
|
||||
import { open, realpath, writeFile, mkdir } from "node:fs/promises";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
import { z } from "zod";
|
||||
import type { AppConfig } from "../../config.js";
|
||||
import type { BinaryTarget } from "../../domain/binaryTarget.js";
|
||||
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
|
||||
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { jsonObjectSchema } from "../../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { nativeAotAdapter } from "./nativeaot/NativeAotAdapter.js";
|
||||
|
||||
const digest = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
/** Exact executable extension artifact committed before the session starts. */
|
||||
export const ghidraExtensionSchema = z.strictObject({
|
||||
id: z.string().regex(/^[a-z][a-z0-9-]*$/u),
|
||||
path: z.string().refine(isAbsolute, "Extension path must be absolute"),
|
||||
configured_path: z
|
||||
.string()
|
||||
.refine(isAbsolute, "Extension path must be absolute"),
|
||||
sha256: digest,
|
||||
entry_class: z.string().min(1),
|
||||
integration_api: z.literal(1),
|
||||
});
|
||||
export type GhidraExtension = z.infer<typeof ghidraExtensionSchema>;
|
||||
|
||||
/** Shared extension envelope; each adapter validates its own producer result. */
|
||||
export const ghidraExtensionResultSchema = z.strictObject({
|
||||
id: z.string().min(1),
|
||||
sha256: digest,
|
||||
status: z.enum([
|
||||
"complete",
|
||||
"partial",
|
||||
"not_applicable",
|
||||
"unsupported",
|
||||
"failed",
|
||||
]),
|
||||
reason: z.string().nullable(),
|
||||
result: jsonObjectSchema,
|
||||
});
|
||||
export type GhidraExtensionResult = z.infer<typeof ghidraExtensionResultSchema>;
|
||||
|
||||
/** Provider-local registration contract for independently replaceable analysis adapters. */
|
||||
export interface GhidraExtensionAdapter {
|
||||
readonly id: string;
|
||||
readonly entryClass: string;
|
||||
configuredPath(config: AppConfig): string | undefined;
|
||||
unsupportedReason(
|
||||
target: BinaryTarget,
|
||||
platform: NodeJS.Platform,
|
||||
): string | null;
|
||||
validate(result: GhidraExtensionResult): string | null;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
const adapters: readonly GhidraExtensionAdapter[] = [nativeAotAdapter];
|
||||
const MAX_EXTENSION_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/** Read a bounded regular artifact through its open handle, without ambient state changes. */
|
||||
const readJar = async (path: string): Promise<Buffer> => {
|
||||
const file = await open(
|
||||
path,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
);
|
||||
try {
|
||||
const stat = await file.stat();
|
||||
if (!stat.isFile() || stat.size < 4 || stat.size > MAX_EXTENSION_BYTES)
|
||||
throw new Error(
|
||||
`Ghidra extension must be a regular JAR of 4..${MAX_EXTENSION_BYTES} bytes: ${path}`,
|
||||
);
|
||||
const bytes = Buffer.alloc(stat.size);
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const read = await file.read(
|
||||
bytes,
|
||||
offset,
|
||||
bytes.length - offset,
|
||||
offset,
|
||||
);
|
||||
if (read.bytesRead === 0)
|
||||
throw new Error(`Incomplete Ghidra extension read: ${path}`);
|
||||
offset += read.bytesRead;
|
||||
}
|
||||
const extra = Buffer.alloc(1);
|
||||
if (
|
||||
(await file.read(extra, 0, 1, offset)).bytesRead !== 0 ||
|
||||
bytes.readUInt32LE(0) !== 0x04034b50
|
||||
)
|
||||
throw new Error(
|
||||
`Ghidra extension changed during read or is not a JAR: ${path}`,
|
||||
);
|
||||
return bytes;
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
};
|
||||
|
||||
/** Resolve explicitly configured optional extensions into the immutable analysis profile. */
|
||||
export const resolveGhidraExtensions = async (
|
||||
config: AppConfig,
|
||||
target: BinaryTarget,
|
||||
platform: NodeJS.Platform,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<readonly GhidraExtension[], AnalysisError>> => {
|
||||
const extensions: GhidraExtension[] = [];
|
||||
for (const adapter of adapters) {
|
||||
if (signal?.aborted) return err(new AnalysisCancelledError("open_binary"));
|
||||
const configured = adapter.configuredPath(config);
|
||||
if (configured === undefined) continue;
|
||||
const reason = adapter.unsupportedReason(target, platform);
|
||||
if (reason !== null)
|
||||
return err(
|
||||
new ProviderAdapterError("ghidra", "resolve_analysis_profile", {
|
||||
diagnostics: { extension: adapter.id, reason, path: configured },
|
||||
}),
|
||||
);
|
||||
try {
|
||||
const path = await realpath(configured);
|
||||
const bytes = await readJar(path);
|
||||
extensions.push({
|
||||
id: adapter.id,
|
||||
path,
|
||||
configured_path: configured,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
entry_class: adapter.entryClass,
|
||||
integration_api: 1,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new ProviderAdapterError("ghidra", "resolve_analysis_profile", {
|
||||
cause,
|
||||
diagnostics: {
|
||||
extension: adapter.id,
|
||||
path: configured,
|
||||
reason: cause instanceof Error ? cause.message : String(cause),
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (signal?.aborted) return err(new AnalysisCancelledError("open_binary"));
|
||||
return ok(extensions);
|
||||
};
|
||||
|
||||
/** Require explicit local configuration before admitting executable code from a profile. */
|
||||
export const validateGhidraExtensionProfile = (
|
||||
extensions: readonly GhidraExtension[],
|
||||
config: AppConfig,
|
||||
target: BinaryTarget,
|
||||
platform: NodeJS.Platform,
|
||||
): string | null => {
|
||||
const enabled = adapters.filter(
|
||||
(adapter) => adapter.configuredPath(config) !== undefined,
|
||||
);
|
||||
if (
|
||||
enabled.length !== extensions.length ||
|
||||
new Set(extensions.map((extension) => extension.id)).size !==
|
||||
extensions.length
|
||||
)
|
||||
return "Configured Ghidra extension inventory differs from the resolved analysis profile.";
|
||||
for (const extension of extensions) {
|
||||
const adapter = enabled.find((value) => value.id === extension.id);
|
||||
if (
|
||||
adapter === undefined ||
|
||||
adapter.entryClass !== extension.entry_class ||
|
||||
adapter.configuredPath(config) !== extension.configured_path
|
||||
)
|
||||
return `Ghidra extension profile lacks matching explicit local configuration: ${extension.id}`;
|
||||
const reason = adapter.unsupportedReason(target, platform);
|
||||
if (reason !== null) return reason;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Snapshot committed extension bytes into the private runtime before Java loads them. */
|
||||
export const snapshotGhidraExtensions = async (
|
||||
extensions: readonly GhidraExtension[],
|
||||
runtimeRoot: string,
|
||||
): Promise<readonly GhidraExtension[]> => {
|
||||
if (extensions.length === 0) return [];
|
||||
for (const extension of extensions) {
|
||||
ghidraExtensionSchema.parse(extension);
|
||||
const adapter = adapters.find((value) => value.id === extension.id);
|
||||
if (adapter === undefined || adapter.entryClass !== extension.entry_class)
|
||||
throw new Error(
|
||||
`Unregistered Ghidra extension identity: ${extension.id}`,
|
||||
);
|
||||
if ((await realpath(extension.configured_path)) !== extension.path)
|
||||
throw new Error(
|
||||
`Ghidra extension resolved path differs from explicit configuration: ${extension.id}`,
|
||||
);
|
||||
}
|
||||
const directory = join(runtimeRoot, "extensions");
|
||||
await mkdir(directory, { mode: 0o700 });
|
||||
const result: GhidraExtension[] = [];
|
||||
for (const extension of extensions) {
|
||||
const bytes = await readJar(extension.path);
|
||||
if (createHash("sha256").update(bytes).digest("hex") !== extension.sha256)
|
||||
throw new Error(
|
||||
`Ghidra extension digest differs from committed profile: ${extension.id} (${extension.path})`,
|
||||
);
|
||||
const path = join(directory, `${extension.id}.jar`);
|
||||
await writeFile(path, bytes, { flag: "wx", mode: 0o600 });
|
||||
result.push({ ...extension, path });
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/** Require every configured producer result to match its artifact and registered ABI. */
|
||||
export const validateGhidraExtensionResults = (
|
||||
expected: readonly GhidraExtension[],
|
||||
results: readonly GhidraExtensionResult[],
|
||||
): string | null => {
|
||||
if (
|
||||
results.length !== expected.length ||
|
||||
new Set(results.map((result) => result.id)).size !== results.length
|
||||
)
|
||||
return "Ghidra extension result inventory differs from its committed profile.";
|
||||
for (const extension of expected) {
|
||||
const result = results.find((value) => value.id === extension.id);
|
||||
const adapter = adapters.find((value) => value.id === extension.id);
|
||||
if (
|
||||
result === undefined ||
|
||||
adapter === undefined ||
|
||||
result.sha256 !== extension.sha256
|
||||
)
|
||||
return `Ghidra extension identity mismatch: ${extension.id}`;
|
||||
const invalid = adapter.validate(result);
|
||||
if (invalid !== null) return invalid;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/** Exact adapter limitations for explicitly configured session extensions. */
|
||||
export const ghidraExtensionLimitations = (
|
||||
extensions: readonly GhidraExtension[],
|
||||
): readonly string[] =>
|
||||
adapters
|
||||
.filter((adapter) =>
|
||||
extensions.some((extension) => extension.id === adapter.id),
|
||||
)
|
||||
.flatMap((adapter) => adapter.limitations);
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { GhidraExtensionAdapter } from "../GhidraExtensions.js";
|
||||
import { validateNativeAotReport } from "./NativeAotReport.js";
|
||||
|
||||
/** NativeAOT-specific prerequisites and report interpretation behind the extension boundary. */
|
||||
export const nativeAotAdapter: GhidraExtensionAdapter = {
|
||||
id: "nativeaot",
|
||||
entryClass: "rea.extensions.nativeaot.NativeAotExtension",
|
||||
configuredPath: (config) => config.ghidraNativeAotJar,
|
||||
unsupportedReason: (target, platform) =>
|
||||
platform !== "linux"
|
||||
? "NativeAOT recovery is verified on Linux only; omit REA_GHIDRA_NATIVEAOT_JAR for ordinary native analysis."
|
||||
: !["elf", "pe"].includes(target.format) ||
|
||||
target.architecture !== "x86_64" ||
|
||||
target.managed === true
|
||||
? "NativeAOT recovery requires an x86-64 ELF or native PE target on Linux; PE/CLI and ReadyToRun assemblies use inspect_managed_artifact; omit REA_GHIDRA_NATIVEAOT_JAR for ordinary native analysis."
|
||||
: null,
|
||||
validate: validateNativeAotReport,
|
||||
limitations: [
|
||||
"Optional NativeAOT recovery is verified for .NET 8.0.22 RTR 9.1 Linux x64 ELF and Windows x64 PE targets on a Linux host. Other runtime layouts, target architectures and hosts are unsupported.",
|
||||
"Type names and relationships use recovery heuristics; original C# source and custom field layouts are not recovered. Rehydrated analysis-memory bytes are derived, without original file offsets or runtime observations.",
|
||||
"Method prototypes are Ghidra inferences, not original signatures. Pre-recovery conventions are retained; new functions use the loaded compiler default. Verify parameter roles against instructions and call sites.",
|
||||
"The configured extension retains its actual JAR digest. Its reported source revision is not an attestation of caller-supplied build bytes.",
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,104 @@
|
||||
import { z } from "zod";
|
||||
import type { GhidraExtensionResult } from "../GhidraExtensions.js";
|
||||
|
||||
const report = z
|
||||
.object({
|
||||
id: z.literal("nativeaot"),
|
||||
integration_api: z.literal(1),
|
||||
source_revision: z.literal("effeb734fc570c32650f88b159608979dc7b423e"),
|
||||
source_revision_authority: z.literal("build-reported-unattested"),
|
||||
status: z.enum([
|
||||
"complete",
|
||||
"partial",
|
||||
"not_applicable",
|
||||
"unsupported",
|
||||
"failed",
|
||||
]),
|
||||
reason: z.string().nullable(),
|
||||
method_tables: z.number().int().nonnegative(),
|
||||
diagnostics: z.array(z.string()),
|
||||
header_address: z
|
||||
.string()
|
||||
.regex(/^0x[0-9a-f]+$/u)
|
||||
.optional(),
|
||||
discovery: z.enum(["symbol", "signature-heuristic"]).optional(),
|
||||
format_major: z.number().int().optional(),
|
||||
format_minor: z.number().int().optional(),
|
||||
derived_memory: z
|
||||
.object({
|
||||
address: z.string().regex(/^0x[0-9a-f]+$/u),
|
||||
size_bytes: z.number().int().nonnegative(),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
file_offset: z.null(),
|
||||
})
|
||||
.optional(),
|
||||
coverage: z
|
||||
.strictObject({
|
||||
frozen_object_candidates: z.number().int().nonnegative(),
|
||||
frozen_objects_annotated: z.number().int().nonnegative(),
|
||||
basis: z.literal(
|
||||
"rehydrated-pointer-candidates-and-committed-instance-types",
|
||||
),
|
||||
})
|
||||
.optional(),
|
||||
types: z
|
||||
.array(
|
||||
z.object({
|
||||
address: z.string().regex(/^0x[0-9a-f]+$/u),
|
||||
type: z.string().min(1),
|
||||
}),
|
||||
)
|
||||
.optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
type NativeAotReport = z.infer<typeof report>;
|
||||
|
||||
/** Validate the pinned producer representation before its result enters Evidence. */
|
||||
export const validateNativeAotReport = (
|
||||
value: GhidraExtensionResult,
|
||||
): string | null => {
|
||||
if (
|
||||
value.status === "failed" &&
|
||||
typeof value.result.loader_failure === "string" &&
|
||||
value.result.loader_failure === value.reason
|
||||
)
|
||||
return null;
|
||||
const parsed = report.safeParse(value.result);
|
||||
if (
|
||||
!parsed.success ||
|
||||
parsed.data.status !== value.status ||
|
||||
parsed.data.reason !== value.reason
|
||||
)
|
||||
return "NativeAOT extension returned a malformed or inconsistent producer report.";
|
||||
return validateRecoveredMetadata(parsed.data);
|
||||
};
|
||||
|
||||
const validateRecoveredMetadata = (value: NativeAotReport): string | null => {
|
||||
if (
|
||||
["complete", "partial"].includes(value.status) &&
|
||||
(value.method_tables === 0 ||
|
||||
value.format_major !== 9 ||
|
||||
value.format_minor !== 1 ||
|
||||
value.types?.length !== value.method_tables ||
|
||||
value.derived_memory === undefined ||
|
||||
value.header_address === undefined ||
|
||||
value.discovery === undefined ||
|
||||
value.coverage === undefined ||
|
||||
value.reason !== null)
|
||||
)
|
||||
return "NativeAOT recovery omitted its supported format, method-table inventory or derived-memory identity.";
|
||||
const coverage = value.coverage;
|
||||
if (
|
||||
coverage !== undefined &&
|
||||
(coverage.frozen_objects_annotated > coverage.frozen_object_candidates ||
|
||||
(value.status === "complete" &&
|
||||
coverage.frozen_objects_annotated !==
|
||||
coverage.frozen_object_candidates))
|
||||
)
|
||||
return "NativeAOT recovery coverage contradicts its reported completion status.";
|
||||
const types = value.types ?? [];
|
||||
if (new Set(types.map((type) => type.address)).size !== types.length)
|
||||
return "NativeAOT recovery repeated a method-table identity.";
|
||||
return null;
|
||||
};
|
||||
Reference in New Issue
Block a user