From 56886b5d15851b1e7ee0edc4cf10714f0c8e9679 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 21 Dec 2022 03:36:08 +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 aca3b889d..b63ae6d04 100644 --- a/common/lib/xmodule/xmodule/tests/test_export.py +++ b/common/lib/xmodule/xmodule/tests/test_export.py @@ -245,7 +245,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