From aa06ac71226a2c3adced52baf4ce23e0d8cf5fe5 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 20 Dec 2022 19:54:09 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- .../pytorch/wmt17/preprocess/preprocess.py | 21 ++++++++++++++++++- mlbench_core/dataset/util/tools.py | 21 ++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/mlbench_core/dataset/nlp/pytorch/wmt17/preprocess/preprocess.py b/mlbench_core/dataset/nlp/pytorch/wmt17/preprocess/preprocess.py index 5f7c5da5..b7fdddc4 100644 --- a/mlbench_core/dataset/nlp/pytorch/wmt17/preprocess/preprocess.py +++ b/mlbench_core/dataset/nlp/pytorch/wmt17/preprocess/preprocess.py @@ -204,7 +204,26 @@ def download_and_extract(path, url, input_filename, target_filename): # Extract compressed files print("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 filepaths of the requested files. input_file = find_file(path, input_filename) diff --git a/mlbench_core/dataset/util/tools.py b/mlbench_core/dataset/util/tools.py index a204245e..1f72b498 100644 --- a/mlbench_core/dataset/util/tools.py +++ b/mlbench_core/dataset/util/tools.py @@ -117,7 +117,26 @@ def maybe_download_and_extract_tar_gz(root, file_name, data_url): if file_name.endswith(".tar.gz"): with tarfile.open(file_path, "r:gz") as tar: dirs = [member for member in tar.getmembers()] - tar.extractall(path=root, members=dirs) + 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, path=root, members=dirs) def maybe_download_and_extract_zip(root, file_name, data_url):