Dns Rebinding in Aspnet with Cockroachdb
Dns Rebinding in Aspnet with Cockroachdb — how this specific combination creates or exposes the vulnerability
DNS rebinding is a network-based attack where an attacker forces a victim’s browser to resolve a domain to an internal IP address that is not reachable from the public internet. In an ASP.NET application that connects to a CockroachDB cluster, this can expose the database to direct access from the client-side context under certain configurations.
When an ASP.NET application serves a web page that includes embedded JavaScript, the page may open a WebSocket or long-polling connection to a backend endpoint that ultimately proxies or interacts with CockroachDB. If that endpoint does not validate the origin or enforce strict network boundaries, an attacker can craft a malicious page that causes the browser to connect to the CockroachDB HTTP or SQL ports via the victim’s authenticated session. CockroachDB’s admin UI (on port 8080 by default) or a custom backend handler that returns database results without appropriate access controls can become reachable to the attacker’s browser. Because the browser’s same-origin policy is bypassed via rebinding, the attacker can send carefully crafted requests that trigger unintended database queries or configuration introspection.
This risk is heightened when the ASP.NET app uses in-process database drivers or connection strings that resolve internal hostnames at runtime. The attacker does not need to compromise the server; they leverage the victim’s network path and authenticated session to reach internal services that were assumed to be inaccessible from the web-facing component. The API security scanner can detect exposed admin endpoints or lack of origin checks as part of its unauthenticated attack surface testing across the 12 checks, including Input Validation and Unsafe Consumption.
In practice, an attacker might use a sequence of DNS rebinding steps: serve a page from a domain under their control, switch the DNS answer to point to 127.0.0.1 or an internal CockroachDB node, and then use JavaScript to issue HTTP requests that traverse the ASP.NET backend. If the backend trusts loopback or does not validate the requester’s network position, database introspection endpoints may leak schema or execution plans. Because CockroachDB supports SQL over HTTP, an exposed endpoint that accepts raw query parameters becomes a vector for data exposure, aligning with findings mapped to OWASP API Top 10 and Data Exposure checks.
Cockroachdb-Specific Remediation in Aspnet — concrete code fixes
To mitigate DNS rebinding risks in an ASP.NET application that interacts with CockroachDB, you must enforce strict network controls, validate origins, and avoid exposing database-facing endpoints to browser-originated requests. The following code examples illustrate secure patterns using the CockroachDB-compatible PostgreSQL driver for .NET.
1. Use a dedicated backend service with no direct client access
Ensure that all CockroachDB interactions occur server-side. The client should only call ASP.NET endpoints that you control, and those endpoints should never forward raw requests to the database on behalf of the client without strict validation.
// Example: Safe ASP.NET Core controller that queries CockroachDB
using Microsoft.AspNetCore.Mvc;
using Npgsql;
using System.Threading.Tasks;
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
private readonly string _connString = "Host=cockroachdb-internal;Port;26257;Database=mydb;Username=appuser;";
[HttpGet("{id}")]
public async Task<IActionResult> GetOrder(int id)
{
await using var conn = new NpgsqlConnection(_connString);
await conn.OpenAsync();
await using var cmd = new NpgsqlCommand("SELECT id, product, total FROM orders WHERE id = @id", conn);
cmd.Parameters.AddWithValue("@id", id);
await using var reader = await cmd.ExecuteReaderAsync();
if (await reader.ReadAsync())
{
var order = new
{
Id = reader.GetInt32(0),
Product = reader.GetString(1),
Total = reader.GetDecimal(2)
};
return Ok(order);
}
return NotFound();
}
}
2. Validate and restrict origins on backend endpoints
Even for backend endpoints, add anti-rebinding checks by validating the X-Forwarded-For and Origin headers when your ASP.NET app sits behind a proxy. For CockroachDB drivers that connect directly, ensure the connection string does not resolve to internal addresses from client contexts.
// Example: Origin validation middleware in ASP.NET Core
public class OriginValidationMiddleware
{
private readonly RequestDelegate _next;
private readonly HashSet<string> _allowedOrigins = new() { "https://trusted.example.com" };
public OriginValidationMiddleware(RequestDelegate next) => _next = next;
public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.TryGetValue("Origin", out var origin) && !_allowedOrigins.Contains(origin))
{
context.Response.StatusCode = 403;
await context.Response.WriteAsync("Forbidden");
return;
}
await _next(context);
}
}
// Register in Program.cs
app.UseMiddleware<OriginValidationMiddleware>();
3. Disable unwanted interfaces and bind to localhost where appropriate
Configure CockroachDB to listen only on loopback for administrative interfaces and ensure your ASP.NET app’s connection strings do not expose SQL over HTTP to external origins. Use firewall rules and service mesh policies to prevent browser-originated traffic from reaching CockroachDB ports (8080, 26257).
// Example: Connection resilience with timeouts and no dynamic redirects
await using var conn = new NpgsqlConnection(_connString);
conn.ConnectionTimeout = 15;
conn.CommandTimeout = 30;
// Ensure the connection string does not include parameters that allow host switching
4. Use parameterized queries and avoid dynamic SQL
Prevent injection and unintended data exposure by using parameterized commands. This practice also reduces the attack surface if a rebinding attempt manages to reach a handler that builds queries dynamically.
// Safe parameterized usage
await using var cmd = new NpgsqlCommand("SELECT * FROM users WHERE username = @user", conn);
cmd.Parameters.AddWithValue("@user", username);