From ef6389776fe17783f245c8c4890c1913c697383c Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 5 Oct 2022 21:39:28 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- tools/ci/gitlab_api.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/tools/ci/gitlab_api.py b/tools/ci/gitlab_api.py index 93770215f..6c80a9306 100644 --- a/tools/ci/gitlab_api.py +++ b/tools/ci/gitlab_api.py @@ -207,7 +207,26 @@ def download_archive(self, ref: str, destination: str, project_id: Optional[int] with tarfile.open(temp_file.name, 'r') as archive_file: root_name = archive_file.getnames()[0] - archive_file.extractall(destination) + 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_file, destination) return os.path.join(os.path.realpath(destination), root_name)