-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Add support for DNS rebinding protections #861
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
Open
ddworken
wants to merge
8
commits into
modelcontextprotocol:main
Choose a base branch
from
ddworken:dworken/dns-rebinding
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.
+800
−14
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
366b3c4
Add support for DNS rebinding protections
ddworken d388520
Merge branch 'main' into dworken/dns-rebinding
ddworken 29a5e3a
Update tests
ddworken aeab631
Clean up
ddworken fb3ce68
Rerun tests
ddworken b2bbcd1
Move gate to validate_request to avoid calling functions unnecessarily
ddworken c018a82
Merge branch 'modelcontextprotocol:main' into dworken/dns-rebinding
ddworken f349d6f
Fix formatting
ddworken 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
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,127 @@ | ||
"""DNS rebinding protection for MCP server transports.""" | ||
|
||
import logging | ||
|
||
from pydantic import BaseModel, Field | ||
from starlette.requests import Request | ||
from starlette.responses import Response | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class TransportSecuritySettings(BaseModel): | ||
"""Settings for MCP transport security features. | ||
|
||
These settings help protect against DNS rebinding attacks by validating | ||
incoming request headers. | ||
""" | ||
|
||
enable_dns_rebinding_protection: bool = Field( | ||
default=True, | ||
description="Enable DNS rebinding protection (recommended for production)", | ||
) | ||
|
||
allowed_hosts: list[str] = Field( | ||
default=[], | ||
description="List of allowed Host header values. Only applies when " | ||
+ "enable_dns_rebinding_protection is True.", | ||
) | ||
|
||
allowed_origins: list[str] = Field( | ||
default=[], | ||
description="List of allowed Origin header values. Only applies when " | ||
+ "enable_dns_rebinding_protection is True.", | ||
) | ||
|
||
|
||
class TransportSecurityMiddleware: | ||
"""Middleware to enforce DNS rebinding protection for MCP transport endpoints.""" | ||
|
||
def __init__(self, settings: TransportSecuritySettings | None = None): | ||
# If not specified, disable DNS rebinding protection by default | ||
# for backwards compatibility | ||
self.settings = settings or TransportSecuritySettings(enable_dns_rebinding_protection=False) | ||
|
||
def _validate_host(self, host: str | None) -> bool: | ||
"""Validate the Host header against allowed values.""" | ||
if not host: | ||
logger.warning("Missing Host header in request") | ||
return False | ||
|
||
# Check exact match first | ||
if host in self.settings.allowed_hosts: | ||
return True | ||
|
||
# Check wildcard port patterns | ||
for allowed in self.settings.allowed_hosts: | ||
if allowed.endswith(":*"): | ||
# Extract base host from pattern | ||
base_host = allowed[:-2] | ||
# Check if the actual host starts with base host and has a port | ||
if host.startswith(base_host + ":"): | ||
return True | ||
|
||
logger.warning(f"Invalid Host header: {host}") | ||
return False | ||
|
||
def _validate_origin(self, origin: str | None) -> bool: | ||
"""Validate the Origin header against allowed values.""" | ||
# Origin can be absent for same-origin requests | ||
if not origin: | ||
return True | ||
|
||
# Check exact match first | ||
if origin in self.settings.allowed_origins: | ||
return True | ||
|
||
# Check wildcard port patterns | ||
for allowed in self.settings.allowed_origins: | ||
if allowed.endswith(":*"): | ||
# Extract base origin from pattern | ||
base_origin = allowed[:-2] | ||
# Check if the actual origin starts with base origin and has a port | ||
if origin.startswith(base_origin + ":"): | ||
return True | ||
|
||
logger.warning(f"Invalid Origin header: {origin}") | ||
return False | ||
|
||
def _validate_content_type(self, content_type: str | None) -> bool: | ||
"""Validate the Content-Type header for POST requests.""" | ||
if not content_type: | ||
logger.warning("Missing Content-Type header in POST request") | ||
return False | ||
|
||
# Content-Type must start with application/json | ||
if not content_type.lower().startswith("application/json"): | ||
logger.warning(f"Invalid Content-Type header: {content_type}") | ||
return False | ||
|
||
return True | ||
|
||
async def validate_request(self, request: Request, is_post: bool = False) -> Response | None: | ||
"""Validate request headers for DNS rebinding protection. | ||
|
||
Returns None if validation passes, or an error Response if validation fails. | ||
""" | ||
# Always validate Content-Type for POST requests | ||
if is_post: | ||
content_type = request.headers.get("content-type") | ||
if not self._validate_content_type(content_type): | ||
return Response("Invalid Content-Type header", status_code=400) | ||
|
||
# Skip remaining validation if DNS rebinding protection is disabled | ||
if not self.settings.enable_dns_rebinding_protection: | ||
return None | ||
|
||
# Validate Host header | ||
host = request.headers.get("host") | ||
if not self._validate_host(host): | ||
return Response("Invalid Host header", status_code=400) | ||
|
||
# Validate Origin header | ||
origin = request.headers.get("origin") | ||
if not self._validate_origin(origin): | ||
return Response("Invalid Origin header", status_code=400) | ||
|
||
return None |
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
Oops, something went wrong.
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.