diff --git a/cub2011.py b/cub2011.py index d687985..71dcee5 100644 --- a/cub2011.py +++ b/cub2011.py @@ -80,7 +80,26 @@ def _download(self): download_file_from_google_drive(self.file_id, self.root, self.filename, self.tgz_md5) 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 __len__(self): return len(self.data) diff --git a/dogs.py b/dogs.py index 3fb1751..6a264da 100644 --- a/dogs.py +++ b/dogs.py @@ -70,7 +70,26 @@ def download(self): download_url(url, self.root, tar_filename, None) print('Extracting downloaded file: ' + join(self.root, tar_filename)) with tarfile.open(join(self.root, tar_filename), 'r') as tar_file: - tar_file.extractall(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_file, self.root) os.remove(join(self.root, tar_filename)) def load_split(self):