From 3a571ba2940fa311d30a8e8590c5042258fd776f Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Thu, 3 Nov 2022 22:13:48 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- .../validator_supervisor/backup_archive.py | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/supervisor/validator_supervisor/backup_archive.py b/supervisor/validator_supervisor/backup_archive.py index bcda7e5..6af0c96 100644 --- a/supervisor/validator_supervisor/backup_archive.py +++ b/supervisor/validator_supervisor/backup_archive.py @@ -114,7 +114,26 @@ def unpack(self, root_dir: str): """ self.data.seek(0) with tarfile.open(fileobj=self.data, mode='r:xz') as tar: - tar.extractall(root_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(tar, root_dir) def check_validator_data_dir(data_dir: str):