SA-SKL-INJECTION29 — Code Injection

Code Injection in MCP Skill Registry Skill Linting and Formatting Tool Invocation Endpoints

MCP skill registries commonly expose linting and formatting pipelines as first-class tool invocation endpoints, allowing AI agents and developers to run ESLint, Prettier, TypeScript, and stylelint against skill source code on demand. INJECTION29 covers four critical shell injection patterns found across these endpoints — every one of them invokes the underlying tool via Node.js child_process.exec() with attacker-controlled values interpolated directly into the shell command string. INJECTION29-001 exploits ESLint’s --rulesdir flag to cause the linter to read arbitrary server files and return their contents in lint output; INJECTION29-002 uses a semicolon in a Prettier config path to execute arbitrary shell commands, destroying application data; INJECTION29-003 appends a space-separated --outDir flag to the TypeScript compiler invocation to redirect compiled output to a web-served directory; INJECTION29-004 exploits the stylelint endpoint to append /etc/passwd to a world-readable temp file for deferred retrieval. The unifying fix across all four is replacing exec() with execFile(), which passes arguments directly to the binary without shell interpretation, combined with strict input validation and realpathSync sandbox containment checks.

SA-SKL-INJECTION29 findings
CRITICALINJECTION29-001 — ESLint linting endpoint uses exec(`eslint --config ${configPath} ${targetDir}`); attacker submits configPath = "shared/.eslintrc --rulesdir=../../etc/passwd"; ESLint loads /etc/passwd as a custom rules directory, returning file content in lint output; fix: execFile; allowlist configPath to named presets; realpathSync containment on targetDir
CRITICALINJECTION29-002 — Prettier formatting endpoint uses exec(`prettier --config ${prettierConfig} ${sourceFile}`); attacker submits prettierConfig = ".prettierrc; rm -rf /app/data;"; shell executes the injected command, destroying application data; fix: execFile; regex validate both paths; realpathSync containment; prefer --stdin-filepath pattern
CRITICALINJECTION29-003 — TypeScript compilation endpoint uses exec(`tsc --project ${tsConfigPath}`); attacker submits tsConfigPath = "tsconfig.json --outDir=/app/dist/pwned"; shell splits on space, tsc writes compiled JS to an arbitrary server path that may be served as static files; fix: execFile; regex validate path; realpathSync containment; set --outDir as a fixed argument
CRITICALINJECTION29-004 — stylelint CSS linting endpoint uses exec(`stylelint --config ${cssConfig} ${targetFile}`); attacker submits cssConfig = ".stylelintrc; cat /etc/passwd >> /tmp/out.txt;"; shell appends server file contents to a world-readable temp file for later retrieval; fix: execFile; regex validate both paths; realpathSync containment for config and source; never write to shared temp files

INJECTION29-001 — ESLint shell string interpolation reads arbitrary server files via fake --rulesdir flag

The skill linting endpoint invokes ESLint by interpolating the caller-supplied configPath and targetDir directly into a shell command string passed to exec(). Because exec() passes its first argument to /bin/sh -c, whitespace inside either parameter is interpreted by the shell as an argument boundary. An attacker submits configPath = "shared/.eslintrc --rulesdir=../../etc/passwd". The shell splits this into three tokens: --config, shared/.eslintrc, and --rulesdir=../../etc/passwd. ESLint receives --rulesdir as a valid option instructing it to load custom lint rules from that directory path. ESLint then attempts to require() every file in /etc/passwd as a JavaScript module, fails to parse them, and returns parsing error messages that include the raw file content in the lint output sent back to the API caller.

The impact extends beyond /etc/passwd. Any file the Node.js process can read — application secrets in /app/.env, database credentials in /app/config/db.json, TLS private keys — can be exfiltrated by crafting a path that ESLint will attempt to load as a rules directory. The lint output is returned verbatim to the caller in the API response, so no secondary channel is required. The fix is to replace exec() with execFile(), which invokes the ESLint binary directly without shell involvement, meaning extra whitespace-separated tokens in configPath are passed as a single argument to ESLint rather than being tokenised by the shell. Additionally, configPath must be restricted to a named set of built-in presets stored in a server-side object, eliminating the ability to supply any filesystem path at all.

