From 2ca5f8dbc48b6d320b7eb1012073d93560a5295a Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 26 Nov 2022 00:52:22 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- notebooks/TGAN-2/tgan/model.py | 21 ++++++++++++++++++++- notebooks/TGAN/tgan/model.py | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/notebooks/TGAN-2/tgan/model.py b/notebooks/TGAN-2/tgan/model.py index d453dc3..b4260c9 100644 --- a/notebooks/TGAN-2/tgan/model.py +++ b/notebooks/TGAN-2/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) diff --git a/notebooks/TGAN/tgan/model.py b/notebooks/TGAN/tgan/model.py index 1da098e..e262365 100755 --- a/notebooks/TGAN/tgan/model.py +++ b/notebooks/TGAN/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)