diff --git a/2019/6-azureml-movie-recommendation/movielens-sar/reco_utils/dataset/criteo.py b/2019/6-azureml-movie-recommendation/movielens-sar/reco_utils/dataset/criteo.py index 77b78d1..20e998b 100644 --- a/2019/6-azureml-movie-recommendation/movielens-sar/reco_utils/dataset/criteo.py +++ b/2019/6-azureml-movie-recommendation/movielens-sar/reco_utils/dataset/criteo.py @@ -151,7 +151,26 @@ def extract_criteo(size, compressed_file, path=None): extracted_dir = path with tarfile.open(compressed_file) as tar: - tar.extractall(extracted_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(tar, extracted_dir) filename_selector = { "sample": "dac_sample.txt", diff --git a/2019/6-azureml-movie-recommendation/reco_utils/dataset/criteo.py b/2019/6-azureml-movie-recommendation/reco_utils/dataset/criteo.py index 77b78d1..20e998b 100644 --- a/2019/6-azureml-movie-recommendation/reco_utils/dataset/criteo.py +++ b/2019/6-azureml-movie-recommendation/reco_utils/dataset/criteo.py @@ -151,7 +151,26 @@ def extract_criteo(size, compressed_file, path=None): extracted_dir = path with tarfile.open(compressed_file) as tar: - tar.extractall(extracted_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(tar, extracted_dir) filename_selector = { "sample": "dac_sample.txt",