From b1fffa1381f7a20f3b47a050d1f1315dfbb4b1b7 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 26 Nov 2022 23:12:42 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- cli/polyaxon/utils/path_utils.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/cli/polyaxon/utils/path_utils.py b/cli/polyaxon/utils/path_utils.py index fe19d0527..473d0cea6 100644 --- a/cli/polyaxon/utils/path_utils.py +++ b/cli/polyaxon/utils/path_utils.py @@ -204,7 +204,26 @@ def untar_file( logger.info("Untarring the contents of the file ...") # Untar the file with tarfile.open(filename) as tar: - tar.extractall(extract_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(tar, extract_path) if delete_tar: logger.info("Cleaning up the tar file ...") os.remove(filename)