mirror of
https://github.com/morluto/rea.git
synced 2026-12-06 14:59:05 +00:00
fix(process): accept legal characters in Windows batch paths (#15128)
* fix(process): quote Windows batch operators cmd.exe keeps literal cmd.exe with delayed expansion off keeps & | < > ( ) ^ ! literal inside quotes. Empty tokens and %name% spans are still refused, including when that name is unset, because the child environment can define it. * fix(process): report a refused batch path as invalid configuration A percent expansion or an unusable COMSPEC is configuration_invalid. Packet capture does not append the Wireshark install remediation, and an apktool decode does not report a capability gap. * fix(process): refuse percent spans joined across batch tokens cmd.exe expands a percent span on the joined command line. Tokens that are legal alone are refused when joining them forms a span. The spawn regression kills its child if that child is still running after 10 seconds. * test(process): include the Windows batch regression in CI The curated Windows lane now runs WindowsBatchCommand.test.ts. * fix(domain): preserve a configuration error's caller message ConfigurationError accepted userMessage and dropped it, so the public projection replaced the caller text with the generic doctor sentence. The constructor now stores that message. * fix(pcap): keep a batch refusal in the public configuration message A Windows batch refusal stays in the configuration error the caller sees, including the refused path and the percent-expansion reason. * fix(apktool): report a decode batch refusal as invalid configuration Inspection still reports not_configured. Decoding reports configuration_invalid and names the launcher that cmd.exe cannot receive. A percent span that appears only after the quoted tokens are joined is refused the same way. * test(process): own the Windows batch regression in the package lane The curated Windows job already runs WindowsBatchCommand.test.ts. The package scope did not name that file, so the lane ownership check reported it as unowned.
This commit is contained in:
1 parent
b0a910b8f4
commit
9d5c5f687d
16 files changed
+417
-43
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 [
|
||||
|
||||
+17
-6
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
"lt<name",
|
||||
"gt>name",
|
||||
"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<string>((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");
|
||||
},
|
||||
);
|
||||
@@ -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}"`],
|
||||
};
|
||||
};
|
||||
@@ -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<unknown> =>
|
||||
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"',
|
||||
);
|
||||
});
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user