diff --git a/pedl/utils.py b/pedl/utils.py index 2a9d143..b9b4753 100644 --- a/pedl/utils.py +++ b/pedl/utils.py @@ -302,13 +302,51 @@ def unpack_file(file: Path, unpack_to: Path, mode: str = None, keep: bool = True import tarfile with tarfile.open(file, "r:gz") as tarObj: - tarObj.extractall(unpack_to) + 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(tarObj, unpack_to) elif mode == "tar" or (mode is None and str(file).endswith("tar")): import tarfile with tarfile.open(file, "r") as tarObj: - tarObj.extractall(unpack_to) + 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(tarObj, unpack_to) elif mode == "gz" or (mode is None and str(file).endswith("gz")): import gzip