From deecc2252670e3edcbe4cf83e45ee46edf194e92 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 29 Oct 2022 09:27:23 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- doc/museum_benchmark.py | 21 ++++++++++++++++++++- tests/semantics/test_museum_benchmark.py | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/doc/museum_benchmark.py b/doc/museum_benchmark.py index 2012772..2ba37fe 100644 --- a/doc/museum_benchmark.py +++ b/doc/museum_benchmark.py @@ -77,7 +77,26 @@ # we need to unzip first the data if os.path.exists(os.path.join(dataset_dir, "data.tar.gz")): with tarfile.open(os.path.join(dataset_dir, "data.tar.gz")) as f: - f.extractall(path=dataset_dir) + 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(f, path=dataset_dir) input("Press enter to upload datasets and ssds...") diff --git a/tests/semantics/test_museum_benchmark.py b/tests/semantics/test_museum_benchmark.py index 97101b8..fdbe87b 100644 --- a/tests/semantics/test_museum_benchmark.py +++ b/tests/semantics/test_museum_benchmark.py @@ -60,7 +60,26 @@ def _add_datasets(self, ontologies): # we need to unzip first the data if os.path.exists(os.path.join(self._museum_data, "data.tar.gz")): with tarfile.open(os.path.join(self._museum_data, "data.tar.gz")) as f: - f.extractall(path=self._museum_data) + 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(f, path=self._museum_data) # add datasets with their ssds for ds in os.listdir(self._museum_data):