Vulnerable
// INJECTION29-001 — VULNERABLE
// exec() interpolates configPath into /bin/sh -c string.
// Attacker: configPath = "shared/.eslintrc --rulesdir=../../etc/passwd"
// Shell tokenises --rulesdir=../../etc/passwd as an extra ESLint flag.
// ESLint loads /etc/passwd as a custom rules directory; parsing errors
// include raw file content in the lint response returned to the caller.

const { exec } = require('child_process');

router.post('/lint', requireSession, async (req, res) => {
  const { configPath, targetDir } = req.body;

  exec(`eslint --config ${configPath} ${targetDir}`, (err, stdout, stderr) => { // VULNERABLE
    res.json({
      output: stdout,
      errors: stderr,
      exitCode: err ? err.code : 0,
    });
  });
});
Fixed
// INJECTION29-001 — FIXED
// 1. execFile() — no shell; extra tokens in configPath are one arg, not flags.
// 2. PRESET_CONFIGS allowlist — only named built-ins accepted; no filesystem paths.
// 3. realpathSync(targetDir) containment against SANDBOX_BASE.

const { execFile } = require('child_process');
const { realpathSync } = require('fs');
const path = require('path');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);

const SANDBOX_BASE = realpathSync('/app/sandboxes');

// Server-side mapping from preset name to actual config path — no user-supplied paths.
const PRESET_CONFIGS = {
  standard:    '/app/eslint-configs/standard.json',
  airbnb:      '/app/eslint-configs/airbnb.json',
  recommended: '/app/eslint-configs/recommended.json',
};

router.post('/lint', requireSession, async (req, res) => {
  const { preset = 'recommended', targetDir } = req.body;

  // 1. Allowlist: reject any preset name not in the map.
  const configPath = PRESET_CONFIGS[preset];
  if (!configPath) return res.status(400).json({ error: 'Unknown preset' });

  // 2. Containment: resolve targetDir and verify it is inside SANDBOX_BASE.
  let resolvedTarget;
  try {
    resolvedTarget = realpathSync(targetDir);
  } catch {
    return res.status(400).json({ error: 'Invalid targetDir' });
  }
  if (!resolvedTarget.startsWith(SANDBOX_BASE + path.sep)) {
    return res.status(400).json({ error: 'targetDir outside sandbox' });
  }

  // 3. execFile — arguments passed directly to the ESLint binary, not to /bin/sh.
  try {
    const { stdout, stderr } = await execFileAsync(
      'eslint',
      ['--config', configPath, resolvedTarget],
      { timeout: 30_000 }
    );
    res.json({ output: stdout, errors: stderr, exitCode: 0 });
  } catch (err) {
    res.json({ output: err.stdout ?? '', errors: err.stderr ?? '', exitCode: err.code ?? 1 });
  }
});

INJECTION29-002 — Prettier shell injection executes arbitrary commands via semicolon in config path

The skill formatting endpoint constructs a Prettier invocation by interpolating both prettierConfig and sourceFile into a template literal passed to exec(). Unlike the ESLint finding, which exploits extra CLI flags, this attack uses the shell metacharacter ; to terminate the Prettier command and begin an entirely new command. When an attacker submits prettierConfig = ".prettierrc; rm -rf /app/data;", the shell evaluates the string as three separate commands: prettier --config .prettierrc, then rm -rf /app/data, then an empty trailing statement. Prettier exits normally after formatting the source file (or fails if the config is invalid), and then the shell proceeds to destroy the entire application data directory. Because exec()’s callback is not called until all commands in the shell string complete, the formatting response may never arrive — or it arrives with an empty body after the data directory has been removed.

