From e643591a8505915df944cfa45c250b4b3fe28b69 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Fri, 18 Nov 2022 18:16:49 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- training/transformer/data_download.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/training/transformer/data_download.py b/training/transformer/data_download.py index c53d573..d3cac6a 100644 --- a/training/transformer/data_download.py +++ b/training/transformer/data_download.py @@ -205,7 +205,26 @@ def download_and_extract(path, url, input_filename, target_filename): # Extract compressed files tf.logging.info("Extracting %s." % compressed_file) with tarfile.open(compressed_file, "r:gz") as corpus_tar: - corpus_tar.extractall(path) + 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(corpus_tar, path) # Return file paths of the requested files. input_file = find_file(path, input_filename)