Dns Rebinding in Fastapi with Api Keys
Dns Rebinding in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
DNS rebinding is a client-side attack where an attacker tricks a victim’s browser into resolving a domain name to an arbitrary IP address, often an internal host. In a Fastapi application that relies on API keys for access control, combining weak origin validation with key handling in client-side or cross-origin scenarios can expose internal services or bypass intended network boundaries.
Consider a Fastapi service that validates API keys in request headers and then makes outbound HTTP calls to internal administrative endpoints (for example, a service that proxies requests to internal tools). If the application does not enforce strict host verification or uses permissive CORS settings, an attacker may use a malicious webpage to perform DNS rebinding against the victim’s browser. The victim is authenticated (e.g., session or API key stored in browser context), and the malicious site can make requests that resolve to internal IPs, bypassing network ACLs because the request appears to originate from the victim’s allowed source.
In this context, API keys are typically passed in headers (e.g., x-api-key) and are not inherently bound to an origin. If a Fastapi endpoint accepts requests from any CORS origin and forwards requests internally based on the key, DNS rebinding can allow an attacker to leverage the key’s privileges to probe internal endpoints. The key is validated, but the server’s trust in the caller’s network position is misplaced because the browser’s same-origin policy can be bypassed via controlled DNS and TTL manipulation. This can lead to unauthorized internal access, SSRF-like paths, or exposure of internal APIs that were never intended to be reachable from the internet.
middleBrick’s checks for SSRF and Input Validation are relevant here because DNS rebinding can be used to probe internal services; the scanner flags risky CORS configurations and missing host header validation that may enable such paths. Although API keys provide authentication, they do not mitigate network-based bypasses when origin and host controls are weak.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
To secure Fastapi endpoints using API keys while mitigating DNS rebinding risks, enforce strict host and origin validation, avoid forwarding requests to internal hosts based on untrusted input, and bind key checks to explicit allowlists. Below are concrete, working examples.
Example 1: Strict API key validation with allowed hosts
This example validates the API key and ensures incoming Host headers are restricted to expected values, reducing the impact of DNS rebinding via host manipulation.
from fastapi import Fastapi, Header, HTTPException, Request
from typing import Set
app = Fastapi()
# Allowed hosts to mitigate DNS rebinding via Host header
ALLOWED_HOSTS: Set[str] = {"api.example.com", "app.example.com"}
# Expected API keys (in production, use a secure store)
VALID_API_KEYS: Set[str] = {"s3cr3t-k3y-1", "s3cr3t-k3y-2"}
@app.middleware("http")
async def validate_host_middleware(request: Request, call_next):
host = request.headers.get("host", "")
# Normalize host: strip port if present
host = host.split(":")[0]
if host not in ALLOWED_HOSTS:
raise HTTPException(status_code=403, detail="Host not allowed")
response = await call_next(request)
return response
@app.get("/secure-data")
async def get_secure_data(x_api_key: str = Header(None)):
if x_api_key not in VALID_API_KEYS:
raise HTTPException(status_code=401, detail="Invalid API key")
return {"data": "secure resource"}
Example 2: CORS with explicit origins and key propagation safety
Configure CORS to allow only specific origins and avoid wildcard origins when API keys are used. This prevents malicious sites from making authenticated requests via the browser.
from fastapi import Fastapi
from fastapi.middleware.cors import CORSMiddleware
app = Fastapi()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://trusted.example.com"],
allow_credentials=True,
allow_methods=["GET"],
allow_headers=["x-api-key"],
)
@app.get("/public")
async def public_endpoint():
return {"message": "public"}
@app.get("/private")
async def private_endpoint(x_api_key: str = Header(None)):
if not x_api_key or x_api_key != "expected-key":
raise HTTPException(status_code=401, detail="Invalid API key")
return {"message": "private"}
Additional remediation guidance
- Do not forward or proxy requests to internal administrative endpoints based solely on API key authentication; validate target hosts against an explicit allowlist.
- Use short-lived keys and rotate them regularly to reduce exposure if a key is leaked via a rebinding scenario.
- Enforce HTTPS and HSTS to prevent downgrade attacks that could facilitate rebinding.
- Apply input validation on any user-controlled values used in URLs or host resolution logic.
middleBrick’s scans for Authentication, CORS misconfiguration, and Input Validation can highlight missing host checks and permissive CORS that may enable DNS rebinding in key-protected services.