votes up 3

Detected path traversal attempt in '%s'

Package:
django
github stars 59414
Exception Class:
SuspiciousFileOperation

Raise code

w_relative_path:
        # Use PurePosixPath() because this branch is checked only in
        # FileField.generate_filename() where all file paths are expected to be
        # Unix style (with forward slashes).
        path = pathlib.PurePosixPath(name)
        if path.is_absolute() or '..' in path.parts:
            raise SuspiciousFileOperation(
                "Detected path traversal attempt in '%s'" % name
            )
    elif name != os.path.basename(name):
        raise SuspiciousFileOperation("File name '%s' includes path elements" % name)

    return name


class FileP
😲 Agile task management is now easier than calling a taxi. #Tracklify

Ways to fix

votes up 2 votes down

Error Code:

from django.db.models import FileField
from django.core.files.storage import FileSystemStorage

stor = FileSystemStorage()
f = FileField(storage=stor)
file_name = 'tmp/../traverse/path'   # Suspicious directory path is used as the file name
f.generate_filename(None, file_name)

Fixed Code:

from django.db.models import FileField
from django.core.files.storage import FileSystemStorage

stor = FileSystemStorage()
f = FileField(storage=stor)
file_name = 'tmp/path/file.txt'  # File name with full path is passed
f.generate_filename(None, file_name)

Explanation:

If we try to pass the directory path instead of the filename to the generate_filename method of the FileField model, the Suspicious file operation exception is raised with the error message "Detected Path traversal attempt in ..,". It can be fixed by simply passing the file name instead of the directory path.

Jun 12, 2021 umangtaneja98 answer

Add a possible fix

Please authorize to post fix