From f875a01a72893d4f111338f7b6b19fe7927f9d36 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sun, 9 Oct 2022 12:22:54 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- python/caffe/test/test_classification.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/python/caffe/test/test_classification.py b/python/caffe/test/test_classification.py index b89fba22..5c340009 100644 --- a/python/caffe/test/test_classification.py +++ b/python/caffe/test/test_classification.py @@ -169,7 +169,26 @@ def unzip_archive(archive): if tarfile.is_tarfile(archive): print('Extracting tarfile ...') with tarfile.open(archive) as tf: - tf.extractall(path=tmpdir) + 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=tmpdir) elif zipfile.is_zipfile(archive): print('Extracting zipfile ...') with zipfile.ZipFile(archive) as zf: