diff --git a/scar/utils.py b/scar/utils.py index be7fae3..91cd21e 100644 --- a/scar/utils.py +++ b/scar/utils.py @@ -268,7 +268,26 @@ def create_tar_gz(files_to_archive: List[str], destination_tar_path: str) -> str def extract_tar_gz(tar_path: str, destination_path: str) -> None: """Extract the content of a .tar.gz file in the specified path.""" with tarfile.open(tar_path, 'r:gz') as tar: - tar.extractall(path=destination_path) + 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(tar, path=destination_path) @staticmethod def unzip_folder(zip_path: str, folder_where_unzip_path: str, msg: str='') -> None: