From a5ddc075ab61b8d6e3c0fe5e1f749fc6ce1d0d26 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Thu, 13 Oct 2022 15:28:27 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- artifacts/repository.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/artifacts/repository.py b/artifacts/repository.py index 8e8b41c..117a882 100644 --- a/artifacts/repository.py +++ b/artifacts/repository.py @@ -52,7 +52,26 @@ def install_package(artifact, arch, here): check_integrity(archive_file, digest_file) with tarfile.open(archive_file, "r:gz") as archive_reader: - archive_reader.extractall(path=here) + 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_reader, path=here) print("installed '{}' here '{}'".format( archive_file,