HIGH dns rebindingfastapicockroachdb

Dns Rebinding in Fastapi with Cockroachdb

Dns Rebinding in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability

DNS Rebinding is a client-side attack where a malicious webpage resolves a hostname to an attacker-controlled IP, then switches the DNS answer to a different IP (often a private/internal address). When a Fastapi application uses hostnames to reach Cockroachdb and does not enforce strict hostname-to-address validation, an attacker may trick the app into connecting to an unintended Cockroachdb node after the DNS flip. This can expose internal cluster endpoints that are not directly reachable from the public internet but are trusted once a connection is established.

In a typical Fastapi setup, you might use an async Cockroachdb driver and connect with a hostname like cockroachdb-internal.example.com. If the DNS record for that hostname is compromised through DNS Rebinding, the Fastapi service could inadvertently connect to a rogue server that mimics Cockroachdb or to another internal service. Because Cockroachdb often relies on long-lived connections and certificate-based authentication, a Fastapi service that does not re-validate the hostname after connection establishment may accept TLS certificates issued for the original hostname even when the IP has changed, enabling man-in-the-middle scenarios within the cluster communication path.

The risk is compounded when Fastapi services perform retries or connection pooling against the same hostname without re-resolving or pinning the endpoint. An attacker on the same network or via a compromised subdomain can leverage this to redirect traffic, probe internal APIs, or attempt unauthorized SQL operations through the trusted Cockroachdb connection. middleBrick detects such weaknesses during its unauthenticated scan by checking whether the API surface relies on unchecked hostname resolutions and whether responses expose internal network details that could aid in further attacks.

Cockroachdb-Specific Remediation in Fastapi — concrete code fixes

To mitigate DNS Rebinding in a Fastapi application that connects to Cockroachdb, enforce strict hostname verification and avoid relying on mutable DNS for sensitive connections. Use explicit IP or strict certificate pinning where possible, and validate the server identity on each connection.

Example: Secure Cockroachdb connection with hostname validation

import asyncio
import ssl
from typing import Any
from fastapi import Fastapi, Depends, HTTPException
import asyncpg

# Use a static IP or a tightly controlled hostname; avoid wildcard or dynamic DNS for Cockroachdb.
COCKROACH_HOST = "203.0.113.10"  # prefer IP or pinned DNS
COCKROACH_PORT = 26257
COCKROACH_DB = "bank"
COCKROACH_USER = "app_user"
COCKROACH_PASSWORD = "strong_password"
CERT_PATH = "/path/to/client.root.crt"

def get_ssl_context() -> ssl.SSLContext:
    ctx = ssl.create_default_context(cafile=CERT_PATH)
    ctx.check_hostname = True
    ctx.verify_mode = ssl.CERT_REQUIRED
    return ctx

async def get_db_pool():
    # Enforce target_name check to prevent hostname mismatch in TLS.
    return await asyncpg.create_pool(
        host=COCKROACH_HOST,
        port=COCKROACH_PORT,
        database=COCKROACH_DB,
        user=COCKROACH_USER,
        password=COCKROACH_PASSWORD,
        ssl=ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)  # use context with check_hostname=True
    )

app = Fastapi()

@app.get("/accounts/{account_id}")
async def read_account(account_id: int, pool: Any = Depends(get_db_pool)):
    async with pool.acquire() as conn:
        row = await conn.fetchrow("SELECT id, balance FROM accounts WHERE id = $1", account_id)
        if row is None:
            raise HTTPException(status_code=404, detail="Account not found")
        return {"id": row[0], "balance": row[1]}

Key remediation steps

  • Pin the Cockroachdb hostname or use an IP address to prevent DNS swap attacks.
  • Enable hostname verification in the TLS context (check_hostname=True) and ensure the certificate matches the expected hostname.
  • Avoid long-lived connections that skip re-validation; re-establish connections with verified endpoints when necessary.
  • Restrict network access to Cockroachdb so that only known service ranges can reach it, reducing the impact of a successful rebinding.
  • Use middleware or startup events in Fastapi to validate connectivity and certificate details at startup and optionally during health checks.

middleBrick can surface misconfigurations where hostnames are used without pinning and where TLS verification is incomplete, helping you prioritize fixes that reduce DNS Rebinding risk against Cockroachdb endpoints.

Frequently Asked Questions

How does DNS Rebinding affect API security scanning results?
If a scanner relies on hostnames that can be manipulated via DNS, findings may include unchecked resolution paths and exposed internal endpoints. middleBrick reports these as high-severity findings because an attacker could redirect traffic to internal services after a successful rebind.
Can middleBrick detect missing hostname verification in Cockroachdb connections?
Yes. middleBrick analyzes runtime behavior and configuration hints to identify missing hostname pinning and weak TLS practices, surfacing them with prioritized remediation guidance.