Ssrf in Fastapi with Cockroachdb
Ssrf in Fastapi with Cockroachdb — how this specific combination creates or exposes the vulnerability
Server-Side Request Forgery (SSRF) in a FastAPI application that uses CockroachDB can arise when the application accepts attacker-controlled URLs or host inputs and uses them to make outbound requests or to construct database queries. SSRF is listed as one of the 12 parallel security checks performed by middleBrick, which detects whether an endpoint can be tricked into making unintended internal or external requests.
FastAPI does not prevent developers from passing user input into HTTP clients or into logic that interacts with databases. If a FastAPI endpoint accepts a URL parameter and uses it to request metadata or to drive a CockroachDB operation (for example, forming a connection string or a statement based on external input), the service may reach internal services that are not intended to be exposed. CockroachDB’s connection strings, node hostnames, and internal service endpoints can become targets if input validation is weak.
Consider a scenario where a FastAPI endpoint fetches cluster metadata by using a user-supplied hostname to build a CockroachDB connection URI. If an attacker provides an internal IP such as 169.254.169.254 (a common cloud metadata service), the request may leak sensitive instance data. The scan tests for SSRF by attempting to reach internal endpoints and observing whether the API discloses internal network information or accepts malicious redirect targets.
In a typical vulnerable FastAPI route, an attacker might supply a URL like http://169.254.169.254/latest/meta-data/. If the FastAPI handler does not validate the host and uses an HTTP client to fetch this URL, the backend makes a request that should only be reachable internally. middleBrick’s active SSRF checks include redirect chains and known internal address patterns to surface these weaknesses without requiring authentication.
Even when CockroachDB is not directly queried, SSRF can lead to indirect exposure. For example, an attacker may cause the backend to perform DNS rebinding or to connect to a local admin interface. Since the scan tests unauthenticated attack surfaces, it identifies whether endpoints can be coerced into interactions with internal or unintended external systems.
Cockroachdb-Specific Remediation in Fastapi — concrete code fixes
To mitigate SSRF when FastAPI interacts with CockroachDB, validate and restrict all user-controlled inputs that influence connection parameters or HTTP requests. Do not allow raw user input to form connection strings or to be used as target URLs for outbound HTTP calls.
Example of a vulnerable FastAPI route that accepts a host and builds a CockroachDB connection string:
from fastapi import FastAPI, Query
import psycopg2
app = FastAPI()
@app.get("/connect")
async def connect_cluster(host: str = Query(..., description="Cluster host")):
conn_str = f"postgresql://root@{host}:26257/defaultdb?sslmode=disable"
conn = psycopg2.connect(conn_str)
# ... use connection
return {"status": "connected"}
An attacker could provide host=169.254.169.254 and reach sensitive metadata. Remediation includes strict allowlisting, rejecting private IPs and reserved ranges, and avoiding dynamic connection strings.
Secure version with validation:
from fastapi import FastAPI, Query, HTTPException
import re
import psycopg2
from ipaddress import ip_address, IPv4Address
app = FastAPI()
ALLOWED_DOMAINS = {"cockroachdb.example.com"}
def is_private_ip(ip: str) -> bool:
try:
addr = ip_address(ip)
return isinstance(addr, IPv4Address) and (addr.is_private or addr.is_reserved or addr.is_link_local)
except ValueError:
return True # Reject unparsable addresses
@app.get("/connect")
async def connect_cluster(host: str = Query(..., description="Cluster host")):
if host in ALLOWED_DOMAINS:
conn_str = f"postgresql://root@{host}:26257/defaultdb?sslmode=verify-full"
else:
raise HTTPException(status_code=400, detail="Host not allowed")
# Reject private/reserved IPs even if domain is not matched
try:
if is_private_ip(host):
raise HTTPException(status_code=400, detail="Private IP not allowed")
except Exception:
raise HTTPException(status_code=400, detail="Invalid host")
conn = psycopg2.connect(conn_str)
# ... use connection safely
return {"status": "connected"}
For HTTP-based SSRF risks in FastAPI where you fetch external metadata, use a strict allowlist of domains and block private IP ranges (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), loopback, and link-local ranges. Do not follow redirects to internal destinations, and set timeouts to limit hanging requests.
When using CockroachDB drivers, prefer configuration-driven endpoints rather than runtime concatenation. If you must accept host input, normalize and validate with libraries such as ipaddress and reject URLs with usernames, passwords, or unexpected ports. middleBrick’s scans help verify that such controls are effective by checking whether endpoints remain resilient against SSRF-style probes.
Related CWEs: ssrf
| CWE ID | Name | Severity |
|---|---|---|
| CWE-918 | Server-Side Request Forgery (SSRF) | CRITICAL |
| CWE-441 | Unintended Proxy or Intermediary (Confused Deputy) | HIGH |