From ef7bdbc8fc4d6778f8e6d32b283d6cadee87989e Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Thu, 3 Nov 2022 15:52:41 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- python/runtime/model/tar.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/python/runtime/model/tar.py b/python/runtime/model/tar.py index 9bcd40f2fb..d144b884b7 100644 --- a/python/runtime/model/tar.py +++ b/python/runtime/model/tar.py @@ -48,4 +48,23 @@ def unzip_dir(tarball, dest_dir=None): dest_dir = os.getcwd() with tarfile.open(tarball, 'r:gz') as tar: - tar.extractall(path=dest_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, path=dest_dir)