From 9ffde655f3efbe307f32e83c2154de386229ec96 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 17 Dec 2022 22:56:36 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- text_classification/dataset.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/text_classification/dataset.py b/text_classification/dataset.py index 5dbd1b8..88275c7 100644 --- a/text_classification/dataset.py +++ b/text_classification/dataset.py @@ -137,7 +137,29 @@ def download(path: Path): file.write(req.content) with tarfile.open(archive) as arch: - arch.extractall(path) + + 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(arch, path)