From 18a52fd466f892b90a5d63793206685d3fa70017 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Fri, 16 Dec 2022 12:44:28 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- src/roo/caches/build_cache.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/roo/caches/build_cache.py b/src/roo/caches/build_cache.py index 843ed95..bb9c7e1 100644 --- a/src/roo/caches/build_cache.py +++ b/src/roo/caches/build_cache.py @@ -112,7 +112,29 @@ def restore_build(self, try: with tarfile.open(pkg_path, "r:gz") as targz: - targz.extractall(str(destination)) + + import os + + 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(targz, str(destination)) except FileNotFoundError: raise FileNotFoundError( f"Unable to restore build {package_name} {package_version} "