feat(ghidra): enable Windows x64 read-only analysis (#699)

* feat(ghidra): enable Windows x64 read-only analysis

* test(ghidra): exercise native Windows runtime boundaries

* test(ghidra): verify current Windows inventory and isolate ACL observer

* fix(ghidra): align Windows admission and address P0 review
This commit is contained in:
N0zoM1z0
2026-10-06 16:53:33 +08:00
committed by GitHub
parent cf061159ab
commit 26881da76a
65 changed files with 4091 additions and 356 deletions
+13 -1
View File
@@ -62,7 +62,7 @@ export type GhidraOperation =
/** Owns one authenticated, private, read-only Ghidra headless session. */
export class GhidraClient {
readonly #options: Required<
Pick<GhidraClientOptions, "startupTimeoutMs" | "transport">
Pick<GhidraClientOptions, "startupTimeoutMs" | "transport" | "platform">
> &
GhidraClientOptions;
readonly #logger: Logger;
@@ -76,6 +76,7 @@ export class GhidraClient {
#process: ProviderProcessSupervisor | undefined;
#runtimeRoot: PrivateRuntimeRoot | undefined;
#snapshotPath: string | undefined;
#targetAdmission: JsonValue | undefined;
#token: string | undefined;
// Retain authentication identities for diagnostics from late request settlement.
readonly #authenticationTokens = new Set<string>();
@@ -120,6 +121,7 @@ export class GhidraClient {
this.#options = {
...options,
startupTimeoutMs: options.startupTimeoutMs ?? GHIDRA_STARTUP_TIMEOUT_MS,
platform: options.platform ?? process.platform,
transport: options.transport ?? "unix-socket",
};
this.#logger = options.logger ?? silentLogger;
@@ -281,6 +283,7 @@ export class GhidraClient {
this.#runtimeRoot = await PrivateRuntimeRoot.create({
parent: SESSION_ROOT,
prefix: "rea-ghidra-",
platform: this.#options.platform,
});
} catch (cause: unknown) {
return err(
@@ -302,9 +305,12 @@ export class GhidraClient {
this.#options.targetPath,
this.#runtimeRoot.path,
this.#options.targetSha256,
{ signal: deadline.signal, platform: this.#options.platform },
);
this.#snapshotPath = snapshot.path;
this.#targetAdmission = snapshot.admission;
} catch (cause: unknown) {
if (deadline.signal.aborted) return this.#startupInterrupted(deadline);
const failure = this.#failure(
"start",
"Ghidra target snapshot failed admission",
@@ -403,6 +409,9 @@ export class GhidraClient {
providerVersion: this.#options.providerVersion,
profileDigest: this.#options.profileDigest,
targetSha256: this.#options.targetSha256,
...(this.#targetAdmission === undefined
? {}
: { targetAdmission: this.#targetAdmission }),
...(this.#options.expectedLanguageId === undefined
? {}
: { expectedLanguageId: this.#options.expectedLanguageId }),
@@ -583,6 +592,9 @@ export class GhidraClient {
return createGhidraDiagnostics({
targetPath: this.#options.targetPath,
targetSha256: this.#options.targetSha256,
...(this.#targetAdmission === undefined
? {}
: { targetAdmission: this.#targetAdmission }),
transport: this.#options.transport,
providerVersion: this.#options.providerVersion,
profileDigest: this.#options.profileDigest,
+2
View File
@@ -36,6 +36,8 @@ export interface GhidraClientOptions {
readonly runId?: string;
readonly targetPath: string;
readonly targetSha256: string;
/** Installation host shared by runtime allocation and snapshot admission. */
readonly platform?: NodeJS.Platform;
readonly transport?: GhidraTransportKind;
readonly providerVersion: string;
readonly profileDigest: string;
+4
View File
@@ -9,6 +9,7 @@ import type { GhidraTransportKind } from "./GhidraTransport.js";
export interface GhidraDiagnosticsOptions {
readonly targetPath: string;
readonly targetSha256: string;
readonly targetAdmission?: JsonValue;
readonly transport: GhidraTransportKind;
readonly providerVersion: string;
readonly profileDigest: string;
@@ -37,6 +38,9 @@ export const createGhidraDiagnostics = (
return {
target_path: options.targetPath,
target_sha256: options.targetSha256,
...(options.targetAdmission === undefined
? {}
: { target_admission: options.targetAdmission }),
transport: options.transport,
provider_version: options.providerVersion,
profile_digest: options.profileDigest,
+94 -22
View File
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
import { runDoctor, type DoctorHost } from "../application/Doctor.js";
import { createDoctorHostFixture } from "../application/Doctor.fixture.js";
import { providerRegistrationEnvironment } from "../application/SetupRegistrationEnvironment.js";
import { WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON } from "../process/WindowsAuthority.js";
import {
inspectGhidraInstallation,
type GhidraInstallationHost,
@@ -99,28 +101,6 @@ describe("Ghidra doctor integration", () => {
});
});
it("accepts the experimental Windows x64 Ghidra provider boundary", async () => {
const ghidra = inspection({
installDir: "C:\\tools\\ghidra_12.1.4_PUBLIC",
platform: "win32",
});
const result = await runDoctor(undefined, {
...doctorHost(ghidra),
platform: "win32",
architecture: "x64",
linuxDistribution: () => Promise.resolve(undefined),
});
expect(result.healthy).toBe(true);
expect(result.checks.find(({ name }) => name === "host")).toMatchObject({
ok: true,
detail: "win32 x64",
});
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
ok: true,
});
});
it.each([
[
"bad installation",
@@ -181,3 +161,95 @@ describe("Ghidra doctor integration", () => {
});
});
});
describe("Windows Ghidra doctor authority", () => {
it("distinguishes a valid Windows installation from unavailable native authority", async () => {
const ghidra = inspection({
installDir: "C:\\tools\\ghidra_12.1.4_PUBLIC",
platform: "win32",
});
const result = await runDoctor(undefined, {
...doctorHost(ghidra),
platform: "win32",
architecture: "x64",
linuxDistribution: () => Promise.resolve(undefined),
});
expect(result.healthy).toBe(false);
expect(result.providerInspections?.[0]).toMatchObject({
available: false,
providerVersion: "12.1.4",
registrationEnvironment: {
GHIDRA_INSTALL_DIR: "C:\\tools\\ghidra_12.1.4_PUBLIC",
},
});
expect(
providerRegistrationEnvironment(result.providerInspections ?? []),
).toMatchObject({
GHIDRA_INSTALL_DIR: "C:\\tools\\ghidra_12.1.4_PUBLIC",
});
expect(result.checks.find(({ name }) => name === "host")).toMatchObject({
ok: true,
detail: "win32 x64",
});
expect(result.checks.find(({ name }) => name === "ghidra")).toMatchObject({
ok: true,
});
expect(
result.checks.find(({ name }) => name === "ghidra-java"),
).toMatchObject({ ok: true });
expect(
result.checks.find(({ name }) => name === "ghidra-native_authority"),
).toMatchObject({
ok: false,
classification: "unsupported_host",
detail: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
remediation: expect.stringContaining("cannot enable"),
});
});
it("fails provider-scoped Windows readiness without blaming installation", async () => {
const ghidra = inspection({
installDir: "C:\\tools\\ghidra_12.1.4_PUBLIC",
platform: "win32",
});
const result = await runDoctor(
undefined,
{
...doctorHost(ghidra),
platform: "win32",
linuxDistribution: () => Promise.resolve(undefined),
},
{ providers: ["ghidra"] },
);
expect(result.healthy).toBe(false);
expect(result.scope_checks).toContainEqual(
expect.objectContaining({
name: "ghidra-native_authority",
classification: "unsupported_host",
detail: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
}),
);
});
it("keeps missing Windows Java actionable as a dependency failure", () => {
const projected = projectGhidraDoctorInspection(
inspection(
{
installDir: "C:\\tools\\ghidra_12.1.4_PUBLIC",
platform: "win32",
},
{ probeJava: () => undefined },
),
);
expect(projected.available).toBe(false);
expect(projected.checks).toContainEqual(
expect.objectContaining({
name: "java",
ok: false,
classification: "missing_dependency",
remediation: expect.any(String),
}),
);
});
});
+46 -17
View File
@@ -2,31 +2,60 @@ import type {
DoctorProviderCheck,
DoctorProviderInspection,
} from "../application/Doctor.js";
import {
hasWindowsNativeAuthority,
windowsNativeAuthorityUnavailableReason,
} from "../process/WindowsAuthority.js";
import {
inspectGhidraInstallation,
type GhidraInstallationCheck,
type GhidraInstallationInspection,
} from "./GhidraInstallation.js";
/** Project adapter-owned installation facts into the generic doctor contract. */
/** Project installation and runtime-authority facts into the doctor contract. */
export const projectGhidraDoctorInspection = (
inspection: GhidraInstallationInspection,
): DoctorProviderInspection => ({
id: "ghidra",
configured: inspection.installDir !== null,
available: inspection.status === "available",
providerVersion: inspection.providerVersion,
registrationEnvironment:
inspection.status === "available"
? {
GHIDRA_INSTALL_DIR: inspection.installDir,
JAVA_HOME: inspection.javaHome,
}
: {},
checks: selectedChecks(inspection).map((check) =>
projectCheck(check, inspection.installDir !== null),
),
});
): DoctorProviderInspection => {
const windowsAuthorityUnavailable =
inspection.status === "available" &&
inspection.platform === "win32" &&
!hasWindowsNativeAuthority(inspection.platform);
return {
id: "ghidra",
configured: inspection.installDir !== null,
available:
inspection.status === "available" && !windowsAuthorityUnavailable,
providerVersion: inspection.providerVersion,
registrationEnvironment:
inspection.status === "available"
? {
GHIDRA_INSTALL_DIR: inspection.installDir,
JAVA_HOME: inspection.javaHome,
}
: {},
checks: [
...selectedChecks(inspection).map((check) =>
projectCheck(check, inspection.installDir !== null),
),
...(inspection.status === "available" && inspection.platform === "win32"
? [
{
name: "native_authority",
ok: !windowsAuthorityUnavailable,
code: windowsAuthorityUnavailable ? "unsupported_host" : null,
detail: windowsAuthorityUnavailable
? windowsNativeAuthorityUnavailableReason(inspection.platform)
: "Verified Windows native Job Object, private DACL, and reparse-safe handle controls; local NTFS only.",
remediation: windowsAuthorityUnavailable
? "Use the matching Windows x64 REA package with its bundled native addon and a writable local NTFS temporary directory. The native failure above identifies the failed constraint; Ghidra installation or registration changes cannot enable a missing native backend."
: null,
classification: "unsupported_host" as const,
},
]
: []),
],
};
};
/** Inspect the process-configured BYO Ghidra installation for `rea doctor`. */
export const inspectSystemGhidraProvider =
+1 -1
View File
@@ -487,7 +487,7 @@ const systemGhidraInstallationHost = (): GhidraInstallationHost => ({
probeJava(command, environment) {
const observed = spawnSync(
command,
["-XshowSettings:properties", "-version"],
["-XX:-UsePerfData", "-XshowSettings:properties", "-version"],
{
encoding: "utf8",
env: environment,
+83 -25
View File
@@ -3,6 +3,8 @@ import { basename, dirname, join, win32 } from "node:path";
import writeFileAtomic from "write-file-atomic";
import { windowsPrivateRuntime } from "../windows/WindowsPrivateRuntime.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../domain/result.js";
import {
@@ -80,17 +82,8 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
const platform = this.options.platform ?? process.platform;
let started: SpawnedOwnedProviderProcess | undefined;
try {
await Promise.all(
[
paths.projectRoot,
paths.homeRoot,
paths.tempRoot,
paths.cacheRoot,
paths.configRoot,
paths.dataRoot,
].map((path) => mkdir(path, { recursive: true, mode: 0o700 })),
);
await writeFileAtomic(
await createGhidraRuntimeDirectories(paths, platform);
await writeGhidraRuntimeFile(
paths.descriptorPath,
`${JSON.stringify({
transport: session.transport,
@@ -101,7 +94,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
provider_version: session.providerVersion,
profile_digest: session.profileDigest,
})}\n`,
{ encoding: "utf8", mode: 0o600 },
platform,
);
if (isAborted(options.signal))
return err(new AnalysisCancelledError("open_binary"));
@@ -138,7 +131,7 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
platform,
env: ghidraLaunchEnvironment(paths, this.options.javaHome, platform),
});
await writeFileAtomic(
await writeGhidraRuntimeFile(
paths.ownershipPath,
`${JSON.stringify({
run_id: session.runId,
@@ -146,13 +139,11 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
process_group_id: started.ownership.processGroupId,
parent_pid: process.pid,
ownership_kind:
platform === "win32"
? "windows-process-tree-p0"
: "posix-process-group",
platform === "win32" ? "windows-job-object" : "posix-process-group",
launcher: this.options.analyzeHeadlessPath,
created_at: new Date().toISOString(),
})}\n`,
{ encoding: "utf8", mode: 0o600 },
platform,
);
if (isAborted(options.signal)) {
await cleanupStartedProcess(started, platform);
@@ -258,9 +249,11 @@ const cleanupStartedProcess = (
started: SpawnedOwnedProviderProcess,
platform: NodeJS.Platform,
): Promise<ProcessCleanupResult> =>
platform === "win32"
? cleanupWindowsProcessTree(started.ownership.leaderPid)
: cleanupOwnedProcessGroup(started.ownership);
started.cleanup !== undefined
? started.cleanup()
: platform === "win32"
? cleanupWindowsProcessTree(started.ownership.leaderPid)
: cleanupOwnedProcessGroup(started.ownership);
/** Paths encoded into one bounded analyzeHeadless invocation. */
export interface GhidraHeadlessArgumentOptions {
@@ -332,22 +325,62 @@ const ghidraRuntimePaths = (runtimeRoot: string) => ({
scriptLogPath: join(runtimeRoot, "script.log"),
});
const createGhidraRuntimeDirectories = async (
paths: ReturnType<typeof ghidraRuntimePaths>,
platform: NodeJS.Platform,
): Promise<void> => {
if (platform === "win32") {
const runtime = windowsPrivateRuntime(dirname(paths.projectRoot));
for (const path of [
paths.projectRoot,
paths.homeRoot,
paths.tempRoot,
paths.cacheRoot,
paths.configRoot,
paths.dataRoot,
])
runtime.mkdir(basename(path));
return;
}
await Promise.all(
[
paths.projectRoot,
paths.homeRoot,
paths.tempRoot,
paths.cacheRoot,
paths.configRoot,
paths.dataRoot,
].map((path) => mkdir(path, { recursive: true, mode: 0o700 })),
);
};
const writeGhidraRuntimeFile = async (
path: string,
content: string,
platform: NodeJS.Platform,
): Promise<void> => {
if (platform === "win32") {
windowsPrivateRuntime(dirname(path)).writeFile(basename(path), content);
return;
}
await writeFileAtomic(path, content, { encoding: "utf8", mode: 0o600 });
};
const ghidraLaunchEnvironment = (
paths: ReturnType<typeof ghidraRuntimePaths>,
javaHome: string | undefined,
platform: NodeJS.Platform,
): NodeJS.ProcessEnv => {
// analyzeHeadless.bat wraps GHIDRA_HEADLESS_JAVA_OPTIONS in its own quotes
// when it builds VMARG_LIST. Nested quotes break cmd.exe tokenization before
// Ghidra starts, so keep this option list unquoted on every platform.
const javaOptions = `-Duser.home=${paths.homeRoot} -Djava.io.tmpdir=${paths.tempRoot}`;
return {
...ghidraJavaEnvironment(javaHome, process.env, platform),
...ghidraHeadlessJavaOptions(paths.homeRoot, paths.tempRoot, platform),
HOME: paths.homeRoot,
TMPDIR: paths.tempRoot,
...(platform === "win32"
? {
USERPROFILE: paths.homeRoot,
APPDATA: paths.configRoot,
LOCALAPPDATA: paths.cacheRoot,
TEMP: paths.tempRoot,
TMP: paths.tempRoot,
}
@@ -355,8 +388,33 @@ const ghidraLaunchEnvironment = (
XDG_CACHE_HOME: paths.cacheRoot,
XDG_CONFIG_HOME: paths.configRoot,
XDG_DATA_HOME: paths.dataRoot,
GHIDRA_HEADLESS_JAVA_OPTIONS: javaOptions,
};
};
/** Encode provider-owned JVM paths for the parser that actually consumes them. */
export const ghidraHeadlessJavaOptions = (
homeRoot: string,
tempRoot: string,
platform: NodeJS.Platform,
): Pick<
NodeJS.ProcessEnv,
"JDK_JAVA_OPTIONS" | "GHIDRA_HEADLESS_JAVA_OPTIONS"
> => {
const options = [`-Duser.home=${homeRoot}`, `-Djava.io.tmpdir=${tempRoot}`];
// analyzeHeadless.bat quotes VMARG_LIST, then launch.bat expands it again.
// Inner quotes fail in cmd.exe; unquoted paths with spaces split at the JVM.
// JDK_JAVA_OPTIONS is parsed by Java itself, outside that batch expansion.
return platform === "win32"
? {
JDK_JAVA_OPTIONS: [...options, "-XX:-UsePerfData"]
.map(quoteWindowsBatchToken)
.join(" "),
GHIDRA_HEADLESS_JAVA_OPTIONS: "",
}
: {
JDK_JAVA_OPTIONS: "",
GHIDRA_HEADLESS_JAVA_OPTIONS: options.join(" "),
};
};
const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true;
@@ -0,0 +1,45 @@
import { describe, expect, it } from "vitest";
import { ghidraHeadlessJavaOptions } from "./GhidraLauncher.js";
describe("Ghidra headless JVM environment", () => {
it("passes Windows paths with spaces to Java's environment parser", () => {
expect(
ghidraHeadlessJavaOptions(
"C:\\REA Runtime\\home",
"C:\\REA Runtime\\tmp",
"win32",
),
).toEqual({
JDK_JAVA_OPTIONS:
'"-Duser.home=C:\\REA Runtime\\home" "-Djava.io.tmpdir=C:\\REA Runtime\\tmp" "-XX:-UsePerfData"',
GHIDRA_HEADLESS_JAVA_OPTIONS: "",
});
});
it.each(["linux", "darwin"] as const)(
"keeps the %s headless-script option list and clears inherited JDK options",
(platform) => {
expect(
ghidraHeadlessJavaOptions("/tmp/rea/home", "/tmp/rea/tmp", platform),
).toEqual({
JDK_JAVA_OPTIONS: "",
GHIDRA_HEADLESS_JAVA_OPTIONS:
"-Duser.home=/tmp/rea/home -Djava.io.tmpdir=/tmp/rea/tmp",
});
},
);
it.each(["%TEMP%", 'quote"', "amp&", "line\n", "nul\0"])(
"rejects interpreter metacharacters in either Windows JVM path: %s",
(suffix) => {
for (const [home, temp] of [
[`C:\\runtime\\${suffix}`, "C:\\runtime\\tmp"],
["C:\\runtime\\home", `C:\\runtime\\${suffix}`],
] as const)
expect(() => ghidraHeadlessJavaOptions(home, temp, "win32")).toThrow(
/metacharacters/u,
);
},
);
});
+10 -3
View File
@@ -224,7 +224,9 @@ describe("Ghidra platform support", () => {
expect(ghidra.inspectAvailability()).toMatchObject({
status: "unavailable",
code: "unsupported_host",
reason: expect.stringContaining("native authority is unavailable"),
reason: expect.stringContaining(
"Windows native controls are unavailable",
),
diagnostics: {
windows_security: {
job_object_process_ownership: expect.objectContaining({
@@ -249,8 +251,12 @@ describe("Ghidra platform support", () => {
available: false,
availabilityCode: "unsupported_host",
limitations: expect.arrayContaining([
expect.stringContaining("bounded taskkill cleanup"),
expect.stringContaining("private DACL enforcement"),
expect.stringContaining(
"matching packaged Windows x64 native addon",
),
expect.stringContaining(
"private DACLs, and Job Object ownership automatically",
),
]),
}),
]),
@@ -354,6 +360,7 @@ describe("Ghidra client projection", () => {
expect(factoryOptions).toEqual([
expect.objectContaining({
runId: "11111111-1111-4111-8111-111111111111",
platform: "linux",
}),
]);
expect(toolCalls).toEqual([
+10 -6
View File
@@ -58,7 +58,7 @@ import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
import type { GhidraSessionError } from "./GhidraSessionError.js";
import {
CAPABILITIES,
WINDOWS_P0_CAPABILITIES,
windowsP0Capabilities,
GHIDRA_PROVIDER_IDENTITY,
GHIDRA_PROVIDER_TOOL_CONTRACTS,
healthLimitations,
@@ -66,7 +66,7 @@ import {
limitationsFor,
} from "./GhidraProviderCapabilities.js";
import {
WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
windowsNativeAuthorityUnavailableReason,
hasWindowsNativeAuthority,
windowsNativeCapabilities,
} from "../process/WindowsAuthority.js";
@@ -99,7 +99,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
capabilities(): readonly CapabilityDescriptor[] {
return (this.installationHost?.platform ?? process.platform) === "win32"
? WINDOWS_P0_CAPABILITIES
? windowsP0Capabilities()
: CAPABILITIES;
}
@@ -114,7 +114,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
return {
status: "unavailable",
code: "unsupported_host",
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
reason: windowsNativeAuthorityUnavailableReason(installation.platform),
diagnostics: {
...diagnostics,
windows_security: jsonObjectSchema.parse(
@@ -213,6 +213,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
]
: [];
const client = this.clientFactory({
platform: installation.platform,
launcher: new GhidraHeadlessLauncher({
analyzeHeadlessPath: prerequisites.value.analyzeHeadlessPath,
...(this.config.ghidraJavaHome === undefined
@@ -225,7 +226,10 @@ export class GhidraProvider implements AnalysisProviderCandidate {
...(target.format === "dos-com" ? { dosCom: true } : {}),
platform: installation.platform,
}),
targetPath: target.path,
targetPath:
installation.platform === "win32"
? (target.sourcePath ?? target.path)
: target.path,
targetSha256: target.sha256,
transport:
installation.platform === "win32"
@@ -450,7 +454,7 @@ const ghidraClientPrerequisites = (
new AnalysisCapabilityUnavailableError(
"ghidra",
"health",
WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
windowsNativeAuthorityUnavailableReason(installation.platform),
),
);
if (profile === undefined || profile.provider.id !== "ghidra")
+24 -16
View File
@@ -2,7 +2,10 @@ import type {
CapabilityDescriptor,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON } from "../process/WindowsAuthority.js";
import {
hasWindowsNativeAuthority,
windowsNativeAuthorityUnavailableReason,
} from "../process/WindowsAuthority.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
import { GHIDRA_FUNCTION_OPERATIONS } from "./GhidraFunctionValues.js";
import { GHIDRA_INVENTORY_OPERATIONS } from "./GhidraInventoryValues.js";
@@ -44,7 +47,7 @@ export const healthLimitations = Object.freeze([
export 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 is not admitted until a native authority proves Job Object ownership, private DACL enforcement, and reparse-safe path admission; bounded taskkill cleanup and chmod(0700) do not prove those controls.",
"Windows sessions require the matching packaged Windows x64 native addon, local NTFS targets and runtimes, and Windows 10 or later. Native handles enforce path admission, private DACLs, and Job Object ownership automatically.",
]);
/** Limitation text for one admitted operation, including the common base. */
@@ -172,18 +175,23 @@ export const CAPABILITIES: readonly CapabilityDescriptor[] = Object.freeze(
);
/** Capabilities advertised for the experimental Windows x64 P0 boundary. */
export const WINDOWS_P0_CAPABILITIES: readonly CapabilityDescriptor[] =
Object.freeze(
CAPABILITIES.map((capability) =>
Object.freeze({
...capability,
available: false,
reason: WINDOWS_NATIVE_AUTHORITY_UNAVAILABLE_REASON,
availabilityCode: "unsupported_host" as const,
limitations: Object.freeze([
...capability.limitations,
...windowsP0Limitations,
]),
}),
),
export const windowsP0Capabilities = (): readonly CapabilityDescriptor[] => {
const available = hasWindowsNativeAuthority("win32");
return Object.freeze(
CAPABILITIES.map((capability): CapabilityDescriptor => {
const limitations = Object.freeze([
...capability.limitations,
...windowsP0Limitations,
]);
return available
? Object.freeze({ ...capability, limitations })
: Object.freeze({
...capability,
available: false,
reason: windowsNativeAuthorityUnavailableReason("win32"),
availabilityCode: "unsupported_host",
limitations,
});
}),
);
};
+24
View File
@@ -3,10 +3,14 @@ import { constants, createReadStream } from "node:fs";
import { chmod, copyFile, rm } from "node:fs/promises";
import { extname, join } from "node:path";
import type { JsonValue } from "../domain/jsonValue.js";
import { windowsPrivateRuntime } from "../windows/WindowsPrivateRuntime.js";
/** Immutable target copy admitted to one ephemeral Ghidra import. */
export interface GhidraTargetSnapshot {
readonly path: string;
readonly sha256: string;
readonly admission?: JsonValue;
}
/** Copy one target and require its bytes to match the parsed target identity. */
@@ -14,6 +18,10 @@ export const createGhidraTargetSnapshot = async (
sourcePath: string,
runtimeRoot: string,
expectedSha256: string,
options: {
readonly signal?: AbortSignal;
readonly platform?: NodeJS.Platform;
} = {},
): Promise<GhidraTargetSnapshot> => {
if (!/^[a-f0-9]{64}$/u.test(expectedSha256))
throw new TypeError("Ghidra target SHA-256 commitment is invalid");
@@ -22,6 +30,22 @@ export const createGhidraTargetSnapshot = async (
runtimeRoot,
`target-${expectedSha256.slice(0, 12)}${suffix}`,
);
if ((options.platform ?? process.platform) === "win32") {
const observed = await windowsPrivateRuntime(runtimeRoot).snapshot(
sourcePath,
`target-${expectedSha256.slice(0, 12)}${suffix}`,
options.signal,
);
if (observed.sha256 !== expectedSha256)
throw new Error(
`Ghidra target snapshot digest mismatch: expected ${expectedSha256}, observed ${observed.sha256}`,
);
return {
path: snapshotPath,
sha256: observed.sha256,
admission: { source: observed.source, snapshot: observed.snapshot },
};
}
try {
await copyFile(sourcePath, snapshotPath, constants.COPYFILE_EXCL);
await chmod(snapshotPath, 0o600);
+23
View File
@@ -1,5 +1,7 @@
import { access, open } from "node:fs/promises";
import { readWindowsPrivateRuntimeFile } from "../windows/WindowsPrivateRuntime.js";
import { err, ok, type Result } from "../domain/result.js";
import { GhidraSessionError } from "./GhidraSessionError.js";
@@ -37,6 +39,24 @@ export const observeGhidraEndpoint = async (
);
}
}
if (process.platform === "win32") {
try {
return parseTcpEndpoint(
endpoint,
readWindowsPrivateRuntimeFile(endpoint.path),
);
} catch (cause: unknown) {
return isMissing(cause) || isWindowsEndpointWriterBusy(cause)
? ok(null)
: err(
endpointFailure(
endpoint,
"Ghidra endpoint observation failed",
cause,
),
);
}
}
let handle;
try {
handle = await open(endpoint.path, "r");
@@ -120,3 +140,6 @@ const endpointFailure = (
const isMissing = (cause: unknown): boolean =>
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
const isWindowsEndpointWriterBusy = (cause: unknown): boolean =>
cause instanceof Error && "win32Code" in cause && cause.win32Code === 32;