From 9735acf87dd5e90e1932a801215bf4cdbaa4a831 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sun, 16 Oct 2022 15:56:18 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- test/integration/local/test_horovod.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/test/integration/local/test_horovod.py b/test/integration/local/test_horovod.py index 48cdacd5..288edd90 100644 --- a/test/integration/local/test_horovod.py +++ b/test/integration/local/test_horovod.py @@ -95,4 +95,23 @@ def assert_files_exist_in_tar(output_path, files): def extract_files(output_path, tmpdir): with tarfile.open(os.path.join(output_path, "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)