feat(ghidra): launch bounded Windows headless sessions

Invoke analyzeHeadless.bat through an absolute cmd.exe with fixed interpreter switches, quoted arguments, delayed expansion disabled, and fail-closed metacharacter and length checks. Isolate Windows home and temporary coordinates, hide provider windows, and terminate the P0 launcher tree through bounded taskkill cleanup. Advertise explicit limitations that this preview does not provide Job Object ownership, DACL enforcement, reparse-point authority, or hostile-target safety.
This commit is contained in:
N0zoM1z0
2026-07-17 03:05:19 +09:00
committed by N0zoM1z0
parent 629ffc3872
commit bc0fb45f16
10 changed files with 325 additions and 41 deletions
+122 -29
View File
@@ -1,11 +1,15 @@
import { mkdir } from "node:fs/promises";
import { basename, dirname, join } from "node:path";
import { basename, dirname, join, win32 } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { AnalysisCancelledError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
import {
cleanupOwnedProcessGroup,
cleanupWindowsProcessTree,
type ProcessCleanupResult,
} from "../process/ProcessOwnership.js";
import {
type ProviderProcessLaunch,
type SpawnedOwnedProviderProcess,
@@ -60,6 +64,8 @@ export interface GhidraHeadlessLauncherOptions {
readonly analyzeHeadlessPath: string;
readonly javaHome?: string;
readonly bridgeScriptPath: string;
readonly platform?: NodeJS.Platform;
readonly comSpec?: string;
}
/** Launch Ghidra without copying scripts into or modifying its installation. */
@@ -73,6 +79,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const paths = ghidraRuntimePaths(session.runtimeRoot);
const platform = this.options.platform ?? process.platform;
let started: SpawnedOwnedProviderProcess | undefined;
try {
await Promise.all(
@@ -101,21 +108,30 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
);
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
const headlessArguments = ghidraHeadlessArguments({
projectRoot: paths.projectRoot,
targetPath: session.targetPath,
bridgeScriptPath: this.options.bridgeScriptPath,
descriptorPath: paths.descriptorPath,
ghidraLogPath: paths.ghidraLogPath,
scriptLogPath: paths.scriptLogPath,
});
const command = ghidraHeadlessCommand({
platform,
analyzeHeadlessPath: this.options.analyzeHeadlessPath,
arguments: headlessArguments,
...(this.options.comSpec === undefined
? {}
: { comSpec: this.options.comSpec }),
});
started = await spawnOwnedProviderProcess({
command: this.options.analyzeHeadlessPath,
arguments: ghidraHeadlessArguments({
projectRoot: paths.projectRoot,
targetPath: session.targetPath,
bridgeScriptPath: this.options.bridgeScriptPath,
descriptorPath: paths.descriptorPath,
ghidraLogPath: paths.ghidraLogPath,
scriptLogPath: paths.scriptLogPath,
}),
command: command.command,
arguments: command.arguments,
runId: session.runId,
// analyzeHeadless is an interpreter-driven script. Parent identity and
// the per-process run token remain the cleanup authority.
expectedCommand: null,
env: ghidraLaunchEnvironment(paths, this.options.javaHome),
env: ghidraLaunchEnvironment(paths, this.options.javaHome, platform),
});
await writeFileAtomic(
paths.ownershipPath,
@@ -125,29 +141,31 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
pid: started.ownership.leaderPid,
process_group_id: started.ownership.processGroupId,
parent_pid: process.pid,
ownership_kind:
platform === "win32"
? "windows-process-tree-p0"
: "posix-process-group",
launcher: this.options.analyzeHeadlessPath,
created_at: new Date().toISOString(),
})}\n`,
{ encoding: "utf8", mode: 0o600 },
);
if (isAborted(options.signal)) {
await cleanupOwnedProcessGroup(started.ownership);
await cleanupStartedProcess(started, platform);
return err(new AnalysisCancelledError("open_binary"));
}
const ownership = started.ownership;
const spawned = started;
return ok({
process: started.process,
process: spawned.process,
ownsProcessLifetime: true,
cleanup: () => cleanupOwnedProcessGroup(ownership),
cleanup: () => cleanupStartedProcess(spawned, platform),
projectRoot: paths.projectRoot,
ghidraLogPath: paths.ghidraLogPath,
scriptLogPath: paths.scriptLogPath,
});
} catch (cause: unknown) {
if (started !== undefined)
await cleanupOwnedProcessGroup(started.ownership).catch(
() => undefined,
);
await cleanupStartedProcess(started, platform).catch(() => undefined);
return isAborted(options.signal)
? err(new AnalysisCancelledError("open_binary"))
: err(
@@ -157,6 +175,67 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
}
}
/** Exact executable and argv passed to shell-free process creation. */
export interface GhidraHeadlessCommand {
readonly command: string;
readonly arguments: readonly string[];
}
/** Build a direct POSIX launch or a conservatively quoted Windows batch call. */
export const ghidraHeadlessCommand = (options: {
readonly platform: NodeJS.Platform;
readonly analyzeHeadlessPath: string;
readonly arguments: readonly string[];
readonly comSpec?: string;
}): GhidraHeadlessCommand => {
if (options.platform !== "win32")
return {
command: options.analyzeHeadlessPath,
arguments: [...options.arguments],
};
const comSpec =
options.comSpec ??
process.env.ComSpec ??
(process.env.SystemRoot === undefined
? "C:\\Windows\\System32\\cmd.exe"
: win32.join(process.env.SystemRoot, "System32", "cmd.exe"));
if (
!win32.isAbsolute(comSpec) ||
win32.basename(comSpec).toLowerCase() !== "cmd.exe"
)
throw new GhidraLaunchError(
"Windows ComSpec must be an absolute cmd.exe path",
);
const tokens = [options.analyzeHeadlessPath, ...options.arguments].map(
quoteWindowsBatchToken,
);
const invocation = `"${tokens.join(" ")}"`;
if (invocation.length > 30_000)
throw new GhidraLaunchError(
"Windows Ghidra command exceeds the P0 length limit",
);
return {
command: comSpec,
arguments: ["/d", "/e:on", "/v:off", "/s", "/c", invocation],
};
};
const quoteWindowsBatchToken = (value: string): string => {
if (value.length === 0 || /[\u0000\r\n"%^!&|<>]/u.test(value))
throw new GhidraLaunchError(
"Windows Ghidra P0 paths cannot contain command-interpreter metacharacters",
);
return `"${value}"`;
};
const cleanupStartedProcess = (
started: SpawnedOwnedProviderProcess,
platform: NodeJS.Platform,
): Promise<ProcessCleanupResult> =>
platform === "win32"
? cleanupWindowsProcessTree(started.ownership.leaderPid)
: cleanupOwnedProcessGroup(started.ownership);
/** Paths encoded into one bounded analyzeHeadless invocation. */
export interface GhidraHeadlessArgumentOptions {
readonly projectRoot: string;
@@ -208,15 +287,29 @@ const ghidraRuntimePaths = (runtimeRoot: string) => ({
const ghidraLaunchEnvironment = (
paths: ReturnType<typeof ghidraRuntimePaths>,
javaHome: string | undefined,
): NodeJS.ProcessEnv => ({
...ghidraJavaEnvironment(javaHome),
HOME: paths.homeRoot,
TMPDIR: paths.tempRoot,
XDG_CACHE_HOME: paths.cacheRoot,
XDG_CONFIG_HOME: paths.configRoot,
XDG_DATA_HOME: paths.dataRoot,
GHIDRA_HEADLESS_MAXMEM: GHIDRA_MAX_HEAP,
GHIDRA_HEADLESS_JAVA_OPTIONS: `-Duser.home=${paths.homeRoot} -Djava.io.tmpdir=${paths.tempRoot}`,
});
platform: NodeJS.Platform,
): NodeJS.ProcessEnv => {
const javaOptions =
platform === "win32"
? `"-Duser.home=${paths.homeRoot}" "-Djava.io.tmpdir=${paths.tempRoot}"`
: `-Duser.home=${paths.homeRoot} -Djava.io.tmpdir=${paths.tempRoot}`;
return {
...ghidraJavaEnvironment(javaHome, process.env, platform),
HOME: paths.homeRoot,
TMPDIR: paths.tempRoot,
...(platform === "win32"
? {
USERPROFILE: paths.homeRoot,
TEMP: paths.tempRoot,
TMP: paths.tempRoot,
}
: {}),
XDG_CACHE_HOME: paths.cacheRoot,
XDG_CONFIG_HOME: paths.configRoot,
XDG_DATA_HOME: paths.dataRoot,
GHIDRA_HEADLESS_MAXMEM: GHIDRA_MAX_HEAP,
GHIDRA_HEADLESS_JAVA_OPTIONS: javaOptions,
};
};
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
+24 -3
View File
@@ -109,6 +109,11 @@ const healthLimitations = Object.freeze([
"The session serves operations only after default Ghidra auto-analysis completes; an analysis timeout fails the open instead of exposing partial results.",
"The imported Program and temporary project are ephemeral, read-only to REA, and deleted on close.",
]);
const windowsP0Limitations = Object.freeze([
"Windows Ghidra P0 accepts approved native x86-64 PE applications only; DLL, managed, hostile, sensitive, and mutable-path targets are unsupported.",
"The Windows bridge uses authenticated IPv4 loopback because Node path-based IPC does not expose Java AF_UNIX sockets; the endpoint file contains no bearer token.",
"Windows P0 process-tree cleanup uses bounded taskkill termination and does not claim Job Object ownership, private DACL enforcement, or reparse-point-safe path authority.",
]);
const limitationsFor = (operation: string): readonly string[] => {
const common = [
@@ -228,6 +233,17 @@ const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
}),
),
);
const WINDOWS_P0_CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
CAPABILITIES.map((capability) =>
Object.freeze({
...capability,
limitations: Object.freeze([
...capability.limitations,
...windowsP0Limitations,
]),
}),
),
);
const SUPPORTED_ARCHITECTURES = new Set(["x86", "x86_64", "arm", "arm64"]);
const SUPPORTED_FORMATS = new Set(["elf", "pe", "mach-o"]);
@@ -254,7 +270,9 @@ export class GhidraProvider implements AnalysisProviderCandidate {
}
capabilities(): readonly CapabilityDescriptor[] {
return CAPABILITIES;
return (this.installationHost?.platform ?? process.platform) === "win32"
? WINDOWS_P0_CAPABILITIES
: CAPABILITIES;
}
inspectAvailability(): ProviderAvailability {
@@ -345,6 +363,8 @@ export class GhidraProvider implements AnalysisProviderCandidate {
);
if (!prerequisites.ok) return unavailableClient(prerequisites.error);
const committedProfile = prerequisites.value.profile;
const providerLimitations =
installation.platform === "win32" ? windowsP0Limitations : [];
const client = this.clientFactory({
launcher: new GhidraHeadlessLauncher({
analyzeHeadlessPath: prerequisites.value.analyzeHeadlessPath,
@@ -354,6 +374,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
bridgeScriptPath: fileURLToPath(
new URL("../../bridge/ghidra/ReaGhidraBridge.java", import.meta.url),
),
platform: installation.platform,
}),
targetPath: target.path,
targetSha256: target.sha256,
@@ -386,7 +407,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
return ok(
createAnalysisExecution(started.value, committedProfile.provider, {
analysisProfile: committedProfile,
limitations: healthLimitations,
limitations: [...healthLimitations, ...providerLimitations],
}),
);
}
@@ -410,7 +431,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
createAnalysisExecution(result.value, committedProfile.provider, {
rawResult: called.value,
analysisProfile: committedProfile,
limitations: limitationsFor(operation),
limitations: [...limitationsFor(operation), ...providerLimitations],
}),
);
},