From 3d6e2c7fb0d4762459bf7974db9b5b91bb2fb9f3 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Fri, 9 Dec 2022 15:23:33 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- language/gpt/tools/download/utils.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/language/gpt/tools/download/utils.py b/language/gpt/tools/download/utils.py index 4245dd4..6a296ef 100644 --- a/language/gpt/tools/download/utils.py +++ b/language/gpt/tools/download/utils.py @@ -37,7 +37,26 @@ def chunks(l, n, s=0): def extract_archive(archive_fp, outdir="."): with tarfile.open(archive_fp, "r") as tar: - tar.extractall(outdir) + 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, outdir) return outdir