feat(ghidra): apply validated analyzer overrides before analysis

Apply caller-selected analyzer opt-outs before Ghidra analysis, reject unknown or ineffective names, and commit raw/header imports to the same analyzer profile. Use supported x86 raw compiler specs and cover the real analyzer/readback and raw workflows.

Adopts the original implementation from #1800 with validated corrections. Refs #1783, #1836.

Co-authored-by: akushonkamen <74654766+akushonkamen@users.noreply.github.com>
Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com>
Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
Ysopwnable
2026-10-12 03:49:31 +08:00
committed by GitHub
co-authored by akushonkamen Kaoru0822
parent 12ee785e5e
commit 9878bb7296
22 changed files with 677 additions and 38 deletions
+2
View File
@@ -8,6 +8,7 @@ import {
ghidraCompilerSpecIdSchema,
ghidraLanguageIdSchema,
} from "./ghidraLanguageOverride.js";
import { ghidraDisabledAnalyzersSchema } from "./ghidraDisabledAnalyzers.js";
import {
DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS,
DEFAULT_HOPPER_STARTUP_TIMEOUT_MS,
@@ -48,6 +49,7 @@ const environmentSchema = z.object({
),
REA_GHIDRA_LANGUAGE_ID: ghidraLanguageIdSchema.optional(),
REA_GHIDRA_COMPILER_SPEC_ID: ghidraCompilerSpecIdSchema.optional(),
REA_GHIDRA_DISABLED_ANALYZERS: ghidraDisabledAnalyzersSchema.optional(),
REA_GHIDRA_SEED_FILE: z
.string()
.min(1)
+42
View File
@@ -0,0 +1,42 @@
import { z } from "zod";
export const MAX_GHIDRA_DISABLED_ANALYZER_NAMES = 32;
export const MAX_GHIDRA_DISABLED_ANALYZER_NAME_LENGTH = 120;
// Ghidra's headless parser consumes `-`-prefixed arguments after a script path
// as its own options, and REA joins the names with commas into one pre-script
// argument, so a name can neither start with `-` nor contain a comma. The
// remaining admitted characters keep the argument a single quotable token on
// every supported launcher, including the Windows batch invocation.
const ghidraAnalyzerNamePattern = /^[A-Za-z0-9][A-Za-z0-9 ._-]*$/u;
/**
* Parse `REA_GHIDRA_DISABLED_ANALYZERS` into the Ghidra auto-analyzer names to
* disable before default auto-analysis, such as
* `Objective-C Message Analyzer`. Empty and blank entries are dropped; a list
* without names selects no override.
*/
export const ghidraDisabledAnalyzersSchema = z
.string()
.transform((value) =>
value
.split(",")
.map((name) => name.trim())
.filter((name) => name.length > 0),
)
.refine(
(names) => names.length <= MAX_GHIDRA_DISABLED_ANALYZER_NAMES,
`must list at most ${MAX_GHIDRA_DISABLED_ANALYZER_NAMES} analyzer names`,
)
.refine(
(names) =>
names.every(
(name) => name.length <= MAX_GHIDRA_DISABLED_ANALYZER_NAME_LENGTH,
),
`must keep every analyzer name at most ${MAX_GHIDRA_DISABLED_ANALYZER_NAME_LENGTH} characters`,
)
.refine(
(names) => names.every((name) => ghidraAnalyzerNamePattern.test(name)),
"must be Ghidra analyzer names starting with a letter or digit and containing only letters, digits, spaces, periods, underscores, and hyphens",
)
.transform((names) => (names.length === 0 ? undefined : names));
+3
View File
@@ -88,6 +88,9 @@ export const parseConfig = (
...(env.REA_GHIDRA_SEED_FILE === undefined
? {}
: { ghidraSeedFile: env.REA_GHIDRA_SEED_FILE }),
...(env.REA_GHIDRA_DISABLED_ANALYZERS === undefined
? {}
: { ghidraDisabledAnalyzers: env.REA_GHIDRA_DISABLED_ANALYZERS }),
...(env.REA_GHIDRA_NATIVEAOT_JAR === undefined
? {}
: { ghidraNativeAotJar: env.REA_GHIDRA_NATIVEAOT_JAR }),
+1
View File
@@ -14,6 +14,7 @@ export interface AppConfig {
readonly ghidraJavaHome: string | undefined;
readonly ghidraStartupTimeoutMs: number;
readonly ghidraLanguageOverride?: GhidraLanguageOverride;
readonly ghidraDisabledAnalyzers?: readonly string[];
readonly ghidraSeedFile?: string;
readonly ghidraNativeAotJar?: string;
readonly ilspyCmdPath: string | undefined;
+33 -2
View File
@@ -36,6 +36,7 @@ export const resolveGhidraAnalysisProfile = async (
installation: GhidraInstallationInspection,
signal?: AbortSignal,
languageOverride?: GhidraLanguageOverride,
disabledAnalyzers?: readonly string[],
): Promise<Result<AnalysisProfileResolution, AnalysisError>> => {
if (signal?.aborted === true)
return Promise.resolve(err(new AnalysisCancelledError("open_binary")));
@@ -70,6 +71,13 @@ export const resolveGhidraAnalysisProfile = async (
: null;
if (pspExtension !== null && !pspExtension.ok) return pspExtension;
const provider = { ...identity, version: installation.providerVersion };
const analyzerParameters =
disabledAnalyzers === undefined || disabledAnalyzers.length === 0
? { analyzer_preset: "ghidra-default" }
: {
analyzer_preset: `ghidra-default+disabled:${disabledAnalyzers.join(",")}`,
analysis_options: { disabled_analyzers: [...disabledAnalyzers] },
};
if (target.format === "raw-binary") {
if (languageOverride !== undefined)
return Promise.resolve(
@@ -116,7 +124,7 @@ export const resolveGhidraAnalysisProfile = async (
language_selection: "caller-supplied-v1",
entry_point: target.entryPoint,
entry_seed: "external-entry-and-function-before-analysis-v1",
analyzer_preset: "ghidra-default",
...analyzerParameters,
}),
}),
);
@@ -218,7 +226,7 @@ export const resolveGhidraAnalysisProfile = async (
entry_seed: "external-entry-and-function-before-analysis-v1",
}
: {}),
analyzer_preset: "ghidra-default",
...analyzerParameters,
...ghidraMipsProfileParameters(target),
...(pspExtension?.ok === true
? {
@@ -255,3 +263,26 @@ export const sameGhidraLanguageOverride = (
): boolean =>
left?.languageId === right?.languageId &&
left?.compilerSpecId === right?.compilerSpecId;
/** Read the analyzer-option commitment back from a resolved profile. */
export const ghidraProfileDisabledAnalyzers = (
parameters: Readonly<Record<string, unknown>>,
): readonly string[] | undefined => {
const options = parameters.analysis_options;
if (typeof options !== "object" || options === null) return undefined;
const disabled = (options as Record<string, unknown>).disabled_analyzers;
if (!Array.isArray(disabled)) return undefined;
return disabled.every((name) => typeof name === "string")
? (disabled as readonly string[])
: undefined;
};
/** Whether a committed profile and the active configuration disable the same analyzers. */
export const sameGhidraDisabledAnalyzers = (
left: readonly string[] | undefined,
right: readonly string[] | undefined,
): boolean =>
left === undefined || right === undefined
? left === right
: left.length === right.length &&
left.every((name, index) => name === right[index]);
@@ -0,0 +1,90 @@
import { describe, expect, it } from "vitest";
import {
ghidraDisabledAnalyzersSchema,
MAX_GHIDRA_DISABLED_ANALYZER_NAMES,
} from "../config/ghidraDisabledAnalyzers.js";
import { parseConfig } from "../config/parseConfig.js";
const INSTALL = "/opt/ghidra_12.1.4_PUBLIC";
const configured = (setting?: string) => {
const config = parseConfig({
GHIDRA_INSTALL_DIR: INSTALL,
...(setting === undefined
? {}
: { REA_GHIDRA_DISABLED_ANALYZERS: setting }),
});
if (!config.ok) throw config.error;
return config.value.ghidraDisabledAnalyzers;
};
describe("REA_GHIDRA_DISABLED_ANALYZERS", () => {
it("stays unset without the setting", () => {
expect(configured(undefined)).toBeUndefined();
});
it("splits a comma-separated list and trims each name", () => {
expect(
configured(" Objective-C Message Analyzer,Decompiler Switch Analysis "),
).toEqual(["Objective-C Message Analyzer", "Decompiler Switch Analysis"]);
});
it("treats an empty or blank list as unset", () => {
expect(configured("")).toBeUndefined();
expect(configured(" , ")).toBeUndefined();
});
it("keeps empty names out of the list instead of failing", () => {
expect(
configured("Objective-C Message Analyzer,,Decompiler Switch Analysis"),
).toEqual(["Objective-C Message Analyzer", "Decompiler Switch Analysis"]);
});
it.each([
["a leading flag name", "-Decompiler Switch Analysis"],
["a name with command metacharacters", "Analyzer(&calc)"],
["a non-ASCII name", "分析器"],
["an over-long name", "A".repeat(121)],
])("rejects %s", (_label, setting) => {
const config = parseConfig({
GHIDRA_INSTALL_DIR: INSTALL,
REA_GHIDRA_DISABLED_ANALYZERS: setting,
});
expect(config.ok).toBe(false);
if (!config.ok)
expect(config.error).toMatchObject({
settings: [
expect.objectContaining({
setting: "REA_GHIDRA_DISABLED_ANALYZERS",
}),
],
});
});
it("rejects more than the admitted analyzer count", () => {
const setting = Array.from(
{ length: MAX_GHIDRA_DISABLED_ANALYZER_NAMES + 1 },
(_, index) => `Analyzer ${index}`,
).join(",");
const config = parseConfig({
GHIDRA_INSTALL_DIR: INSTALL,
REA_GHIDRA_DISABLED_ANALYZERS: setting,
});
expect(config.ok).toBe(false);
if (!config.ok)
expect(config.error).toMatchObject({
settings: [
expect.objectContaining({
setting: "REA_GHIDRA_DISABLED_ANALYZERS",
}),
],
});
});
it("admits the documented Objective-C analyzer name", () => {
expect(
ghidraDisabledAnalyzersSchema.parse("Objective-C Message Analyzer"),
).toEqual(["Objective-C Message Analyzer"]);
});
});
+17
View File
@@ -108,6 +108,8 @@ export interface GhidraHeadlessLauncherOptions {
};
/** Explicit import language committed by the analysis profile. */
readonly languageOverride?: GhidraLanguageOverride;
/** Auto-analyzers disabled before default auto-analysis, as configured. */
readonly disabledAnalyzers?: readonly string[];
/** Caller seeds committed by the analysis profile, applied before analysis. */
readonly analysisSeeds?: GhidraSeedCommitment;
readonly analysisExtensions?: readonly GhidraExtension[];
@@ -213,6 +215,9 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
? {}
: { languageOverride: this.options.languageOverride }),
...(seedPath === undefined ? {} : { seedPath }),
...(this.options.disabledAnalyzers === undefined
? {}
: { disabledAnalyzers: this.options.disabledAnalyzers }),
});
const scriptCommand = ghidraHeadlessCommand({
environment: this.options.environment,
@@ -425,6 +430,8 @@ export interface GhidraHeadlessArgumentOptions {
readonly baseAddr: string;
};
readonly languageOverride?: GhidraLanguageOverride;
/** Auto-analyzers disabled by the pre-analysis options script. */
readonly disabledAnalyzers?: readonly string[];
/** Canonical seed snapshot passed to the pre-analysis seed script. */
readonly seedPath?: string;
}
@@ -555,6 +562,16 @@ export const ghidraHeadlessArguments = (
scriptPath.join(bridgeDirectory, GHIDRA_SEED_SCRIPT),
options.seedPath,
]),
// Analyzer options must apply before default auto-analysis and before the
// post-analysis repair and bridge scripts start serving.
...(options.disabledAnalyzers === undefined ||
options.disabledAnalyzers.length === 0
? []
: [
"-preScript",
scriptPath.join(bridgeDirectory, "ReaGhidraAnalysisOptions.java"),
options.disabledAnalyzers.join(","),
]),
...((options.platform ?? process.platform) === "win32"
? []
: [
+150
View File
@@ -23,6 +23,7 @@ import { parseExecutableHeader } from "../domain/binaryTarget.js";
import { GhidraProvider } from "./GhidraProvider.js";
import type { GhidraTargetSnapshot } from "./GhidraClient.js";
import type { GhidraProviderClientFactory } from "./GhidraProviderClient.js";
import type { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
import type { GhidraInstallationHost } from "./GhidraInstallation.js";
import { GHIDRA_SESSION_CAPABILITIES } from "./GhidraSessionValues.js";
import { err, ok } from "../domain/result.js";
@@ -1810,3 +1811,152 @@ describe("Ghidra analysis seeds and configured language", () => {
}
});
});
describe("Ghidra disabled analyzer options", () => {
const configuredProvider = (
environment: Record<string, string>,
clientFactory?: GhidraProviderClientFactory,
) => {
const config = parseConfig({ GHIDRA_INSTALL_DIR: INSTALL, ...environment });
if (!config.ok) throw config.error;
return new GhidraProvider(
config.value,
silentLogger,
{},
installationHost(),
clientFactory,
);
};
it("records the configured analyzer options in the analysis profile", async () => {
const ghidra = configuredProvider({
REA_GHIDRA_DISABLED_ANALYZERS:
"Objective-C Message Analyzer,Decompiler Switch Analysis",
});
const resolved = await ghidra.resolveAnalysisProfile(
executableTarget("elf", "x86_64"),
);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("expected a bound Ghidra profile");
expect(resolved.value.profile.parameters).toMatchObject({
analyzer_preset:
"ghidra-default+disabled:Objective-C Message Analyzer,Decompiler Switch Analysis",
analysis_options: {
disabled_analyzers: [
"Objective-C Message Analyzer",
"Decompiler Switch Analysis",
],
},
});
});
it("hands the configured analyzers to the launcher for a matching profile", async () => {
const launchers: GhidraHeadlessLauncher[] = [];
const ghidra = configuredProvider(
{ REA_GHIDRA_DISABLED_ANALYZERS: "Objective-C Message Analyzer" },
(options) => {
launchers.push(options.launcher as GhidraHeadlessLauncher);
return {
start: () => Promise.resolve(ok(sessionInfo())),
callTool: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(ok(null)),
};
},
);
const target = executableTarget("elf", "x86_64");
const resolved = await ghidra.resolveAnalysisProfile(target);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("expected a bound Ghidra profile");
const client = ghidra.createClient(target, resolved.value.profile);
const health = await client.execute("health", {});
expect(health.ok).toBe(true);
expect(launchers).toHaveLength(1);
expect(launchers[0]?.options.disabledAnalyzers).toEqual([
"Objective-C Message Analyzer",
]);
});
it("binds analyzer overrides and raw import settings in one profile", async () => {
const launchers: GhidraHeadlessLauncher[] = [];
const ghidra = configuredProvider(
{ REA_GHIDRA_DISABLED_ANALYZERS: "Decompiler Switch Analysis" },
(options) => {
launchers.push(options.launcher as GhidraHeadlessLauncher);
return {
start: () => Promise.resolve(ok(sessionInfo())),
callTool: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(ok(null)),
};
},
);
const target: BinaryTarget = {
path: "/tmp/entry.bin",
sha256: "a".repeat(64),
kind: "executable",
format: "raw-binary",
architecture: "x86",
availableArchitectures: ["x86"],
entryPoint: "0x1000",
entryPointSource: "0x1000",
};
const resolved = await ghidra.resolveAnalysisProfile(target);
if (!resolved.ok || resolved.value.profile === null)
throw new Error("expected a bound raw-binary profile");
expect(resolved.value.profile.parameters).toMatchObject({
target_format: "raw-binary",
entry_point: "0x1000",
analyzer_preset: "ghidra-default+disabled:Decompiler Switch Analysis",
analysis_options: { disabled_analyzers: ["Decompiler Switch Analysis"] },
});
const client = ghidra.createClient(target, resolved.value.profile);
expect(launchers).toHaveLength(1);
expect(launchers[0]?.options).toMatchObject({
disabledAnalyzers: ["Decompiler Switch Analysis"],
rawBinary: {
languageId: "x86:LE:32:default",
compilerSpecId: "gcc",
baseAddr: "0x1000",
},
});
await client.close();
});
it("refuses a profile resolved without or with other analyzer options", async () => {
const target = executableTarget("elf", "x86_64");
const plainProvider = configuredProvider({});
const plain = await plainProvider.resolveAnalysisProfile(target);
if (!plain.ok || plain.value.profile === null)
throw new Error("expected profile");
const configuredProvider2 = configuredProvider({
REA_GHIDRA_DISABLED_ANALYZERS: "Objective-C Message Analyzer",
});
const configured = await configuredProvider2.resolveAnalysisProfile(target);
if (!configured.ok || configured.value.profile === null)
throw new Error("expected configured profile");
for (const [profile, environment] of [
[
plain.value.profile,
{ REA_GHIDRA_DISABLED_ANALYZERS: "Objective-C Message Analyzer" },
],
[configured.value.profile, {}],
[
configured.value.profile,
{ REA_GHIDRA_DISABLED_ANALYZERS: "Decompiler Switch Analysis" },
],
] as const) {
let starts = 0;
const client = configuredProvider(environment, () => ({
start: () => {
starts++;
return Promise.resolve(ok(sessionInfo()));
},
callTool: () => Promise.resolve(ok(null)),
close: () => Promise.resolve(ok(null)),
})).createClient(target, profile);
const failed = await client.execute("health", {});
expect(failed.ok).toBe(false);
if (!failed.ok) expect(failed.error._tag).toBe("ProviderAdapterError");
expect(starts).toBe(0);
}
});
});
+1
View File
@@ -200,6 +200,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
installation,
options?.signal,
this.config.ghidraLanguageOverride,
this.config.ghidraDisabledAnalyzers,
);
if (!resolved.ok || resolved.value.profile === null) return resolved;
const override = this.config.ghidraLanguageOverride;
+22
View File
@@ -14,7 +14,9 @@ import {
ghidraSeedLimitations,
} from "./GhidraAnalysisSeeds.js";
import {
ghidraProfileDisabledAnalyzers,
ghidraProfileLanguageOverride,
sameGhidraDisabledAnalyzers,
sameGhidraLanguageOverride,
} from "./GhidraAnalysisProfile.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
@@ -431,6 +433,23 @@ export const createGhidraProviderClient = (input: {
},
}),
);
const disabledAnalyzers = ghidraProfileDisabledAnalyzers(
committedProfile.parameters,
);
if (
!sameGhidraDisabledAnalyzers(
disabledAnalyzers,
config.ghidraDisabledAnalyzers,
)
)
return unavailableClient(
new ProviderAdapterError("ghidra", "open_binary", {
diagnostics: {
reason:
"The committed analysis profile and REA_GHIDRA_DISABLED_ANALYZERS differ; reopen the target to resolve a new profile.",
},
}),
);
const invalidProfile = validateGhidraExtensionProfile(
extensions,
config,
@@ -501,6 +520,9 @@ export const createGhidraProviderClient = (input: {
},
}),
...(languageOverride === undefined ? {} : { languageOverride }),
...(config.ghidraDisabledAnalyzers === undefined
? {}
: { disabledAnalyzers: config.ghidraDisabledAnalyzers }),
...(seeds === undefined ? {} : { analysisSeeds: seeds }),
platform: installation.platform,
...(extensions.length === 0 ? {} : { analysisExtensions: extensions }),
+6 -4
View File
@@ -3,21 +3,23 @@ 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";
readonly compilerSpecId: "default" | "gcc";
}
/**
* 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.
* languages with a supported generic compiler specification. These are
* analysis conventions, not evidence of the target's original compiler.
* 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" };
return { languageId: "x86:LE:32:default", compilerSpecId: "gcc" };
case "x86_64":
return { languageId: "x86:LE:64:default", compilerSpecId: "default" };
return { languageId: "x86:LE:64:default", compilerSpecId: "gcc" };
case "arm":
return { languageId: "ARM:LE:32:v7", compilerSpecId: "default" };
case "arm64":
+2 -2
View File
@@ -8,11 +8,11 @@ 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",
compilerSpecId: "gcc",
});
expect(ghidraRawBinaryLanguage("x86_64")).toEqual({
languageId: "x86:LE:64:default",
compilerSpecId: "default",
compilerSpecId: "gcc",
});
expect(ghidraRawBinaryLanguage("arm")).toEqual({
languageId: "ARM:LE:32:v7",