From a484d161b6a8d386927b52b788715cc4293e2d6a Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 8 Oct 2022 23:50:36 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- dask-tutorial/prep.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/dask-tutorial/prep.py b/dask-tutorial/prep.py index c60dee80..27fd575e 100644 --- a/dask-tutorial/prep.py +++ b/dask-tutorial/prep.py @@ -62,7 +62,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")):