
Harden Your Local MCP Server Against AutoJack RCE
Summary
AutoJack turned a local MCP server into RCE. Harden yours with origin checks, auth, and allowlists.
Harden Your Local MCP Server Against AutoJack RCE
On June 18, 2026, Microsoft's Defender research team published AutoJack, an exploit chain that turns an AI browsing agent into a remote code execution vector on the machine it runs on. The setup is unnervingly small: the agent opens one attacker-controlled web page, JavaScript on that page reaches a privileged service listening on localhost (in the disclosure, AutoGen Studio's MCP WebSocket), and a process gets spawned on the host. No login screen, no credentials, no second click.
What made it work was not one exotic bug. It was three ordinary assumptions stacked together: that anything talking to 127.0.0.1 is trusted, that a local service doesn't need authentication, and that tool parameters coming from the model are safe to pass straight through. Pull any one of those out and the chain breaks.
If you run a local MCP server, and most people building agents now do (over stdio, SSE, or streamable HTTP), this is your problem too. Trend Micro counted 492 MCP servers exposed to the internet with zero authentication this month. This guide hardens a local MCP server end to end with a small runnable example, and maps every control back to the MCP specification's own security requirements.
Why localhost stopped being a trust boundary
The mental model that breaks here is "localhost is private." A browser will happily let a page make requests to http://127.0.0.1:8765. The page usually can't read cross-origin responses, but an attack that only needs to trigger an action (run a command, write a file) doesn't care about the response. With DNS rebinding, the attacker points a domain they control at 127.0.0.1 shortly after the page loads, so the browser starts treating requests to your local server as same-origin. The packets really are local; only the intent is hostile. Binding to localhost does not save you here, because the request originates from a process already on the machine.
It helps to name the shape. Security researchers call it the lethal trifecta: an agent that can read sensitive context, ingest untrusted content, and reach a sink that acts on the outside world. AutoJack is the trifecta wearing a network costume. The untrusted content is the web page, the sensitive context is your machine's filesystem and shell, and the sink is the unauthenticated local service. Remove the agent's unmediated reach to that sink and the page becomes just words on a screen again. The controls below all do one of two things: shrink what the sink will do, or prove that only you are allowed to ask it.
Prerequisites
- Python 3.9+ (the example server uses the standard library only)
- A working idea of JSON-RPC, which is what MCP speaks, and basic HTTP headers
- A local MCP server or tool process you control and can edit
- Optional: the MCP Inspector for re-testing your Origin checks afterward
Step 1 - Map the three root causes to three fixes
AutoJack chained three weaknesses. Each has a direct, boring defense, and you need all three because any single one left in place re-opens the chain:
- Localhost treated as trusted → require authentication anyway, and validate request origin.
- No authentication on the transport → a per-install bearer token, checked in constant time.
- Unsafe parameter handling → an allowlist of named tools mapped to fixed argv, never a shell.
Step 2 - Bind to localhost, never 0.0.0.0
The first mistake is binding to 0.0.0.0, which exposes the server on every network interface, including your LAN. Bind to 127.0.0.1 so only same-machine processes can connect:
HOST, PORT = "127.0.0.1", 8765 # never "0.0.0.0" for a local server
Necessary, but not sufficient. A browser on the same machine still reaches you (that is exactly what DNS rebinding abuses). The next two controls do the real work.
Step 3 - Validate the Origin and Host headers
The MCP transport spec is blunt: servers MUST validate the Origin header on all incoming connections to prevent DNS rebinding, and respond 403 Forbidden when it is present and untrusted. Keep an allowlist of origins you expect, and also pin the Host header, because a rebound domain shows up there even when a non-browser client omits Origin:
origin = self.headers.get("Origin")
if origin is not None and origin not in ALLOWED_ORIGINS:
return self._send(403, {"error": "forbidden origin"})
if self.headers.get("Host") not in ALLOWED_HOSTS:
return self._send(403, {"error": "forbidden host"})
Decide deliberately how to treat a missing Origin. Legitimate non-browser clients omit it, but so can an attacker's request, so the Host pin is your backstop. If your clients always send Origin, reject when it is absent.
Step 4 - Authenticate every request, even on localhost
"It's only localhost" is the exact assumption AutoJack punished. Require a bearer token on every request and compare it with hmac.compare_digest so you do not leak it through timing. Generate the secret per install and never ship a default credential:
auth = self.headers.get("Authorization", "")
token = auth[7:] if auth.startswith("Bearer ") else ""
if not hmac.compare_digest(token, AUTH_TOKEN):
return self._send(401, {"error": "unauthorized"})
Step 5 - Allowlist tools; never pass model input to a shell
The final link was unsafe parameter handling: data the model controlled flowed into process execution. Do not give the model a generic "run this command" tool. Expose a fixed set of named tools, each mapped to an explicit argv, and run them with subprocess.run([...]) (a list, never a string, and never shell=True). Unknown name, instant reject:
SAFE_TOOLS = {
"list_files": ["ls", "-1", "."],
"disk_usage": ["df", "-h", "."],
}
name = req.get("params", {}).get("name")
if name not in SAFE_TOOLS:
return self._send(200, err(rid, -32602, f"tool '{name}' not allowed"))
out = subprocess.run(SAFE_TOOLS[name], capture_output=True, text=True, timeout=5)
The full hardened server
Putting all four controls into one standard-library server. Copy it, set MCP_TOKEN, and run it:
import hmac, json, os, subprocess
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
HOST, PORT = "127.0.0.1", 8765 # bind localhost only
AUTH_TOKEN = os.environ["MCP_TOKEN"] # per-install secret
ALLOWED_ORIGINS = {"http://127.0.0.1:8765",
"http://localhost:8765", "null"}
ALLOWED_HOSTS = {"127.0.0.1:8765", "localhost:8765"}
SAFE_TOOLS = { # fixed argv, no shell
"list_files": ["ls", "-1", "."],
"disk_usage": ["df", "-h", "."],
}
def err(rid, code, msg):
return {"jsonrpc": "2.0", "id": rid,
"error": {"code": code, "message": msg}}
class Handler(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def _send(self, status, payload):
body = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_POST(self):
# 1) Anti DNS-rebinding: Origin (if present) and Host must match.
origin = self.headers.get("Origin")
if origin is not None and origin not in ALLOWED_ORIGINS:
return self._send(403, {"error": "forbidden origin"})
if self.headers.get("Host") not in ALLOWED_HOSTS:
return self._send(403, {"error": "forbidden host"})
# 2) Authenticate even on localhost; constant-time compare.
auth = self.headers.get("Authorization", "")
token = auth[7:] if auth.startswith("Bearer ") else ""
if not hmac.compare_digest(token, AUTH_TOKEN):
return self._send(401, {"error": "unauthorized"})
# 3) Parse JSON-RPC.
n = int(self.headers.get("Content-Length", 0))
try:
req = json.loads(self.rfile.read(n) or b"{}")
except json.JSONDecodeError:
return self._send(400, {"error": "bad json"})
rid = req.get("id")
if req.get("method") != "tools/call":
return self._send(200, err(rid, -32601, "method not found"))
name = req.get("params", {}).get("name")
# 4) Unsafe-parameter defense: allowlist only, fixed argv.
if name not in SAFE_TOOLS:
return self._send(200, err(rid, -32602,
f"tool '{name}' not allowed"))
out = subprocess.run(SAFE_TOOLS[name], capture_output=True,
text=True, timeout=5)
return self._send(200, {"jsonrpc": "2.0", "id": rid,
"result": {"content": [{"type": "text",
"text": out.stdout.strip()}]}})
if __name__ == "__main__":
print(f"hardened MCP server on http://{HOST}:{PORT}")
ThreadingHTTPServer((HOST, PORT), Handler).serve_forever()
Test it
This probe client exercises each guardrail: no token, a forged origin, an allowed tool, and a tool that is not on the allowlist.
import json, urllib.request, urllib.error
URL = "http://127.0.0.1:8765"
def call(headers, body):
req = urllib.request.Request(
URL, data=json.dumps(body).encode(),
headers={"Content-Type": "application/json", **headers}, method="POST")
try:
r = urllib.request.urlopen(req); return r.status, json.load(r)
except urllib.error.HTTPError as e:
return e.code, json.loads(e.read() or b"{}")
valid = {"Authorization": "Bearer dev-secret-please-rotate",
"Host": "127.0.0.1:8765"}
ok = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
"params": {"name": "list_files", "arguments": {}}}
print("A) no token ->", call({"Host": "127.0.0.1:8765"}, ok))
print("B) bad origin ->", call({**valid, "Origin": "http://evil.example"}, ok))
print("C) allowed tool ->", call(valid, ok))
print("D) blocked tool ->", call(valid, {"jsonrpc": "2.0", "id": 2,
"method": "tools/call", "params": {"name": "rm_rf_slash"}}))
Start the server with MCP_TOKEN=dev-secret-please-rotate python3 hardened_server.py, then run python3 probe.py. Real output:
A) no token -> (401, {'error': 'unauthorized'})
B) bad origin -> (403, {'error': 'forbidden origin'})
C) allowed tool -> (200, {'jsonrpc': '2.0', 'id': 1, 'result':
{'content': [{'type': 'text', 'text': 'hardened_server.py\nprobe.py'}]}})
D) blocked tool -> (200, {'jsonrpc': '2.0', 'id': 2, 'error':
{'code': -32602, 'message': "tool 'rm_rf_slash' not allowed"}})
Every malicious shape is refused before it reaches subprocess: the unauthenticated call gets 401, the forged origin gets 403, and the off-allowlist tool name returns a JSON-RPC -32602 error. Only the legitimate, authenticated, allowlisted call runs.
Worked example: the same controls on a WebSocket transport
AutoJack hit a WebSocket, not a plain POST handler, but the fixes are identical because the weaknesses are. On a WebSocket server, read the handshake headers before you accept the connection: validate Origin and pin Host there, require the bearer token (as an Authorization header or a signed subprotocol value), and dispatch only to your allowlisted tools. Reject the upgrade with a 403 when Origin is wrong, rather than accepting the socket and checking later. The rule of thumb: every transport that an agent can be steered into opening needs origin validation, authentication, and an argv allowlist, no exceptions for "internal" or "local" services.
Common pitfalls
- Binding 0.0.0.0 "so I can test from my phone." That turns a localhost RCE into a LAN-wide one. Use an SSH tunnel for remote testing instead.
- Treating a missing Origin as trusted. Browsers always send it; attackers can omit it. Pin the Host header as a backstop and decide the missing-Origin policy explicitly.
- Comparing tokens with
==. That is a timing side channel. Always usehmac.compare_digest. - shell=True or string-built commands. An allowlist of tool names still fails if the values are concatenated into a shell line. Keep argv as a list.
- Reflecting raw tool stdout/errors back to the model. Tool output is untrusted content and can carry injected instructions; sanitize or wrap it before it re-enters the prompt.
- Forgetting SSE and WebSocket need the same checks. Origin validation is not just for POST; it belongs on every transport entry point.
- Assuming a reverse proxy protects you. If the server also listens on localhost, the proxy is simply bypassed by a local request.
- Putting secrets in argv. They show up in
ps. Pass credentials through environment variables or files, not command lines. - A read_file or fetch_url tool with a model-supplied path. That is its own lethal trifecta. Allowlist directories and hosts the same way you allowlist commands.
Quick reference
| AutoJack root cause | Control | MCP spec / rule |
|---|---|---|
| Localhost treated as trusted | Bind 127.0.0.1; require auth regardless | SHOULD bind localhost; SHOULD authenticate |
| DNS rebinding from a web page | Validate Origin, pin Host, 403 on mismatch | MUST validate Origin header |
| No authentication on transport | Bearer token, constant-time compare | SHOULD authenticate all connections |
| Unsafe parameter handling | Allowlist tools, fixed argv, no shell | Input validation (general guidance) |
| Default credentials | Per-install secret, rotate regularly | Eliminate default credentials |
How to tell if you are already exposed
Before you trust your hardening, look at what your machine is actually advertising. Run lsof -iTCP -sTCP:LISTEN -P -n | grep -v 127.0.0.1 to find any local agent or MCP service bound to something other than loopback; a line showing *: or 0.0.0.0: means a tool you forgot about is listening to the network. Then send your own server a request with a forged Origin: http://evil.example header and confirm it answers 403, and a request with no Authorization header and confirm it answers 401. If either one returns 200, you have an AutoJack-shaped hole. Many agent frameworks spin up these helper servers automatically during a session, so check while your agent is actually running, not just at rest.
Next steps
- Add structured audit logging of every tool call: name, caller, arguments hash, and result code.
- Put human-in-the-loop confirmation on any state-changing or destructive tool.
- Scope file and network tools with explicit path and host allowlists, using the same pattern as the command allowlist.
- Read the MCP transports specification's security section and your SDK's transport docs, then re-test with the MCP Inspector sending forged Origin headers.
- Treat anything the agent browses as hostile by default, and assume the next AutoJack is already being written.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,604 newsletter subscribers.