- 
                Notifications
    You must be signed in to change notification settings 
- Fork 2.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
          
     Merged
      
      
            jerome3o-anthropic
  merged 9 commits into
  modelcontextprotocol:main
from
ddworken:dworken/dns-rebinding
  
      
      
   
  Jun 17, 2025 
      
    
  
     Merged
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            9 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 64ddbe2
              
                Use HTTP 421 for invalid Host headers in DNS rebinding protection
              
              
                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") | ||
|         
                  ddworken marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| if not self._validate_host(host): | ||
| return Response("Invalid Host header", status_code=421) | ||
|  | ||
| # 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.
  
    
  
    
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.
It might make sense to reject the request for DNS rebinding protection before other checks.
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.
Looking at this code, I think it is in a reasonable order. I don't see any weaknesses exposed by doing it in this order. Do you?
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.
I don't believe there is any significant difference in term of security.
It is just that logically speaking it would make sense to always return 421 when the Host is incorrect, for any request, even if the request path does no match any route for example (
http::/unxpectedhost/unspectedpathshould return 421 instead of 404). (Somewhat nitpicky)(What could be event better in term of DNS-rebinding protection would be to drop the connection altogether when the host is invalid. I guess that doing so DNS-rebinding could not even be used for fingerprinting (think something like the Facebook localhost scanning thing). I think some reverse proxies may support that when returning some special status code but I don't think it is possible with portable ASGI.)