From a268a9044caf13f7e0437f8caff0fb58f8a1b3c7 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 23 Nov 2022 01:00:52 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- src/hvc/utils/datasets.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/hvc/utils/datasets.py b/src/hvc/utils/datasets.py index a842a37..1e78bc0 100644 --- a/src/hvc/utils/datasets.py +++ b/src/hvc/utils/datasets.py @@ -514,7 +514,26 @@ def fetch(dataset_str, destination_path=".", remove_compressed_file=True): if file_name.endswith(".tar.gz"): with tarfile.open(file_name) as tar: - tar.extractall(path=destination_path) + 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, path=destination_path) elif file_name.endswith(".zip"): with ZipFile(file_name, "r") as zipfile: