From 74adc6cc8b20d1b891b7911cab5bae2b84174fe4 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sun, 30 Oct 2022 11:48:23 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- rootmaker/packers/tar_packer.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/rootmaker/packers/tar_packer.py b/rootmaker/packers/tar_packer.py index 231a641..01ef20c 100644 --- a/rootmaker/packers/tar_packer.py +++ b/rootmaker/packers/tar_packer.py @@ -7,4 +7,26 @@ def pack(path, fileobj): def unpack(path, fileobj): with tarfile.open(fileobj = fileobj, mode = 'r') as tar: - tar.extractall(path) \ No newline at end of file + +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, path) \ No newline at end of file