From 94a1dd81e9a26d8716e213d875116153deba7233 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 22 Oct 2022 10:00:51 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- cnn_text_classification/mydatasets.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/cnn_text_classification/mydatasets.py b/cnn_text_classification/mydatasets.py index e06c38a..7edab2c 100644 --- a/cnn_text_classification/mydatasets.py +++ b/cnn_text_classification/mydatasets.py @@ -26,7 +26,26 @@ def download_or_unzip(cls, root): urllib.request.urlretrieve(cls.url, tpath) with tarfile.open(tpath, 'r') as tfile: print('extracting') - tfile.extractall(root) + 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(tfile, root) return os.path.join(path, '')