From 629c8c55309a097ff2fe16f8a1f9e4278cb9e617 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Fri, 16 Dec 2022 12:28:27 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- ntclient/persistence/sql/usda/__init__.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/ntclient/persistence/sql/usda/__init__.py b/ntclient/persistence/sql/usda/__init__.py index b210326c..e9e9dd16 100644 --- a/ntclient/persistence/sql/usda/__init__.py +++ b/ntclient/persistence/sql/usda/__init__.py @@ -32,7 +32,26 @@ def download_extract_usda() -> None: # Extract the archive with tarfile.open(save_path, mode="r:xz") as usda_sqlite_file: print("\n" + "tar xvf %s.tar.xz" % USDA_DB_NAME) - usda_sqlite_file.extractall(NUTRA_HOME) + 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(usda_sqlite_file, NUTRA_HOME) print("==> done downloading %s" % USDA_DB_NAME)