summaryrefslogtreecommitdiff
path: root/django/utils/text.py
diff options
context:
space:
mode:
authorFlorian Apolloner <florian@apolloner.eu>2021-04-14 18:23:44 +0200
committerCarlton Gibson <carlton.gibson@noumenal.es>2021-04-27 19:12:15 +0200
commit25d84d64122c15050a0ee739e859f22ddab5ac48 (patch)
tree15fc59bd9e377fdf8ced4a60af221412fefffe15 /django/utils/text.py
parent6b0c7e6f5081a0dbe8acdbdcba9cfa6e5dff2792 (diff)
[3.1.x] Fixed CVE-2021-31542 -- Tightened path & file name sanitation in file uploads.
Diffstat (limited to 'django/utils/text.py')
-rw-r--r--django/utils/text.py10
1 files changed, 7 insertions, 3 deletions
diff --git a/django/utils/text.py b/django/utils/text.py
index fb5f6298c4..86594a0199 100644
--- a/django/utils/text.py
+++ b/django/utils/text.py
@@ -5,6 +5,7 @@ import warnings
from gzip import GzipFile
from io import BytesIO
+from django.core.exceptions import SuspiciousFileOperation
from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.functional import SimpleLazyObject, keep_lazy_text, lazy
from django.utils.regex_helper import _lazy_re_compile
@@ -219,7 +220,7 @@ class Truncator(SimpleLazyObject):
@keep_lazy_text
-def get_valid_filename(s):
+def get_valid_filename(name):
"""
Return the given string converted to a string that can be used for a clean
filename. Remove leading and trailing spaces; convert other spaces to
@@ -228,8 +229,11 @@ def get_valid_filename(s):
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
"""
- s = str(s).strip().replace(' ', '_')
- return re.sub(r'(?u)[^-\w.]', '', s)
+ s = str(name).strip().replace(' ', '_')
+ s = re.sub(r'(?u)[^-\w.]', '', s)
+ if s in {'', '.', '..'}:
+ raise SuspiciousFileOperation("Could not derive file name from '%s'" % name)
+ return s
@keep_lazy_text