From 5c2ca8e2edcaffae779d4a741ce933340be19855 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 17 Oct 2022 11:46:38 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- dataloaders/inc_ssl.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/dataloaders/inc_ssl.py b/dataloaders/inc_ssl.py index 9456260..689c5ce 100644 --- a/dataloaders/inc_ssl.py +++ b/dataloaders/inc_ssl.py @@ -456,7 +456,26 @@ def download(self): # extract file with tarfile.open(os.path.join(self.root, self.filename), "r:gz") as tar: - tar.extractall(path=self.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=self.root) def __repr__(self): fmt_str = 'Dataset ' + self.__class__.__name__ + '\n'