From 70e867013b99658e0f34e389b4da659c386926bf Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 15 Oct 2022 11:49:34 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- src/util/bot/go/bootstrap.py | 21 ++++++++++++++++++++- src/util/bot/update_clang.py | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/util/bot/go/bootstrap.py b/src/util/bot/go/bootstrap.py index 407d306..a9a8003 100755 --- a/src/util/bot/go/bootstrap.py +++ b/src/util/bot/go/bootstrap.py @@ -132,7 +132,26 @@ def install_toolset(toolset_root, url): f.extractall(toolset_root) elif pkg_path.endswith('.tar.gz'): with tarfile.open(pkg_path, 'r:gz') as f: - f.extractall(toolset_root) + 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, toolset_root) else: raise Failure('Unrecognized archive format') diff --git a/src/util/bot/update_clang.py b/src/util/bot/update_clang.py index 3ba423d..e46956c 100644 --- a/src/util/bot/update_clang.py +++ b/src/util/bot/update_clang.py @@ -60,7 +60,26 @@ def main(args): with tempfile.NamedTemporaryFile() as temp: DownloadFile(cds_full_url, temp.name) with tarfile.open(temp.name, "r:gz") as tar_file: - tar_file.extractall(LLVM_BUILD_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_file, LLVM_BUILD_DIR) with open(STAMP_FILE, "wb") as stamp_file: stamp_file.write(PACKAGE_VERSION)