From 2faca1e8475be31c08845a59a7340f28c5316813 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 21 Nov 2022 06:27:29 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- degas/runner.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/degas/runner.py b/degas/runner.py index b9a47a8..3376d29 100644 --- a/degas/runner.py +++ b/degas/runner.py @@ -27,7 +27,29 @@ def download_data(url, output_filepath: click.Path): filename, headers = urllib.request.urlretrieve(url) logging.info("Downloaded %s to %s", url, filename) with tarfile.open(filename) as tar: - tar.extractall(str(output_filepath)) + + import os + + 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, str(output_filepath)) logging.info("Extracted %s to %s", filename, output_filepath)