From 9df8c77f52165b1115640ba873e5c5d1a68e0100 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Fri, 16 Dec 2022 13:10:04 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- dataset/text/cfq.py | 21 ++++++++++++++++++++- dataset/text/dm_math.py | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/dataset/text/cfq.py b/dataset/text/cfq.py index 031cafa..921ee88 100644 --- a/dataset/text/cfq.py +++ b/dataset/text/cfq.py @@ -77,7 +77,26 @@ def build_cache(self) -> TextDatasetCache: "folder. Google login needed." with tarfile.open(gzfile, "r") as tf: - tf.extractall(path=self.cache_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(tf, path=self.cache_dir) splitdir = os.path.join(self.cache_dir, "cfq", "splits") for f in os.listdir(splitdir): diff --git a/dataset/text/dm_math.py b/dataset/text/dm_math.py index 1c53552..d133d11 100644 --- a/dataset/text/dm_math.py +++ b/dataset/text/dm_math.py @@ -34,7 +34,26 @@ def download(self): f" {os.path.abspath(self.cache_dir)} folder." with tarfile.open(os.path.join(self.cache_dir, "mathematics_dataset-v1.0.tar.gz"), "r") as tf: - tf.extractall(path=self.cache_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(tf, path=self.cache_dir) def load_file(self, path: str) -> Tuple[List[str], List[str]]: print(f"Loading {path}")