From 09972d2e25f104f0a2a4d19642f35d07c035702a Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sun, 18 Dec 2022 19:34:05 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- iglu/data/download.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/iglu/data/download.py b/iglu/data/download.py index fbef234..041e5f1 100644 --- a/iglu/data/download.py +++ b/iglu/data/download.py @@ -61,7 +61,26 @@ def download(directory=None, raw_data=False): logger.info('Extracting files...') path = os.path.join(directory, f'{prefix}.tar.gz') with tarfile.open(path, mode="r:*") as tf: - tf.extractall(path=directory) + 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=directory) return directory if __name__ == "__main__":