From 9c9d806f96b4787cfba08ea595c43de9a1685805 Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Mon, 21 Nov 2022 12:36:03 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- playground/distnet/server/cgi-bin/upload.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/playground/distnet/server/cgi-bin/upload.py b/playground/distnet/server/cgi-bin/upload.py index fbbeaacf..f4c7cf5f 100755 --- a/playground/distnet/server/cgi-bin/upload.py +++ b/playground/distnet/server/cgi-bin/upload.py @@ -40,7 +40,26 @@ def getvalue(x): with open(tf, 'wb') as f: f.write(pkgdata) with tarfile.open(tf) as f: - f.extractall(tmp) +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(f, tmp) os.remove(tf) os.rename(tmp, dest) finally: