From 9eb6b6ec7d1a51c34b9207d7b8cf5450419e4383 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 26 Nov 2022 02:56:17 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- .../kbe/res/scripts/common/Lib/tarfile.py | 21 ++++++++++++++++++- .../kbe/src/lib/python/Lib/tarfile.py | 21 ++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/kbengine-0.8.2/kbe/res/scripts/common/Lib/tarfile.py b/kbengine-0.8.2/kbe/res/scripts/common/Lib/tarfile.py index 9e291c2..5511929 100644 --- a/kbengine-0.8.2/kbe/res/scripts/common/Lib/tarfile.py +++ b/kbengine-0.8.2/kbe/res/scripts/common/Lib/tarfile.py @@ -2475,7 +2475,26 @@ def main(): if is_tarfile(src): with TarFile.open(src, 'r:*') as tf: - tf.extractall(path=curdir) + 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(tf, path=curdir) if args.verbose: if curdir == '.': msg = '{!r} file is extracted.'.format(src) diff --git a/kbengine-0.8.2/kbe/src/lib/python/Lib/tarfile.py b/kbengine-0.8.2/kbe/src/lib/python/Lib/tarfile.py index 9e291c2..5511929 100644 --- a/kbengine-0.8.2/kbe/src/lib/python/Lib/tarfile.py +++ b/kbengine-0.8.2/kbe/src/lib/python/Lib/tarfile.py @@ -2475,7 +2475,26 @@ def main(): if is_tarfile(src): with TarFile.open(src, 'r:*') as tf: - tf.extractall(path=curdir) + 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(tf, path=curdir) if args.verbose: if curdir == '.': msg = '{!r} file is extracted.'.format(src)