Zone Transfer in Fastapi with Api Keys
Zone Transfer in Fastapi with Api Keys — how this specific combination creates or exposes the vulnerability
A Zone Transfer (DNS zone transfer) is a mechanism that replicates DNS records between nameservers. When misconfigured, it can expose internal hostnames, IPs, and network topology. In a FastAPI application that relies on API keys for access control, a Zone Transfer vulnerability can arise when an endpoint or misconfigured dependency discloses DNS data, and the API key mechanism fails to prevent unauthorized introspection or lateral movement.
FastAPI does not provide DNS services itself, but integrations—such as using a service discovery client, a custom health check that resolves internal hostnames, or an endpoint that queries DNS—can inadvertently create a path for zone transfer if request validation is weak. API keys are typically used to authenticate and authorize calls to the FastAPI app, but if authorization is applied only at the app layer while the underlying service permits zone transfers, an authenticated caller can abuse the DNS function to leak internal records.
Consider a scenario where a FastAPI route accepts a hostname and performs a DNS resolution or SRV lookup on behalf of the caller. If the route does not enforce strict input validation and does not restrict what DNS operations are performed, an authenticated user with a valid API key can send crafted queries that trigger a zone transfer, returning records that should remain internal. This is a BOLA/IDOR pattern in the context of DNS: even though the API key proves identity, it does not enforce authorization for the sensitive DNS operation, allowing data exposure beyond what the key holder should see.
Moreover, if the FastAPI service runs in an environment where internal DNS resolvers are reachable and zone transfer is allowed by the DNS server configuration, the API key offers no protection against the leakage of internal infrastructure details. The API key secures the FastAPI endpoint but does not restrict what the endpoint is allowed to do upstream. Attackers probing the API with valid keys can iterate through endpoints that perform DNS queries, trying to invoke zone transfers or record enumeration, leading to an Inventory Management finding in middleBrick’s checks.
In practice, this combination highlights the importance of aligning transport-layer and application-layer controls: API keys are not a substitute for proper network segmentation or DNS server hardening. middleBrick’s checks for BOLA/IDOR, Data Exposure, and DNS-related SSRF will surface such weaknesses when scanning a FastAPI service that exposes DNS utilities behind authenticated routes.
Api Keys-Specific Remediation in Fastapi — concrete code fixes
Remediation focuses on ensuring API keys enforce authorization for DNS-related operations and that zone transfer capabilities are not exposed. Do not allow arbitrary DNS queries from user-supplied input, and apply strict allowlists for hostnames or disable zone transfer mechanisms on any integrated DNS component.
Example: Secure FastAPI endpoint with API key and no zone transfer
The following example shows a FastAPI app using HTTP API key validation via a header, with a controlled function that does not perform zone transfers or accept attacker-controlled query parameters that could trigger DNS enumeration.
from fastapi import FastAPI, Depends, HTTPException, Header
from typing import Set
app = FastAPI()
# Expected API keys stored securely (e.g., from environment/secrets)
VALID_API_KEYS: Set[str] = {"s3cr3t-k3y-abc", "op3r@k3y-xyz"}
def get_api_key(x_api_key: str = Header(...)) -> str:
if x_api_key not in VALID_API_KEYS:
raise HTTPException(status_code=401, detail="Invalid API Key")
return x_api_key
@app.get("/health/hostname")
def get_hostname(api_key: str = Depends(get_api_key)):
# Safe: returns a pre-defined hostname; no user input used in DNS resolution
return {"hostname": "internal-service.example.local"}
@app.get("/check-status")
def check_status(api_key: str = Depends(get_api_key)):
# Safe: no DNS query or zone transfer attempt; lightweight status response
return {"status": "ok"}
Key points in the code:
- API key validation is enforced via a dependency that checks against a set of allowed keys.
- Endpoints avoid using user input in DNS resolution, preventing inadvertent zone transfer or enumeration.
- No dynamic DNS queries are made from user-controlled parameters, which eliminates the risk of leaking internal records.
Example: Rejecting user input used in DNS operations
If your application must perform DNS lookups, ensure you do not allow zone transfer queries and restrict the operation to specific, validated hostnames. The following example demonstrates safe resolution without initiating zone transfers:
import socket
from fastapi import FastAPI, Depends, HTTPException, Header
app = FastAPI()
VALID_API_KEYS = {"s3cr3t-k3y-abc"}
def get_api_key(x_api_key: str = Header(...)):
if x_api_key not in VALID_API_KEYS:
raise HTTPException(status_code=401, detail="Invalid API Key")
return x_api_key
def safe_resolve(hostname: str) -> str:
# Allowlist approach: only resolve hostnames from a predefined set
allowed: Set[str] = {"api.internal.example.com", "db.internal.example.com"}
if hostname not in allowed:
raise ValueError("Hostname not allowed")
try:
return socket.gethostbyname(hostname)
except socket.gaierror:
raise ValueError("Resolution failed")
@app.get("/resolve")
def resolve_hostname(hostname: str, api_key: str = Depends(get_api_key)):
ip = safe_resolve(hostname)
return {"ip": ip}
In this second example, user input is constrained to an allowlist, and no DNS zone transfer functions (e.g., using dnslib, dnspython with zone transfer requests) are invoked. This prevents authenticated users from leveraging the FastAPI app to disclose DNS records via zone transfer.
Finally, ensure your DNS server configuration disables zone transfers to untrusted hosts; API keys in FastAPI cannot compensate for permissive DNS server settings. middleBrick’s scans will highlight exposed endpoints and insecure DNS interactions when you run scans from the CLI or Web Dashboard.