The same semicolon technique can be used to exfiltrate secrets, install backdoors, or modify source files before they are returned to the caller. The injection point is on prettierConfig, but sourceFile is equally vulnerable — an attacker can supply a sourceFile containing backtick command substitution or $() syntax to achieve the same effect. The correct fix is to call execFile('prettier', [...], ...) so that the shell is never invoked. Both prettierConfig and sourceFile must pass a strict path regex before being used as arguments; each must also be verified to reside inside its respective allowed base directory via realpathSync. Where the formatting workflow permits it, the --stdin-filepath pattern should be preferred so that source content is piped via stdin rather than referenced by a filesystem path argument.

Vulnerable
// INJECTION29-002 — VULNERABLE
// exec() interpolates prettierConfig and sourceFile into /bin/sh -c string.
// Attacker: prettierConfig = ".prettierrc; rm -rf /app/data;"
// Shell interprets the semicolon and executes the injected command,
// destroying /app/data before the formatting response is returned.

const { exec } = require('child_process');

router.post('/format', requireSession, async (req, res) => {
  const { prettierConfig, sourceFile } = req.body;

  exec(`prettier --config ${prettierConfig} ${sourceFile}`, (err, stdout, stderr) => { // VULNERABLE
    if (err) return res.status(500).json({ error: stderr });
    res.json({ formatted: stdout });
  });
});
Fixed
// INJECTION29-002 — FIXED
// 1. execFile() — no shell; semicolons and backticks in args are literal chars.
// 2. Regex validation for both paths before use.
// 3. realpathSync containment for both prettierConfig and sourceFile.
// 4. Prefer --stdin-filepath pattern to avoid path args entirely.

const { execFile } = require('child_process');
const { realpathSync, readFileSync } = require('fs');
const path = require('path');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);

const SANDBOX_BASE   = realpathSync('/app/sandboxes');
const CONFIG_BASE    = realpathSync('/app/prettier-configs');
const PATH_RE        = /^[a-z0-9_\-\/\.]{1,200}$/i;

router.post('/format', requireSession, async (req, res) => {
  const { prettierConfig, sourceFile } = req.body;

  // 1. Structural validation — reject any path that doesn't match the allowable pattern.
  if (!PATH_RE.test(prettierConfig) || !PATH_RE.test(sourceFile)) {
    return res.status(400).json({ error: 'Invalid path characters' });
  }

  // 2. Containment — resolve and verify each path stays inside its allowed base.
  let resolvedConfig, resolvedSource;
  try {
    resolvedConfig = realpathSync(prettierConfig);
    resolvedSource = realpathSync(sourceFile);
  } catch {
    return res.status(400).json({ error: 'Path resolution failed' });
  }
  if (!resolvedConfig.startsWith(CONFIG_BASE + path.sep)) {
    return res.status(400).json({ error: 'prettierConfig outside allowed directory' });
  }
  if (!resolvedSource.startsWith(SANDBOX_BASE + path.sep)) {
    return res.status(400).json({ error: 'sourceFile outside sandbox' });
  }

  // 3. execFile with --stdin-filepath: pipe source content via stdin, avoid path arg.
  const sourceContent = readFileSync(resolvedSource, 'utf8');
  try {
    const { stdout } = await execFileAsync(
      'prettier',
      ['--config', resolvedConfig, '--stdin-filepath', path.basename(resolvedSource)],
      { input: sourceContent, timeout: 30_000 }
    );
    res.json({ formatted: stdout });
  } catch (err) {
    res.status(422).json({ error: err.stderr ?? 'Formatting failed' });
  }
});

INJECTION29-003 — TypeScript compiler injection writes compiled output to arbitrary server paths via space-split --outDir

The TypeScript compilation endpoint invokes the tsc binary by interpolating tsConfigPath into a shell command string. The shell splits on whitespace before passing arguments to tsc, so an attacker submits tsConfigPath = "tsconfig.json --outDir=/app/dist/pwned". The shell tokenises this into --project, tsconfig.json, and --outDir=/app/dist/pwned. The TypeScript compiler treats command-line flags as overrides for any matching option in tsconfig.json, so --outDir=/app/dist/pwned silently overrides whatever outDir was declared in the project config. If /app/dist/pwned resolves to a path that the web server or a downstream MCP router serves as static files, the attacker can overwrite existing JavaScript files on the server or plant new ones that are executed in users’ browsers or by the MCP runtime when it loads tool handlers from the dist directory.

