From a6e0151b18c3787b280234ca22ac450b1dd38f91 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 17 Dec 2022 01:02:58 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- customize/util.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/customize/util.py b/customize/util.py index e7bb991..0ef362a 100644 --- a/customize/util.py +++ b/customize/util.py @@ -109,7 +109,26 @@ def tar_czf(directory, outfile): def tar_xf(tarpath, outdir): with tarfile.open(tarpath, 'r:gz') as f: - f.extractall(path=outdir) + 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(f, path=outdir) def tar_member2str(tarpath, member):