From f29881f75010947c0f594b0363995f43aae6748e Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 11 Oct 2022 10:14:02 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- download_model.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/download_model.py b/download_model.py index 798a6e3..96b3400 100755 --- a/download_model.py +++ b/download_model.py @@ -88,7 +88,26 @@ def main(): with open(stub_tgz_fn, 'wb') as fp: fp.write(request.urlopen(model_url).read()) with tarfile.open(stub_tgz_fn, 'r:gz') as tar_fp: - tar_fp.extractall(modeldir) + 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_fp, modeldir) os.remove(stub_tgz_fn) except Exception as e: sys.stderr.write('Error for {} ({})\n'.format(stub_base, e))