From 4e104e08a0c0ed6a285c62ac6c51887c152373e2 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 31 Oct 2022 02:48:28 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- isochrones/grid.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/isochrones/grid.py b/isochrones/grid.py index 87b28dc..f492a7a 100644 --- a/isochrones/grid.py +++ b/isochrones/grid.py @@ -94,7 +94,26 @@ def extract_tarball(self, **kwargs): try: with tarfile.open(tarball) as tar: getLogger().info("Extracting {}...".format(tarball)) - tar.extractall(self.datadir) + 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, self.datadir) except EOFError: getLogger().error("{} corrupted; deleting and re-downloading.".format(tarball)) os.remove(tarball)