HIGH dangling dnsfastapi

Dangling Dns in Fastapi

How Dangling DNS Manifests in FastAPI

Dangling DNS occurs when a DNS record (like an A, CNAME, or MX record) points to a cloud resource—such as an S3 bucket, Azure Blob Storage, or a legacy server—that has been deprovisioned or is no longer under your organization's control. In FastAPI applications, this vulnerability typically emerges through dynamic URL generation or external service integration, where the application constructs or redirects to URLs based on environment variables, configuration files, or even user-controlled input without validating that the target domain is still owned by your organization.

FastAPI's flexibility with routing and dependency injection creates specific attack patterns. A common manifestation is in RedirectResponse or URL objects that use a base URL from an environment variable. For example:

from fastapi import FastAPI, Request, RedirectResponse
import os

app = FastAPI()

@app.get("/legacy")
async def legacy_redirect(request: Request):
    # VULNERABLE: base_url from env might point to decommissioned resource
    base_url = os.getenv("LEGACY_API_BASE", "https://legacy.api.example.com")
    target = f"{base_url}/v1/data"
    return RedirectResponse(url=target)

If LEGACY_API_BASE points to a cloud storage bucket that was deleted but the DNS record remains, an attacker could register that same bucket name in their own cloud account, intercepting sensitive data or serving malicious content. This is a form of subdomain takeover, which falls under OWASP API Security Top 10's A05:2021 – Security Misconfiguration and can enable SSRF (CWE-918) or data exposure (CWE-200).

Another FastAPI-specific pattern involves url_for with dynamic host resolution. If your app uses request.headers.get("host") to generate absolute URLs (e.g., in email templates or webhooks), and that header is spoofed or the DNS record is dangling, you may leak links to attacker-controlled infrastructure.

FastAPI-Specific Detection

Detecting dangling DNS in a FastAPI app requires examining both code and runtime behavior. Start by auditing all places where external URLs are constructed: environment variable usage (e.g., os.getenv), configuration objects (like Settings from Pydantic), and any RedirectResponse, URL, or starlette.datastructures.URL instances. Look for patterns where the host component comes from a variable rather than a hardcoded, verified domain.

At runtime, you can test endpoints that perform redirects or call external services. Use tools like dig or nslookup to check if the DNS records for those domains resolve to resources you control. For example, if your FastAPI app redirects to https://storage.example.com/data, verify that the storage.example.com CNAME points to an active bucket in your AWS account. A dangling record will either not resolve or resolve to a default cloud provider page (like AWS's "NoSuchBucket").

Automated scanning with middleBrick simplifies this process. When you submit your FastAPI endpoint URL to middleBrick, it performs a black-box scan that includes dangling DNS detection as part of its Inventory Management and SSRF checks. The scanner will:

  • Identify endpoints that issue redirects or fetch external resources.
  • Extract target domains from responses (Location headers, JSON payloads, etc.).
  • Check DNS resolution and HTTP responses to infer if the domain points to an unclaimed resource (e.g., generic "Not Found" pages from cloud providers).
  • Provide a risk score and prioritized finding with remediation guidance specific to your API's behavior.

For example, a scan might report: "Dangling DNS vulnerability detected on /redirect endpoint: target domain old-cdn.example.net resolves to a default Azure Blob Storage page, indicating potential subdomain takeover." This aligns with middleBrick's 12 parallel security checks and maps to OWASP API Top 10:2023-A05 and PCI-DSS requirement 8.3.

FastAPI-Specific Remediation

Remediation in FastAPI revolves around strict validation of any domain used in URL construction and eliminating reliance on mutable DNS records. Follow these steps using FastAPI's native features:

1. Validate All External Domains with Pydantic
Never trust environment variables or user input for domain names. Use Pydantic's HttpUrl or AnyUrl with custom validators to ensure domains are in an allowlist. For example, define a settings model:

from pydantic import BaseSettings, HttpUrl, validator

class Settings(BaseSettings):
    LEGACY_API_BASE: HttpUrl

    @validator("LEGACY_API_BASE")
    def domain_must_be_owned(cls, v):
        allowed_domains = {"api.trusted.com", "v2.trusted.com"}
        if v.host not in allowed_domains:
            raise ValueError(f"Domain {v.host} not in allowlist")
        return v

settings = Settings()

This ensures that even if an environment variable is misconfigured, the app fails fast at startup.

2. Avoid Dynamic Redirects Based on Unverified Input
If you must redirect to an external URL, validate the host against a strict allowlist. Use middleware or a dependency:

from fastapi import Request, HTTPException, Depends
from starlette.responses import RedirectResponse

ALLOWED_REDIRECT_DOMAINS = {"docs.trusted.com", "help.trusted.com"}

async def validate_redirect_target(target: str):
    from urllib.parse import urlparse
    parsed = urlparse(target)
    if parsed.hostname not in ALLOWED_REDIRECT_DOMAINS:
        raise HTTPException(status_code=400, detail="Invalid redirect target")
    return target

@app.get("/go")
async def go(url: str, validated_url: str = Depends(validate_redirect_target)):
    return RedirectResponse(url=validated_url)

3. Use Relative Paths for Internal Redirects
Where possible, use relative paths instead of absolute URLs. FastAPI's url_for with a route name automatically generates correct relative URLs without exposing host information:

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

# Safe: generates "/items/123" without host
redirect_url = app.url_path_for("read_item", item_id=123)

4. Monitor DNS Records Separately
Dangling DNS is fundamentally an infrastructure issue. Implement a separate process (outside FastAPI) to audit DNS records quarterly, ensuring all CNAME/A records point to active resources. Tools like AWS Route 53's "Health Checks" or Azure DNS's "Zone monitoring" can automate this.

5. Secure Webhook/External Service Configurations
If your FastAPI app calls third-party APIs (e.g., payment gateways), store their base URLs in a configuration with strict domain validation as shown above. Never allow these to be overridden by request parameters.

FAQ

Q: How does Dangling DNS differ from SSRF in FastAPI?
A: Dangling DNS is a specific misconfiguration where a DNS record points to an unowned resource, enabling an attacker to claim that resource. SSRF (Server-Side Request Forgery) is a broader attack where an application makes an unintended HTTP request to an attacker-controlled destination. Dangling DNS often facilitates SSRF by providing a domain that resolves to attacker infrastructure. In FastAPI, SSRF might occur via a parameter like ?url= in an endpoint that fetches external data, while dangling DNS arises from static configuration pointing to stale DNS records.

Q: Can middleBrick detect Dangling DNS in any FastAPI deployment?
A: Yes. middleBrick performs black-box scanning, so it works with any publicly accessible FastAPI endpoint—whether deployed on AWS, Azure, Google Cloud, or on-premises. It does not require code access, agents, or credentials. The scanner analyzes HTTP responses (redirects, external links) and DNS behavior to identify potential dangling DNS vulnerabilities, then provides a risk score and remediation steps tailored to your API's observed behavior.

Frequently Asked Questions

How does Dangling DNS differ from SSRF in FastAPI?
Dangling DNS is a specific misconfiguration where a DNS record points to an unowned resource, enabling an attacker to claim that resource. SSRF (Server-Side Request Forgery) is a broader attack where an application makes an unintended HTTP request to an attacker-controlled destination. Dangling DNS often facilitates SSRF by providing a domain that resolves to attacker infrastructure. In FastAPI, SSRF might occur via a parameter like ?url= in an endpoint that fetches external data, while dangling DNS arises from static configuration pointing to stale DNS records.
Can middleBrick detect Dangling DNS in any FastAPI deployment?
Yes. middleBrick performs black-box scanning, so it works with any publicly accessible FastAPI endpoint—whether deployed on AWS, Azure, Google Cloud, or on-premises. It does not require code access, agents, or credentials. The scanner analyzes HTTP responses (redirects, external links) and DNS behavior to identify potential dangling DNS vulnerabilities, then provides a risk score and remediation steps tailored to your API's observed behavior.