From 8014a49b4c3253865e9fde07a275808d80bb7d5a Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 13 Dec 2022 15:48:43 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- datasets/torchvision_datasets/voc.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/datasets/torchvision_datasets/voc.py b/datasets/torchvision_datasets/voc.py index 3d8ee80..d9aab68 100644 --- a/datasets/torchvision_datasets/voc.py +++ b/datasets/torchvision_datasets/voc.py @@ -247,4 +247,23 @@ def parse_voc_xml(self, node): def download_extract(url, root, filename, md5): download_url(url, root, filename, md5) with tarfile.open(os.path.join(root, filename), "r") as tar: - tar.extractall(path=root) + 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=root)