From 56852a1882f760fece43684cd938a5acd49c9273 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Thu, 27 Oct 2022 19:10:57 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- MDAnalysisData/adk_transitions.py | 24 +++++++++++++++++++++++- MDAnalysisData/vesicles.py | 24 +++++++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/MDAnalysisData/adk_transitions.py b/MDAnalysisData/adk_transitions.py index bb31ca5..dc72f36 100644 --- a/MDAnalysisData/adk_transitions.py +++ b/MDAnalysisData/adk_transitions.py @@ -174,7 +174,29 @@ def _fetch_adk_transitions(metadata, data_home=None, download_if_missing=True): logger.info("Unpacking {}...".format(archive_path)) with tarfile.open(archive_path, 'r') as tar: - tar.extractall(path=data_location) + + import os + + 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, path=data_location) records.topology = join(data_location, metadata['CONTENTS']['topology']) if not exists(records.topology): diff --git a/MDAnalysisData/vesicles.py b/MDAnalysisData/vesicles.py index b6f26d7..0e16c92 100644 --- a/MDAnalysisData/vesicles.py +++ b/MDAnalysisData/vesicles.py @@ -92,7 +92,29 @@ def fetch_vesicle_lib(data_home=None, download_if_missing=True): logger.info("Unpacking {}...".format(archive_path)) with tarfile.open(archive_path, 'r') as tar: - tar.extractall(path=data_location) + + import os + + 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, path=data_location) records.structures = [join(data_location, path) for path in metadata['CONTENTS']['structures'] if exists(join(data_location, path))]