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: