From 9b80cbcff7a4aeafb0192c2dfef5331cf7acdfbf Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 1 Nov 2022 05:56:16 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- tensorcraft/asynclib.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/tensorcraft/asynclib.py b/tensorcraft/asynclib.py index 26e228c..522a20e 100644 --- a/tensorcraft/asynclib.py +++ b/tensorcraft/asynclib.py @@ -39,7 +39,29 @@ async def write(self, b): async def extract_tar(fileobj: io.IOBase, dest: str) -> None: """Extract content of the TAR archive into the given directory.""" with tarfile.open(fileobj=fileobj, mode="r") as tf: - tf.extractall(dest) + + 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(tf, dest) async def create_tar(fileobj: io.IOBase, path: str) -> None: