From ca3bbec9690ea5782ed0eb278247c8b58aa28cc9 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 26 Nov 2022 22:17:23 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- tgan/model.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/tgan/model.py b/tgan/model.py index 1da098e..e262365 100755 --- a/tgan/model.py +++ b/tgan/model.py @@ -778,7 +778,26 @@ def load(cls, path): """Load a pretrained model from a given path.""" with tarfile.open(path, 'r:gz') as tar_handle: destination_dir = os.path.dirname(tar_handle.getmembers()[0].name) - tar_handle.extractall() + 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_handle) with open('{}/TGANModel'.format(destination_dir), 'rb') as f: instance = pickle.load(f)