From 03b458018e568741347135c66072962f5df9ef21 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 10 Oct 2022 18:30:18 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- test/test_extractor.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/test/test_extractor.py b/test/test_extractor.py index 4b4aad7..188dfdf 100644 --- a/test/test_extractor.py +++ b/test/test_extractor.py @@ -76,7 +76,26 @@ def test_device_tree(tmpdir): devicetree_name = Path(os.path.join(test_data_folder, "device-tree.tar.gz")) with tarfile.open(devicetree_name) as tar_file: - tar_file.extractall(tmpdir) + 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, tmpdir) extractor = DeviceTreeExtractor(os.path.join(tmpdir, "device-tree"))