Skip to content

Commit 5faed22

Browse files
shigechikaclaude
andauthored
fix(serve): validate the Origin header against DNS rebinding (#450)
* fix(serve): validate the Origin header against DNS rebinding Streamable HTTP requires servers to validate Origin and answer 403 when it is present and invalid. serve did not, so a web page that rebinds its hostname to 127.0.0.1 could initialize a session on a loopback gateway and call the child's tools, even with no auth configured. Every request (POST, GET, DELETE; all paths) now runs _reject_bad_origin before routing and auth. No Origin passes (non-browser clients send none); a loopback origin, the explicit --public-url origin, or a new repeatable --allow-origin entry passes after canonicalization and exact comparison; anything else, including null, userinfo and duplicate headers, gets 403. The request-derived issuer is never trusted, since a rebinding request controls Host. Fixes #449 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(serve): check Origin before the body, widen loopback, extension origins (#450 review) - do_POST checks Origin first: a disallowed Origin always gets 403 (not the Content-Length 400/413), the body is never read and the connection is closed. - Loopback means localhost, *.localhost, 127.0.0.0/8 and ::1. - --allow-origin also takes an exact non-http(s) origin such as chrome-extension://<id>; such origins never match the loopback rule. - --public-url's origin is trusted without --enable-oauth too. - Reject every control character, quote and whitespace; share _canonical_netloc with _normalize_public_url; parse each request's Origin once; normalize allowlist entries in build_server only. - Log several rejected Origin values distinguishably. - Docs/help: --allow-origin does not add CORS headers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(serve): refuse non-ASCII origins; document opaque non-http authorities (#450 review) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(serve): punycode an internationalized --public-url origin (#450 review) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(serve): do not guess the origin of an internationalized --public-url (#450 review) Python's idna codec (IDNA 2003) can map a name differently from browsers, and encoding the whole authority broke ports. Warn and let the operator list the punycode origin with --allow-origin instead. The test compares the allowlist by equality (CodeQL py/incomplete-url-substring-sanitization). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7a6c2cc commit 5faed22

9 files changed

Lines changed: 486 additions & 19 deletions

File tree

‎CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ The substantive modules under `src/mcp_stdio/`:
5656
- **`server.py`** — the `mcp-stdio serve` reverse gateway (dispatched from `cli.py` when `argv[1] == "serve"`). **Dual-era** since #270 Phase 3: one endpoint answers both revisions, and `_request_era()` classifies each POST body conservatively — modern only on positive evidence (`params._meta` carries the `protocolVersion` KEY, or the method is `server/discover`); everything else falls through to the untouched legacy path.
5757
- **Legacy path (unchanged, AC2).** One backend stdio child per MCP session (`SessionRegistry`, keyed on `Mcp-Session-Id`) over a stdlib `http.server` Streamable HTTP endpoint: session minted on `initialize`, 400 sessionless, 404 on an unknown id, DELETE to terminate, GET SSE for server-initiated messages. Pinned byte-for-byte by `tests_integration/test_serve_legacy_pin.py`, which every Phase 3 PR had to keep green **with zero diffs**.
5858
- **Modern path (2026-07-28).** A request-plane validation ladder (`_validate_modern`; first failure wins, in python-sdk v2's order — the header rungs run BEFORE the unsupported-version rung): required `_meta` → `-32602`; `MCP-Protocol-Version` / `Mcp-Method` / `Mcp-Name` agreement, the last sentinel-decoded via relay's `_decode_mcp_name` → `-32020`; unsupported version → `-32022` with `data.supported`. Notifications are exempt from the ladder entirely (O9). `_dispatch_modern` then serves the request statelessly from a `ModernBackendPool` child, keyed on the **authenticated principal and NOT on a session** (one shared child under no-auth or a static token, one per OAuth user), with the gateway performing the `initialize` + `notifications/initialized` handshake the modern wire omits and caching the result. `server/discover` is synthesised locally and never forwarded (a legacy child would answer `-32601`); every modern result is stamped `resultType: "complete"`, the six cacheable ops additionally get `ttlMs` (`--cache-ttl-ms`, default 60000) / `cacheScope: "private"`, and every result carries the child's `serverInfo` under `_meta`. Client ids are remapped to a minted `mcp-stdio/serve/` id so concurrent stateless clients sharing one child cannot collide. `subscriptions/listen` is SERVED by serve itself, never forwarded: SCOPE is the listChanged trio (`_LISTEN_FILTER_METHODS`, #374) plus `resourceSubscriptions` (#381, detailed below), honor-all on the three booleans, attach-BEFORE-ack, ack as frame 1 with the honored subset at `params.notifications` and the id at `params._meta[subscriptionId]` (both nestings are load-bearing — a top-level echo is silently ignored by a compliant client). Every frame is stamped with the subscription id. `BackendProcess` fans notifications out to attached `_ListenStream`s (filtering on the reader thread, bounded 1024-deep queue per stream, ≤4 streams per pooled child → `-32603`/503 pre-ack). Endings: gateway shutdown → terminal `resultType: "complete"` frame then close (`signal_end(graceful=True)` + a bounded `drain_listeners`); child death or backlog overflow → abrupt close with NO terminal frame; NEVER a server-sent `notifications/cancelled` (the v2 client settles that as LOST). First ending wins. **#381 added the fourth field, `resourceSubscriptions`**: honoring is entirely LOCAL (child's advertised `resources.subscribe` via `_child_supports_resource_subscribe`, then sanitize + dedup + cap at `_LISTEN_MAX_RESOURCE_SUBSCRIPTIONS=256` with truncate-and-honor), so the ack ships BEFORE any `resources/subscribe` is driven — the drive runs on a background daemon thread and can never stall the ack or the pump. `notifications/resources/updated` gets its OWN routing branch (never folded into `_LISTEN_FORWARDED_METHODS`, which would make any non-empty URI list match every URI and leak across streams); matching is exact string equality, no normalization. URIs are refcounted per child in `BackendProcess._resource_refs` under a dedicated `_sub_lock` HELD ACROSS the send (order `_sub_lock` -> `_lock`, never reversed): subscribe on the first reference, unsubscribe on the last, ids from the existing `_mint_modern_id()`. `_ListenStream.torn_down` closes the async-drive-vs-sync-release race. Failure is reply-then-degrade (log once per URI per stream via `_ListenStream.subscribe_failure_logged`, #388 review, keep honored). `_UNDELIVERABLE_NOTIFICATION_FLAGS` still lists `resources.subscribe` as the DEFAULT, lifted per-child by `_synthesize_discover_result`'s `keep=` on the same predicate the ack uses. **O16 is closed by construction, zero production code**: `notifications/message` is never in any listen-forward set, serve's modern face has no other streaming channel to gate, and SEP-2577 deprecated the feature. Pool lifecycle (#376): entries carry a `holds` checkout refcount (taken by `get_or_create`, released in `_dispatch_modern`'s `finally`) which — together with `has_pending` and the PENDING check — forms the single `_reapable_locked` predicate shared by cap-eviction and the `modern-pool-reaper` idle thread (`--modern-idle-ttl`, 0 = off); `holds` is also #374's attach seam. `--modern-only` refuses legacy callers after the auth gate (GET/DELETE 405 + `Allow`, legacy `initialize` → `-32022`).
59-
- Auth is optional, layered, and applies to both eras: open by default, `--auth-token` (or the `MCP_STDIO_SERVE_TOKEN` env var, preferred so the token isn't exposed in `ps`) for a static bearer, or `--enable-oauth` for an embedded OAuth 2.1 authorization server with optional `--token-store` persistence. Incoming `Host`/`X-Forwarded-Host` values are sanitized against `_HOST_ALLOWED` before they reach the `WWW-Authenticate` challenge / metadata responses. Stdlib only — adds no runtime dependency.
59+
- Auth is optional, layered, and applies to both eras: open by default, `--auth-token` (or the `MCP_STDIO_SERVE_TOKEN` env var, preferred so the token isn't exposed in `ps`) for a static bearer, or `--enable-oauth` for an embedded OAuth 2.1 authorization server with optional `--token-store` persistence. Every request's `Origin` is checked first (`_reject_bad_origin`, #449): absent passes, an http(s) loopback origin (`localhost`, `*.localhost`, 127/8, `::1`) / the `--public-url` origin / an exact `--allow-origin` entry (any scheme, e.g. `chrome-extension://`) passes, anything else (including `null`) gets 403 and the connection is closed before the body is read — never derived from `Host`, which a DNS-rebinding request controls. Incoming `Host`/`X-Forwarded-Host` values are sanitized against `_HOST_ALLOWED` before they reach the `WWW-Authenticate` challenge / metadata responses. Stdlib only — adds no runtime dependency.
6060

6161
Entry point: `mcp-stdio` command → `mcp_stdio.cli:main` (which also dispatches `serve` to `server.py`).
6262

‎README.ja.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -370,6 +370,11 @@ open-gateway と共有 static-token principal は、いずれも本物の呼び
370370
ではないため注入対象から除外される。`--max-sessions-per-owner` と同じ除外規則。
371371
`PATH`・`LD_PRELOAD`・`PYTHONPATH` など、子プロセス自身のランタイムが起動に
372372
必要とする検索パス/動的リンカ系の変数名は指定を拒否する);
373+
`--allow-origin ORIGIN`(繰り返し指定可。ブラウザからのリクエストで `Origin` が
374+
ループバック、`--public-url` のオリジン、ここで指定したもののいずれでもなければ
375+
`403` を返し、ループバックのゲートウェイへの DNS rebinding を防ぐ。`Origin`
376+
ヘッダーを送らないブラウザ以外の MCP クライアントには影響しない。CORS ヘッダーは
377+
付けない。#449);
373378
埋め込み AS 用: `--enable-oauth`、`--public-url URL`(issuer 固定・
374379
プロキシ背後で推奨)、`--trusted-user-header HEADER`、`--dev-user USER`
375380
(非セキュア・検証用)、`--access-token-ttl SECONDS`、`--allow-redirect-uri URL`

‎README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,12 @@ its caller's identity without its own OAuth stack — requires
377377
`--enable-oauth`; the open-gateway and shared static-token principals are
378378
exempt, same as `--max-sessions-per-owner`; refuses a search-path /
379379
dynamic-linker variable name such as `PATH`, `LD_PRELOAD`, or `PYTHONPATH`
380-
that the child's own runtime needs to start); and for the embedded AS:
380+
that the child's own runtime needs to start); `--allow-origin ORIGIN`
381+
(repeatable; a browser request whose `Origin` is not loopback, the
382+
`--public-url` origin, or one of these gets `403`, which closes the DNS
383+
rebinding path to a loopback gateway; requests without an `Origin` header,
384+
as non-browser MCP clients send them, are unaffected; it adds no CORS
385+
headers; #449); and for the embedded AS:
381386
`--enable-oauth`, `--public-url URL` (pins the issuer; recommended behind a
382387
proxy), `--trusted-user-header HEADER`, `--dev-user USER` (insecure, testing
383388
only), `--access-token-ttl SECONDS`, `--allow-redirect-uri URL` (repeatable;

‎docs/guides/serve.ja.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,18 @@ spawn、切断か idle タイムアウトで破棄)、認証済みアイデン
7676
- `--token-store` のファイルは秘密鍵と同様に扱ってください。`0700` の
7777
ディレクトリに `0600` で作成されます。
7878
- 全リクエストはクエリ文字列を redact した形で stderr にログされます。
79+
- ブラウザからのリクエストは `Origin` ヘッダーで検証します(DNS rebinding
80+
対策、#449)。自分のホスト名を `127.0.0.1` に向け直した Web ページから、
81+
ループバックのゲートウェイを操作することはできません(認証なしの場合でも)。
82+
ループバックのオリジン(`localhost`、`*.localhost`、`127.0.0.0/8`、`[::1]`)と
83+
`--public-url` のオリジンは受け付けます。それ以外のブラウザのクライアントは
84+
`--allow-origin https://app.example.com`、ブラウザ拡張なら
85+
`--allow-origin chrome-extension://<id>` で追加してください(繰り返し指定可、
86+
完全一致)。それ以外には `403` を返します。`Origin` を送らないクライアント
87+
(Claude Code、Claude Desktop、mcp-stdio の relay、SDK のクライアント)には
88+
影響しません。`--allow-origin` はこの検証を緩めるだけで、serve は CORS
89+
ヘッダーを返さないため、別オリジンのブラウザクライアントには CORS ヘッダーを
90+
付けるプロキシも必要です。
7991
- セッション処理は厳密かつライフサイクル準拠です:リクエストは
8092
`Mcp-Session-Id` のみでルーティングされ(JSON-RPC のリクエスト id では
8193
相関しません)、各セッションは専用の子プロセスを持ちます。新しい

‎docs/guides/serve.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,17 @@ a crossover.
7474
- Treat `--token-store`'s file like a private key. It is created `0600` in
7575
a `0700` directory.
7676
- Every request is logged to stderr with query strings redacted.
77+
- Browser requests are checked against their `Origin` header (DNS-rebinding
78+
protection, #449): a web page that rebinds its own hostname to `127.0.0.1`
79+
cannot drive a loopback gateway, even one with no auth. Loopback origins
80+
(`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`) and the `--public-url`
81+
origin are accepted; add any other browser client's origin with
82+
`--allow-origin https://app.example.com` or, for a browser extension,
83+
`--allow-origin chrome-extension://<id>` (repeatable, exact match).
84+
Anything else gets `403`. Clients that send no `Origin` — Claude Code,
85+
Claude Desktop, the mcp-stdio relay, SDK clients — are unaffected.
86+
`--allow-origin` only relaxes this check; serve sends no CORS headers, so a
87+
browser client on another origin also needs a proxy that adds them.
7788
- Session handling is strict and lifecycle-correct: requests route by
7889
`Mcp-Session-Id` only (never by JSON-RPC request id), and each session has its
7990
own child. A fresh `initialize` mints a new session; an unknown or terminated

‎docs/reference.ja.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ Arguments:
107107
| `--port PORT` | `8080` | バインドポート |
108108
| `--path PATH` | `/mcp` | HTTP エンドポイントパス |
109109
| `--max-message-size BYTES` | 10 MiB | 宣言された `Content-Length` がこれを超えるリクエストを、本文を読む前に `413` で拒否する。0 で無効化(#416) |
110+
| `--allow-origin ORIGIN` | — | このオリジンからのブラウザのリクエストも受け付ける。`scheme://host[:port]` のほか、`chrome-extension://<id>` のような拡張機能や webview のオリジンも指定できる(繰り返し可能、完全一致)。ループバックのオリジン(`localhost`、`*.localhost`、`127.0.0.0/8`、`[::1]`。ポートは問わない)と `--public-url` のオリジンは常に受け付け(`--public-url` のホストが国際化ドメイン名の場合は変換しないので、punycode のオリジンをここに指定する)、それ以外の `Origin` には `403` を返す。`Origin` ヘッダーを送らないリクエスト(ブラウザ以外のクライアント)には影響しない。DNS rebinding 対策(#449)。CORS を有効にするものではないので、別オリジンのブラウザクライアントには CORS ヘッダーを付けるプロキシが別途必要 |
110111

111112
### 認証
112113

‎docs/reference.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ Arguments:
107107
| `--port PORT` | `8080` | Bind port |
108108
| `--path PATH` | `/mcp` | HTTP endpoint path |
109109
| `--max-message-size BYTES` | 10 MiB | Reject a request whose declared `Content-Length` exceeds this with `413`, before reading any of the body; 0 disables the cap (#416) |
110+
| `--allow-origin ORIGIN` | — | Also accept browser requests from this origin: `scheme://host[:port]`, or an extension/webview origin such as `chrome-extension://<id>` (repeatable, exact match). Loopback origins (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`, any port) and the `--public-url` origin are always accepted (an internationalized `--public-url` host is not converted: list its punycode origin here); any other `Origin` gets `403`, and requests without an `Origin` header (non-browser clients) are unaffected — DNS-rebinding protection (#449). It does not enable CORS: a cross-origin browser client still needs a proxy that adds CORS headers |
110111

111112
### Authentication
112113

0 commit comments

Comments
 (0)