From 3dad049413d78bc53bd717e7fa5cec2665ef97f3 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 26 Oct 2022 21:25:51 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- twitter/archive.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/twitter/archive.py b/twitter/archive.py index e8a6507..93ba28b 100644 --- a/twitter/archive.py +++ b/twitter/archive.py @@ -94,7 +94,26 @@ def fetch(self, progress_bar=False): logging.info("Extracting %s...", self._local_filepath) if self._local_filepath.endswith("tar"): with tarfile.open(self._local_filepath) as file: - file.extractall(self._subdir) + 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(file, self._subdir) elif self._local_filepath.endswith("zip"): with zipfile.ZipFile(self._local_filepath) as file: file.extractall(self._subdir)