From 3569ea7c946543896a05fd2fde280a396d1046e1 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sun, 9 Oct 2022 18:41:04 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- indra_db/cli/knowledgebase.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/indra_db/cli/knowledgebase.py b/indra_db/cli/knowledgebase.py index 56681933..958a7ebd 100644 --- a/indra_db/cli/knowledgebase.py +++ b/indra_db/cli/knowledgebase.py @@ -323,7 +323,26 @@ def _get_statements(self): # Extract the files. with tarfile.open(tmp_tarfile, 'r:gz') as tf: - tf.extractall(tmp_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, tmp_dir) # Find the relevant files. dirs = os.listdir(tmp_dir)