logo

Database

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".

Weakness:

184 - Lack of data validation

Category: Unexpected Injection

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")...