feat(native): admit raw binaries with caller-supplied architecture and entry (#1868)

* feat(native): admit raw binaries with caller-supplied architecture and entry

* fix(native): honor raw-binary preparation and entry identity

* fix(ghidra): stream raw snapshot attestation with cancellation

* fix(native): preserve and validate raw lifecycle entries

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Matt Van Horn
2026-10-12 00:06:29 +08:00
committed by GitHub
co-authored by morluto
parent d3e83b0899
commit 7c207c7951
57 changed files with 2453 additions and 336 deletions
+52
View File
@@ -14,6 +14,7 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import type { GhidraInstallationInspection } from "./GhidraInstallation.js";
import { ghidraMipsProfileParameters } from "./GhidraMipsProfile.js";
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
import {
ghidraProcessorUnsupportedReason,
@@ -69,6 +70,57 @@ export const resolveGhidraAnalysisProfile = async (
: null;
if (pspExtension !== null && !pspExtension.ok) return pspExtension;
const provider = { ...identity, version: installation.providerVersion };
if (target.format === "raw-binary") {
if (languageOverride !== undefined)
return Promise.resolve(
err(
new AnalysisUnsupportedTargetError(
"resolve_analysis_profile",
target.path,
"REA_GHIDRA_LANGUAGE_ID cannot override the admitted raw-binary import.",
),
),
);
const language = ghidraRawBinaryLanguage(target.architecture);
return Promise.resolve(
ok({
profile: createAnalysisProfile(provider, {
target_kind: target.kind,
target_format: target.format,
architecture: target.architecture,
available_architectures: [...target.availableArchitectures].sort(),
import_mode: "ephemeral-source-immutable",
annotation_policy: "atomic-function-entry-metadata-v1",
load_image_observations: "source-mappings-entry-context-v2",
function_body_evidence: "complete-inclusive-ranges-v1",
function_references: "complete-body-and-entry-reference-manager-v2",
string_inventory_evidence: "defined-data-coverage-v1",
location_resolution: "explicit-address-exact-entry-symbol-first-v3",
instruction_flow_evidence: "decoded-return-pcode-v1",
instruction_references: "exact-address-incoming-v1",
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
no_return_repair:
installation.platform === "win32"
? "disabled-windows-p0"
: "returning-imports-decoded-return-v2",
process_launch:
installation.platform === "win32"
? "official-headless-script-v1"
: "inspected-jvm-launch-support-v1",
load_image_evidence: "independent-raw-mapping-context-v2",
jump_table_evidence: "typed-case-default-blocks-v1",
decompiler_jump_loads: true,
loader: "BinaryLoader",
language_id: language.languageId,
compiler_spec_id: language.compilerSpecId,
language_selection: "caller-supplied-v1",
entry_point: target.entryPoint,
entry_seed: "external-entry-and-function-before-analysis-v1",
analyzer_preset: "ghidra-default",
}),
}),
);
}
const dosMz = target.format === "dos-mz";
const dosCom = target.format === "dos-com";
const dos = dosMz || dosCom;
+96 -74
View File
@@ -1,4 +1,6 @@
import { randomBytes, randomUUID } from "node:crypto";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import type { Stats } from "node:fs";
import type { FileHandle } from "node:fs/promises";
import type { Socket } from "node:net";
import type { ProgressReporter } from "../application/ProgressReporter.js";
@@ -43,11 +45,12 @@ import {
type GhidraSessionInfo,
} from "./GhidraSessionValues.js";
import { createGhidraTargetSnapshot } from "./GhidraTargetSnapshot.js";
import { readFile } from "node:fs/promises";
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
import {
openRegularFile,
RegularFileChangedError,
RegularFileAdmissionFailure,
sameRegularFileState,
} from "../filesystem/RegularFile.js";
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
@@ -286,12 +289,66 @@ export class GhidraClient {
);
}
/** Read the private immutable source for independent import verification. */
async readTargetSnapshot(
/** Read the private immutable source for format parsers that require captured bytes. */
readTargetSnapshot(
maximumBytes?: number,
signal?: AbortSignal,
): Promise<Result<GhidraTargetSnapshot, GhidraSessionError>> {
if (this.#snapshotPath === undefined)
return this.#withTargetSnapshot(async (handle, initial, path) => {
if (
maximumBytes !== undefined &&
(!Number.isSafeInteger(maximumBytes) || maximumBytes < 0)
)
throw new RangeError("Snapshot byte limit must be a safe integer");
if (maximumBytes !== undefined && initial.size > maximumBytes)
return {
kind: "over-capacity",
sourceBytesAtLeast: initial.size,
maximumBytes,
};
const bytes = await readBoundedFileBytes(
handle,
maximumBytes ?? initial.size,
signal,
initial.size,
);
if (bytes === undefined || bytes.length !== initial.size)
throw new RegularFileChangedError(path);
return { kind: "captured", bytes };
}, signal);
}
/** Measure the complete snapshot identity without retaining its bytes in memory. */
hashTargetSnapshot(
signal?: AbortSignal,
): Promise<
Result<
{ readonly sha256: string; readonly bytes: number },
GhidraSessionError
>
> {
return this.#withTargetSnapshot(async (handle, initial, path) => {
const hash = createHash("sha256");
let bytes = 0;
for await (const chunk of readFileHandleChunks(handle, {
end: initial.size,
signal,
})) {
bytes += chunk.length;
if (bytes > initial.size) throw new RegularFileChangedError(path);
hash.update(chunk);
}
if (bytes !== initial.size) throw new RegularFileChangedError(path);
return { sha256: hash.digest("hex"), bytes };
}, signal);
}
async #withTargetSnapshot<T>(
read: (handle: FileHandle, initial: Stats, path: string) => Promise<T>,
signal?: AbortSignal,
): Promise<Result<T, GhidraSessionError>> {
const path = this.#snapshotPath;
if (path === undefined)
return err(
this.#failure(
"protocol",
@@ -299,77 +356,42 @@ export class GhidraClient {
),
);
try {
if (maximumBytes !== undefined) {
signal?.throwIfAborted();
if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0)
throw new RangeError("Snapshot byte limit must be a safe integer");
const handle = await openRegularFile(this.#snapshotPath, {
symlinks: "reject",
});
const owner = new OwnedFileHandle(handle);
this.#snapshotOwners.add(owner);
let result: GhidraTargetSnapshot;
let readFailure: unknown;
try {
const metadata = await handle.stat();
signal?.throwIfAborted();
if (metadata.size > maximumBytes)
result = {
kind: "over-capacity",
sourceBytesAtLeast: metadata.size,
maximumBytes,
};
else {
const bytes = await readBoundedFileBytes(
handle,
maximumBytes,
signal,
metadata.size,
);
signal?.throwIfAborted();
const after = await handle.stat();
if (
bytes !== undefined &&
bytes.length === metadata.size &&
sameRegularFileState(metadata, after)
) {
result = { kind: "captured", bytes };
} else if (
bytes === undefined &&
after.isFile() &&
after.size > maximumBytes
) {
result = {
kind: "over-capacity",
sourceBytesAtLeast: after.size,
maximumBytes,
};
} else {
throw new RegularFileChangedError(this.#snapshotPath);
}
}
} catch (cause: unknown) {
readFailure = cause;
}
try {
await owner.close();
this.#snapshotOwners.delete(owner);
} catch (closeFailure: unknown) {
throw new AggregateError(
readFailure === undefined
? [closeFailure]
: [readFailure, closeFailure],
"Ghidra target snapshot read or descriptor cleanup failed",
);
}
if (readFailure !== undefined) throw readFailure;
return ok(result!);
}
return ok({
kind: "captured",
bytes: await readFile(this.#snapshotPath),
const handle = await openRegularFile(path, {
symlinks: "reject",
signal,
});
const owner = new OwnedFileHandle(handle);
this.#snapshotOwners.add(owner);
let result: Result<T, unknown>;
try {
const initial = await handle.stat();
signal?.throwIfAborted();
if (!Number.isSafeInteger(initial.size) || initial.size < 0)
throw new RangeError("Snapshot size must be a safe integer");
const value = await read(handle, initial, path);
signal?.throwIfAborted();
const after = await handle.stat();
signal?.throwIfAborted();
if (!sameRegularFileState(initial, after))
throw new RegularFileChangedError(path);
result = ok(value);
} catch (cause: unknown) {
result = err(cause);
}
try {
await owner.close();
this.#snapshotOwners.delete(owner);
} catch (closeFailure: unknown) {
throw new AggregateError(
result.ok ? [closeFailure] : [result.error, closeFailure],
"Ghidra target snapshot read or descriptor cleanup failed",
);
}
if (!result.ok) throw result.error;
return result;
} catch (cause: unknown) {
if (cause instanceof RegularFileAdmissionFailure)
this.#snapshotOwners.add(cause.owner);
return err(
this.#failure(
signal?.aborted === true ? "cancelled" : "protocol",
+63 -15
View File
@@ -101,6 +101,11 @@ export interface GhidraHeadlessLauncherOptions {
/** Select the admitted 16-bit real-mode MZ import instead of auto-detection. */
readonly dosMz?: true;
readonly dosCom?: true;
readonly rawBinary?: {
readonly languageId: string;
readonly compilerSpecId: string;
readonly baseAddr: string;
};
/** Explicit import language committed by the analysis profile. */
readonly languageOverride?: GhidraLanguageOverride;
/** Caller seeds committed by the analysis profile, applied before analysis. */
@@ -201,6 +206,9 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
...(this.options.dosMz === undefined
? {}
: { dosMz: this.options.dosMz }),
...(this.options.rawBinary === undefined
? {}
: { rawBinary: this.options.rawBinary }),
...(this.options.languageOverride === undefined
? {}
: { languageOverride: this.options.languageOverride }),
@@ -411,6 +419,11 @@ export interface GhidraHeadlessArgumentOptions {
readonly psp?: true;
readonly dosMz?: true;
readonly dosCom?: true;
readonly rawBinary?: {
readonly languageId: string;
readonly compilerSpecId: string;
readonly baseAddr: string;
};
readonly languageOverride?: GhidraLanguageOverride;
/** Canonical seed snapshot passed to the pre-analysis seed script. */
readonly seedPath?: string;
@@ -426,6 +439,7 @@ export const ghidraHeadlessArguments = (
(options.platform ?? process.platform) === "win32" ? win32 : posix;
const bridgeDirectory = scriptPath.dirname(options.bridgeScriptPath);
const override = options.languageOverride;
const rawBinary = options.rawBinary;
if (
options.psp === true &&
(options.dosMz === true ||
@@ -435,6 +449,10 @@ export const ghidraHeadlessArguments = (
throw new Error(
"A PSP ELF import cannot be combined with DOS or a generic Ghidra language override.",
);
if (options.psp === true && rawBinary !== undefined)
throw new Error(
"A PSP ELF import cannot be combined with a raw-binary import.",
);
if (
override !== undefined &&
(options.dosMz === true || options.dosCom === true)
@@ -442,6 +460,17 @@ export const ghidraHeadlessArguments = (
throw new Error(
"A Ghidra language override cannot be combined with a DOS import.",
);
if (override !== undefined && rawBinary !== undefined)
throw new Error(
"A Ghidra language override cannot be combined with a raw-binary import.",
);
if (
rawBinary !== undefined &&
(options.dosMz === true || options.dosCom === true)
)
throw new Error(
"A raw-binary import cannot be combined with a DOS import.",
);
return [
options.projectRoot,
"rea-project",
@@ -467,24 +496,35 @@ export const ghidraHeadlessArguments = (
"-cspec",
"default",
]
: options.psp === true
? [
"-loader",
"PspElfLoader",
"-processor",
"Allegrex:LE:32:default",
"-cspec",
"default",
]
: override !== undefined
: rawBinary === undefined
? options.psp === true
? [
"-loader",
"PspElfLoader",
"-processor",
override.languageId,
...(override.compilerSpecId === undefined
? []
: ["-cspec", override.compilerSpecId]),
"Allegrex:LE:32:default",
"-cspec",
"default",
]
: []),
: override !== undefined
? [
"-processor",
override.languageId,
...(override.compilerSpecId === undefined
? []
: ["-cspec", override.compilerSpecId]),
]
: []
: [
"-loader",
"BinaryLoader",
"-loader-baseAddr",
rawBinary.baseAddr,
"-processor",
rawBinary.languageId,
"-cspec",
rawBinary.compilerSpecId,
]),
"-readOnly",
"-deleteProject",
"-log",
@@ -499,6 +539,14 @@ export const ghidraHeadlessArguments = (
scriptPath.join(bridgeDirectory, "ReaGhidraPrepareCom.java"),
]
: []),
...(rawBinary === undefined
? []
: [
"-preScript",
scriptPath.join(bridgeDirectory, "ReaGhidraPrepareRaw.java"),
rawBinary.languageId,
rawBinary.baseAddr,
]),
// Seeds follow any loader preparation and precede default auto-analysis.
...(options.seedPath === undefined
? []
+42 -13
View File
@@ -12,17 +12,15 @@ import { err, ok, type Result } from "../domain/result.js";
import {
attestGhidraDosComLoadImage,
attestGhidraDosLoadImage,
attestGhidraRawBinaryLoadImage,
} from "./GhidraLoadImageValues.js";
import type { NativeAotPeResult } from "../domain/native/nativeAotPe.js";
import type { GhidraTargetSnapshot } from "./GhidraClient.js";
import type { GhidraClient } from "./GhidraClient.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
type LoadImageSnapshotClient = {
readonly readTargetSnapshot?: (
maximumBytes?: number,
signal?: AbortSignal,
) => Promise<Result<GhidraTargetSnapshot, GhidraSessionError>>;
};
type LoadImageSnapshotClient = Partial<
Pick<GhidraClient, "hashTargetSnapshot" | "readTargetSnapshot">
>;
type NativeLoadImageAttestationInput = {
readonly target: BinaryTarget;
@@ -37,7 +35,7 @@ type NativeLoadImageAttestationInput = {
const isSignalAborted = (signal: AbortSignal | undefined): boolean =>
signal?.aborted === true;
/** Independently verify measured load-image observations for admitted DOS targets. */
/** Independently verify measured load-image observations for admitted DOS and raw-binary targets. */
export const attestGhidraNativeLoadImage = async (
input: NativeLoadImageAttestationInput,
): Promise<Result<JsonValue, AnalysisError>> => {
@@ -71,7 +69,7 @@ export const attestGhidraNativeLoadImage = async (
nativeLoadImageSchema.parse({
status: "unsupported",
reason:
"Independent load-image verification currently supports DOS MZ and explicit DOS COM targets only.",
"Independent load-image verification currently supports DOS MZ, explicit DOS COM, and caller-supplied raw-binary targets only.",
observations: {
...observations,
metadata_recovery: [
@@ -98,13 +96,17 @@ export const attestGhidraNativeLoadImage = async (
);
}
}
if (target.format !== "dos-mz" && target.format !== "dos-com") {
if (
target.format !== "dos-mz" &&
target.format !== "dos-com" &&
target.format !== "raw-binary"
) {
return ok(
jsonValueSchema.parse(
nativeLoadImageSchema.parse({
status: "unsupported",
reason:
"Independent load-image verification currently supports DOS MZ and explicit DOS COM targets only.",
"Independent load-image verification currently supports DOS MZ, explicit DOS COM, and caller-supplied raw-binary targets only.",
observations,
limitations: [
"Other formats expose measured mappings and source identities; no format-specific verification was performed.",
@@ -113,6 +115,33 @@ export const attestGhidraNativeLoadImage = async (
),
);
}
if (target.format === "raw-binary") {
if (client.hashTargetSnapshot === undefined)
return err(
new ProviderAdapterError("ghidra", operation, {
diagnostics: {
reason:
"The Ghidra client does not expose its immutable target snapshot identity for independent raw-binary load-image verification.",
},
}),
);
const snapshot = await client.hashTargetSnapshot(signal);
if (!snapshot.ok) return err(mapSessionError(snapshot.error));
if (isSignalAborted(signal))
return err(new AnalysisCancelledError(operation));
const attested = attestGhidraRawBinaryLoadImage(
snapshot.value,
target,
observations,
);
return attested.ok
? ok(jsonValueSchema.parse(attested.value))
: err(
new ProviderAdapterError("ghidra", operation, {
diagnostics: { reason: attested.error },
}),
);
}
if (client.readTargetSnapshot === undefined)
return err(
new ProviderAdapterError("ghidra", operation, {
@@ -122,14 +151,14 @@ export const attestGhidraNativeLoadImage = async (
},
}),
);
const snapshot = await client.readTargetSnapshot();
const snapshot = await client.readTargetSnapshot(undefined, signal);
if (!snapshot.ok) return err(mapSessionError(snapshot.error));
if (snapshot.value.kind !== "captured")
return err(
new ProviderAdapterError("ghidra", operation, {
diagnostics: {
reason:
"The uncapped DOS load-image snapshot was unexpectedly not captured.",
"The uncapped load-image snapshot was unexpectedly not captured.",
},
}),
);
+110
View File
@@ -7,8 +7,10 @@ import {
} from "../domain/native/nativeLoadImage.js";
import { parseDosMzHeader, type DosMzHeader } from "../domain/dosMz.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { validateDosComLength } from "../domain/dosCom.js";
import { err, ok, type Result } from "../domain/result.js";
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
const sha256 = (bytes: Buffer): string =>
createHash("sha256").update(bytes).digest("hex");
@@ -325,3 +327,111 @@ export const attestGhidraDosComLoadImage = (
}),
);
};
const hexAddress = (value: bigint): string => `0x${value.toString(16)}`;
/** Verify a caller-supplied raw-binary mapping against measured Ghidra import facts. */
export const attestGhidraRawBinaryLoadImage = (
snapshot: { readonly sha256: string; readonly bytes: number },
target: Extract<BinaryTarget, { format: "raw-binary" }>,
observations: NativeLoadImageObservation,
): Result<NativeLoadImage, string> => {
if (snapshot.sha256 !== target.sha256)
return err(
"Ghidra raw-binary snapshot digest does not match the admitted target",
);
const language = ghidraRawBinaryLanguage(target.architecture);
const base = BigInt(target.entryPoint);
const last = hexAddress(base + BigInt(snapshot.bytes) - 1n);
const checks: NativeLoadImageCheck[] = [];
const check = (
name: string,
expected: JsonValue,
observed: JsonValue,
fileOffset: number | null = null,
location: string | null = null,
): void => {
checks.push({
name,
matched: JSON.stringify(expected) === JSON.stringify(observed),
expected,
observed,
file_offset: fileOffset,
address: location,
});
};
const source = observations.source_files[0];
const mapping = observations.mappings[0];
check("executable_format", "Raw Binary", observations.executable_format);
check("language_id", language.languageId, observations.language_id);
check(
"compiler_spec_id",
language.compilerSpecId,
observations.compiler_spec_id,
);
// BinaryLoader's block base is independent of the Program image base.
check("image_base", "0x0", observations.image_base);
check("source_file_count", 1, observations.source_files.length);
check("source_file_size", snapshot.bytes, source?.size ?? null);
check("original_file_sha256", target.sha256, source?.original_sha256 ?? null);
check("modified_file_sha256", target.sha256, source?.modified_sha256 ?? null);
check("mapping_count", 1, observations.mappings.length);
check(
"mapping.file_offset",
0,
mapping?.file_offset ?? null,
0,
mapping?.start ?? null,
);
check(
"mapping.start",
target.entryPoint,
mapping?.start ?? null,
0,
mapping?.start ?? null,
);
check("mapping.end", last, mapping?.end ?? null, 0, mapping?.end ?? null);
check(
"mapping.length",
snapshot.bytes,
mapping?.length ?? null,
0,
mapping?.start ?? null,
);
check(
"mapping.sha256",
snapshot.sha256,
mapping?.sha256 ?? null,
0,
mapping?.start ?? null,
);
check(
"entry_point",
target.entryPoint,
observations.entry_points.find((entry) => entry === target.entryPoint) ??
null,
);
check("relocation_records", [], observations.relocations);
return ok(
nativeLoadImageSchema.parse({
status: checks.every((item) => item.matched) ? "verified" : "mismatch",
format: "raw-binary",
target_sha256: target.sha256,
architecture: target.architecture,
language_id: language.languageId,
compiler_spec_id: language.compilerSpecId,
base_address: target.entryPoint,
file_bytes: snapshot.bytes,
entry: { address: target.entryPoint, file_offset: 0 },
observations,
checks,
limitations: [
"Raw binary is a headerless interpretation explicitly selected by the caller, not format identification from file bytes.",
"Verification covers complete original/modified source identity, mapped file bytes, the caller-supplied entry, and the bound little-endian Ghidra language. File offset 0 is mapped at the entry address.",
"Ghidra may report additional language-defined external entries outside the mapped image. They are preserved as observations; verification requires the caller-supplied entry and does not attest other entries.",
"Reset vectors, memory-mapped I/O, big-endian and Thumb-only variants, and runtime boot behavior are not modeled or verified. No original executable bytes are changed.",
"Mapping ends are inclusive; a mismatching digest identifies its source range, not the first differing byte.",
],
}),
);
};
+127
View File
@@ -10,6 +10,7 @@ import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { describe, expect, it } from "vitest";
import { fixtureDosLoadImage } from "./GhidraLoadImage.fixture.js";
import { fixtureRawBinaryLoadImage } from "./GhidraRawBinaryLoadImage.fixture.js";
import {
nativeAotPeDigest,
nativeAotPeFixture,
@@ -177,6 +178,50 @@ describe("Ghidra provider", () => {
});
});
describe("Ghidra raw-binary profile", () => {
it("commits BinaryLoader language and caller-supplied entry", async () => {
const ghidra = provider();
const target: BinaryTarget = {
path: "/tmp/ecu.bin",
sha256: "a".repeat(64),
kind: "executable",
format: "raw-binary",
architecture: "arm",
availableArchitectures: ["arm"],
entryPoint: "0x8000000",
entryPointSource: "0x08000000",
};
expect(ghidra.inspectTargetSupport(target).status).toBe("supported");
const resolved = await ghidra.resolveAnalysisProfile(target);
expect(resolved.ok && resolved.value).toMatchObject({
profile: {
parameters: {
target_format: "raw-binary",
architecture: "arm",
loader: "BinaryLoader",
language_id: "ARM:LE:32:v7",
compiler_spec_id: "default",
language_selection: "caller-supplied-v1",
entry_point: "0x8000000",
},
},
});
const shifted = await ghidra.resolveAnalysisProfile({
...target,
entryPoint: "0x8001000",
entryPointSource: "0x8001000",
});
expect(resolved.ok && shifted.ok).toBe(true);
if (!resolved.ok || !shifted.ok || resolved.value.profile === null)
throw new Error("expected raw-binary profiles");
expect(shifted.value.profile?.digest).not.toBe(
resolved.value.profile.digest,
);
const windows = provider({ ...installationHost(), platform: "win32" });
expect(windows.inspectTargetSupport(target).status).toBe("unsupported");
});
});
describe("Ghidra Mach-O slice support", () => {
it("refuses universal targets whose selected slice cannot be enforced", () => {
const ghidra = provider();
@@ -718,6 +763,88 @@ describe("Ghidra result projection", () => {
});
describe("Ghidra measured load-image projection", () => {
it.each(["verified", "changed-snapshot", "cancelled"] as const)(
"streams raw snapshot identity and preserves %s outcomes",
async (state) => {
const fixture = fixtureRawBinaryLoadImage();
const controller = new AbortController();
const signals: (AbortSignal | undefined)[] = [];
const ghidra = provider(installationHost(), () => ({
start: () => Promise.resolve(ok(sessionInfo())),
callTool: (operation) => {
if (operation !== "inspect_native_load_image")
throw new Error(`unexpected operation ${operation}`);
return Promise.resolve(
ok(jsonValueSchema.parse(fixture.observation)),
);
},
readTargetSnapshot: () => {
throw new Error(
"raw verification must not capture the complete file",
);
},
hashTargetSnapshot: (signal) => {
signals.push(signal);
if (state === "cancelled") {
controller.abort();
return Promise.resolve(
err(
new GhidraSessionError(
"cancelled",
"Snapshot hashing cancelled",
),
),
);
}
return Promise.resolve(
ok({
...fixture.snapshot,
...(state === "changed-snapshot"
? { sha256: "f".repeat(64) }
: {}),
}),
);
},
close: () => Promise.resolve(ok(null)),
}));
const resolved = await ghidra.resolveAnalysisProfile(fixture.target);
if (!resolved.ok) throw resolved.error;
if (resolved.value.profile === null)
throw new Error("expected raw profile");
const client = ghidra.createClient(
fixture.target,
resolved.value.profile,
);
try {
const result = await client.execute(
"inspect_native_load_image",
{},
{ signal: controller.signal },
);
expect(signals).toEqual([controller.signal]);
if (state === "verified") {
if (!result.ok) throw result.error;
expect(result.value.result).toMatchObject({
status: "verified",
observations: fixture.observation,
});
} else {
expect(result).toMatchObject({
ok: false,
error: {
_tag:
state === "cancelled"
? "AnalysisCancelledError"
: "ProviderAdapterError",
},
});
}
} finally {
await client.close();
}
},
);
it.each([
"verified",
"mismatch",
+38 -7
View File
@@ -87,12 +87,18 @@ import {
windowsNativeAuthorityUnavailableReason,
hasWindowsNativeAuthority,
} from "../process/WindowsAuthority.js";
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
/** Production seam for exercising provider projection without a real process. */
export type GhidraProviderClientFactory = (
options: GhidraClientOptions,
) => Pick<GhidraClient, "start" | "callTool" | "close"> &
Partial<Pick<GhidraClient, "runtimeLineage" | "readTargetSnapshot">>;
Partial<
Pick<
GhidraClient,
"runtimeLineage" | "readTargetSnapshot" | "hashTargetSnapshot"
>
>;
type GhidraProviderClientInstance = ReturnType<GhidraProviderClientFactory>;
@@ -440,6 +446,10 @@ export const createGhidraProviderClient = (input: {
let extensionFailure: AnalysisError | undefined;
// Replaced by the reported outcome once the session handshake is checked.
const seedLimitations: string[] = [...ghidraSeedLimitations(seeds)];
const rawLanguage =
target.format === "raw-binary"
? ghidraRawBinaryLanguage(target.architecture)
: undefined;
const targetLimitations = [
...(target.format === "dos-mz"
? [
@@ -447,6 +457,13 @@ export const createGhidraProviderClient = (input: {
"Static DOS analysis does not emulate BIOS, DOS interrupts, device ports, or self-modifying unpacking code. Packed targets require a separately identified unpacked artifact for original-program analysis; appended overlays are not the initialized load module.",
]
: []),
...(target.format === "raw-binary"
? [
"Headerless raw-binary analysis uses the caller-supplied architecture and entry address; file offset 0 is mapped at that address. Headers are not discovered from file bytes.",
"Little-endian generic Ghidra languages are used for x86, x86_64, arm, and arm64. Big-endian, Thumb-only, Cortex-M, and other processor variants are unsupported in this increment.",
"Static analysis does not emulate reset vectors, memory-mapped I/O, or firmware boot sequences.",
]
: []),
...(target.kind === "executable" && target.architecture === "mips"
? (target.mips.limitations ?? [])
: []),
@@ -474,6 +491,15 @@ export const createGhidraProviderClient = (input: {
: {}),
...(target.format === "dos-mz" ? { dosMz: true } : {}),
...(target.format === "dos-com" ? { dosCom: true } : {}),
...(rawLanguage === undefined || target.format !== "raw-binary"
? {}
: {
rawBinary: {
languageId: rawLanguage.languageId,
compilerSpecId: rawLanguage.compilerSpecId,
baseAddr: target.entryPoint,
},
}),
...(languageOverride === undefined ? {} : { languageOverride }),
...(seeds === undefined ? {} : { analysisSeeds: seeds }),
platform: installation.platform,
@@ -495,13 +521,18 @@ export const createGhidraProviderClient = (input: {
expectedLanguageId: "x86:LE:16:Real Mode",
expectedCompilerSpecId: "default",
}
: languageOverride === undefined
? {}
: rawLanguage === undefined
? languageOverride === undefined
? {}
: {
expectedLanguageId: languageOverride.languageId,
...(languageOverride.compilerSpecId === undefined
? {}
: { expectedCompilerSpecId: languageOverride.compilerSpecId }),
}
: {
expectedLanguageId: languageOverride.languageId,
...(languageOverride.compilerSpecId === undefined
? {}
: { expectedCompilerSpecId: languageOverride.compilerSpecId }),
expectedLanguageId: rawLanguage.languageId,
expectedCompilerSpecId: rawLanguage.compilerSpecId,
}),
...(psp
? {
+26
View File
@@ -0,0 +1,26 @@
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
/** Bound Ghidra language for a caller-supplied raw-binary architecture. */
export interface GhidraRawBinaryLanguage {
readonly languageId: string;
readonly compilerSpecId: "default";
}
/**
* Map the four caller-visible CPU families to little-endian generic Ghidra
* languages. Big-endian, Thumb-only, and Cortex-M variants are out of scope.
*/
export const ghidraRawBinaryLanguage = (
architecture: Exclude<BinaryArchitecture, "mips">,
): GhidraRawBinaryLanguage => {
switch (architecture) {
case "x86":
return { languageId: "x86:LE:32:default", compilerSpecId: "default" };
case "x86_64":
return { languageId: "x86:LE:64:default", compilerSpecId: "default" };
case "arm":
return { languageId: "ARM:LE:32:v7", compilerSpecId: "default" };
case "arm64":
return { languageId: "AARCH64:LE:64:v8A", compilerSpecId: "default" };
}
};
@@ -0,0 +1,62 @@
import { createHash } from "node:crypto";
import type { NativeLoadImageObservation } from "../domain/native/nativeLoadImage.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
const hash = (bytes: Buffer): string =>
createHash("sha256").update(bytes).digest("hex");
export const fixtureRawBinaryLoadImage = (): {
snapshot: { sha256: string; bytes: number };
target: Extract<BinaryTarget, { format: "raw-binary" }>;
observation: NativeLoadImageObservation;
} => {
const bytes = Buffer.from("1eff2fe1", "hex");
const digest = hash(bytes);
return {
snapshot: { sha256: digest, bytes: bytes.length },
target: {
path: "/tmp/ecu.bin",
sha256: digest,
kind: "executable",
format: "raw-binary",
architecture: "arm",
availableArchitectures: ["arm"],
entryPoint: "0x8000000",
entryPointSource: "0x08000000",
},
observation: {
executable_format: "Raw Binary",
language_id: "ARM:LE:32:v7",
compiler_spec_id: "default",
image_base: "0x0",
default_address_space: "ram",
source_files: [
{
name: "ecu.bin",
size: bytes.length,
original_sha256: digest,
modified_sha256: digest,
},
],
mappings: [
{
block: "ram",
start: "0x8000000",
end: "0x8000003",
address_space: "ram",
initialized: true,
loaded: true,
overlay: false,
length: bytes.length,
source_file_index: 0,
file_offset: 0,
sha256: digest,
},
],
relocations: [],
entry_points: ["0x8000000"],
entry_context: [],
},
};
};
@@ -0,0 +1,98 @@
import { describe, expect, it } from "vitest";
import { attestGhidraRawBinaryLoadImage } from "./GhidraLoadImageValues.js";
import { fixtureRawBinaryLoadImage } from "./GhidraRawBinaryLoadImage.fixture.js";
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
describe("raw-binary Ghidra language binding", () => {
it("maps the four admitted families to little-endian generic languages", () => {
expect(ghidraRawBinaryLanguage("x86")).toEqual({
languageId: "x86:LE:32:default",
compilerSpecId: "default",
});
expect(ghidraRawBinaryLanguage("x86_64")).toEqual({
languageId: "x86:LE:64:default",
compilerSpecId: "default",
});
expect(ghidraRawBinaryLanguage("arm")).toEqual({
languageId: "ARM:LE:32:v7",
compilerSpecId: "default",
});
expect(ghidraRawBinaryLanguage("arm64")).toEqual({
languageId: "AARCH64:LE:64:v8A",
compilerSpecId: "default",
});
});
});
describe("raw-binary independent load-image checks", () => {
it("verifies mapped bytes at the caller-supplied entry", () => {
const f = fixtureRawBinaryLoadImage();
const result = attestGhidraRawBinaryLoadImage(
f.snapshot,
f.target,
f.observation,
);
expect(result).toMatchObject({
ok: true,
value: {
status: "verified",
format: "raw-binary",
architecture: "arm",
language_id: "ARM:LE:32:v7",
base_address: "0x8000000",
file_bytes: 4,
entry: { address: "0x8000000", file_offset: 0 },
},
});
});
it("retains mismatch evidence for a drifted language", () => {
const f = fixtureRawBinaryLoadImage();
f.observation.language_id = "x86:LE:32:default";
const result = attestGhidraRawBinaryLoadImage(
f.snapshot,
f.target,
f.observation,
);
expect(result).toMatchObject({
ok: true,
value: { status: "mismatch", observations: f.observation },
});
});
it("preserves additional language entries while requiring the caller entry", () => {
const f = fixtureRawBinaryLoadImage();
f.observation.entry_points = ["0x0", f.target.entryPoint, "0xffff0000"];
expect(
attestGhidraRawBinaryLoadImage(f.snapshot, f.target, f.observation),
).toMatchObject({
ok: true,
value: { status: "verified", observations: f.observation },
});
f.observation.entry_points = ["0x0", "0xffff0000"];
expect(
attestGhidraRawBinaryLoadImage(f.snapshot, f.target, f.observation),
).toMatchObject({
ok: true,
value: {
status: "mismatch",
checks: expect.arrayContaining([
expect.objectContaining({
name: "entry_point",
matched: false,
observed: null,
}),
]),
},
});
});
it("rejects stale snapshot identity", () => {
const f = fixtureRawBinaryLoadImage();
expect(
attestGhidraRawBinaryLoadImage(
f.snapshot,
{ ...f.target, sha256: "f".repeat(64) },
f.observation,
).ok,
).toBe(false);
});
});