Skip to content

Commit 007a543

Browse files
Add DNS rebinding protection middleware for conformance tests
Implement Host header validation middleware to prevent DNS rebinding attacks: - Validates Host header against allowed hosts (localhost, 127.0.0.1) - Returns 421 Misdirected Request for invalid hosts - Configured for conformance testing environment This addresses the dns-rebinding-protection conformance test. Co-authored-by: eiriktsarpalis <2813363+eiriktsarpalis@users.noreply.github.com>
1 parent 428103a commit 007a543

File tree

1 file changed

+23
-0
lines changed
  • tests/ModelContextProtocol.ConformanceServer

1 file changed

+23
-0
lines changed

tests/ModelContextProtocol.ConformanceServer/Program.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,29 @@ public static async Task MainAsync(string[] args, ILoggerProvider? loggerProvide
9292

9393
var app = builder.Build();
9494

95+
// DNS Rebinding Protection Middleware
96+
// Validates Host header to prevent DNS rebinding attacks
97+
app.Use(async (context, next) =>
98+
{
99+
var host = context.Request.Host.Host;
100+
var port = context.Request.Host.Port;
101+
var hostHeader = port.HasValue ? $"{host}:{port.Value}" : host;
102+
103+
// Allow localhost and 127.0.0.1 on any port for conformance testing
104+
// In production, this should be more restrictive
105+
var allowed = host == "localhost" || host == "127.0.0.1" ||
106+
host.StartsWith("localhost.") || host.StartsWith("127.0.0.1.");
107+
108+
if (!allowed)
109+
{
110+
context.Response.StatusCode = 421; // Misdirected Request
111+
await context.Response.WriteAsync($"Invalid Host header: {hostHeader}");
112+
return;
113+
}
114+
115+
await next();
116+
});
117+
95118
app.MapMcp();
96119

97120
app.MapGet("/health", () => TypedResults.Ok("Healthy"));

0 commit comments

Comments
 (0)