Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(win32): probe .cmd/.bat runtime shims via cmd.exe to avoid spawn EINVAL (#505)

Ahmad Kurniawan31ed005183c3
diff --git a/src/application/RuntimeExecutableDiagnostics.ts b/src/application/RuntimeExecutableDiagnostics.ts
index 3c65d729c..fcc1fb3b7 100644
--- a/src/application/RuntimeExecutableDiagnostics.ts
+++ b/src/application/RuntimeExecutableDiagnostics.ts
@@ -106,7 +106,13 @@ export const inspectRuntimeExecutables = async (
const diagnostics = await mapConcurrentBounded(
uniqueCandidates,
PROBE_CONCURRENCY,
- (candidate) => probeCandidate(candidate, options.timeoutMs, options.path),
+ (candidate) =>
+ probeCandidate(
+ candidate,
+ options.timeoutMs,
+ options.path,
+ options.platform,
+ ),
);
return {
launcher_node: await canonicalPath(options.launcherNode),
@@ -151,9 +157,15 @@ const probeCandidate = async (
},
timeoutMs: number | undefined,
effectivePath: string,
+ platform: NodeJS.Platform,
): Promise<RuntimeExecutableDiagnostic> => {
const canonical = await canonicalPath(candidate.path);
- const result = await executeVersion(candidate.path, timeoutMs, effectivePath);
+ const result = await executeVersion(
+ candidate.path,
+ timeoutMs,
+ effectivePath,
+ platform,
+ );
const identity = {
tool: candidate.tool,
lexical_path: candidate.path,
@@ -179,13 +191,26 @@ const executeVersion = (
path: string,
timeoutMs: number | undefined,
effectivePath: string,
+ platform: NodeJS.Platform = process.platform,
): Promise<VersionResult> =>
new Promise((resolve) => {
- const child = spawn(path, ["--version"], {
- windowsHide: true,
- env: environmentWithPath(effectivePath),
- stdio: ["ignore", "pipe", "pipe"],
- });
+ // Node >= 18.20 refuses to spawn .cmd/.bat files without a shell
+ // (CVE-2024-27980 mitigation) and throws spawn EINVAL. On Windows, npm and
+ // npx PATH shims are .CMD files, so every probe of them failed. Route
+ // batch-file candidates through cmd.exe instead.
+ const command = windowsBatchCommand(path, platform);
+ const child = command
+ ? spawn(command.executable, command.arguments, {
+ windowsHide: true,
+ windowsVerbatimArguments: true,
+ env: environmentWithPath(effectivePath),
+ stdio: ["ignore", "pipe", "pipe"],
+ })
+ : spawn(path, ["--version"], {
+ windowsHide: true,
+ env: environmentWithPath(effectivePath),
+ stdio: ["ignore", "pipe", "pipe"],
+ });
let stdout = "";
let stderr = "";
let spawnError: Error | undefined;
@@ -235,6 +260,37 @@ const executeVersion = (
});
});
+/**
+ * Build the cmd.exe invocation for a Windows batch-file candidate
+ * (.cmd/.bat/.CMD/.BAT). Returns null for anything else, including on
+ * non-Windows platforms. The whole command line is passed as one
+ * /c argument so paths with spaces survive; `windowsVerbatimArguments`
+ * keeps Node from re-quoting it. Embedded double quotes are doubled,
+ * since a bare quote would terminate the /c string and allow argument
+ * injection via a crafted PATH entry.
+ */
+const windowsBatchCommand = (
+ path: string,
+ platform: NodeJS.Platform = process.platform,
+ systemRoot: string = process.env.SystemRoot ?? "C:\\Windows",
+): { executable: string; arguments: string[] } | null => {
+ if (platform !== "win32") return null;
+ if (!/\.(cmd|bat)$/iu.test(path)) return null;
+ return {
+ executable: `${systemRoot}\\System32\\cmd.exe`,
+ arguments: ["/d", "/s", "/c", `"${path.replaceAll('"', '""')}" --version`],
+ };
+};
+
+/**
+ * Testing-only re-export of the batch-command builder. Pure and
+ * platform-injected, so it is fully exercisable on non-Windows hosts.
+ */
+export const windowsBatchCommandForTesting = windowsBatchCommand;
+
+/** Testing-only re-export of the version probe. */
+export const executeVersionForTesting = executeVersion;
+
const classifyProbeFailure = (
cause: Error,
child: ChildProcess,
diff --git a/src/application/RuntimeExecutableDiagnostics.win32.test.ts b/src/application/RuntimeExecutableDiagnostics.win32.test.ts
new file mode 100644
index 000000000..c9aa52773
--- /dev/null
+++ b/src/application/RuntimeExecutableDiagnostics.win32.test.ts
@@ -0,0 +1,80 @@
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import {
+ executeVersionForTesting as executeVersion,
+ windowsBatchCommandForTesting as windowsBatchCommand,
+} from "./RuntimeExecutableDiagnostics.js";
+
+const roots: string[] = [];
+
+afterEach(async () => {
+ await Promise.all(
+ roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
+ );
+});
+
+describe("windowsBatchCommand", () => {
+ it("returns null off Windows even for batch files", () => {
+ expect(windowsBatchCommand("C:\\tools\\npm.cmd", "linux")).toBeNull();
+ expect(windowsBatchCommand("C:\\tools\\npm.cmd", "darwin")).toBeNull();
+ });
+
+ it("returns null for non-batch candidates on win32", () => {
+ expect(windowsBatchCommand("C:\\tools\\node.exe", "win32")).toBeNull();
+ expect(windowsBatchCommand("/usr/local/bin/npm", "win32")).toBeNull();
+ });
+
+ it.each(["npm.cmd", "npm.CMD", "tool.bat", "tool.BAT"])(
+ "routes %s through cmd.exe on win32",
+ (file) => {
+ expect(windowsBatchCommand(`C:\\tools\\${file}`, "win32")).toEqual({
+ executable: "C:\\Windows\\System32\\cmd.exe",
+ arguments: ["/d", "/s", "/c", `"C:\\tools\\${file}" --version`],
+ });
+ },
+ );
+
+ it("preserves paths with spaces in a single /c argument", () => {
+ const command = windowsBatchCommand(
+ "C:\\Program Files\\nodejs\\npm.cmd",
+ "win32",
+ );
+ expect(command?.arguments[3]).toBe(
+ '"C:\\Program Files\\nodejs\\npm.cmd" --version',
+ );
+ });
+
+ it("doubles embedded quotes so they cannot break out of the /c string", () => {
+ const command = windowsBatchCommand('C:\\tools\\evil".cmd', "win32");
+ expect(command?.arguments[3]).toBe('"C:\\tools\\evil"".cmd" --version');
+ });
+
+ it("honours an explicit SystemRoot", () => {
+ const command = windowsBatchCommand(
+ "C:\\tools\\npm.cmd",
+ "win32",
+ "D:\\Win",
+ );
+ expect(command?.executable).toBe("D:\\Win\\System32\\cmd.exe");
+ });
+});
+
+describe.runIf(process.platform === "win32")("executeVersion on win32", () => {
+ it("probes a real .bat shim without spawn EINVAL", async () => {
+ const dir = await mkdtemp(join(tmpdir(), "rea-win32-"));
+ roots.push(dir);
+ const shim = join(dir, "probe.bat");
+ await writeFile(shim, "@echo 9.9.9\r\n");
+ const result = await executeVersion(
+ shim,
+ 10_000,
+ process.env.PATH ?? "",
+ "win32",
+ );
+ expect(result).toMatchObject({ ok: true, version: "9.9.9" });
+ });
+});