From 4435bc7789785fb11cb6cdd26d6f296f05e37cff Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Sat, 29 Oct 2022 03:44:44 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- scelvis/app.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/scelvis/app.py b/scelvis/app.py index ee66677..0834e2c 100644 --- a/scelvis/app.py +++ b/scelvis/app.py @@ -230,7 +230,26 @@ def find(name, path): elif filepath.endswith(".tar") or filepath.endswith(".tar.gz"): logger.info("Extracting TAR file %s to %s", filepath, tmpdir) with tarfile.open(filepath) as tarf: - tarf.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(tarf, tmpdir) else: return """