From 99802a6eaaadea8c8a17ddba2ea75a7e04082327 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 29 Nov 2022 18:58:01 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- data-processing/common/unpack.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/data-processing/common/unpack.py b/data-processing/common/unpack.py index f1944fb4..e60c0bea 100644 --- a/data-processing/common/unpack.py +++ b/data-processing/common/unpack.py @@ -27,7 +27,26 @@ def unpack_archive(archive_path: str, dest_dir: str) -> None: # quarantines TeX and the compilation process using chroot. try: with tarfile.open(archive_path, mode="r:gz") as archive: - archive.extractall(dest_dir, members=get_safe_files(archive, dest_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, dest_dir, members=get_safe_files(archive,dest_dir)) logging.debug("Unpacked %s as a tar archive", archive_path) return except tarfile.ReadError: