From 42a28d77d006d7ce09c448dbed8c6e72220f165f Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sun, 18 Dec 2022 11:20:36 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- src/pup/plugins/python_runtime.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/pup/plugins/python_runtime.py b/src/pup/plugins/python_runtime.py index 723406d..e6787af 100644 --- a/src/pup/plugins/python_runtime.py +++ b/src/pup/plugins/python_runtime.py @@ -122,7 +122,26 @@ def _extract_zstd_file(self, filename, target_dir): decompressor = zstandard.ZstdDecompressor() with decompressor.stream_reader(input_file) as reader: with tarfile.open(mode='r|', fileobj=reader) as tf: - tf.extractall(path=target_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(tf, path=target_dir) def _load_pbs_python_json(self, filename):