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:
@@ -17,6 +17,11 @@ const environmentSchema = z.object({
|
||||
.min(1)
|
||||
.refine(isAbsolute, "JAVA_HOME must be absolute")
|
||||
.optional(),
|
||||
REA_GHIDRA_NATIVEAOT_JAR: z
|
||||
.string()
|
||||
.min(1)
|
||||
.refine(isAbsolute, "REA_GHIDRA_NATIVEAOT_JAR must be absolute")
|
||||
.optional(),
|
||||
REA_ILSPY_CMD_PATH: z
|
||||
.string()
|
||||
.min(1)
|
||||
|
||||
@@ -27,6 +27,9 @@ export const parseConfig = (
|
||||
analysisProvider: env.REA_ANALYSIS_PROVIDER,
|
||||
ghidraInstallDir: env.GHIDRA_INSTALL_DIR,
|
||||
ghidraJavaHome: env.JAVA_HOME,
|
||||
...(env.REA_GHIDRA_NATIVEAOT_JAR === undefined
|
||||
? {}
|
||||
: { ghidraNativeAotJar: env.REA_GHIDRA_NATIVEAOT_JAR }),
|
||||
ilspyCmdPath: env.REA_ILSPY_CMD_PATH,
|
||||
hopperLauncherPath: env.HOPPER_LAUNCHER_PATH ?? defaultHopperLauncherPath(),
|
||||
hopperTargetPath: env.HOPPER_TARGET_PATH,
|
||||
|
||||
@@ -6,6 +6,7 @@ export interface AppConfig {
|
||||
readonly analysisProvider: AnalysisProviderSelector;
|
||||
readonly ghidraInstallDir: string | undefined;
|
||||
readonly ghidraJavaHome: string | undefined;
|
||||
readonly ghidraNativeAotJar?: string;
|
||||
readonly ilspyCmdPath: string | undefined;
|
||||
readonly hopperLauncherPath: string;
|
||||
readonly hopperTargetPath: string | undefined;
|
||||
|
||||
@@ -199,7 +199,14 @@ describe("analysis error projection: caller contract", () => {
|
||||
"capability_unavailable",
|
||||
"target_unavailable",
|
||||
]);
|
||||
expect(projected[1]).toMatchObject({ category: "unsupported_provider" });
|
||||
expect(projected[1]).toMatchObject({
|
||||
category: "unsupported_provider",
|
||||
details: {
|
||||
provider_id: "fixture",
|
||||
operation: "overview",
|
||||
reason: "absent",
|
||||
},
|
||||
});
|
||||
expect(projected[2]).toMatchObject({
|
||||
details: { path: "/local/targets/app" },
|
||||
});
|
||||
|
||||
@@ -227,7 +227,11 @@ const providerErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof AnalysisCapabilityUnavailableError)
|
||||
return { provider_id: error.providerId, operation: error.operation };
|
||||
return {
|
||||
provider_id: error.providerId,
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
};
|
||||
if (error instanceof ProviderSelectionError)
|
||||
return {
|
||||
operation: error.operation,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { nativeMetadataRecoverySchema } from "./nativeMetadataRecovery.js";
|
||||
|
||||
/** Select a database type by exact category path or a defined typed data address. */
|
||||
export const nativeDataTypeInputSchema = z
|
||||
@@ -54,4 +55,5 @@ export const nativeDataTypeSchema = z.strictObject({
|
||||
total_fields: z.number().int().nonnegative(),
|
||||
truncated: z.boolean(),
|
||||
limitations: z.array(z.string()),
|
||||
metadata_recovery: nativeMetadataRecoverySchema.optional(),
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { nativeMetadataRecoverySummarySchema } from "./nativeMetadataRecovery.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
||||
@@ -8,6 +9,7 @@ const address = z.string().min(1);
|
||||
|
||||
/** Measured provider image, without exporting the complete executable bytes. */
|
||||
export const nativeLoadImageObservationSchema = z.strictObject({
|
||||
metadata_recovery: z.array(nativeMetadataRecoverySummarySchema).optional(),
|
||||
executable_format: z.string().min(1),
|
||||
language_id: z.string().min(1),
|
||||
compiler_spec_id: z.string().min(1),
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
nativeMetadataRecoverySchema,
|
||||
nativeMetadataRecoverySummarySchema,
|
||||
} from "./nativeMetadataRecovery.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
const metadata = {
|
||||
format: "dotnet-nativeaot",
|
||||
status: "partial",
|
||||
header_address: "0x401000",
|
||||
format_major: 9,
|
||||
format_minor: 1,
|
||||
method_table_address: "0x402000",
|
||||
name_origin: "generated",
|
||||
original_name: null,
|
||||
base_size_bytes: 24,
|
||||
related_type: { address: "0x403000", type: null },
|
||||
interfaces: [],
|
||||
virtual_slots: [
|
||||
{
|
||||
slot: 0,
|
||||
slot_address: "0x402018",
|
||||
target_address: null,
|
||||
procedure_name: null,
|
||||
basis: "method-table-pointer",
|
||||
},
|
||||
],
|
||||
derived_memory: {
|
||||
address: "0x402000",
|
||||
size_bytes: 128,
|
||||
sha256: "a".repeat(64),
|
||||
file_offset: null,
|
||||
},
|
||||
diagnostics: ["candidate annotation missing"],
|
||||
limitations: ["Names are generated; original fields unknown"],
|
||||
};
|
||||
describe("NativeAOT recovery evidence", () => {
|
||||
it("preserves generated identities, unresolved relationships and null virtual targets", () => {
|
||||
expect(
|
||||
jsonValueSchema.parse(nativeMetadataRecoverySchema.parse(metadata)),
|
||||
).toEqual(metadata);
|
||||
});
|
||||
it("rejects invented source authority and original file offsets for derived memory", () => {
|
||||
expect(
|
||||
nativeMetadataRecoverySchema.safeParse({
|
||||
...metadata,
|
||||
original_name: "InventedClass",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
nativeMetadataRecoverySchema.safeParse({
|
||||
...metadata,
|
||||
derived_memory: { ...metadata.derived_memory, file_offset: 128 },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
it("keeps a negative discovery explicit without fabricating a header", () => {
|
||||
const summary = {
|
||||
format: "dotnet-nativeaot",
|
||||
status: "not_applicable",
|
||||
reason: "No supported row layout found",
|
||||
analysis_artifact_sha256: "b".repeat(64),
|
||||
header_address: null,
|
||||
discovery: null,
|
||||
format_major: null,
|
||||
format_minor: null,
|
||||
method_tables: 0,
|
||||
types: [],
|
||||
derived_memory: null,
|
||||
coverage: null,
|
||||
diagnostics: [],
|
||||
limitations: [],
|
||||
};
|
||||
expect(nativeMetadataRecoverySummarySchema.parse(summary)).toEqual(summary);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const address = z.string().regex(/^0x[0-9a-f]+$/u);
|
||||
const relatedType = z.strictObject({ address, type: z.string().nullable() });
|
||||
|
||||
/** Runtime-format metadata recovered in an analysis image, with explicit inference boundaries. */
|
||||
export const nativeMetadataRecoverySchema = z.strictObject({
|
||||
format: z.literal("dotnet-nativeaot"),
|
||||
status: z.enum(["complete", "partial"]),
|
||||
header_address: address,
|
||||
format_major: z.number().int().nonnegative(),
|
||||
format_minor: z.number().int().nonnegative(),
|
||||
method_table_address: address,
|
||||
name_origin: z.enum(["generated", "inferred"]),
|
||||
original_name: z.null(),
|
||||
base_size_bytes: z.number().int().nonnegative(),
|
||||
related_type: relatedType.nullable(),
|
||||
interfaces: z.array(relatedType),
|
||||
virtual_slots: z.array(
|
||||
z.strictObject({
|
||||
slot: z.number().int().nonnegative(),
|
||||
slot_address: address,
|
||||
target_address: address.nullable(),
|
||||
procedure_name: z.string().nullable(),
|
||||
basis: z.literal("method-table-pointer"),
|
||||
}),
|
||||
),
|
||||
derived_memory: z.strictObject({
|
||||
address,
|
||||
size_bytes: z.number().int().nonnegative(),
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
file_offset: z.null(),
|
||||
}),
|
||||
diagnostics: z.array(z.string()),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
|
||||
/** Discover a recovered runtime format and reusable type identities from the loaded image. */
|
||||
export const nativeMetadataRecoverySummarySchema = z.strictObject({
|
||||
format: z.literal("dotnet-nativeaot"),
|
||||
status: z.enum(["complete", "partial", "not_applicable"]),
|
||||
reason: z.string().nullable(),
|
||||
analysis_artifact_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
header_address: address.nullable(),
|
||||
discovery: z.enum(["symbol", "signature-heuristic"]).nullable(),
|
||||
format_major: z.number().int().nonnegative().nullable(),
|
||||
format_minor: z.number().int().nonnegative().nullable(),
|
||||
method_tables: z.number().int().nonnegative(),
|
||||
types: z.array(relatedType),
|
||||
derived_memory: nativeMetadataRecoverySchema.shape.derived_memory.nullable(),
|
||||
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",
|
||||
),
|
||||
})
|
||||
.nullable(),
|
||||
diagnostics: z.array(z.string()),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
@@ -19,7 +19,11 @@ import {
|
||||
functionDossierSchema,
|
||||
type FunctionDossier,
|
||||
} from "../domain/hopperValues.js";
|
||||
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../domain/jsonValue.js";
|
||||
import { nativeApiBoundarySchema } from "../domain/nativeApiBoundary.js";
|
||||
import { nativeValueFlowSchema } from "../domain/nativeValueFlow.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
@@ -386,7 +390,7 @@ export const parseGhidraFunctionResult = (
|
||||
): Result<JsonValue, AnalysisOutputError> => {
|
||||
const parsed = resultSchemas[operation].safeParse(value);
|
||||
return parsed.success
|
||||
? ok(parsed.data)
|
||||
? ok(jsonValueSchema.parse(parsed.data))
|
||||
: err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
functionBodySchema,
|
||||
functionBodyEntryAgrees,
|
||||
} from "../domain/hopperValues.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Read-only direct inventory operations admitted by the Ghidra adapter. */
|
||||
@@ -274,7 +274,7 @@ export const parseGhidraInventoryResult = (
|
||||
): Result<JsonValue, AnalysisOutputError> => {
|
||||
const parsed = resultSchemas[operation].safeParse(value);
|
||||
return parsed.success
|
||||
? ok(parsed.data)
|
||||
? ok(jsonValueSchema.parse(parsed.data))
|
||||
: err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
|
||||
@@ -19,6 +19,10 @@ import {
|
||||
} from "../process/ProviderProcess.js";
|
||||
import { ghidraJavaEnvironment } from "./GhidraInstallation.js";
|
||||
import type { GhidraTransportKind } from "./GhidraTransport.js";
|
||||
import {
|
||||
snapshotGhidraExtensions,
|
||||
type GhidraExtension,
|
||||
} from "./extensions/GhidraExtensions.js";
|
||||
|
||||
/** Private paths and identity material for one headless Ghidra import. */
|
||||
export interface GhidraLaunchSession {
|
||||
@@ -66,6 +70,7 @@ export interface GhidraHeadlessLauncherOptions {
|
||||
/** Select the admitted 16-bit real-mode MZ import instead of auto-detection. */
|
||||
readonly dosMz?: true;
|
||||
readonly dosCom?: true;
|
||||
readonly analysisExtensions?: readonly GhidraExtension[];
|
||||
}
|
||||
|
||||
/** Launch Ghidra without copying scripts into or modifying its installation. */
|
||||
@@ -83,6 +88,10 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
let started: SpawnedOwnedProviderProcess | undefined;
|
||||
try {
|
||||
await createGhidraRuntimeDirectories(paths, platform);
|
||||
const extensions = await snapshotGhidraExtensions(
|
||||
this.options.analysisExtensions ?? [],
|
||||
session.runtimeRoot,
|
||||
);
|
||||
await writeGhidraRuntimeFile(
|
||||
paths.descriptorPath,
|
||||
`${JSON.stringify({
|
||||
@@ -93,6 +102,9 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
target_sha256: session.targetSha256,
|
||||
provider_version: session.providerVersion,
|
||||
profile_digest: session.profileDigest,
|
||||
...(extensions.length === 0
|
||||
? {}
|
||||
: { analysis_extensions: extensions }),
|
||||
})}\n`,
|
||||
platform,
|
||||
);
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { createHash } from "node:crypto";
|
||||
// Fake-backed provider coverage; real Ghidra verification lives in
|
||||
// `npm run verify:ghidra` and its focused variants.
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fixtureDosLoadImage } from "./GhidraLoadImage.fixture.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
@@ -688,3 +692,102 @@ const peTarget = (
|
||||
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();
|
||||
},
|
||||
}),
|
||||
);
|
||||
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 });
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ghidraExtensionFailure } from "./extensions/GhidraExtensionFailures.js";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import {
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { AppConfig } from "../config.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import { createAnalysisProfile } from "../domain/analysisProfile.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import {
|
||||
jsonObjectSchema,
|
||||
@@ -60,6 +62,13 @@ import {
|
||||
import { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
|
||||
import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
|
||||
import type { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
import type { GhidraSessionInfo } from "./GhidraSessionValues.js";
|
||||
import {
|
||||
ghidraExtensionSchema,
|
||||
resolveGhidraExtensions,
|
||||
validateGhidraExtensionProfile,
|
||||
ghidraExtensionLimitations,
|
||||
} from "./extensions/GhidraExtensions.js";
|
||||
import {
|
||||
CAPABILITIES,
|
||||
windowsP0Capabilities,
|
||||
@@ -188,16 +197,33 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
};
|
||||
}
|
||||
|
||||
resolveAnalysisProfile(
|
||||
async resolveAnalysisProfile(
|
||||
target: BinaryTarget,
|
||||
options?: AnalysisProfileResolutionOptions,
|
||||
) {
|
||||
return resolveGhidraAnalysisProfile(
|
||||
const installation = this.#inspectInstallation();
|
||||
const resolved = await resolveGhidraAnalysisProfile(
|
||||
target,
|
||||
GHIDRA_PROVIDER_IDENTITY,
|
||||
this.#inspectInstallation(),
|
||||
installation,
|
||||
options?.signal,
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null) return resolved;
|
||||
const extensions = await resolveGhidraExtensions(
|
||||
this.config,
|
||||
target,
|
||||
installation.platform,
|
||||
options?.signal,
|
||||
);
|
||||
if (!extensions.ok) return extensions;
|
||||
if (extensions.value.length === 0) return resolved;
|
||||
return ok({
|
||||
...resolved.value,
|
||||
profile: createAnalysisProfile(resolved.value.profile.provider, {
|
||||
...resolved.value.profile.parameters,
|
||||
analysis_extensions: jsonValueSchema.parse(extensions.value),
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
createClient(
|
||||
@@ -213,6 +239,36 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
);
|
||||
if (!prerequisites.ok) return unavailableClient(prerequisites.error);
|
||||
const committedProfile = prerequisites.value.profile;
|
||||
const extensionProfile = ghidraExtensionSchema
|
||||
.array()
|
||||
.safeParse(committedProfile.parameters.analysis_extensions ?? []);
|
||||
if (
|
||||
!extensionProfile.success ||
|
||||
(this.config.ghidraNativeAotJar !== undefined &&
|
||||
extensionProfile.data.length === 0)
|
||||
)
|
||||
return unavailableClient(
|
||||
new ProviderAdapterError("ghidra", "open_binary", {
|
||||
diagnostics: {
|
||||
reason:
|
||||
"Resolve the configured Ghidra extensions into an analysis profile before opening the session.",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const extensions = extensionProfile.data;
|
||||
const invalidProfile = validateGhidraExtensionProfile(
|
||||
extensions,
|
||||
this.config,
|
||||
target,
|
||||
installation.platform,
|
||||
);
|
||||
if (invalidProfile !== null)
|
||||
return unavailableClient(
|
||||
new ProviderAdapterError("ghidra", "open_binary", {
|
||||
diagnostics: { reason: invalidProfile },
|
||||
}),
|
||||
);
|
||||
let extensionFailure: AnalysisError | undefined;
|
||||
const targetLimitations =
|
||||
target.format === "dos-mz"
|
||||
? [
|
||||
@@ -241,6 +297,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
...(target.format === "dos-mz" ? { dosMz: true } : {}),
|
||||
...(target.format === "dos-com" ? { dosCom: true } : {}),
|
||||
platform: installation.platform,
|
||||
...(extensions.length === 0 ? {} : { analysisExtensions: extensions }),
|
||||
}),
|
||||
targetPath:
|
||||
installation.platform === "win32"
|
||||
@@ -262,8 +319,22 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
...(context === undefined ? {} : { runId: context.runId }),
|
||||
logger: this.logger.child({ layer: "ghidra-bridge" }),
|
||||
});
|
||||
const checkExtensions = async (
|
||||
operation: AnalysisOperation,
|
||||
info: GhidraSessionInfo,
|
||||
): Promise<AnalysisError | undefined> => {
|
||||
extensionFailure = ghidraExtensionFailure(
|
||||
extensions,
|
||||
info.analysis_extensions ?? [],
|
||||
operation,
|
||||
);
|
||||
if (extensionFailure === undefined) return undefined;
|
||||
await client.close();
|
||||
return extensionFailure;
|
||||
};
|
||||
return {
|
||||
execute: async (operation, parameters, options) => {
|
||||
if (extensionFailure !== undefined) return err(extensionFailure);
|
||||
if (
|
||||
operation !== "health" &&
|
||||
!isGhidraInventoryOperation(operation) &&
|
||||
@@ -280,6 +351,8 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
const started = await client.start(options?.signal);
|
||||
if (!started.ok)
|
||||
return err(projectSessionError(operation, started.error));
|
||||
const failed = await checkExtensions(operation, started.value);
|
||||
if (failed !== undefined) return err(failed);
|
||||
return ok(
|
||||
createAnalysisExecution(started.value, committedProfile.provider, {
|
||||
analysisProfile: committedProfile,
|
||||
@@ -287,6 +360,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
...healthLimitations,
|
||||
...providerLimitations,
|
||||
...targetLimitations,
|
||||
...ghidraExtensionLimitations(extensions),
|
||||
],
|
||||
}),
|
||||
);
|
||||
@@ -295,6 +369,13 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
? parseGhidraFunctionInput(operation, parameters)
|
||||
: parseGhidraInventoryInput(operation, parameters);
|
||||
if (!input.ok) return input;
|
||||
if (extensions.length > 0) {
|
||||
const started = await client.start(options?.signal);
|
||||
if (!started.ok)
|
||||
return err(projectSessionError(operation, started.error));
|
||||
const failed = await checkExtensions(operation, started.value);
|
||||
if (failed !== undefined) return err(failed);
|
||||
}
|
||||
const called = await client.callTool(
|
||||
operation,
|
||||
input.value,
|
||||
@@ -358,6 +439,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
...limitationsFor(operation),
|
||||
...providerLimitations,
|
||||
...targetLimitations,
|
||||
...ghidraExtensionLimitations(extensions),
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { GHIDRA_INVENTORY_OPERATIONS } from "./GhidraInventoryValues.js";
|
||||
import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionValues.js";
|
||||
import { ghidraExtensionResultSchema } from "./extensions/GhidraExtensions.js";
|
||||
|
||||
/** Exact methods proved by the bridge handshake after auto-analysis. */
|
||||
export const GHIDRA_SESSION_CAPABILITIES = [
|
||||
@@ -29,6 +30,7 @@ const sessionInfoSchema = z
|
||||
read_only: z.boolean(),
|
||||
analysis_complete: z.boolean(),
|
||||
analysis_timed_out: z.boolean(),
|
||||
analysis_extensions: z.array(ghidraExtensionResultSchema).optional(),
|
||||
capabilities: z.array(capabilitySchema),
|
||||
target: z
|
||||
.object({
|
||||
|
||||
@@ -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