From f949f4cfdf72ec3ac569e9a866cb071907afe146 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 25 Oct 2022 12:13:02 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- test/test_api_util.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/test/test_api_util.py b/test/test_api_util.py index ebe7a39..89081f8 100644 --- a/test/test_api_util.py +++ b/test/test_api_util.py @@ -61,7 +61,26 @@ def test_tar_gz(self): # Tar file should be able to decompress and have same contents as # before. with tarfile.open(tar_path) as f: - f.extractall(checkdir) + 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(f, checkdir) with open(check_filename) as f: s = f.read()