From cc0fd578fccd0191abbfff31288ec80d4ecc3863 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 2 Nov 2022 13:06:46 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- check-kernelpage.py | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/check-kernelpage.py b/check-kernelpage.py index 6841042..25f6dcf 100644 --- a/check-kernelpage.py +++ b/check-kernelpage.py @@ -16,7 +16,26 @@ def extract(filename): with tarfile.open(filename) as tar: - tar.extractall() + 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) else: from urllib import urlretrieve @@ -27,7 +46,26 @@ def extract(filename): file_content = f.read() fout.write(file_content) with tarfile.open(filename[:-3]) as tar: - tar.extractall() + 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) from configparser import ConfigParser import os