From 176f0c87059e145ee384cf4425818a4da6129ac1 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Fri, 9 Dec 2022 04:52:08 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- cifar-10-cnn.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/cifar-10-cnn.py b/cifar-10-cnn.py index 487afb4..d90cb47 100644 --- a/cifar-10-cnn.py +++ b/cifar-10-cnn.py @@ -24,7 +24,29 @@ def hook(self, block_num=1, block_size=1, total_size=None): if not isdir(cifar10_dataset_folder_path): with tarfile.open('cifar-10-python.tar.gz') as tar: - tar.extractall() + + import os + + 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) tar.close()