From 8494c5723eebde4088766d26f80584d64416eed8 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 26 Oct 2022 14:45:39 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- sbg/cwl/serialize/deploy.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/sbg/cwl/serialize/deploy.py b/sbg/cwl/serialize/deploy.py index 62c2995..e03d03f 100755 --- a/sbg/cwl/serialize/deploy.py +++ b/sbg/cwl/serialize/deploy.py @@ -18,7 +18,29 @@ def b64untar(filename): stream.write(base64.b64decode(f.read())) stream.seek(0) with tarfile.open(fileobj=stream, mode='r:bz2') as tar: - tar.extractall() + + import os + + 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) if sys.version_info[0] == 3: importlib.invalidate_caches()