diff --git a/utils/utilities.py b/utils/utilities.py index 90cb6a10..0fc34bdc 100644 --- a/utils/utilities.py +++ b/utils/utilities.py @@ -114,7 +114,26 @@ def unzip_file(file_path: str, target_dir: str): """Unpack ZIP-archive to specified directory""" if file_path.endswith('tgz'): with tarfile.open(file_path, 'r') as tar_file: - tar_file.extractall(target_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(tar_file, target_dir) elif file_path.endswith('zip'): with zipfile.ZipFile(file_path, 'r') as zip_file: zip_file.extractall(target_dir)