From ecfcaa298a79432cd66c778c3b265d6901526418 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 17 Dec 2022 04:23:08 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- src/python/gem5/resources/downloader.py | 21 ++++++++++++++++++++- tests/gem5/fixture.py | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/src/python/gem5/resources/downloader.py b/src/python/gem5/resources/downloader.py index 7f4480158e..36b5da0452 100644 --- a/src/python/gem5/resources/downloader.py +++ b/src/python/gem5/resources/downloader.py @@ -433,5 +433,24 @@ def get_resource( ) unpack_to = download_dest[:-len(tar_extension)] with tarfile.open(download_dest) as f: - f.extractall(unpack_to) + 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(f, unpack_to) os.remove(download_dest) diff --git a/tests/gem5/fixture.py b/tests/gem5/fixture.py index a6b2881e8b..4b75d0e56c 100644 --- a/tests/gem5/fixture.py +++ b/tests/gem5/fixture.py @@ -340,7 +340,26 @@ class DownloadedArchive(DownloadedProgram): def _extract(self): import tarfile with tarfile.open(self.filename) as tf: - tf.extractall(self.path) + 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(tf, self.path) def _setup(self, testitem): # Check to see if there is a file downloaded