From 7984834309dec017277ef03181290c2bd3091e3d Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Thu, 20 Oct 2022 13:02:22 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- datasets/file_readers/tar_reader.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/datasets/file_readers/tar_reader.py b/datasets/file_readers/tar_reader.py index cfd1899..94c6754 100644 --- a/datasets/file_readers/tar_reader.py +++ b/datasets/file_readers/tar_reader.py @@ -40,7 +40,26 @@ def open(path): for member in f.getmembers(): if member.isfile(): filenames.append(member.name) - f.extractall(extract_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(f, extract_dir) file_info = {'extract_dir': extract_dir, 'filenames': filenames} tar_files[path] = file_info