diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2810a107afd..5f4b16aefb2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1227,6 +1227,7 @@ jobs: src/process/ProcessOwnership.part2.test.ts src/process/ProcessOwnership.part3.test.ts src/process/ProcessOwnership.validation.test.ts + src/process/WindowsBatchCommand.test.ts src/application/Update.test.ts tests/process-global/updateMaintenance.test.ts tests/process-global/runnerCancellation.test.ts diff --git a/docs/guides/android/apktool-resource-analysis.md b/docs/guides/android/apktool-resource-analysis.md index 51cced04372..b204ff27d2b 100644 --- a/docs/guides/android/apktool-resource-analysis.md +++ b/docs/guides/android/apktool-resource-analysis.md @@ -51,10 +51,13 @@ is not a security recommendation. REA does not fetch advisories at runtime. On Windows, a `.bat` or `.cmd` launcher (such as Chocolatey's `apktool.bat`) runs through an explicit `cmd.exe /d /s /c` call. That call has no AutoRun, no delayed expansion, and quotes every argument. A launcher path that -contains `"`, `%`, `^`, `!`, `&`, `|`, `<` or `>` is reported as -`not_configured` instead of being passed to `cmd.exe`. If REA's temporary -decode paths contain those characters, decoding through a batch launcher -reports `capability_unavailable`. +contains a quote, a line break, or a percent expansion is not passed to +`cmd.exe`. Inspection reports `not_configured`. Decoding reports +`configuration_invalid`. A percent span that appears only after the quoted +tokens are joined is refused the same way. Quoted `&`, `^`, and `!` are +passed through. If REA's temporary decode paths contain a quote, a line +break, or a percent expansion, decoding through a batch launcher reports +`configuration_invalid`. ## Answer an analyst question diff --git a/docs/providers/windows-ghidra-p0.md b/docs/providers/windows-ghidra-p0.md index 2e4d9b6d19f..a651ed7ec7c 100644 --- a/docs/providers/windows-ghidra-p0.md +++ b/docs/providers/windows-ghidra-p0.md @@ -248,8 +248,10 @@ object's private DACL. The random 256-bit bearer token stays in the private, immutable session descriptor and is redacted from diagnostic output. The batch launcher uses an absolute `cmd.exe`, fixed switches, delayed -expansion disabled, and quoted tokens. Command-interpreter metacharacters in -launch paths are unsupported. JVM home and temporary properties use quoted +expansion disabled, and quoted tokens. Quotes, line breaks, and percent +expansions in launch paths are unsupported. A percent span that appears only +after the quoted tokens are joined is refused the same way. Quoted `&`, `^`, +and `!` are passed through. JVM home and temporary properties use quoted `JDK_JAVA_OPTIONS`, preserving spaces. `APPDATA` and `LOCALAPPDATA` point into the private runtime, isolating Ghidra preferences, logs, and caches. diff --git a/scripts/ci/scopes.mjs b/scripts/ci/scopes.mjs index c57a11fc193..d05db9fe5a2 100644 --- a/scripts/ci/scopes.mjs +++ b/scripts/ci/scopes.mjs @@ -374,6 +374,7 @@ const PATH_SCOPES = { "src/process/ProcessOwnership.part2.test.ts", "src/process/ProcessOwnership.part3.test.ts", "src/process/ProcessOwnership.validation.test.ts", + "src/process/WindowsBatchCommand.test.ts", "src/application/Update.test.ts", "tests/process-global/updateMaintenance.test.ts", "tests/conformance/providers/ghidra/realGhidraWindowsWorkflow.test.ts", diff --git a/src/apktool/ApktoolConfiguration.test.ts b/src/apktool/ApktoolConfiguration.test.ts index d92a729a1c6..c0540805fd1 100644 --- a/src/apktool/ApktoolConfiguration.test.ts +++ b/src/apktool/ApktoolConfiguration.test.ts @@ -275,10 +275,24 @@ describe("apktoolInvocation", () => { }); }); + it("quotes an ampersand in a Windows batch launcher path", () => { + expect( + apktoolInvocation( + { + command: "C:\\tools & more\\apktool.cmd", + commandSource: "environment", + }, + ["--version"], + windows, + "win32", + ).arguments.at(-1), + ).toBe('""C:\\tools & more\\apktool.cmd" "--version""'); + }); + it("reports a batch launcher that cmd.exe would reinterpret before running it", async () => { const failure = await inspectApktoolClient( { - command: "C:\\tools & more\\apktool.cmd", + command: "C:\\tools\\apk%tool%.cmd", commandSource: "environment", }, commands, @@ -293,7 +307,7 @@ describe("apktoolInvocation", () => { code: "not_configured", remediation: expect.stringContaining(APKTOOL_COMMAND_ENV), diagnostics: { - selected_command: "C:\\tools & more\\apktool.cmd", + selected_command: "C:\\tools\\apk%tool%.cmd", }, }); }); diff --git a/src/apktool/ApktoolConfiguration.ts b/src/apktool/ApktoolConfiguration.ts index 7d6a4ca068a..5846acad566 100644 --- a/src/apktool/ApktoolConfiguration.ts +++ b/src/apktool/ApktoolConfiguration.ts @@ -293,7 +293,7 @@ export const inspectApktoolClient = async ( throw new ApktoolConfigurationFailure( "launcher_unsupported", `The selected apktool launcher cannot be run through cmd.exe: ${cause.message}`, - `Set ${APKTOOL_COMMAND_ENV} to a launcher path without cmd.exe metacharacters (" % ^ ! & | < >), or to a native apktool executable.`, + `Set ${APKTOOL_COMMAND_ENV} to a native apktool executable, or to a launcher path whose arguments do not contain quotes, line breaks, or percent expansions.`, { selected_command: selection.command, command_source: selection.commandSource, diff --git a/src/apktool/ApktoolProvider.test.ts b/src/apktool/ApktoolProvider.test.ts index 84eb8db3925..2be682f7b16 100644 --- a/src/apktool/ApktoolProvider.test.ts +++ b/src/apktool/ApktoolProvider.test.ts @@ -21,6 +21,7 @@ import { } from "../process/ProcessOwnershipObservation.js"; import { ApktoolWorkspace } from "./ApktoolWorkspace.js"; import { createApktoolResourceAnalysisService } from "../application/ProviderOperationServices.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; import { projectAnalysisError } from "../domain/analysisErrorProjection.js"; import { apktoolRequestSchema, @@ -1911,3 +1912,34 @@ it("matches the launcher variable by the selected host's environment rules", asy diagnostics: { selected_command: command }, }); }); + +test("reports a Windows batch launcher refusal as invalid configuration when decoding", async () => { + const provider = new ApktoolProvider({ + platform: "win32", + environment: { + REA_APKTOOL_COMMAND: "C:\\tools\\apk%tool%.cmd", + COMSPEC: "C:\\Windows\\System32\\cmd.exe", + SYSTEMROOT: "C:\\Windows", + }, + }); + try { + expect(await provider.inspectAvailability()).toMatchObject({ + status: "unavailable", + code: "not_configured", + }); + const result = await provider.execute({ + operation: "decode_android_resources", + input: { path: "C:\\targets\\app.apk", include_strings: true }, + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(result.error).toBeInstanceOf(ConfigurationError); + const projected = projectAnalysisError(result.error); + expect(projected.code).toBe("configuration_invalid"); + expect(projected.message).toContain("apk%tool%"); + expect(projected.message).toContain("REA_APKTOOL_COMMAND"); + expect(projected.message).not.toContain("rea doctor"); + } finally { + await provider.close(); + } +}); diff --git a/src/apktool/ApktoolProvider.ts b/src/apktool/ApktoolProvider.ts index bf0cf37a88e..2c79414388d 100644 --- a/src/apktool/ApktoolProvider.ts +++ b/src/apktool/ApktoolProvider.ts @@ -53,12 +53,12 @@ import { } from "../domain/apktool/apktoolResourceAnalysis.js"; import { projectApktoolStringTables } from "./ApktoolStringTables.js"; import { - AnalysisCapabilityUnavailableError, AnalysisProtocolError, cancelledBy, OwnerCancellation, unsupportedTarget, } from "../domain/analysisErrorCore.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js"; import { err, ok, type Result } from "../domain/result.js"; import { finalizedResult, runOwned } from "../providers/runOwned.js"; @@ -78,6 +78,7 @@ import { ownedProcessPrerequisiteAvailability } from "../providers/ownedProcessA import { ApktoolConfigurationFailure, apktoolConfigurationAvailability, + APKTOOL_COMMAND_ENV, apktoolInvocation, inspectApktoolClient, resolveApktoolCommand, @@ -126,6 +127,18 @@ const throwIfCancelled = ( if (signal?.aborted === true) throw cancelledBy(operation, signal); }; +const apktoolBatchConfigurationError = ( + cause: WindowsBatchCommandError, + message: string, +): ConfigurationError => { + const remediationAction = `Use a launcher path and decode paths without quotes, line breaks, or percent expansions, or set ${APKTOOL_COMMAND_ENV} to a native apktool executable.`; + return new ConfigurationError(message, { + cause, + userMessage: `${message} ${remediationAction}`, + remediationAction, + }); +}; + interface DecodeLimits { readonly timeoutMs: number; readonly maxOutputBytes: number; @@ -155,13 +168,10 @@ const runApktool = async ( ); } catch (cause) { if (!(cause instanceof WindowsBatchCommandError)) throw cause; - const reason = `The apktool batch launcher cannot receive REA's decode paths through cmd.exe: ${cause.message}`; return err( - new AnalysisCapabilityUnavailableError( - APKTOOL_PROVIDER_IDENTITY.id, - operation, - reason, - { cause, userMessage: reason }, + apktoolBatchConfigurationError( + cause, + `The apktool batch launcher ${selection.command} cannot receive REA's decode paths through cmd.exe: ${cause.message}`, ), ); } @@ -466,6 +476,21 @@ export class ApktoolProvider { ), ); if (cause instanceof ApktoolConfigurationFailure) { + const batch = cause.cause; + if ( + request.operation === "decode_android_resources" && + cause.code === "launcher_unsupported" && + batch instanceof WindowsBatchCommandError + ) { + const selected = cause.diagnostics["selected_command"]; + const launcher = typeof selected === "string" ? selected : "apktool"; + return err( + apktoolBatchConfigurationError( + batch, + `The apktool batch launcher ${launcher} cannot receive this decode through cmd.exe: ${batch.message}`, + ), + ); + } return err( providerConfigurationRefusal( APKTOOL_PROVIDER_IDENTITY.id, diff --git a/src/domain/configurationErrors.ts b/src/domain/configurationErrors.ts index ee354efb25d..6f974e82f51 100644 --- a/src/domain/configurationErrors.ts +++ b/src/domain/configurationErrors.ts @@ -19,6 +19,8 @@ export interface ConfigurationErrorOptions extends AnalysisErrorOptions { readonly settings?: readonly ConfigurationSettingIssue[]; /** Producer-owned recovery when this setting can be repaired in a running session. */ readonly remediationAction?: string; + /** Caller-facing outcome. The generic doctor sentence is used when this is absent. */ + readonly userMessage?: string; } /** Runtime configuration could not be parsed safely. */ @@ -26,9 +28,11 @@ export class ConfigurationError extends AnalysisError { readonly _tag = "ConfigurationError"; readonly settings: readonly ConfigurationSettingIssue[]; readonly remediationAction: string | undefined; + override readonly userMessage: string | undefined; constructor(message: string, options?: ConfigurationErrorOptions) { super(message, options); this.remediationAction = options?.remediationAction; + this.userMessage = options?.userMessage; this.settings = (options?.settings ?? []).map((issue) => ({ setting: issue.setting, constraint: issue.constraint, diff --git a/src/ghidra/GhidraLauncherEnvironment.test.ts b/src/ghidra/GhidraLauncherEnvironment.test.ts index afd25fc62af..c8787414c60 100644 --- a/src/ghidra/GhidraLauncherEnvironment.test.ts +++ b/src/ghidra/GhidraLauncherEnvironment.test.ts @@ -22,7 +22,21 @@ describe("Ghidra headless JVM environment", () => { }); }); - it.each(["%TEMP%", 'quote"', "amp&", "line\n", "nul\0"])( + it("quotes an ampersand in a Windows JVM path", () => { + expect( + ghidraHeadlessJavaOptions( + "C:\\runtime\\amp&", + "C:\\runtime\\tmp", + "win32", + ), + ).toEqual({ + JDK_JAVA_OPTIONS: + '"-Duser.home=C:\\runtime\\amp&" "-Djava.io.tmpdir=C:\\runtime\\tmp" "-XX:-UsePerfData"', + GHIDRA_HEADLESS_JAVA_OPTIONS: "", + }); + }); + + it.each(["%TEMP%", 'quote"', "line\n", "nul\0"])( "rejects interpreter metacharacters in either Windows JVM path: %s", (suffix) => { for (const [home, temp] of [ diff --git a/src/pcap/PcapCommand.ts b/src/pcap/PcapCommand.ts index ff16f3f3e4f..75b95f61dbe 100644 --- a/src/pcap/PcapCommand.ts +++ b/src/pcap/PcapCommand.ts @@ -24,6 +24,7 @@ import { cancelledBy, unsupportedTarget, } from "../domain/analysisErrorCore.js"; +import { ConfigurationError } from "../domain/configurationErrors.js"; import { OwnedCommandFailure, ownedCommandResources, @@ -270,12 +271,22 @@ export const runPcapCommand = async (options: { }, } : {}; - if (cause instanceof WindowsBatchCommandError) - throw pcapToolUnavailable( - operation, - `Cannot run selected tool ${command}: ${cause.message}`, - { cause, ...cleanupDetails }, - ); + if (cause instanceof WindowsBatchCommandError) { + const message = + cause.reason === "invalid_comspec" + ? `Cannot run selected tool ${command}: ${cause.message}` + : `Cannot run selected tool ${command} because a batch argument cannot be passed to cmd.exe: ${cause.message}`; + const remediationAction = + cause.reason === "invalid_comspec" + ? "Set COMSPEC to an absolute cmd.exe path." + : "Remove quotes, line breaks, and percent expansions from the batch arguments, including REA runtime paths."; + throw new ConfigurationError(message, { + cause, + ...cleanupDetails, + userMessage: `${message} ${remediationAction}`, + remediationAction, + }); + } const selectedLimiter = options.nativeBound?.limiter?.command.invocationPath; const launchedPath = selectedLimiter ?? command; diff --git a/src/process/WindowsBatchCommand.test.ts b/src/process/WindowsBatchCommand.test.ts new file mode 100644 index 00000000000..39f9059a341 --- /dev/null +++ b/src/process/WindowsBatchCommand.test.ts @@ -0,0 +1,127 @@ +import { spawn } from "node:child_process"; +import { describe, expect, it } from "vitest"; + +import { + quoteWindowsBatchToken, + windowsBatchCommand, + WindowsBatchCommandError, +} from "./WindowsBatchCommand.js"; + +const refusal = (value: string): WindowsBatchCommandError => { + try { + quoteWindowsBatchToken(value); + } catch (cause) { + if (cause instanceof WindowsBatchCommandError) return cause; + throw cause; + } + throw new Error(`expected ${JSON.stringify(value)} to be refused`); +}; + +describe("quoteWindowsBatchToken", () => { + it.each([ + "C:\\Users\\R&D", + "caret^name", + "bang!name", + "pipe|name", + "ltname", + "paren(name)", + "100%", + "percent%only", + "%%", + ])("quotes %s", (value) => { + expect(quoteWindowsBatchToken(value)).toBe(`"${value}"`); + }); + + it.each(["%PATH%", "%%PATH%%", "a%b%c", "file%name%.txt"])( + "refuses a percent expansion %s", + (value) => { + expect(refusal(value)).toMatchObject({ reason: "metacharacter" }); + }, + ); + + it.each(['say "hi"', "line\n", "line\r", "nul\0"])( + "refuses a quote or control character %s", + (value) => { + expect(refusal(value).reason).toBe("metacharacter"); + }, + ); + + it("refuses an empty argument with its own reason", () => { + expect(refusal("")).toMatchObject({ + reason: "empty", + message: "Windows batch arguments cannot be empty", + }); + }); +}); + +const batchEnvironment = { + SYSTEMROOT: "C:\\Windows", + COMSPEC: "C:\\Windows\\System32\\cmd.exe", +}; + +it("refuses a percent span that appears only after quoted tokens are joined", () => { + expect(quoteWindowsBatchToken("%PATH:__REA_NO_MATCH__")).toBe( + '"%PATH:__REA_NO_MATCH__"', + ); + expect(quoteWindowsBatchToken("=ignored%")).toBe('"=ignored%"'); + expect(() => + windowsBatchCommand({ + environment: batchEnvironment, + batchPath: "C:\\tools\\tool.cmd", + arguments: ["%PATH:__REA_NO_MATCH__", "=ignored%"], + }), + ).toThrow(WindowsBatchCommandError); +}); + +it("keeps a trailing percent when the following token has none", () => { + expect( + windowsBatchCommand({ + environment: batchEnvironment, + batchPath: "C:\\tools\\tool.cmd", + arguments: ["100%", "done"], + }).arguments.at(-1), + ).toBe(`""C:\\tools\\tool.cmd" "100%" "done""`); +}); + +it.skipIf(process.platform !== "win32")( + "cmd.exe receives an ampersand path as one argument", + async () => { + const invocation = windowsBatchCommand({ + environment: process.env, + batchPath: process.execPath, + arguments: [ + "-e", + "process.stdout.write(process.argv[1])", + "C:\\Users\\R&D", + ], + }); + const output = await new Promise((resolve, reject) => { + const child = spawn(invocation.command, [...invocation.arguments], { + windowsVerbatimArguments: true, + }); + const timer = setTimeout(() => { + child.kill(); + reject(new Error("cmd.exe did not exit")); + }, 10_000); + let out = ""; + let err = ""; + child.stdout.on("data", (chunk: Buffer) => { + out += chunk.toString("utf8"); + }); + child.stderr.on("data", (chunk: Buffer) => { + err += chunk.toString("utf8"); + }); + child.on("error", (error) => { + clearTimeout(timer); + reject(error); + }); + child.on("close", (code) => { + clearTimeout(timer); + if (code === 0) resolve(out); + else reject(new Error(`exit ${String(code)}: ${err}`)); + }); + }); + expect(output).toBe("C:\\Users\\R&D"); + }, +); diff --git a/src/process/WindowsBatchCommand.ts b/src/process/WindowsBatchCommand.ts index 52467dde04d..5ec1e804ccf 100644 --- a/src/process/WindowsBatchCommand.ts +++ b/src/process/WindowsBatchCommand.ts @@ -3,7 +3,10 @@ import { win32 } from "node:path"; import { snapshotEnvironment } from "./snapshotEnvironment.js"; /** Why a batch launcher cannot be passed safely to cmd.exe. */ -export type WindowsBatchCommandFailure = "invalid_comspec" | "metacharacter"; +export type WindowsBatchCommandFailure = + | "invalid_comspec" + | "empty" + | "metacharacter"; export class WindowsBatchCommandError extends Error { constructor( @@ -30,16 +33,38 @@ export const isWindowsBatchFile = (command: string): boolean => /\.(?:bat|cmd)$/iu.test(command); /** - * Quote one token for cmd.exe. Tokens that cmd.exe could expand, split or - * redirect are rejected instead of escaped. + * A `%name%` span, including the inner span of `%%name%%`. cmd.exe expands + * that span inside quotes. A trailing `%` has no span. `%%` restarts at the + * second percent so `%%PATH%%` is still a span. + */ +const percentExpansion = (value: string): boolean => { + for (let index = 0; index < value.length; index += 1) { + if (value[index] !== "%") continue; + const next = value.indexOf("%", index + 1); + if (next === -1) return false; + if (next > index + 1) return true; + } + return false; +}; + +/** + * Quote one token for `cmd.exe /s /c`. Quotes keep `& | < > ( ) ^` literal, + * and the launcher disables delayed expansion so `!` is literal. Every + * `%name%` span is refused, including when that name is unset, because the + * child environment can define it. */ export const quoteWindowsBatchToken = (value: string): string => { + if (value.length === 0) + throw new WindowsBatchCommandError( + "empty", + "Windows batch arguments cannot be empty", + ); if ( - value.length === 0 || value.includes("\0") || value.includes("\r") || value.includes("\n") || - /["%^!&|<>]/u.test(value) + value.includes('"') || + percentExpansion(value) ) throw new WindowsBatchCommandError( "metacharacter", @@ -74,8 +99,16 @@ export const windowsBatchCommand = (options: { const tokens = [options.batchPath, ...options.arguments].map( quoteWindowsBatchToken, ); + const joined = tokens.join(" "); + // cmd.exe sees the joined line, so a `%…%` span can cross a token boundary + // even when each token has only one percent. + if (percentExpansion(joined)) + throw new WindowsBatchCommandError( + "metacharacter", + "Windows batch arguments cannot contain command-interpreter metacharacters", + ); return { command: comSpec, - arguments: ["/d", "/e:on", "/v:off", "/s", "/c", `"${tokens.join(" ")}"`], + arguments: ["/d", "/e:on", "/v:off", "/s", "/c", `"${joined}"`], }; }; diff --git a/tests/boundary/pcap/pcapCommand.test.ts b/tests/boundary/pcap/pcapCommand.test.ts index 7ca3182fbb7..94b11cf9694 100644 --- a/tests/boundary/pcap/pcapCommand.test.ts +++ b/tests/boundary/pcap/pcapCommand.test.ts @@ -22,6 +22,8 @@ import { AnalysisProtocolError, AnalysisTargetFailureError, } from "../../../src/domain/analysisErrorCore.js"; +import { ConfigurationError } from "../../../src/domain/configurationErrors.js"; +import { PCAP_TOOL_REMEDIATION } from "../../../src/pcap/PcapConfiguration.js"; const posixIt = test.skipIf(process.platform === "win32"); import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.js"; @@ -552,3 +554,95 @@ it.each([ ]); }, ); + +const refusedWindowsBatch = ( + command: string, + environment: NodeJS.ProcessEnv, +): Promise => + runPcapCommand({ + platform: "win32", + operation: "inspect_pcap_client", + command, + arguments: ["--version"], + limits: { timeoutMs: 5000, maxOutputBytes: 1024 }, + environment, + signal: undefined, + launcher: async () => { + throw new Error("batch refusal must not launch"); + }, + retain: () => { + throw new Error("No provider resources were acquired"); + }, + }).catch((cause: unknown) => cause); + +it("reports a Windows batch percent expansion as configuration, not a missing tool", async () => { + const failure = await refusedWindowsBatch("C:\\Tools\\tshark%PATH%.cmd", { + SYSTEMROOT: "C:\\Windows", + COMSPEC: "C:\\Windows\\System32\\cmd.exe", + }); + expect(failure).toBeInstanceOf(ConfigurationError); + if (!(failure instanceof ConfigurationError)) throw failure; + expect(failure.message).not.toContain(PCAP_TOOL_REMEDIATION); + expect(failure.remediationAction ?? "").not.toContain(PCAP_TOOL_REMEDIATION); + expect(failure.remediationAction).toContain("percent expansions"); + const projected = projectAnalysisError(failure); + expect(projected.code).toBe("configuration_invalid"); + expect(projected.message).toContain("tshark%PATH%"); + expect(projected.message).toContain("percent expansions"); + expect(projected.message).not.toContain("rea doctor"); +}); + +it("reports an unusable Windows COMSPEC as configuration, not a missing tool", async () => { + const failure = await refusedWindowsBatch("C:\\Tools\\tshark.cmd", { + SYSTEMROOT: "C:\\Windows", + COMSPEC: "cmd", + }); + expect(failure).toBeInstanceOf(ConfigurationError); + if (!(failure instanceof ConfigurationError)) throw failure; + expect(failure.message).toContain("absolute cmd.exe path"); + expect(failure.message).not.toContain(PCAP_TOOL_REMEDIATION); + expect(failure.remediationAction).toBe( + "Set COMSPEC to an absolute cmd.exe path.", + ); + const projected = projectAnalysisError(failure); + expect(projected.code).toBe("configuration_invalid"); + expect(projected.message).toContain("absolute cmd.exe path"); + expect(projected.message).not.toContain("rea doctor"); +}); + +it("quotes an ampersand in a Windows batch tool path and still launches it", async () => { + const launches: { + readonly command: string; + readonly arguments: readonly string[]; + readonly windowsVerbatimArguments: boolean | undefined; + }[] = []; + await runPcapCommand({ + platform: "win32", + operation: "inspect_pcap_client", + command: "C:\\Tools\\R&D\\tshark.cmd", + arguments: ["--version"], + limits: { timeoutMs: 5000, maxOutputBytes: 1024 }, + environment: { SYSTEMROOT: "C:\\Windows" }, + signal: undefined, + launcher: async (spawn) => { + launches.push({ + command: spawn.command, + arguments: spawn.arguments, + windowsVerbatimArguments: spawn.windowsVerbatimArguments, + }); + throw new Error("recorded launch"); + }, + retain: () => { + throw new Error("No provider resources were acquired"); + }, + }).catch(() => undefined); + expect(launches).toEqual([ + expect.objectContaining({ + command: "C:\\Windows\\System32\\cmd.exe", + windowsVerbatimArguments: true, + }), + ]); + expect(launches[0]?.arguments.at(-1)).toContain( + '"C:\\Tools\\R&D\\tshark.cmd"', + ); +}); diff --git a/tests/boundary/providers/ghidra/ghidraLauncher.test.ts b/tests/boundary/providers/ghidra/ghidraLauncher.test.ts index 97ed6390df6..5e7adc9278c 100644 --- a/tests/boundary/providers/ghidra/ghidraLauncher.test.ts +++ b/tests/boundary/providers/ghidra/ghidraLauncher.test.ts @@ -1276,21 +1276,33 @@ describe("Ghidra Windows batch command construction", () => { }); }); - it.each([ - "C:\\targets\\%TEMP%\\fixture.exe", - "C:\\targets\\fixture & calc.exe", - 'C:\\targets\\fixture".exe', - ])("rejects a Windows command-interpreter path: %s", (targetPath) => { - expect(() => - ghidraHeadlessCommand({ - environment: {}, - platform: "win32", - analyzeHeadlessPath: "C:\\Ghidra\\support\\analyzeHeadless.bat", - arguments: ["-import", targetPath], - comSpec: "C:\\Windows\\System32\\cmd.exe", - }), - ).toThrow(/metacharacters/u); + it("quotes an ampersand in a Windows import path", () => { + const command = ghidraHeadlessCommand({ + environment: {}, + platform: "win32", + analyzeHeadlessPath: "C:\\Ghidra\\support\\analyzeHeadless.bat", + arguments: ["-import", "C:\\targets\\fixture & calc.exe"], + comSpec: "C:\\Windows\\System32\\cmd.exe", + }); + expect(command.arguments.at(-1)).toContain( + '"C:\\targets\\fixture & calc.exe"', + ); }); + + it.each(["C:\\targets\\%TEMP%\\fixture.exe", 'C:\\targets\\fixture".exe'])( + "rejects a Windows command-interpreter path: %s", + (targetPath) => { + expect(() => + ghidraHeadlessCommand({ + environment: {}, + platform: "win32", + analyzeHeadlessPath: "C:\\Ghidra\\support\\analyzeHeadless.bat", + arguments: ["-import", targetPath], + comSpec: "C:\\Windows\\System32\\cmd.exe", + }), + ).toThrow(/metacharacters/u); + }, + ); }); describe("Ghidra Windows release configuration", () => { diff --git a/tests/process-global/curatedWindowsLane.test.ts b/tests/process-global/curatedWindowsLane.test.ts index 23f2cc4ecad..19b970f79d3 100644 --- a/tests/process-global/curatedWindowsLane.test.ts +++ b/tests/process-global/curatedWindowsLane.test.ts @@ -128,6 +128,7 @@ describe("curated Windows test lane", () => { "tests/boundary/mcp/rawBinaryMcp.test.ts", "tests/boundary/filesystem/windowsTargetSeparators.test.ts", "tests/boundary/mcp/serverIdentity.test.ts", + "src/process/WindowsBatchCommand.test.ts", ]), ); });