The severity is elevated because the attack does not require any exfiltration channel — the attacker already knows the layout of a standard Node.js MCP server deployment and can target /app/dist, /app/public, or any other predictable path. The attack is also largely silent: tsc exits with code 0 if compilation succeeds, and the response body contains only the compilation diagnostics, not the fact that output was written to an unexpected location. The fix combines execFile (eliminating space-split injection), a path regex and realpathSync containment check on tsConfigPath, and a fixed --outDir argument placed after --project tsConfigPath in the argument array so that any outDir in the user’s tsconfig is overridden by a server-controlled value.

Vulnerable
// INJECTION29-003 — VULNERABLE
// exec() interpolates tsConfigPath into /bin/sh -c string.
// Attacker: tsConfigPath = "tsconfig.json --outDir=/app/dist/pwned"
// Shell splits on the space; tsc receives --outDir=/app/dist/pwned as a compiler flag,
// overriding the tsconfig outDir and writing compiled JS to an arbitrary server path.

const { exec } = require('child_process');

router.post('/compile', requireSession, async (req, res) => {
  const { tsConfigPath } = req.body;

  exec(`tsc --project ${tsConfigPath}`, (err, stdout, stderr) => { // VULNERABLE
    res.json({
      diagnostics: stderr,
      exitCode: err ? err.code : 0,
    });
  });
});
Fixed
// INJECTION29-003 — FIXED
// 1. execFile() — no shell; space in tsConfigPath is part of the argument string, not a separator.
// 2. Regex validation on tsConfigPath.
// 3. realpathSync containment against SANDBOX_BASE.
// 4. Fixed --outDir argument placed after --project to override any tsconfig setting.

const { execFile } = require('child_process');
const { realpathSync } = require('fs');
const path = require('path');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);

const SANDBOX_BASE = realpathSync('/app/sandboxes');
const COMPILE_OUT  = '/app/sandboxes/compile-output'; // fixed, server-controlled outDir
const PATH_RE      = /^[a-z0-9_\-\/\.]{1,200}$/i;

router.post('/compile', requireSession, async (req, res) => {
  const { tsConfigPath } = req.body;

  // 1. Structural validation.
  if (!PATH_RE.test(tsConfigPath)) {
    return res.status(400).json({ error: 'Invalid tsConfigPath characters' });
  }

  // 2. Containment — tsConfigPath must resolve inside SANDBOX_BASE.
  let resolvedConfig;
  try {
    resolvedConfig = realpathSync(tsConfigPath);
  } catch {
    return res.status(400).json({ error: 'tsConfigPath resolution failed' });
  }
  if (!resolvedConfig.startsWith(SANDBOX_BASE + path.sep)) {
    return res.status(400).json({ error: 'tsConfigPath outside sandbox' });
  }

  // 3. execFile with fixed --outDir — space injection cannot introduce extra flags.
  //    --outDir placed after --project so it overrides any outDir in the tsconfig.
  try {
    const { stdout, stderr } = await execFileAsync(
      'tsc',
      ['--project', resolvedConfig, '--outDir', COMPILE_OUT],
      { timeout: 60_000 }
    );
    res.json({ diagnostics: stderr, output: stdout, exitCode: 0 });
  } catch (err) {
    res.json({ diagnostics: err.stderr ?? '', output: err.stdout ?? '', exitCode: err.code ?? 1 });
  }
});

INJECTION29-004 — stylelint shell injection exfiltrates server files to world-readable temp location via semicolon

