Path traversal

Prevent user-controlled paths from reaching files outside the intended base directory.

Description

Opening a filename from a request can let the caller reach files outside the intended directory. Choose a server-controlled base for file reads and downloads.

Potential impact

Reads can expose configuration or another user’s data. Depending on the service account’s permissions, writes or deletions can damage important files or change files that will later run.

Remediation

  • For a single filename in Flask/Werkzeug, reject an empty result from secure_filename(). If only certain files should be accessible, check their names against a server-managed allow-list.
  • Protect the base and its contents from file or symlink replacement. When opening an existing file directly, resolve links and verify that the actual target is inside the base.

Examples

open

Before

python
# Unsafe Flask code
from flask import Flask, request

app = Flask(__name__)

@app.route('/read')
def unsafe_read():
    filename = request.args.get('filename')
    with open(filename, 'r') as file:
        content = file.read()
    return content

After

python
# Safe Flask code
from flask import Flask, request, abort
from pathlib import Path
from werkzeug.security import safe_join
from werkzeug.utils import secure_filename

app = Flask(__name__)
# Server-managed directory that attackers cannot modify
BASE_DIR = Path("/safe/directory").resolve(strict=True)

@app.route('/read')
def safe_read():
    filename = secure_filename(request.args.get('filename', ''))
    if not filename:
        return abort(400, description="Invalid file path")

    candidate = safe_join(str(BASE_DIR), filename)
    if candidate is None:
        return abort(400, description="Invalid file path")

    try:
        fullpath = Path(candidate).resolve(strict=True)
        fullpath.relative_to(BASE_DIR)
    except FileNotFoundError:
        return abort(404, description="File not found")
    except ValueError:
        return abort(400, description="Invalid file path")

    if not fullpath.is_file():
        return abort(404, description="File not found")
    with open(fullpath, 'r') as file:
        content = file.read()
    return content

safe_join() combines the name with the base. Path.resolve(strict=True) finds the existing target, and relative_to() checks its location before the view opens a regular file.

Using only the filename component

python
import os
from pathlib import PurePath

def filename_only(raw_name):
    if not isinstance(raw_name, str):
        raise TypeError("filename must be a string")
    # Remove directory components using either method
    name = os.path.basename(raw_name)
    # name = PurePath(raw_name).name
    if name in {"", ".", ".."}:
        raise ValueError("invalid filename")
    return name

os.path.basename() and pathlib.PurePath(...).name extract the final component. Reject empty names, ., and .. as shown, then join the result to the trusted base.

Flask send_file

Before

python
# Unsafe Flask send_file
from flask import Flask, request, send_file

app = Flask(__name__)

@app.route('/read')
def unsafe_read():
    filename = request.args.get('filename')
    return send_file(filename)

After

python
# Safe Flask send_from_directory
from flask import Flask, request, send_from_directory
from pathlib import Path
from werkzeug.utils import secure_filename

app = Flask(__name__)
BASE_DIR = Path("/safe/directory").resolve(strict=True)

@app.route('/read')
def safe_read():
    filename = secure_filename(request.args.get('filename', ''))
    if not filename:
        return "Invalid file path", 400
    return send_from_directory(BASE_DIR, filename, as_attachment=True)

The download view rejects an empty name and sends an attachment with send_from_directory. Its trusted base must contain no links leading outside it.

References