Brute Force Attack in Fastapi (Python)
Brute Force Attack in FastAPI with Python
FastAPI applications are vulnerable to brute force attacks when authentication endpoints lack proper rate limiting or account lockout mechanisms. Attackers can automate login attempts using tools like Hydra or custom scripts, targeting weak passwords or enumerating valid usernames. Since FastAPI is async by design, high-concurrency brute force attempts can overwhelm endpoints faster than synchronous frameworks if not mitigated. middleBrick detects this risk during its unauthenticated scan by testing the login endpoint for missing rate limiting controls, which falls under the 'Rate Limiting' security check. A successful brute force can lead to account takeover, especially if combined with BOLA/IDOR flaws in subsequent API calls.
For example, a simple FastAPI login endpoint without protections might look like this:
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
app = FastAPI()
class LoginData(BaseModel):
username: str
password: str
FAKE_USERS = {"admin": "password123"}
@app.post("/login")
async def login(data: LoginData):
if FAKE_USERS.get(data.username) == data.password:
return {"access_token": "fake-token"}
raise HTTPException(status_code=401, detail="Invalid credentials")
This endpoint allows unlimited login attempts, making it trivial for an attacker to guess credentials via brute force. middleBrick would flag this as a medium to high risk finding under Rate Limiting, with remediation guidance to implement request throttling.
Python-Specific Remediation in FastAPI
To mitigate brute force attacks in FastAPI, implement rate limiting using a middleware or dependency that tracks request frequency per IP or username. The slowapi library integrates cleanly with FastAPI and supports async endpoints. Configure limits on the login endpoint to block IPs after too many failed attempts within a time window. Additionally, consider adding exponential backoff or CAPTCHA for persistent offenders, though rate limiting is the primary defense.
Here’s a corrected version using slowapi:
from fastapi import FastAPI, HTTPException, Depends, Request
from pydantic import BaseModel
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
app = FastAPI()
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
class LoginData(BaseModel):
username: str
password: str
FAKE_USERS = {"admin": "password123"}
@app.post("/login")
@limiter.limit("5/minute")
async def login(request: Request, data: LoginData):
if FAKE_USERS.get(data.username) == data.password:
return {"access_token": "fake-token"}
raise HTTPException(status_code=401, detail="Invalid credentials")
This limits login attempts to 5 per minute per IP address. middleBrick validates such fixes by rescanning the endpoint and confirming rate limiting headers (like Retry-After) or blocked responses after threshold breaches. For Starter and Pro plans, continuous monitoring ensures the protection remains effective over time.
Frequently Asked Questions
Does middleBrick test for brute force vulnerabilities in FastAPI login endpoints?
Can I use the middleBrick CLI to scan my FastAPI app for brute force risks during development?
middlebrick scan http://localhost:8000 from your terminal to test the unauthenticated attack surface, including login endpoints. The CLI returns a security score and findings, helping you catch missing rate limiting before deploying to staging or production.