From 31e7b2b689ec0ab2c221988f0381d0a7873e903c Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 17 Oct 2022 10:01:46 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- pythonforandroid/pythonpackage.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/pythonforandroid/pythonpackage.py b/pythonforandroid/pythonpackage.py index 3b03a513f5..375985b3a5 100644 --- a/pythonforandroid/pythonpackage.py +++ b/pythonforandroid/pythonpackage.py @@ -401,7 +401,26 @@ def to_unicode(s): # Needed for Python 2. elif result_folder_or_file.find(".tar.") > 0: # Probably a tarball. with tarfile.open(result_folder_or_file) as f: - f.extractall(os.path.join(venv_path, + 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, os.path.join(venv_path,"download","extracted")) "download", "extracted" )) result_folder_or_file = os.path.join(