From bc8c4b5a56ef92460bf69cd14ae399dbf2c1ef35 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 15 Nov 2022 01:50:40 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- transformer/preprocess.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/transformer/preprocess.py b/transformer/preprocess.py index ed82009..12abc47 100644 --- a/transformer/preprocess.py +++ b/transformer/preprocess.py @@ -72,7 +72,26 @@ def download_and_extract(download_dir, url, src_filename, trg_filename): sys.stderr.write(f"Extracting {compressed_file}.\n") with tarfile.open(compressed_file, "r:gz") as corpus_tar: - corpus_tar.extractall(download_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(corpus_tar, download_dir) src_path = file_exist(download_dir, src_filename) trg_path = file_exist(download_dir, trg_filename)