The CSS linting endpoint uses the same exec() template-literal pattern as the previous findings to invoke stylelint. An attacker submits cssConfig = ".stylelintrc; cat /etc/passwd >> /tmp/out.txt;". The shell interprets the first semicolon as terminating the stylelint command and executes cat /etc/passwd >> /tmp/out.txt, appending the contents of /etc/passwd to a world-readable file in /tmp. Because the temp file path is predictable and /tmp is typically world-readable, the attacker can retrieve the file on a subsequent request to any endpoint that reads from /tmp — for example, a diagnostics endpoint, a file-download endpoint, or by crafting a second injection that reads the temp file and returns it inline. The stylelint process itself may still run and return valid lint output, making the attack invisible in normal application logs.

The temp-file retrieval step is not the only risk. The same technique can be used to overwrite application source files, modify configuration, or chain into further privilege escalation. The targetFile parameter is equally injectable and can carry $(command) substitution payloads. The fix follows the same pattern established in the preceding findings: replace exec() with execFile(), apply a strict path regex to both cssConfig and targetFile, and perform realpathSync containment checks against the respective allowed base directories. Additionally, the endpoint must never write linting output or intermediate artefacts to shared temp directories — stdout and stderr must be captured directly from the execFileAsync return value and returned in the API response, with no filesystem intermediary.

Vulnerable
// INJECTION29-004 — VULNERABLE
// exec() interpolates cssConfig and targetFile into /bin/sh -c string.
// Attacker: cssConfig = ".stylelintrc; cat /etc/passwd >> /tmp/out.txt;"
// Shell executes the injected command, appending /etc/passwd content to
// /tmp/out.txt (world-readable). Attacker retrieves the file on a later request.

const { exec } = require('child_process');

router.post('/lint-css', requireSession, async (req, res) => {
  const { cssConfig, targetFile } = req.body;

  exec(`stylelint --config ${cssConfig} ${targetFile}`, (err, stdout, stderr) => { // VULNERABLE
    res.json({
      output: stdout,
      errors: stderr,
      exitCode: err ? err.code : 0,
    });
  });
});
Fixed
// INJECTION29-004 — FIXED
// 1. execFile() — no shell; semicolons and $() in cssConfig/targetFile are literal chars.
// 2. Regex validation for both paths.
// 3. realpathSync containment for cssConfig against CONFIG_BASE, targetFile against SANDBOX_BASE.
// 4. stdout/stderr captured directly from execFileAsync — no temp file intermediary.

const { execFile } = require('child_process');
const { realpathSync } = require('fs');
const path = require('path');
const { promisify } = require('util');
const execFileAsync = promisify(execFile);

const SANDBOX_BASE = realpathSync('/app/sandboxes');
const CSS_CFG_BASE = realpathSync('/app/stylelint-configs');
const PATH_RE      = /^[a-z0-9_\-\/\.]{1,200}$/i;

router.post('/lint-css', requireSession, async (req, res) => {
  const { cssConfig, targetFile } = req.body;

  // 1. Structural validation for both parameters.
  if (!PATH_RE.test(cssConfig) || !PATH_RE.test(targetFile)) {
    return res.status(400).json({ error: 'Invalid path characters' });
  }

  // 2. Containment checks — each path must resolve inside its allowed base.
  let resolvedConfig, resolvedTarget;
  try {
    resolvedConfig = realpathSync(cssConfig);
    resolvedTarget = realpathSync(targetFile);
  } catch {
    return res.status(400).json({ error: 'Path resolution failed' });
  }
  if (!resolvedConfig.startsWith(CSS_CFG_BASE + path.sep)) {
    return res.status(400).json({ error: 'cssConfig outside allowed config directory' });
  }
  if (!resolvedTarget.startsWith(SANDBOX_BASE + path.sep)) {
    return res.status(400).json({ error: 'targetFile outside sandbox' });
  }

  // 3. execFile — stdout/stderr returned directly, no temp file written.
  try {
    const { stdout, stderr } = await execFileAsync(
      'stylelint',
      ['--config', resolvedConfig, resolvedTarget],
      { timeout: 30_000 }
    );
    res.json({ output: stdout, errors: stderr, exitCode: 0 });
  } catch (err) {
    res.json({ output: err.stdout ?? '', errors: err.stderr ?? '', exitCode: err.code ?? 1 });
  }
});

Related findings