Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 82 additions & 2 deletions src/cf-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,82 @@ import * as os from "os";
import * as path from "path";
import { execSync } from "child_process";

/**
* Security: Resolve cf binary to a trusted absolute path
* Only accepts cf binaries from system directories to prevent PATH injection
*/
function resolveCFBinary(): string {
// Trusted system directories where cf should be installed
const trustedPaths = [
"/usr/local/bin/cf",
"/usr/bin/cf",
"/opt/homebrew/bin/cf", // macOS Homebrew on Apple Silicon
"/home/linuxbrew/.linuxbrew/bin/cf", // Linux Homebrew
];

// On Windows, also check common installation paths
if (process.platform === "win32") {
trustedPaths.push(
"C:\\Program Files\\Cloud Foundry\\cf.exe",
"C:\\Program Files (x86)\\Cloud Foundry\\cf.exe"
);
}

// Check trusted paths first
for (const trustedPath of trustedPaths) {
if (fs.existsSync(trustedPath)) {
return trustedPath;
}
}

// If not in trusted paths, try to resolve via PATH and validate
try {
const resolvedPath = execSync("which cf 2>/dev/null || command -v cf", {
encoding: "utf8",
stdio: "pipe",
}).trim();

if (resolvedPath && fs.existsSync(resolvedPath)) {
// Validate that the resolved path is in a system directory
const absolutePath = fs.realpathSync(resolvedPath);

// Only accept paths in system directories, not in user writable locations
const isInSystemDir =
absolutePath.startsWith("/usr/") ||
absolutePath.startsWith("/opt/") ||
absolutePath.startsWith("/home/linuxbrew/") ||
(process.platform === "win32" &&
absolutePath.match(/^[A-Z]:\\Program Files/i));

if (isInSystemDir) {
return absolutePath;
}

console.warn(
`[Security] cf binary at ${absolutePath} is not in a trusted system directory`
);
}
} catch {
// PATH resolution failed
}

// Fallback to bare name (will rely on PATH) with a warning
console.warn(
"[Security Warning] Could not resolve cf binary to a trusted path. Using PATH resolution."
);
return "cf";
}

// Cache the resolved cf binary path to avoid repeated resolution
let cachedCFBinary: string | null = null;

function getCFBinary(): string {
if (!cachedCFBinary) {
cachedCFBinary = resolveCFBinary();
}
return cachedCFBinary;
}

