From 0b79eb36915d178aef5c6a7bbce71b1e76d376d3 Mon Sep 17 00:00:00 2001 From: Florian Apolloner Date: Wed, 14 Apr 2021 18:23:44 +0200 Subject: Fixed CVE-2021-31542 -- Tightened path & file name sanitation in file uploads. --- django/utils/text.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'django/utils') diff --git a/django/utils/text.py b/django/utils/text.py index 7cc388f7fe..7f3368b16a 100644 --- a/django/utils/text.py +++ b/django/utils/text.py @@ -4,6 +4,7 @@ import unicodedata from gzip import GzipFile from io import BytesIO +from django.core.exceptions import SuspiciousFileOperation from django.utils.functional import SimpleLazyObject, keep_lazy_text, lazy from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext as _, gettext_lazy, pgettext @@ -221,7 +222,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 @@ -230,8 +231,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 -- cgit v1.3