From 0bce5244cf9bdbfb03385b997f513cb2d2aaba4c Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 28 Nov 2022 03:01:53 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- opendeep/utils/file_ops.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/opendeep/utils/file_ops.py b/opendeep/utils/file_ops.py index c7d40fb..395ac25 100755 --- a/opendeep/utils/file_ops.py +++ b/opendeep/utils/file_ops.py @@ -321,7 +321,26 @@ def untar(source_filename, destination_dir='.'): log.debug('Unzipping tarball data from %s to %s', source_filename, destination_dir) try: with tarfile.open(source_filename) as tar: - tar.extractall(destination_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, destination_dir) return True except: log.exception('Error unzipping tarball data from %s to %s', source_filename, destination_dir)