From 9b54e3d0c0e8043bb9a6a611bc114bc346d6ae55 Mon Sep 17 00:00:00 2001 From: Gavin D'souza Date: Fri, 14 Jan 2022 14:33:21 +0530 Subject: [PATCH] fix: Disallow sites to have file access beyond site folder --- frappe/core/doctype/file/file.py | 5 ++++- frappe/utils/file_manager.py | 8 ++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/frappe/core/doctype/file/file.py b/frappe/core/doctype/file/file.py index 50a7b31bca..8a1b2e516f 100755 --- a/frappe/core/doctype/file/file.py +++ b/frappe/core/doctype/file/file.py @@ -29,7 +29,7 @@ from frappe import _, conf, safe_decode from frappe.model.document import Document from frappe.utils import call_hook_method, cint, cstr, encode, get_files_path, get_hook_method, random_string, strip from frappe.utils.image import strip_exif_data, optimize_image -from frappe.utils.file_manager import safe_b64decode +from frappe.utils.file_manager import is_safe_path, safe_b64decode if TYPE_CHECKING: from PIL.ImageFile import ImageFile @@ -412,6 +412,9 @@ class File(Document): elif not self.file_url: frappe.throw(_("There is some problem with the file url: {0}").format(file_path)) + if not is_safe_path(file_path): + frappe.throw(f"Cannot access file path {file_path}") + return file_path def write_file(self): diff --git a/frappe/utils/file_manager.py b/frappe/utils/file_manager.py index 1e654d7881..15ba5d3d25 100644 --- a/frappe/utils/file_manager.py +++ b/frappe/utils/file_manager.py @@ -397,3 +397,11 @@ def add_attachments(doctype, name, attachments): files.append(f) return files + +def is_safe_path(path): + basedir = frappe.get_site_path() + # ref: https://docs.python.org/3/library/os.path.html#os.path.commonpath + matchpath = os.path.realpath(os.path.abspath(path)) + basedir = os.path.realpath(os.path.abspath(basedir)) + + return basedir == os.path.commonpath((basedir, matchpath))