From e895da7b9d2da1fa57318df8fd5de2e6bf2e2b35 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 1 Nov 2022 16:13:24 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- femb/data/util.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/femb/data/util.py b/femb/data/util.py index 6f866cb..496e2b1 100644 --- a/femb/data/util.py +++ b/femb/data/util.py @@ -34,4 +34,23 @@ def http_get(url, path): def extract_archive(archive, destination): with tarfile.open(archive, "r:gz") as tar: - tar.extractall(path=destination) + 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, path=destination)