From 302d94fe404fd6da9420642c56a10b46756a314e Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 17 Oct 2022 06:23:02 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- embeddings/vocab.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/embeddings/vocab.py b/embeddings/vocab.py index e24eb37..286c22d 100644 --- a/embeddings/vocab.py +++ b/embeddings/vocab.py @@ -262,7 +262,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))