feat(ghidra): admit bounded PSP ELF through installed Allegrex (#1599)

* feat(ghidra): admit bounded PSP ELF through installed Allegrex

Build on merged generic MIPS without weakening its policy. Bind caller-installed processor files into the analysis profile, check them again before launch, force and verify PSP language selection, retain limitations, and extend the public CLI/MCP verifier with source-owned PSP and target-switching checks. Local actual focused Vitest: 102 passed, one existing permission skip. Hosted static and real-provider results are pending.

* fix(ghidra): validate PSPSDK ABI records in PSP admission

* test(ghidra): bind PSP ABI verification to snapshot profiles

* test(ghidra): declare independent PSP ABI reader contract

* test(ghidra): retain the PSP fixture discriminated type

* test(ghidra): contextually type PSP metadata as the MIPS target variant

* test(ghidra): keep carved firmware checks scoped to generic MIPS fixtures

* style(ghidra): format PSP language-override guard

* style(test): format PSP language override regressions

* fix(ghidra): bound PSP extension enumeration before allocation

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Jay-Alexander Elliot
2026-10-11 19:47:33 +08:00
committed by GitHub
co-authored by github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> morluto
parent 0153b4d95b
commit e4407dbed5
17 changed files with 1637 additions and 146 deletions
+30 -5
View File
@@ -13,10 +13,13 @@ import { ProviderAdapterError } from "../domain/providerAdapterError.js";
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 {
ghidraMipsProfileParameters,
ghidraMipsUnsupportedReason,
} from "./GhidraMipsProfile.js";
ghidraProcessorUnsupportedReason,
isGhidraPspTarget,
} from "./GhidraPspProfile.js";
import { resolveGhidraPspExtension } from "./GhidraPspExtension.js";
import {
NATIVE_AOT_MAX_REPORT_BYTES,
NATIVE_AOT_MAX_SOURCE_BYTES,
@@ -26,7 +29,7 @@ import {
} from "../domain/native/nativeAotPe.js";
/** Resolve version-bound, deterministic semantics before Ghidra imports a target. */
export const resolveGhidraAnalysisProfile = (
export const resolveGhidraAnalysisProfile = async (
target: BinaryTarget,
identity: ProviderIdentity,
installation: GhidraInstallationInspection,
@@ -41,7 +44,7 @@ export const resolveGhidraAnalysisProfile = (
return Promise.resolve(
err(new ProviderAdapterError(identity.id, "resolve_analysis_profile")),
);
const mipsReason = ghidraMipsUnsupportedReason(target);
const mipsReason = ghidraProcessorUnsupportedReason(target);
if (mipsReason !== null)
return Promise.resolve(
err(
@@ -52,6 +55,19 @@ export const resolveGhidraAnalysisProfile = (
),
),
);
// A caller-selected generic processor cannot override this verified PSP loader.
if (isGhidraPspTarget(target) && languageOverride !== undefined)
return err(
new AnalysisUnsupportedTargetError(
"resolve_analysis_profile",
target.path,
"The bounded PSP Allegrex profile does not accept REA_GHIDRA_LANGUAGE_ID overrides.",
),
);
const pspExtension = isGhidraPspTarget(target)
? await resolveGhidraPspExtension(installation, signal)
: null;
if (pspExtension !== null && !pspExtension.ok) return pspExtension;
const provider = { ...identity, version: installation.providerVersion };
const dosMz = target.format === "dos-mz";
const dosCom = target.format === "dos-com";
@@ -151,6 +167,15 @@ export const resolveGhidraAnalysisProfile = (
: {}),
analyzer_preset: "ghidra-default",
...ghidraMipsProfileParameters(target),
...(pspExtension?.ok === true
? {
mips_support_lane: "psp-elf32-exec-eabi32-allegrex-v2",
loader: "PspElfLoader",
language_id: "Allegrex:LE:32:default",
compiler_spec_id: "default",
psp_extension: { ...pspExtension.value },
}
: {}),
}),
}),
);
+58 -7
View File
@@ -5,7 +5,7 @@ import {
} from "./GhidraAnalysisSeeds.js";
import type { GhidraLanguageOverride } from "../config/ghidraLanguageOverride.js";
import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { mkdir } from "node:fs/promises";
import { mkdir, realpath } from "node:fs/promises";
import { basename, dirname, join, posix, win32 } from "node:path";
import writeFileAtomic from "write-file-atomic";
@@ -37,6 +37,11 @@ import {
type GhidraExtension,
} from "./extensions/GhidraExtensions.js";
import {
inspectGhidraPspExtension,
type GhidraPspExtension,
} from "./GhidraPspExtension.js";
/** Private paths and identity material for one headless Ghidra import. */
export interface GhidraLaunchSession {
readonly runtimeRoot: string;
@@ -101,6 +106,7 @@ export interface GhidraHeadlessLauncherOptions {
/** Caller seeds committed by the analysis profile, applied before analysis. */
readonly analysisSeeds?: GhidraSeedCommitment;
readonly analysisExtensions?: readonly GhidraExtension[];
readonly pspExtension?: GhidraPspExtension;
/** Spawn seam for provider-boundary lifecycle tests. */
readonly spawnProcess?: typeof spawnOwnedProviderProcess;
}
@@ -125,6 +131,31 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
const platform = this.options.platform ?? process.platform;
let started: SpawnedOwnedProviderProcess | undefined;
try {
const psp = this.options.pspExtension;
if (psp !== undefined) {
const installedRoot = await realpath(
join(
dirname(this.options.analyzeHeadlessPath),
"..",
"Ghidra",
"Extensions",
"ghidra-allegrex",
),
);
if (installedRoot !== psp.root)
throw new GhidraLaunchError(
"Allegrex profile does not belong to the selected Ghidra installation.",
);
const inspected = await inspectGhidraPspExtension(
psp.root,
psp.ghidra_version,
options.signal,
);
if (inspected.sha256 !== psp.sha256)
throw new GhidraLaunchError(
"Installed Allegrex content changed since profile resolution; reopen the target to resolve a fresh profile.",
);
}
await createGhidraRuntimeDirectories(paths, platform);
const seedPath =
this.options.analysisSeeds === undefined
@@ -157,6 +188,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
return err(new AnalysisCancelledError("open_binary"));
const headlessArguments = ghidraHeadlessArguments({
platform,
...(psp === undefined ? {} : { psp: true as const }),
projectRoot: paths.projectRoot,
targetPath: session.targetPath,
bridgeScriptPath: this.options.bridgeScriptPath,
@@ -376,6 +408,7 @@ export interface GhidraHeadlessArgumentOptions {
readonly descriptorPath: string;
readonly ghidraLogPath: string;
readonly scriptLogPath: string;
readonly psp?: true;
readonly dosMz?: true;
readonly dosCom?: true;
readonly languageOverride?: GhidraLanguageOverride;
@@ -393,6 +426,15 @@ export const ghidraHeadlessArguments = (
(options.platform ?? process.platform) === "win32" ? win32 : posix;
const bridgeDirectory = scriptPath.dirname(options.bridgeScriptPath);
const override = options.languageOverride;
if (
options.psp === true &&
(options.dosMz === true ||
options.dosCom === true ||
override !== undefined)
)
throw new Error(
"A PSP ELF import cannot be combined with DOS or a generic Ghidra language override.",
);
if (
override !== undefined &&
(options.dosMz === true || options.dosCom === true)
@@ -425,15 +467,24 @@ export const ghidraHeadlessArguments = (
"-cspec",
"default",
]
: override !== 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]),
]
: []),
"-readOnly",
"-deleteProject",
"-log",
+1 -1
View File
@@ -105,7 +105,7 @@ describe("bounded Ghidra MIPS admission", () => {
[{ type: 1 }, "ET_EXEC"],
[{ type: 3 }, "ET_EXEC"],
[{ type: 0xffa0 }, "ET_EXEC"],
[{ flags: 0x10a23001 }, "Machine-specific"],
[{ flags: 0x10a23001 }, "separate MIPS ABI flags"],
[{ flags: 0x70001021 }, "o32"],
[{ flags: 0x70000001 }, "o32"],
[{ flags: 0x70002001 }, "o32"],
+10 -2
View File
@@ -37,7 +37,10 @@ import {
admitGhidraLanguageOverride,
readGhidraLanguageCatalog,
} from "./GhidraLanguageCatalog.js";
import { ghidraMipsUnsupportedReason } from "./GhidraMipsProfile.js";
import {
ghidraProcessorUnsupportedReason,
isGhidraPspTarget,
} from "./GhidraPspProfile.js";
import { resolveGhidraExtensions } from "./extensions/GhidraExtensions.js";
import {
CAPABILITIES,
@@ -149,7 +152,12 @@ export class GhidraProvider implements AnalysisProviderCandidate {
};
if (hostPlatform === "win32")
return inspectWindowsP0TargetSupport(target, diagnostics);
const mipsReason = ghidraMipsUnsupportedReason(target);
const mipsReason =
isGhidraPspTarget(target) &&
(hostPlatform !== "linux" ||
(this.installationHost?.architecture ?? process.arch) !== "x64")
? "The initial PSP Allegrex profile is verified on Linux x64 only."
: ghidraProcessorUnsupportedReason(target);
if (mipsReason !== null)
return {
status: "unsupported",
+35
View File
@@ -49,6 +49,11 @@ import {
ghidraInstallationDiagnostics,
type GhidraInstallationInspection,
} from "./GhidraInstallation.js";
import {
isGhidraPspTarget,
GHIDRA_PSP_LIMITATIONS,
} from "./GhidraPspProfile.js";
import { ghidraPspExtensionSchema } from "./GhidraPspExtension.js";
import { unverifiedGhidraBuildLimitation } from "./GhidraInstallationPolicy.js";
import { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
import { attestGhidraNativeLoadImage } from "./GhidraLoadImageAttest.js";
@@ -353,6 +358,26 @@ export const createGhidraProviderClient = (input: {
);
if (!prerequisites.ok) return unavailableClient(prerequisites.error);
const committedProfile = prerequisites.value.profile;
const psp = isGhidraPspTarget(target);
const pspExtension = psp
? ghidraPspExtensionSchema.safeParse(
committedProfile.parameters.psp_extension,
)
: null;
if (
pspExtension !== null &&
(!pspExtension.success ||
committedProfile.parameters.language_id !== "Allegrex:LE:32:default" ||
committedProfile.parameters.loader !== "PspElfLoader")
)
return unavailableClient(
new ProviderAdapterError("ghidra", "open_binary", {
diagnostics: {
reason:
"Resolve the supported PSP profile and installed Allegrex extension before opening the session.",
},
}),
);
const extensionProfile = ghidraExtensionSchema
.array()
.safeParse(committedProfile.parameters.analysis_extensions ?? []);
@@ -444,6 +469,9 @@ export const createGhidraProviderClient = (input: {
bridgeScriptPath: fileURLToPath(
new URL("../../bridge/ghidra/ReaGhidraBridge.java", import.meta.url),
),
...(pspExtension?.success === true
? { pspExtension: pspExtension.data }
: {}),
...(target.format === "dos-mz" ? { dosMz: true } : {}),
...(target.format === "dos-com" ? { dosCom: true } : {}),
...(languageOverride === undefined ? {} : { languageOverride }),
@@ -475,6 +503,12 @@ export const createGhidraProviderClient = (input: {
? {}
: { expectedCompilerSpecId: languageOverride.compilerSpecId }),
}),
...(psp
? {
expectedLanguageId: "Allegrex:LE:32:default",
expectedCompilerSpecId: "default",
}
: {}),
...(context === undefined ? {} : { runId: context.runId }),
logger: logger.child({ layer: "ghidra-bridge" }),
});
@@ -510,6 +544,7 @@ export const createGhidraProviderClient = (input: {
const sessionLimitations = (): readonly string[] => [
...providerLimitations,
...targetLimitations,
...(psp ? GHIDRA_PSP_LIMITATIONS : []),
...ghidraExtensionLimitations(extensions),
...seedLimitations,
...(releaseLimitation === undefined ? [] : [releaseLimitation]),
+212
View File
@@ -0,0 +1,212 @@
import { createHash } from "node:crypto";
import { lstat, opendir, realpath } from "node:fs/promises";
import { isAbsolute, join } from "node:path";
import { z } from "zod";
import {
openRegularFile,
sameRegularFileState,
} from "../filesystem/RegularFile.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
} from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import type { GhidraInstallationInspection } from "./GhidraInstallation.js";
/** Installed processor code and data, distinct from REA's analysis-extension ABI. */
export const ghidraPspExtensionSchema = z.strictObject({
id: z.literal("ghidra-allegrex"),
root: z.string().refine(isAbsolute),
ghidra_version: z.string().min(1),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
});
export type GhidraPspExtension = z.infer<typeof ghidraPspExtensionSchema>;
// Resource bounds for scanning a caller-installed extension, not target limits.
const MAX_ENTRIES = 1024;
const MAX_BYTES = 64 * 1024 * 1024;
const MAX_DEPTH = 16;
const REQUIRED = [
"Module.manifest",
"extension.properties",
"data/languages/allegrex.ldefs",
"data/languages/allegrex.sla",
"data/languages/allegrex.pspec",
"data/languages/allegrex.cspec",
];
/** Read-only fingerprint of all installed files; no home scanning or installation. */
export const inspectGhidraPspExtension = async (
root: string,
ghidraVersion: string,
signal?: AbortSignal,
): Promise<GhidraPspExtension> => {
signal?.throwIfAborted();
if (!isAbsolute(root) || (await realpath(root)) !== root)
throw new Error(
"The installed Allegrex directory must be a canonical non-symlink path.",
);
const files: string[] = [];
let entries = 1; // The root itself consumes one inventory entry.
const visit = async (relative: string, depth: number): Promise<void> => {
signal?.throwIfAborted();
if (depth > MAX_DEPTH)
throw new Error(
"Allegrex extension directory nesting exceeds the inspection limit.",
);
const path = join(root, relative);
const metadata = await lstat(path);
if (metadata.isDirectory()) {
const children: string[] = [];
for await (const child of await opendir(path)) {
signal?.throwIfAborted();
if (++entries > MAX_ENTRIES)
throw new Error(
"Allegrex extension inventory exceeds the inspection limit.",
);
children.push(child.name);
}
children.sort();
for (const child of children)
await visit(
relative === "" ? child : `${relative}/${child}`,
depth + 1,
);
} else if (metadata.isFile()) {
files.push(relative);
} else
throw new Error(
`Allegrex extension entries must be regular files or directories: ${relative}`,
);
};
await visit("", 0);
for (const required of REQUIRED)
if (!files.includes(required))
throw new Error(`Missing installed Allegrex component: ${required}`);
if (!files.some((path) => path.startsWith("lib/") && path.endsWith(".jar")))
throw new Error("The installed Allegrex extension has no loader JAR.");
const hash = createHash("sha256");
let bytesRead = 0;
let properties = "";
for (const relative of files) {
signal?.throwIfAborted();
const path = join(root, relative);
const handle = await openRegularFile(path, { symlinks: "reject", signal });
try {
const before = await handle.stat();
if (
!Number.isSafeInteger(before.size) ||
before.size > MAX_BYTES - bytesRead
)
throw new Error(
"Allegrex extension bytes exceed the inspection limit.",
);
if (relative === "extension.properties" && before.size > 65536)
throw new Error(
"Allegrex extension properties exceed the inspection limit.",
);
hash.update(JSON.stringify([relative, before.size]));
const buffer = Buffer.alloc(Math.min(65536, before.size + 1));
let offset = 0;
const chunks: Buffer[] = [];
while (offset < before.size) {
signal?.throwIfAborted();
const read = await handle.read(
buffer,
0,
Math.min(buffer.length, before.size - offset),
offset,
);
if (read.bytesRead === 0)
throw new Error(`Truncated Allegrex component: ${relative}`);
const chunk = buffer.subarray(0, read.bytesRead);
hash.update(chunk);
if (relative === "extension.properties")
chunks.push(Buffer.from(chunk));
offset += read.bytesRead;
}
if (
!sameRegularFileState(before, await handle.stat()) ||
!sameRegularFileState(before, await lstat(path))
)
throw new Error(
`Allegrex component changed during inspection: ${relative}`,
);
bytesRead += before.size;
if (relative === "extension.properties")
properties = Buffer.concat(chunks).toString("utf8");
} finally {
await handle.close();
}
}
// Ghidra's extension.properties version is the compatible Ghidra version,
// not the extension release (e.g. v21.4); content identity supplies the latter.
const property = (name: string): string => {
const values = properties.split(/\r?\n/u).flatMap((line) => {
const match = /^\s*([A-Za-z][A-Za-z0-9]*)\s*=\s*(.*?)\s*$/u.exec(line);
return match?.[1] === name ? [match[2] ?? ""] : [];
});
if (values.length !== 1)
throw new Error(`Allegrex extension must declare exactly one ${name}.`);
return values[0] ?? "";
};
if (
property("name") !== "ghidra-allegrex" ||
property("version") !== ghidraVersion
)
throw new Error(
`Allegrex extension metadata does not match the selected Ghidra ${ghidraVersion}; install or rebuild a compatible extension.`,
);
signal?.throwIfAborted();
return {
id: "ghidra-allegrex",
root,
ghidra_version: ghidraVersion,
sha256: hash.digest("hex"),
};
};
/** Resolve prerequisites before opening or admitting cached PSP analysis. */
export const resolveGhidraPspExtension = async (
installation: GhidraInstallationInspection,
signal?: AbortSignal,
): Promise<Result<GhidraPspExtension, AnalysisError>> => {
if (signal?.aborted)
return err(new AnalysisCancelledError("resolve_analysis_profile"));
try {
if (
installation.status !== "available" ||
installation.platform !== "linux" ||
installation.architecture !== "x64"
)
throw new Error(
"The initial PSP profile requires a supported Linux x64 Ghidra installation.",
);
const root = join(
await realpath(installation.installDir),
"Ghidra",
"Extensions",
"ghidra-allegrex",
);
return ok(
await inspectGhidraPspExtension(
root,
installation.providerVersion,
signal,
),
);
} catch (cause: unknown) {
if (signal?.aborted)
return err(new AnalysisCancelledError("resolve_analysis_profile"));
const reason = `PSP_EXTENSION_UNAVAILABLE: ${cause instanceof Error ? cause.message : String(cause)} Use a compatible caller-installed ghidra-allegrex under GHIDRA_INSTALL_DIR/Ghidra/Extensions; REA does not install it.`;
return err(
new AnalysisCapabilityUnavailableError(
"ghidra",
"resolve_analysis_profile",
reason,
{ cause, userMessage: reason },
),
);
}
};
+60
View File
@@ -0,0 +1,60 @@
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import { ghidraMipsUnsupportedReason } from "./GhidraMipsProfile.js";
/** Allegrex's ELF machine declaration, not a filename or inferred instruction. */
export const isGhidraPspTarget = (target: BinaryTarget): boolean =>
target.kind === "executable" &&
target.format === "elf" &&
target.architecture === "mips" &&
target.mips !== undefined &&
(target.mips.flags & 0x00ff0000) === 0x00a20000;
/** PSP has its own verified interpretation; generic MIPS rules remain unchanged. */
export const ghidraProcessorUnsupportedReason = (
target: BinaryTarget,
): string | null => {
if (
target.kind !== "executable" ||
target.architecture !== "mips" ||
!isGhidraPspTarget(target)
)
return ghidraMipsUnsupportedReason(target);
const metadata = target.mips;
if (metadata === undefined) return "PSP analysis requires ELF metadata.";
if (metadata.elfClass !== 32 || metadata.byteOrder !== "little")
return "The PSP Allegrex profile requires little-endian ELF32.";
if (metadata.type !== 2)
return "The PSP Allegrex profile supports static ET_EXEC only; PRX, shared and relocatable images require separate verification.";
// PSPSDK emits MIPS-II / Allegrex / EABI32 with NOREORDER. Do not accept
// unknown producer flags or treat this as proof of instruction semantics.
if (metadata.flags !== 0x10a23001)
return "The PSP Allegrex profile requires the verified PSPSDK ELF declaration 0x10a23001; other ISA/ABI/ASE flags are not inferred.";
const abi = metadata.abiFlags;
if (abi === undefined || abi === null)
return "The PSP Allegrex profile requires an inspected separate MIPS ABI flags record; missing declarations are not inferred.";
// PSPDEV v20261001: GNU readelf 2.44 and the 24-byte record agree on
// MIPS II, 32-bit registers, single-precision hard float and flags1=1.
// This is a bounded producer declaration, not a claim about VFPU semantics.
if (
abi.version !== 0 ||
abi.isaLevel !== 2 ||
abi.isaRevision !== 0 ||
abi.gprSize !== 1 ||
abi.cpr1Size !== 1 ||
abi.cpr2Size !== 0 ||
abi.fpAbi !== 2 ||
abi.isaExtension !== 0 ||
abi.ases !== 0 ||
abi.flags1 !== 1 ||
abi.flags2 !== 0
)
return "The separate MIPS ABI flags record does not match the verified PSP MIPS-II/32-bit/single-float declaration; other versions, register modes and extension flags require separate verification.";
return null;
};
/** Propagated with every PSP observation, including successful decompilation. */
export const GHIDRA_PSP_LIMITATIONS = [
"PSP/Allegrex analysis uses the caller-installed ghidra-allegrex extension. ELF declarations and selected instruction checks are not proof of runtime semantics.",
"ghidra-allegrex does not model VFPU prefix effects completely in decompiled output. Verify vector behavior independently; pseudocode is not an execution oracle.",
"This PSP profile covers static ELF32 ET_EXEC only. PRX relocations, PBP/ISO containers, live overlays and PSP emulation are outside this verified lane.",
] as const;