From fcccb7c7264f5063a9fc103e425a072778a20b3a Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Thu, 6 Oct 2022 10:59:16 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- ch08/files/compression/tar.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/ch08/files/compression/tar.py b/ch08/files/compression/tar.py index 69af6c2..593c0fc 100644 --- a/ch08/files/compression/tar.py +++ b/ch08/files/compression/tar.py @@ -8,4 +8,26 @@ tar.add('subfolder/content4.txt') with tarfile.open('example.tar.gz', 'r:gz') as tar: - tar.extractall('extract_tar') + + 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(tar, "extract_tar")