Man In The Middle in Fastapi
How Man In The Middle Manifests in FastAPI
Man-in-the-Middle (MITM) attacks against FastAPI applications exploit weaknesses in transport security or trust assumptions. FastAPI, built on Starlette and Uvicorn, inherits common web framework risks but has specific patterns:
- TLS Misconfiguration: Running Uvicorn without SSL (
uvicorn main:app) exposes all traffic in plaintext. Even with SSL, weak protocol versions (TLS 1.0/1.1) or cipher suites can be negotiated. FastAPI itself doesn't enforce HTTPS; this is an operational deployment gap. - Missing HSTS: Without
Strict-Transport-Securityheaders, browsers may accept downgraded connections. FastAPI apps often miss this header, enabling SSL stripping. - Proxy Header Spoofing: When behind a reverse proxy (Nginx, Traefik), FastAPI's
ProxyHeadersMiddlewaretrustsX-Forwarded-*headers. If the proxy isn't configured to strip externalX-Forwarded-Hostheaders, an attacker can inject malicious values, leading to cache poisoning or open redirects. - Client-Side Validation Bypass: FastAPI clients (e.g.,
httpxoraiohttpwithin the app) might disable certificate verification (verify=False) to simplify local development, creating MITM opportunities if deployed that way. - WebSocket Security: FastAPI WebSocket routes (
@app.websocket()) often lackwss://enforcement. An attacker on the same network can intercept WebSocket messages.
Example vulnerable proxy configuration in FastAPI:
from fastapi import FastAPI
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.middleware.proxy_headers import ProxyHeadersMiddleware
app = FastAPI()
# Dangerous: trusting all X-Forwarded-* headers from any source
app.add_middleware(ProxyHeadersMiddleware)If the reverse proxy doesn't filter external X-Forwarded-For headers, an attacker can send a request with X-Forwarded-For: evil.com to spoof IP-based logic.
FastAPI-Specific Detection
Detecting MITM vulnerabilities requires testing both the live endpoint and the OpenAPI specification. middleBrick's Encryption and Data Exposure checks target these issues:
- TLS Configuration: Scans the API's HTTPS endpoint for protocol versions, cipher strength, and certificate validity. It flags support for TLS 1.0/1.1, weak ciphers (e.g.,
RC4), and missing intermediate certificates. - HTTP Endpoint Exposure: Checks if the same API is accessible over plain HTTP. FastAPI apps sometimes run both ports (80/443) without redirects.
- HSTS Header: Tests for the presence and correct directives (
max-age,includeSubDomains) in responses. - OpenAPI Spec Analysis: Parses the
/openapi.jsonor/docsendpoints. If the spec'sserversarray useshttp://URLs, it indicates the API expects non-encrypted traffic, a misconfiguration. - Proxy Header Handling: Sends requests with spoofed
X-Forwarded-*headers to see if FastAPI accepts them without proxy validation.
Use middleBrick's CLI for a quick scan from your terminal:
middlebrick scan https://api.example.comThe report will show an Encryption category score (0–100) and specific findings like "TLS 1.0 supported" or "HSTS header missing." For CI/CD integration, the GitHub Action can fail a build if the encryption score drops below a threshold, preventing deployment of insecure configurations.
FastAPI-Specific Remediation
Remediation focuses on enforcing encryption at all layers and validating trust boundaries. Use FastAPI's native middleware and deployment configurations:
- Enforce HTTPS at the Proxy: Configure your reverse proxy (Nginx/Traefik) to redirect all HTTP to HTTPS and set HSTS. Example Nginx snippet:
server {
listen 80;
server_name api.example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
ssl_certificate /path/to/fullchain.pem;
ssl_certificate_key /path/to/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
location / {
proxy_pass http://fastapi_backend;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Optional: strip incoming X-Forwarded-* from clients
proxy_set_header X-Forwarded-Host "";
}
}- Validate Proxy Headers in FastAPI: Only enable
ProxyHeadersMiddlewareif the proxy is configured to set (not pass through)X-Forwarded-*headers. Combine withTrustedHostMiddlewareto restrict allowed hostnames:
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.middleware.proxy_headers import ProxyHeadersMiddleware
app = FastAPI()
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["api.example.com", "*.example.com"])
# Only use ProxyHeadersMiddleware if your proxy (e.g., Nginx) sets X-Forwarded-* itself
app.add_middleware(ProxyHeadersMiddleware)- Client Certificate Verification: When your FastAPI app makes outbound requests (to databases, external APIs), always verify certificates. Use
httpxwith defaultverify=True:
import httpx
async def call_external_api():
async with httpx.AsyncClient() as client:
response = await client.get("https://external.api/endpoint")
# Never set verify=False in production
return response.json()- WebSocket Security: Accept only
wss://connections. In your WebSocket route, check thescope["scheme"]:
@app.websocket_route("/ws")
async def websocket_endpoint(websocket: WebSocket):
if websocket.scope["scheme"] != "wss":
await websocket.close(code=1008) # Policy violation
return
await websocket.accept()
# ... rest of logicFinally, test your fixes with middleBrick's continuous monitoring (Pro plan) to ensure TLS settings remain compliant over time.
FAQ
Q: Can middleBrick detect MITM vulnerabilities in FastAPI apps running behind a cloud load balancer?
A: Yes. middleBrick tests the public-facing endpoint's TLS configuration, HSTS headers, and HTTP/HTTPS exposure regardless of underlying infrastructure. It also analyzes the OpenAPI spec for server URL schemes.
Q: How does middleBrick's OpenAPI analysis help prevent MITM risks in FastAPI?
A: FastAPI auto-generates OpenAPI specs. If the servers array in /openapi.json uses http:// URLs, it indicates the API is designed for non-encrypted traffic—a configuration flaw. middleBrick cross-references this spec with runtime findings to highlight inconsistencies, such as an HTTPS endpoint whose spec advertises HTTP.