From 0ceb86d7722dff256b9a10870019923c79f1703d Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 17 Oct 2022 20:10:14 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- whitebox/download_wbt.py | 21 ++++++++++++++++++++- whitebox/whitebox_tools.py | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/whitebox/download_wbt.py b/whitebox/download_wbt.py index 723d367..a491df8 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 bc96c19..5184ab3 100644 --- a/whitebox/whitebox_tools.py +++ b/whitebox/whitebox_tools.py @@ -113,7 +113,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))