-
Notifications
You must be signed in to change notification settings - Fork 123
[Server] Add DNS rebinding protection feature with middleware #260
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
Draft
chr-hertel
wants to merge
2
commits into
main
Choose a base branch
from
dns-rebinding-protection
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+332
−2
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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
92 changes: 92 additions & 0 deletions
92
src/Server/Transport/Http/Middleware/DnsRebindingProtectionMiddleware.php
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,92 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| /* | ||
| * This file is part of the official PHP MCP SDK. | ||
| * | ||
| * A collaboration between Symfony and the PHP Foundation. | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace Mcp\Server\Transport\Http\Middleware; | ||
|
|
||
| use Http\Discovery\Psr17FactoryDiscovery; | ||
| use Psr\Http\Message\ResponseFactoryInterface; | ||
| use Psr\Http\Message\ResponseInterface; | ||
| use Psr\Http\Message\ServerRequestInterface; | ||
| use Psr\Http\Message\StreamFactoryInterface; | ||
| use Psr\Http\Server\MiddlewareInterface; | ||
| use Psr\Http\Server\RequestHandlerInterface; | ||
|
|
||
| /** | ||
| * Protects against DNS rebinding attacks by validating Host and Origin headers. | ||
| * | ||
| * Rejects requests where the Host or Origin header points to a non-allowed hostname. | ||
| * By default, only localhost variants (localhost, 127.0.0.1, [::1]) are allowed. | ||
| * | ||
| * @see https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#local-mcp-server-compromise | ||
| * @see https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#security-warning | ||
| */ | ||
| final class DnsRebindingProtectionMiddleware implements MiddlewareInterface | ||
| { | ||
| private ResponseFactoryInterface $responseFactory; | ||
| private StreamFactoryInterface $streamFactory; | ||
|
|
||
| /** | ||
| * @param string[] $allowedHosts Allowed hostnames (without port). Defaults to localhost variants. | ||
| * @param ResponseFactoryInterface|null $responseFactory PSR-17 response factory | ||
| * @param StreamFactoryInterface|null $streamFactory PSR-17 stream factory | ||
| */ | ||
| public function __construct( | ||
| private readonly array $allowedHosts = ['localhost', '127.0.0.1', '[::1]', '::1'], | ||
| ?ResponseFactoryInterface $responseFactory = null, | ||
| ?StreamFactoryInterface $streamFactory = null, | ||
| ) { | ||
| $this->responseFactory = $responseFactory ?? Psr17FactoryDiscovery::findResponseFactory(); | ||
| $this->streamFactory = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory(); | ||
| } | ||
chr-hertel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | ||
| { | ||
| $host = $request->getHeaderLine('Host'); | ||
| if ('' !== $host && !$this->isAllowedHost($host)) { | ||
| return $this->createForbiddenResponse('Forbidden: Invalid Host header.'); | ||
| } | ||
|
|
||
| $origin = $request->getHeaderLine('Origin'); | ||
| if ('' !== $origin && !$this->isAllowedOrigin($origin)) { | ||
| return $this->createForbiddenResponse('Forbidden: Invalid Origin header.'); | ||
| } | ||
|
|
||
| return $handler->handle($request); | ||
| } | ||
|
|
||
| private function isAllowedHost(string $hostHeader): bool | ||
| { | ||
| // Strip port from Host header (e.g., "localhost:8000" -> "localhost") | ||
| $host = strtolower(preg_replace('/:\d+$/', '', $hostHeader) ?? $hostHeader); | ||
|
|
||
chr-hertel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return \in_array($host, $this->allowedHosts, true); | ||
| } | ||
|
|
||
| private function isAllowedOrigin(string $origin): bool | ||
| { | ||
| $parsed = parse_url($origin); | ||
| if (false === $parsed || !isset($parsed['host'])) { | ||
| return false; | ||
| } | ||
|
|
||
| return \in_array(strtolower($parsed['host']), $this->allowedHosts, true); | ||
| } | ||
|
|
||
| private function createForbiddenResponse(string $message): ResponseInterface | ||
| { | ||
| return $this->responseFactory | ||
| ->createResponse(403) | ||
| ->withHeader('Content-Type', 'text/plain') | ||
| ->withBody($this->streamFactory->createStream($message)); | ||
| } | ||
| } | ||
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
210 changes: 210 additions & 0 deletions
210
tests/Unit/Server/Transport/Http/Middleware/DnsRebindingProtectionMiddlewareTest.php
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,210 @@ | ||
| <?php | ||
|
|
||
| /* | ||
| * This file is part of the official PHP MCP SDK. | ||
| * | ||
| * A collaboration between Symfony and the PHP Foundation. | ||
| * | ||
| * For the full copyright and license information, please view the LICENSE | ||
| * file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace Mcp\Tests\Unit\Server\Transport\Http\Middleware; | ||
|
|
||
| use Mcp\Server\Transport\Http\Middleware\DnsRebindingProtectionMiddleware; | ||
| use Nyholm\Psr7\Factory\Psr17Factory; | ||
| use PHPUnit\Framework\Attributes\TestDox; | ||
| use PHPUnit\Framework\TestCase; | ||
| use Psr\Http\Message\ResponseFactoryInterface; | ||
| use Psr\Http\Message\ResponseInterface; | ||
| use Psr\Http\Message\ServerRequestInterface; | ||
| use Psr\Http\Server\RequestHandlerInterface; | ||
|
|
||
| class DnsRebindingProtectionMiddlewareTest extends TestCase | ||
| { | ||
| private Psr17Factory $factory; | ||
| private RequestHandlerInterface $handler; | ||
|
|
||
| protected function setUp(): void | ||
| { | ||
| $this->factory = new Psr17Factory(); | ||
| $this->handler = new class($this->factory) implements RequestHandlerInterface { | ||
| public function __construct(private ResponseFactoryInterface $factory) | ||
| { | ||
| } | ||
|
|
||
| public function handle(ServerRequestInterface $request): ResponseInterface | ||
| { | ||
| return $this->factory->createResponse(200); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| #[TestDox('allows request with localhost Host header')] | ||
| public function testAllowsLocalhostHost(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://localhost:8000/') | ||
| ->withHeader('Host', 'localhost:8000'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
chr-hertel marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| $this->assertSame(200, $response->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('allows request with 127.0.0.1 Host header')] | ||
| public function testAllows127001Host(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://127.0.0.1/') | ||
| ->withHeader('Host', '127.0.0.1:3000'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(200, $response->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('allows request with [::1] Host header')] | ||
| public function testAllowsIpv6LocalhostHost(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://[::1]/') | ||
| ->withHeader('Host', '[::1]:8000'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(200, $response->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('allows request with no Host header')] | ||
| public function testAllowsEmptyHost(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://localhost/') | ||
| ->withoutHeader('Host'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(200, $response->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('rejects request with evil Host header')] | ||
| public function testRejectsEvilHost(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://evil.example.com/') | ||
| ->withHeader('Host', 'evil.example.com'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(403, $response->getStatusCode()); | ||
| $this->assertStringContainsString('Host', (string) $response->getBody()); | ||
| } | ||
|
|
||
| #[TestDox('rejects request with evil Host header even with port')] | ||
| public function testRejectsEvilHostWithPort(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://evil.example.com:8000/') | ||
| ->withHeader('Host', 'evil.example.com:8000'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(403, $response->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('allows request with valid localhost Origin header')] | ||
| public function testAllowsLocalhostOrigin(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://localhost/') | ||
| ->withHeader('Host', 'localhost:8000') | ||
| ->withHeader('Origin', 'http://localhost:8000'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(200, $response->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('rejects request with evil Origin header')] | ||
| public function testRejectsEvilOrigin(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://localhost/') | ||
| ->withHeader('Host', 'localhost:8000') | ||
| ->withHeader('Origin', 'http://evil.example.com'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(403, $response->getStatusCode()); | ||
| $this->assertStringContainsString('Origin', (string) $response->getBody()); | ||
| } | ||
|
|
||
| #[TestDox('rejects malformed Origin header')] | ||
| public function testRejectsMalformedOrigin(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://localhost/') | ||
| ->withHeader('Host', 'localhost') | ||
| ->withHeader('Origin', 'not-a-url'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(403, $response->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('Host matching is case-insensitive')] | ||
| public function testHostMatchingIsCaseInsensitive(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://localhost/') | ||
| ->withHeader('Host', 'LOCALHOST:8000'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(200, $response->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('supports custom allowed hosts')] | ||
| public function testCustomAllowedHosts(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware( | ||
| allowedHosts: ['myapp.local'], | ||
| responseFactory: $this->factory, | ||
| ); | ||
|
|
||
| $allowed = $this->factory->createServerRequest('POST', 'http://myapp.local/') | ||
| ->withHeader('Host', 'myapp.local:9000'); | ||
| $this->assertSame(200, $middleware->process($allowed, $this->handler)->getStatusCode()); | ||
|
|
||
| $rejected = $this->factory->createServerRequest('POST', 'http://localhost/') | ||
| ->withHeader('Host', 'localhost'); | ||
| $this->assertSame(403, $middleware->process($rejected, $this->handler)->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('allows request with no Origin header')] | ||
| public function testAllowsEmptyOrigin(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://localhost/') | ||
| ->withHeader('Host', 'localhost'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(200, $response->getStatusCode()); | ||
| } | ||
|
|
||
| #[TestDox('Host header check runs before Origin header check')] | ||
| public function testHostCheckRunsBeforeOriginCheck(): void | ||
| { | ||
| $middleware = new DnsRebindingProtectionMiddleware(responseFactory: $this->factory); | ||
| $request = $this->factory->createServerRequest('POST', 'http://evil.example.com/') | ||
| ->withHeader('Host', 'evil.example.com') | ||
| ->withHeader('Origin', 'http://evil.example.com'); | ||
|
|
||
| $response = $middleware->process($request, $this->handler); | ||
|
|
||
| $this->assertSame(403, $response->getStatusCode()); | ||
| $this->assertStringContainsString('Host', (string) $response->getBody()); | ||
| } | ||
| } | ||
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.
Uh oh!
There was an error while loading. Please reload this page.