From 0d87a5d5daf7c906ac514bf692db3a75b5027eb3 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 12 Oct 2022 22:16:51 +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 4a52d9e..73572df 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 1824393..844b8cc 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)