From b647e638f1ef9c2d22af0fc1f938bd9d99863c12 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 10 Dec 2022 08:53:17 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- 2.1a_python_hpc/1_dask_tutorial/prep.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/2.1a_python_hpc/1_dask_tutorial/prep.py b/2.1a_python_hpc/1_dask_tutorial/prep.py index d2de337..a9d2532 100644 --- a/2.1a_python_hpc/1_dask_tutorial/prep.py +++ b/2.1a_python_hpc/1_dask_tutorial/prep.py @@ -63,7 +63,26 @@ def flights(small=None): print("- Extracting flight data... ", end='', flush=True) tar_path = os.path.join(data_dir, 'nycflights.tar.gz') with tarfile.open(tar_path, mode='r:gz') as flights: - flights.extractall('data/') + 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(flights, "data/") if small: for path in glob(os.path.join(data_dir, "nycflights", "*.csv")):