Skip to content

Commit 52f0ee6

Browse files
committed
fix: command injection in runCommand (CVSS 7.8)
Fixes a HIGH severity command injection vulnerability where validated arguments differed from executed command, allowing shell metacharacter injection via newlines and quote manipulation. Security improvements: - Replace execSync with execFileSync for proper argv array execution - Add pre-tokenization check for \r\n in raw command string - Execute validated argv array instead of raw command string - Add \r to injection character validation regex - Enforce allowedArgs allowlists (previously dead code) - Minimize shell usage (only Windows .cmd/yo when required) Changes: - src/utils.ts: - runCommand: Changed from execSync(command) to execFileSync(baseCommand, args) - Added /[\r\n]/ check on raw command before tokenization - validateCommandArgs: Added \r to denylist, implemented allowedArgs enforcement - Only enables shell for Windows .cmd/yo files via shell:true option Attack scenario prevented: Before: command="yo\nmalicious" → tokenized as ["yo", "malicious"] → validation passed → execSync executed "yo\nmalicious" with shell After: command="yo\nmalicious" → rejected at raw string check → error thrown before execution Impact: Prevents arbitrary command execution via newline/CR injection and quote manipulation in any attacker-influenced command segment. Testing: All 117 tests passing (0 failures) CVSS: 7.8 HIGH - CVSS:3.1/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:H/A:H PSS Violations: SEC-100
1 parent 8089b92 commit 52f0ee6

1 file changed

Lines changed: 58 additions & 12 deletions

File tree

‎src/utils.ts‎

Lines changed: 58 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { execSync } from "child_process";
1+
import { execSync, execFileSync } from "child_process";
22
import fs from "fs";
33
import * as path from "path";
44
import xml2js from "xml2js";
@@ -316,13 +316,41 @@ function validateCommandArgs(command: string, args: string[]): void {
316316

317317
// Validate each argument
318318
for (const arg of args) {
319-
// Check for command injection patterns
320-
if (/[;&|`$(){}[\]<>\n]/.test(arg)) {
319+
// Check for command injection patterns including carriage return
320+
if (/[;&|`$(){}[\]<>\r\n]/.test(arg)) {
321321
throw new Error(
322322
`Invalid argument: '${arg}' contains potentially dangerous characters`
323323
);
324324
}
325325

326+
// Enforce allowedArgs if configured for this command
327+
// Only check flag arguments (starting with - or --), not positional args
328+
if (
329+
allowedCommand.allowedArgs &&
330+
allowedCommand.allowedArgs.length > 0 &&
331+
arg.startsWith("-")
332+
) {
333+
// Check if this flag matches any allowed pattern
334+
const isAllowed = allowedCommand.allowedArgs.some(allowedArg => {
335+
// Exact match
336+
if (arg === allowedArg) {
337+
return true;
338+
}
339+
// Prefix match for arguments with values (e.g., --project=value)
340+
if (allowedArg.endsWith("=") && arg.startsWith(allowedArg)) {
341+
return true;
342+
}
343+
return false;
344+
});
345+
346+
if (!isAllowed) {
347+
throw new Error(
348+
`Flag '${arg}' not allowed for command '${baseCommand}'. ` +
349+
`Allowed flags: ${allowedCommand.allowedArgs.join(", ")}`
350+
);
351+
}
352+
}
353+
326354
// For path arguments, validate they are safe
327355
if (arg.startsWith("./") || arg.startsWith("../")) {
328356
try {
@@ -341,6 +369,14 @@ export function runCommand(
341369
console.error(`[MDK MCP Server] Executing command: ${command}`);
342370

343371
try {
372+
// Security: Check for newlines/carriage returns in raw command string BEFORE tokenizing
373+
// These are command separators that would bypass tokenization-based validation
374+
if (/[\r\n]/.test(command)) {
375+
throw new Error(
376+
"Invalid command: Command contains newline or carriage return characters"
377+
);
378+
}
379+
344380
// Parse command and arguments, handling quoted arguments properly
345381
const parts = command.trim().match(/(?:[^\s"]+|"[^"]*")+/g) || [];
346382
if (parts.length === 0) {
@@ -353,7 +389,7 @@ export function runCommand(
353389
}
354390
const args = parts.slice(1).map(arg => arg.replace(/"/g, "")); // Remove quotes from args
355391

356-
// Security: Validate the command and arguments
392+
// Security: Validate the command and arguments THAT WILL BE EXECUTED
357393
validateCommandArgs(baseCommand, args);
358394

359395
// Security: Validate working directory if provided
@@ -385,25 +421,35 @@ export function runCommand(
385421
commandTimeout = options.timeout || 300000; // 5 minutes for yeoman generation
386422
}
387423

388-
// For Windows, handle shell selection properly
389424
// eslint-disable-next-line @typescript-eslint/no-explicit-any
390425
const execOptions: Record<string, any> = {
391426
cwd: safeCwd,
392427
env: process.env,
393428
stdio: "pipe",
394429
encoding: "utf-8",
395430
timeout: commandTimeout,
396-
maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large output (validation can produce lots of output)
431+
maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large output
397432
};
398433

399-
// On Windows, ensure we use the correct shell for .cmd files
400-
if (process.platform === "win32") {
401-
if (baseCommand.endsWith(".cmd") || baseCommand === "yo") {
402-
execOptions.shell = true;
403-
}
434+
// Security: Determine if shell is required
435+
// Only use shell for specific Windows commands that require it
436+
const needsShell =
437+
process.platform === "win32" &&
438+
(baseCommand.endsWith(".cmd") || baseCommand === "yo");
439+
440+
let output: Buffer;
441+
442+
if (needsShell) {
443+
// Windows .cmd files and yo require shell
444+
// Still use execFileSync but with shell:true for these specific cases
445+
execOptions.shell = true;
446+
output = execFileSync(baseCommand, args, execOptions);
447+
} else {
448+
// Execute with execFileSync and shell:false (default) for security
449+
// This prevents shell metacharacter interpretation
450+
output = execFileSync(baseCommand, args, execOptions);
404451
}
405452

406-
const output = execSync(command, execOptions);
407453
console.error(`[MDK MCP Server] Command completed successfully`);
408454
return output.toString();
409455
} catch (err: unknown) {

0 commit comments

Comments
 (0)