From 148b8b8edeb87377b4b39bfed94e6664d8567a35 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 10 Oct 2022 18:48:54 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- test_transform.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/test_transform.py b/test_transform.py index 62153c0..6a85f9a 100755 --- a/test_transform.py +++ b/test_transform.py @@ -16,7 +16,29 @@ def setUpClass(cls): for lang in cls.languages: cls.wn_names[lang] = '.wordnet_' + lang with tarfile.open('wordnet_' + lang + '.tar.gz') as f: - f.extractall(cls.wn_names[lang]) + + 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(f, cls.wn_names[lang]) def test_all_synsets(self): self.wncr = WordNetCorpusReader(self.wn_names['spa'], None)