Repository navigation
feat: add DNS rebinding protection conformance tests #115
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1a3d913
feat: add DNS rebinding protection conformance tests
pcarleton 30cda52
feat: add negative test case for DNS rebinding protection
pcarleton b1e3a47
fix: accept any 4xx status code for DNS rebinding rejection
pcarleton b1cf903
refactor: address PR review comments
pcarleton f3210a1
fix: include error details in catch block
pcarleton 2420796
refactor: simplify negative test server to stateless
pcarleton 7c1b3db
refactor: check both Host and Origin headers for DNS rebinding protec…
pcarleton File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
examples/servers/typescript/no-dns-rebinding-protection.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| #!/usr/bin/env node | ||
|
|
||
| /** | ||
| * MCP Server WITHOUT DNS Rebinding Protection - Negative Test Case | ||
| * | ||
| * This is the simplest possible vulnerable server to demonstrate what happens | ||
| * when DNS rebinding protection is omitted. DO NOT use this pattern in production. | ||
| * | ||
| * This server should FAIL the dns-rebinding-protection conformance scenario. | ||
| */ | ||
|
|
||
| import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; | ||
| import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'; | ||
| import express from 'express'; | ||
|
|
||
| // Create minimal MCP server | ||
| const server = new McpServer({ | ||
| name: 'no-dns-rebinding-protection-server', | ||
| version: '1.0.0' | ||
| }); | ||
|
|
||
| // Add a simple tool | ||
| server.tool( | ||
| 'echo', | ||
| 'Echo the input back', | ||
| { message: { type: 'string' } }, | ||
| async ({ message }) => ({ | ||
| content: [{ type: 'text', text: `Echo: ${message}` }] | ||
| }) | ||
| ); | ||
|
|
||
| // === VULNERABLE EXPRESS APP === | ||
| // This intentionally does NOT use createMcpExpressApp() or localhostHostValidation() | ||
| const app = express(); | ||
| app.use(express.json()); | ||
| // NO DNS rebinding protection middleware here! | ||
|
|
||
| app.post('/mcp', async (req, res) => { | ||
| try { | ||
| // Stateless: no session ID | ||
| const transport = new StreamableHTTPServerTransport({ | ||
| sessionIdGenerator: undefined | ||
| }); | ||
| await server.connect(transport); | ||
| await transport.handleRequest(req, res, req.body); | ||
| } catch (error) { | ||
| if (!res.headersSent) { | ||
| res.status(500).json({ | ||
| jsonrpc: '2.0', | ||
| error: { | ||
| code: -32603, | ||
| message: `Internal error: ${error instanceof Error ? error.message : String(error)}` | ||
| }, | ||
| id: null | ||
| }); | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| const PORT = parseInt(process.env.PORT || '3003', 10); | ||
| app.listen(PORT, '127.0.0.1', () => { | ||
| console.log(`Vulnerable server running on http://localhost:${PORT}/mcp`); | ||
| console.log(`WARNING: No DNS rebinding protection enabled!`); | ||
| }); |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| /** | ||
| * DNS Rebinding Protection test scenarios for MCP servers | ||
| * | ||
| * Tests that localhost MCP servers properly validate Host headers to prevent | ||
| * DNS rebinding attacks. See GHSA-w48q-cv73-mx4w for details on the attack. | ||
| */ | ||
|
|
||
| import { ClientScenario, ConformanceCheck } from '../../types'; | ||
| import { request } from 'undici'; | ||
|
|
||
| const SPEC_REFERENCE = { | ||
| id: 'MCP-DNS-Rebinding-Protection', | ||
| url: 'https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise' | ||
| }; | ||
|
|
||
| /** | ||
| * Check if URL is a localhost URL | ||
| */ | ||
| function isLocalhostUrl(serverUrl: string): boolean { | ||
| const url = new URL(serverUrl); | ||
| const hostname = url.hostname.toLowerCase(); | ||
| return ( | ||
| hostname === 'localhost' || | ||
| hostname === '127.0.0.1' || | ||
|
maxisbey marked this conversation as resolved.
|
||
| hostname === '[::1]' || | ||
| hostname === '::1' | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * Get the host header value from a URL (hostname:port) | ||
| */ | ||
| function getHostFromUrl(serverUrl: string): string { | ||
| const url = new URL(serverUrl); | ||
| return url.host; // includes port if present | ||
| } | ||
|
|
||
| /** | ||
| * Send an MCP initialize request with a custom Host header | ||
| */ | ||
| async function sendRequestWithHost( | ||
| serverUrl: string, | ||
| hostHeader: string | ||
| ): Promise<{ statusCode: number; body: unknown }> { | ||
| const response = await request(serverUrl, { | ||
| method: 'POST', | ||
| headers: { | ||
| 'Content-Type': 'application/json', | ||
| Host: hostHeader, | ||
| Accept: 'application/json, text/event-stream' | ||
| }, | ||
| body: JSON.stringify({ | ||
| jsonrpc: '2.0', | ||
| id: 1, | ||
| method: 'initialize', | ||
| params: { | ||
| protocolVersion: '2024-11-05', | ||
|
pcarleton marked this conversation as resolved.
Outdated
|
||
| capabilities: {}, | ||
| clientInfo: { name: 'conformance-dns-rebinding-test', version: '1.0.0' } | ||
| } | ||
| }) | ||
| }); | ||
|
|
||
| let body: unknown; | ||
| try { | ||
| body = await response.body.json(); | ||
| } catch { | ||
| body = null; | ||
| } | ||
|
|
||
| return { | ||
| statusCode: response.statusCode, | ||
| body | ||
| }; | ||
| } | ||
|
|
||
| export class DNSRebindingProtectionScenario implements ClientScenario { | ||
| name = 'dns-rebinding-protection'; | ||
| description = `Test DNS rebinding protection for localhost servers. | ||
|
|
||
| **Scope:** This test applies to localhost MCP servers running without HTTPS and without | ||
| authentication. These servers are vulnerable to DNS rebinding attacks where a malicious | ||
| website tricks a user's browser into making requests to the local server. | ||
|
|
||
| **Attack scenario:** | ||
| 1. User visits malicious website (e.g., evil.com) | ||
| 2. evil.com's DNS is configured to resolve to 127.0.0.1 | ||
| 3. Browser makes request to evil.com which actually goes to localhost | ||
| 4. Without Host header validation, the local MCP server processes the request | ||
|
|
||
| **Requirements:** | ||
| - Server **MUST** validate the Host header on incoming requests | ||
| - Server **MUST** reject requests with non-localhost Host headers (HTTP 4xx) | ||
| - Server **MUST** accept requests with valid localhost Host headers | ||
|
|
||
| **Valid localhost hosts:** \`localhost\`, \`127.0.0.1\`, \`[::1]\` (with optional port) | ||
|
|
||
| **Note:** This test requires a localhost server URL. Non-localhost URLs will fail. | ||
|
|
||
| See: https://github.com/modelcontextprotocol/typescript-sdk/security/advisories/GHSA-w48q-cv73-mx4w`; | ||
|
|
||
| async run(serverUrl: string): Promise<ConformanceCheck[]> { | ||
| const checks: ConformanceCheck[] = []; | ||
| const timestamp = new Date().toISOString(); | ||
|
|
||
| // Common check properties | ||
| const rejectedCheckBase = { | ||
| id: 'localhost-host-rebinding-rejected', | ||
| name: 'DNSRebindingRejected', | ||
| description: 'Server rejects requests with non-localhost Host headers', | ||
| timestamp, | ||
| specReferences: [SPEC_REFERENCE] | ||
| }; | ||
|
|
||
| const acceptedCheckBase = { | ||
| id: 'localhost-host-valid-accepted', | ||
| name: 'LocalhostHostAccepted', | ||
| description: 'Server accepts requests with valid localhost Host headers', | ||
| timestamp, | ||
| specReferences: [SPEC_REFERENCE] | ||
| }; | ||
|
|
||
| // First check: Is this a localhost URL? | ||
| if (!isLocalhostUrl(serverUrl)) { | ||
| const errorMessage = | ||
| 'DNS rebinding tests require a localhost server URL (localhost, 127.0.0.1, or [::1])'; | ||
| const details = { serverUrl, reason: 'non-localhost-url' }; | ||
|
|
||
| checks.push({ | ||
|
pcarleton marked this conversation as resolved.
|
||
| ...rejectedCheckBase, | ||
| status: 'FAILURE' as const, | ||
|
pcarleton marked this conversation as resolved.
Outdated
|
||
| errorMessage, | ||
| details | ||
| }); | ||
| checks.push({ | ||
| ...acceptedCheckBase, | ||
| status: 'FAILURE' as const, | ||
|
pcarleton marked this conversation as resolved.
Outdated
|
||
| errorMessage, | ||
| details | ||
| }); | ||
| return checks; | ||
| } | ||
|
|
||
| const validHost = getHostFromUrl(serverUrl); | ||
| const attackerHost = 'evil.example.com'; | ||
|
|
||
| // Check 1: Invalid Host header should be rejected with a 4xx error | ||
| try { | ||
| const response = await sendRequestWithHost(serverUrl, attackerHost); | ||
| const isRejected = | ||
| response.statusCode >= 400 && response.statusCode < 500; | ||
|
pcarleton marked this conversation as resolved.
|
||
|
|
||
| const details = { | ||
| hostHeader: attackerHost, | ||
| statusCode: response.statusCode, | ||
| body: response.body | ||
| }; | ||
|
|
||
| if (isRejected) { | ||
| checks.push({ | ||
| ...rejectedCheckBase, | ||
| status: 'SUCCESS' as const, | ||
| details | ||
| }); | ||
| } else { | ||
| checks.push({ | ||
| ...rejectedCheckBase, | ||
| status: 'FAILURE' as const, | ||
| errorMessage: `Expected HTTP 4xx for invalid Host header, got ${response.statusCode}`, | ||
| details | ||
| }); | ||
| } | ||
| } catch (error) { | ||
| checks.push({ | ||
| ...rejectedCheckBase, | ||
| status: 'FAILURE' as const, | ||
| errorMessage: `Request failed: ${error instanceof Error ? error.message : String(error)}`, | ||
| details: { hostHeader: attackerHost } | ||
| }); | ||
| } | ||
|
|
||
| // Check 2: Valid localhost Host header should be accepted (2xx response) | ||
| try { | ||
| const response = await sendRequestWithHost(serverUrl, validHost); | ||
| const isAccepted = | ||
| response.statusCode >= 200 && response.statusCode < 300; | ||
|
|
||
| const details = { | ||
| hostHeader: validHost, | ||
| statusCode: response.statusCode, | ||
| body: response.body | ||
| }; | ||
|
|
||
| if (isAccepted) { | ||
| checks.push({ | ||
| ...acceptedCheckBase, | ||
| status: 'SUCCESS' as const, | ||
| details | ||
| }); | ||
| } else { | ||
| checks.push({ | ||
| ...acceptedCheckBase, | ||
| status: 'FAILURE' as const, | ||
| errorMessage: `Expected HTTP 2xx for valid localhost Host header, got ${response.statusCode}`, | ||
| details | ||
| }); | ||
| } | ||
| } catch (error) { | ||
| checks.push({ | ||
| ...acceptedCheckBase, | ||
| status: 'FAILURE' as const, | ||
| errorMessage: `Request failed: ${error instanceof Error ? error.message : String(error)}`, | ||
| details: { hostHeader: validHost } | ||
| }); | ||
| } | ||
|
|
||
| return checks; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
note: this example is going to get deleted in a follow-up PR to make the typescript-sdk example the source of truth. updating it in place for now.