Python Fastapi Open Path Traversal
Description
This vulnerability detector identifies path traversal vulnerabilities in FastAPI applications where user-controlled input can be used to construct file paths that escape intended directory boundaries. When pathlib constructors use unsanitized user input from FastAPI request parameters, attackers can access arbitrary files on the server using sequences like "../../../etc/passwd".
Detection Strategy
• FastAPI framework must be imported in the analyzed file
• Code must contain pathlib constructor calls (like Path, PurePath, etc.) that are used to build file paths
• The pathlib constructor must receive input that originates from FastAPI user input sources (request parameters, path parameters, query parameters, request body, etc.)
• The user input must flow to the pathlib constructor without proper sanitization or validation to prevent directory traversal sequences
• The constructed path must be used in a context that could lead to file access (like file opening operations)
Vulnerable code example
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/read")
def vulnerable_file_read(filename: str = Query(...)):
# VULNERABLE: User input directly used in file path
return open(filename).read()✅ Secure code example
from fastapi import FastAPI, Query
from pathlib import Path
app = FastAPI()
BASE_DIR = Path("/opt/application/data")
@app.get("/read")...Search for vulnerabilities in your apps for free with Fluid Attacks' automated security testing! Start your 21-day free trial and discover the benefits of the Continuous Hacking Essential plan. If you prefer the Advanced plan, which includes the expertise of Fluid Attacks' hacking team, fill out this contact form.