From 06c81e863f4a88629dcf3920227de5b0bd55b181 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Thu, 27 Oct 2022 18:12:58 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- download_sample_data.py | 63 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/download_sample_data.py b/download_sample_data.py index 060083e..1432203 100644 --- a/download_sample_data.py +++ b/download_sample_data.py @@ -198,15 +198,72 @@ def _extract_downloaded_archive(output_path): delete the archive''' if output_path.endswith("tar.gz"): with tarfile.open(output_path, "r:gz") as tar: - tar.extractall() + 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) os.remove(output_path) elif output_path.endswith("tar"): with tarfile.open(output_path, "r:") as tar: - tar.extractall() + 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) os.remove(output_path) elif output_path.endswith("tar.bz2"): with tarfile.open(output_path, "r:bz2") as tar: - tar.extractall() + 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) os.remove(output_path) elif output_path.endswith("zip"): with zipfile.ZipFile(output_path, 'r') as zipf: