From c8ae6384c692fffb78347229e591e16abb0e3c55 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 22 Oct 2022 06:18:07 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- pixels/behaviours/base.py | 42 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/pixels/behaviours/base.py b/pixels/behaviours/base.py index dc98056..964bb45 100644 --- a/pixels/behaviours/base.py +++ b/pixels/behaviours/base.py @@ -250,11 +250,49 @@ def find_file(self, name: str, copy: bool=True) -> Optional[Path]: if copy: print(f" {self.name}: Extracting {tar.name} to interim") with tarfile.open(tar) as open_tar: - open_tar.extractall(path=self.interim) + 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(open_tar, path=self.interim) return interim print(f" {self.name}: Extracting {tar.name}") with tarfile.open(tar) as open_tar: - open_tar.extractall(path=self.raw) + 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(open_tar, path=self.raw) return raw return None