From 64adcfb9818170449a95c08f0007e26d7c6116a3 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 31 Oct 2022 02:57:27 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- .../lib/xmodule/xmodule/tests/test_export.py | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/common/lib/xmodule/xmodule/tests/test_export.py b/common/lib/xmodule/xmodule/tests/test_export.py index 2595ec7..053fa39 100644 --- a/common/lib/xmodule/xmodule/tests/test_export.py +++ b/common/lib/xmodule/xmodule/tests/test_export.py @@ -246,7 +246,26 @@ def _expand_archive(self, name): target = path(self.temp_dir) / uuid.uuid4().hex os.mkdir(target) with tarfile.open(self.data_dir / name) as tar_file: - tar_file.extractall(path=target) + def is_within_directory(directory, target): + + abs_directory = os.path.abspath(directory) + abs_target = os.path.abspath(target) + + prefix = os.path.commonprefix([abs_directory, abs_target]) + + return prefix == abs_directory + + def safe_extract(tar, path=".", members=None, *, numeric_owner=False): + + for member in tar.getmembers(): + member_path = os.path.join(path, member.name) + if not is_within_directory(path, member_path): + raise Exception("Attempted Path Traversal in Tar File") + + tar.extractall(path, members, numeric_owner=numeric_owner) + + + safe_extract(tar_file, path=target) return target