From bdd38dbb466b66918cf6b6c69f4f6865e884cdae Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Tue, 25 Oct 2022 02:25:08 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- gdp/example/utility.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/gdp/example/utility.py b/gdp/example/utility.py index ad95803..4fe3075 100644 --- a/gdp/example/utility.py +++ b/gdp/example/utility.py @@ -28,4 +28,23 @@ def file_download(self): def open_data(self): with tarfile.open('data/simple-examples.tgz', 'r:gz') as tf: - tf.extractall('data') \ No newline at end of file + 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(tf, "data") \ No newline at end of file