/**
* Cloud Foundry configuration structure from ~/.cf/config.json
*/
Expand Down Expand Up @@ -70,9 +146,11 @@ export function getCFConfig(): CFConfig | null {
*/
export function isCFLoggedIn(): boolean {
try {
// Security: Use resolved cf binary path instead of bare "cf"
const cfBinary = getCFBinary();
// Try to execute a simple CF command to verify the token is valid
// Using 'cf target' is fast and will fail if token is expired
execSync("cf target", {
execSync(`"${cfBinary}" target`, {
stdio: "pipe",
encoding: "utf-8",
});
Expand Down Expand Up @@ -144,9 +222,11 @@ export function refreshCFToken(): boolean {
try {
console.error("[MDK MCP Server] Refreshing CF OAuth token...");

// Security: Use resolved cf binary path instead of bare "cf"
const cfBinary = getCFBinary();
// Execute cf oauth-token command
// This command refreshes the token and updates ~/.cf/config.json
execSync("cf oauth-token", {
execSync(`"${cfBinary}" oauth-token`, {
stdio: "pipe", // Suppress output
encoding: "utf-8",
});
Expand Down
102 changes: 88 additions & 14 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { execSync } from "child_process";
import { execSync, execFileSync } from "child_process";
import fs from "fs";
import * as path from "path";
import xml2js from "xml2js";
Expand Down Expand Up @@ -316,13 +316,41 @@ function validateCommandArgs(command: string, args: string[]): void {

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

// Enforce allowedArgs if configured for this command
// Only check flag arguments (starting with - or --), not positional args
if (
allowedCommand.allowedArgs &&
allowedCommand.allowedArgs.length > 0 &&
arg.startsWith("-")
) {
// Check if this flag matches any allowed pattern
const isAllowed = allowedCommand.allowedArgs.some(allowedArg => {
// Exact match
if (arg === allowedArg) {
return true;
}
// Prefix match for arguments with values (e.g., --project=value)
if (allowedArg.endsWith("=") && arg.startsWith(allowedArg)) {
return true;
}
return false;
});

if (!isAllowed) {
throw new Error(
`Flag '${arg}' not allowed for command '${baseCommand}'. ` +
`Allowed flags: ${allowedCommand.allowedArgs.join(", ")}`
);
}
}

// For path arguments, validate they are safe
if (arg.startsWith("./") || arg.startsWith("../")) {
try {
Expand All @@ -341,6 +369,14 @@ export function runCommand(
console.error(`[MDK MCP Server] Executing command: ${command}`);

try {
// Security: Check for newlines/carriage returns in raw command string BEFORE tokenizing
// These are command separators that would bypass tokenization-based validation
if (/[\r\n]/.test(command)) {
throw new Error(
"Invalid command: Command contains newline or carriage return characters"
);
}

// Parse command and arguments, handling quoted arguments properly
const parts = command.trim().match(/(?:[^\s"]+|"[^"]*")+/g) || [];
if (parts.length === 0) {
Expand All @@ -353,7 +389,7 @@ export function runCommand(
}
const args = parts.slice(1).map(arg => arg.replace(/"/g, "")); // Remove quotes from args

// Security: Validate the command and arguments
// Security: Validate the command and arguments THAT WILL BE EXECUTED
validateCommandArgs(baseCommand, args);

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

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

// On Windows, ensure we use the correct shell for .cmd files
if (process.platform === "win32") {
if (baseCommand.endsWith(".cmd") || baseCommand === "yo") {
execOptions.shell = true;
}
// Security: Determine if shell is required
// Only use shell for specific Windows commands that require it
const needsShell =
process.platform === "win32" &&
(baseCommand.endsWith(".cmd") || baseCommand === "yo");

let output: Buffer;

if (needsShell) {
// Windows .cmd files and yo require shell
// Still use execFileSync but with shell:true for these specific cases
execOptions.shell = true;
output = execFileSync(baseCommand, args, execOptions);
} else {
// Execute with execFileSync and shell:false (default) for security
// This prevents shell metacharacter interpretation
output = execFileSync(baseCommand, args, execOptions);
}

const output = execSync(command, execOptions);
console.error(`[MDK MCP Server] Command completed successfully`);
return output.toString();
} catch (err: unknown) {
Expand Down Expand Up @@ -946,6 +992,7 @@ export async function generateTemplateBasedMetadata(
);
} else {
// Fallback: check system PATH for yo (e.g. /extbin/globals/bun/bin/yo)
// Security: Validate that resolved path is in a trusted location
let yoInPath: string;
try {
yoInPath = execSync(
Expand All @@ -956,8 +1003,35 @@ export async function generateTemplateBasedMetadata(
yoInPath = "";
}
if (yoInPath && fs.existsSync(yoInPath)) {
yoCommand = yoInPath;
console.error(`[MDK MCP Server] Using system PATH yo at ${yoInPath}`);
// Security: Validate that yo is in a trusted directory
const absolutePath = fs.realpathSync(yoInPath);

// Trusted locations for yo:
// - System directories (/usr/, /opt/)
// - node_modules/.bin directories
// - Homebrew directories
const isTrusted =
absolutePath.includes("/node_modules/.bin/") ||
absolutePath.includes("/.bin/") || // global bun/npm bin
absolutePath.startsWith("/usr/") ||
absolutePath.startsWith("/opt/") ||
absolutePath.startsWith("/home/linuxbrew/") ||
(process.platform === "win32" &&
absolutePath.match(/^[A-Z]:\\Program Files/i));

if (isTrusted) {
yoCommand = absolutePath;
console.error(
`[MDK MCP Server] Using system PATH yo at ${absolutePath}`
);
} else {
console.warn(
`[Security Warning] yo binary at ${absolutePath} is not in a trusted directory. Skipping.`
);
throw new Error(
`yo executable not found in trusted locations. Found at ${absolutePath} but it's not in a trusted directory.`
);
}
} else {
throw new Error(
`yo executable not found at ${yoExecutable}. Please ensure 'yo' package is installed.`
Expand Down
Loading