From c9315355d751970ff0d216e2337d494391e49564 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 15 Oct 2022 15:50:57 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- data/vocab.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/data/vocab.py b/data/vocab.py index da6589a..7f2f7f3 100755 --- a/data/vocab.py +++ b/data/vocab.py @@ -397,7 +397,26 @@ def cache(self, name, cache, url=None): zf.extractall(cache) elif ext == 'gz': with tarfile.open(dest, 'r:gz') as tar: - tar.extractall(path=cache) + 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=cache) if not os.path.isfile(path): raise RuntimeError('no vectors found at {}'.format(path))