Detected path traversal attempt in '%s'
Package:
django
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
Links to the raise (1)
https://github.com/django/django/blob/7cca22964c09e8dafc313a400c428242404d527a/django/core/files/utils.py#L18Ways to fix
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.
Add a possible fix
Please authorize to post fix