From 79868032bd2bf8efc8f5ec350cf7810f1bdb6be0 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 13 Dec 2022 00:51:54 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- gamma/utils.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/gamma/utils.py b/gamma/utils.py index db76ebd..313a2a5 100644 --- a/gamma/utils.py +++ b/gamma/utils.py @@ -156,7 +156,26 @@ def reporthook(blocknum, bs, size): if not os.path.exists(fpath): if tarfile.is_tarfile(fpath+sfx): with tarfile.open(fpath+sfx) as archive: - archive.extractall(fpath) + 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(archive, fpath) elif zipfile.is_zipfile(fpath+sfx): with zipfile.ZipFile(fpath+sfx) as archive: archive.extractall(fpath)