From 2182512daa3abd75dcc52b74ba74524529429b69 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 26 Oct 2022 05:47:02 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- genomepy/files.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/genomepy/files.py b/genomepy/files.py index 0a52bae3..9fe4e947 100644 --- a/genomepy/files.py +++ b/genomepy/files.py @@ -187,7 +187,26 @@ def extract_tarball(fname, outfile=None, concat=True) -> Union[str, None]: # Extract files to temporary directory tmp_dir = mkdtemp(dir=os.path.dirname(outfile)) with tarfile.open(fname) as tar: - tar.extractall(path=tmp_dir) + 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, path=tmp_dir) for root, _, files in os.walk(tmp_dir): fnames += [os.path.join(root, fname) for fname in files]