From 9254e17816be251b4f906e0d1400e02a103d258a Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sun, 23 Oct 2022 23:44:24 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- espa_api_client/Downloaders.py | 42 ++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/espa_api_client/Downloaders.py b/espa_api_client/Downloaders.py index a7db092..e298ea7 100644 --- a/espa_api_client/Downloaders.py +++ b/espa_api_client/Downloaders.py @@ -28,7 +28,26 @@ def set_destpath(destpath, file_ext): if source_path.endswith(".tar.gz"): with tarfile.open(source_path, 'r:gz') as tfile: - tfile.extractall(set_destpath(destination_path, ".tar.gz")) + 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(tfile, set_destpath(destination_path,".tar.gz")) ret = destination_path # gzip only compresses single files @@ -41,7 +60,26 @@ def set_destpath(destpath, file_ext): elif source_path.endswith(".tar"): with tarfile.open(source_path, 'r') as tfile: - tfile.extractall(set_destpath(destination_path, ".tar")) + 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(tfile, set_destpath(destination_path,".tar")) ret = destination_path elif source_path.endswith(".zip"):