diff --git a/whitebox/download_wbt.py b/whitebox/download_wbt.py index d62479f..a466956 100644 --- a/whitebox/download_wbt.py +++ b/whitebox/download_wbt.py @@ -85,7 +85,26 @@ def download_wbt(verbose=True): zip_ref.extractall(pkg_dir) else: # Decompress Linux tar file with tarfile.open(zip_name, "r") as tar_ref: - tar_ref.extractall(pkg_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_ref, pkg_dir) if verbose: print("WhiteboxTools package directory: {}".format(pkg_dir)) diff --git a/whitebox/whitebox_tools.py b/whitebox/whitebox_tools.py index ca868b3..e51a960 100644 --- a/whitebox/whitebox_tools.py +++ b/whitebox/whitebox_tools.py @@ -114,7 +114,26 @@ def download_wbt(verbose=True): zip_ref.extractall(pkg_dir) else: # Decompress Linux tar file with tarfile.open(zip_name, "r") as tar_ref: - tar_ref.extractall(pkg_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_ref, pkg_dir) if verbose: print("WhiteboxTools package directory: {}".format(pkg_dir))