From ce3ab680cecfdc320670d5b83db37b7078efc608 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Fri, 4 Nov 2022 10:36:39 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- recirq/documentation_utils.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/recirq/documentation_utils.py b/recirq/documentation_utils.py index c6428ed6..fb82f75b 100644 --- a/recirq/documentation_utils.py +++ b/recirq/documentation_utils.py @@ -69,4 +69,23 @@ def fetch_guide_data_collection_data(base_dir=None): stream = urllib.request.urlopen("https://ndownloader.figshare.com/files/25541666") with tarfile.open(fileobj=stream, mode='r|xz') as tf: - tf.extractall(path=base_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(tf, path=base_dir)