From fcbb019c4020ce4ac343c25592d8f7275437344c Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 12 Oct 2022 05:31:41 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- test/integration/local/test_horovod.py | 21 ++++++++++++++++++++- test/integration/sagemaker/test_horovod.py | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/test/integration/local/test_horovod.py b/test/integration/local/test_horovod.py index 1e87135a..8eef41eb 100644 --- a/test/integration/local/test_horovod.py +++ b/test/integration/local/test_horovod.py @@ -43,7 +43,26 @@ def test_horovod_simple(sagemaker_local_session, image_uri, framework_version, t estimator.fit() with tarfile.open(os.path.join(str(tmpdir), 'model.tar.gz')) as tar: - tar.extractall(tmpdir) + 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, tmpdir) size = instances * processes diff --git a/test/integration/sagemaker/test_horovod.py b/test/integration/sagemaker/test_horovod.py index 09276e44..e20d2ef4 100644 --- a/test/integration/sagemaker/test_horovod.py +++ b/test/integration/sagemaker/test_horovod.py @@ -65,7 +65,26 @@ def test_horovod_simple( ) with tarfile.open(os.path.join(str(tmpdir), "model.tar.gz")) as tar: - tar.extractall(tmpdir) + 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, tmpdir) size = instances * processes