From 3f1fde7307f0018eed5a82dc210c729e35523428 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sun, 9 Oct 2022 12:52:11 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- docs/python/uncompress_ls.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/python/uncompress_ls.py b/docs/python/uncompress_ls.py index ba5fecc..8d331d7 100755 --- a/docs/python/uncompress_ls.py +++ b/docs/python/uncompress_ls.py @@ -35,7 +35,26 @@ def uncompress_ls(dirname,temp_dir='temp'): temp_dir = temp_dir or tempfile.mkdtemp() with tarfile.open(tar_path, 'r') as tar_file: thisDict = {} - tar_file.extractall(temp_dir) + 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_file, temp_dir) # Move the extracted xml directory to its final location try: shutil.move(glob(temp_dir+'/*xml')[0], extraction_dir)