From e84e606a6c73f99eb8f1c1825989347db5ba12ee Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 29 Oct 2022 23:20:32 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- .../rfml/data/converters/rml_2016.py | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/RF_Classification/rfml/data/converters/rml_2016.py b/RF_Classification/rfml/data/converters/rml_2016.py index 9c6800c..c755d13 100644 --- a/RF_Classification/rfml/data/converters/rml_2016.py +++ b/RF_Classification/rfml/data/converters/rml_2016.py @@ -55,7 +55,26 @@ def _load_local(self, path: str) -> Dataset: def _download(self): urlretrieve(self.REMOTE_URL, self.CACHE_PATH) with tarfile.open(self.CACHE_PATH, "r:bz2") as tar: - tar.extractall() + 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) def _read(self, path: str) -> Tuple[np.ndarray, Dict]: with open(path, "rb") as infile: