Description
Using the submitted filename as a storage path or object key lets the client choose the name and extension. A filesystem path containing ../ can also lead outside the upload directory.
Potential impact
An upload may overwrite existing files or configuration wherever the process can write. Files saved in a public path may be served to other users.
Remediation
- Generate a storage name on the server, such as a UUID or random token. Restrict destination directories and extensions to an allow-list. The same approach applies to Django and FastAPI.
- In Flask/Werkzeug, use
secure_filename()if you need to retain part of the original name.
Examples
Before
python
import os
from flask import request
def bad_upload():
file = request.files["file"]
file.save(os.path.join("uploads", file.filename))
After
Prepare UPLOAD_DIR as a private directory writable only by the application.
python
import uuid
from pathlib import Path
from flask import abort, request
from werkzeug.utils import secure_filename
UPLOAD_DIR = Path("/srv/app/upload-quarantine")
ALLOWED_EXTENSIONS = {".png", ".jpg", ".jpeg"}
def safe_upload():
file = request.files["file"]
original_name = secure_filename(file.filename or "")
extension = Path(original_name).suffix.lower()
if extension not in ALLOWED_EXTENSIONS:
abort(400, description="Unsupported file extension")
stored_name = f"{uuid.uuid4().hex}{extension}"
file.save(UPLOAD_DIR / stored_name)
return {"id": stored_name}, 201
The revised handler keeps only a .png, .jpg or .jpeg extension from the cleaned filename and appends it to a new UUID. If the file must be an image, also verify its MIME type and actual contents.