diff --git a/src/image_classification/cub/cub_dataset.py b/src/image_classification/cub/cub_dataset.py index 49f94f5..f9e2464 100644 --- a/src/image_classification/cub/cub_dataset.py +++ b/src/image_classification/cub/cub_dataset.py @@ -69,7 +69,26 @@ def _download(self): download_url(self.url, 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)