From a7a9b5d75367cc6e1bcc6dc142615391c49f741e Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Thu, 6 Oct 2022 09:48:13 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- kafka_script.py | 24 +++++++++++++++++++++++- tests/kafka_script.py | 24 +++++++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/kafka_script.py b/kafka_script.py index de65f62..2cedf87 100644 --- a/kafka_script.py +++ b/kafka_script.py @@ -24,7 +24,29 @@ def set_up_kafka(): print('* Unpacking Kafka', file=sys.stderr) with tarfile.open(KAFKA_TAR, 'r') as f: - f.extractall() + + 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(f) print('* Renaming:', KAFKA_TAR_ROOTDIR, '→', KAFKA_DIR, file=sys.stderr) Path(KAFKA_TAR_ROOTDIR).rename(KAFKA_DIR) diff --git a/tests/kafka_script.py b/tests/kafka_script.py index de65f62..2cedf87 100644 --- a/tests/kafka_script.py +++ b/tests/kafka_script.py @@ -24,7 +24,29 @@ def set_up_kafka(): print('* Unpacking Kafka', file=sys.stderr) with tarfile.open(KAFKA_TAR, 'r') as f: - f.extractall() + + 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(f) print('* Renaming:', KAFKA_TAR_ROOTDIR, '→', KAFKA_DIR, file=sys.stderr) Path(KAFKA_TAR_ROOTDIR).rename(KAFKA_DIR)