logo

Database

Python Fastapi Path Traversal

Description

This detector identifies path traversal vulnerabilities in FastAPI applications where user-controlled input is passed to FileResponse without proper validation. When untrusted user input is used directly in file paths, attackers can use "../" sequences to access files outside the intended directory, potentially exposing sensitive system files or application data.

Weakness:

063 - Lack of data validation - Path Traversal

Category: Unexpected Injection

Detection Strategy

    Code must import the FastAPI library (specifically fastapi.responses.FileResponse or similar FileResponse functionality)

    A FileResponse constructor call must be present in the code

    The 'path' parameter of FileResponse must receive user-controlled input from FastAPI request sources (query parameters, path parameters, form data, request body, etc.)

    The user input passed to the path parameter must not be properly sanitized or validated to prevent directory traversal attacks

Vulnerable code example

from fastapi import FastAPI, Query, Request
from fastapi.responses import FileResponse

app = FastAPI()

@app.get("/download")
async def unsafe_file_download(request: Request):
    # VULNERABLE: User-controlled file path enables directory traversal...

✅ Secure code example

from fastapi import FastAPI, Query, Request
from fastapi.responses import FileResponse
from werkzeug.utils import secure_filename
import os

app = FastAPI()

@app.get("/download")...