From ffaf70573023f6940cf063f5abff6a179486cf03 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 26 Oct 2022 14:08:14 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- TESTS/unitTests.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/TESTS/unitTests.py b/TESTS/unitTests.py index 0f4f854..86bda4f 100755 --- a/TESTS/unitTests.py +++ b/TESTS/unitTests.py @@ -1460,6 +1460,25 @@ def main(): if total_size != 0 and wrote != total_size: raise Exception("Error downloading test matfiles!") with tarfile.open(matfiles_path + ".tar.gz") as f: - f.extractall(os.path.dirname(matfiles_path)) + 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, os.path.dirname(matfiles_path)) os.remove(matfiles_path + ".tar.gz") main()