From 182b9ab3cf64c13f58a9b8961bfe845bf69ec84c Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sun, 9 Oct 2022 01:05:18 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- src/captchamonitor/utils/collector.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/captchamonitor/utils/collector.py b/src/captchamonitor/utils/collector.py index 6ff4d92..9bcbb0e 100644 --- a/src/captchamonitor/utils/collector.py +++ b/src/captchamonitor/utils/collector.py @@ -120,7 +120,26 @@ def __download_consensus_from_archive(self, consensus_date: datetime) -> None: # Extract the archive with tarfile.open(archive_path) as archive: - archive.extractall(download_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(archive, download_dir) # Recursively move files for day_folder in os.listdir(extracted_path):