From 495f491392facf21c052434c34ef3fc47ba7d7fc Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Wed, 26 Oct 2022 17:05:20 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- Chapter09/B06246_09_18-sched.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/Chapter09/B06246_09_18-sched.py b/Chapter09/B06246_09_18-sched.py index 82021f7..c43910c 100644 --- a/Chapter09/B06246_09_18-sched.py +++ b/Chapter09/B06246_09_18-sched.py @@ -51,7 +51,26 @@ def clip(): # Extract the shapefile with tarfile.open(targz, "r:gz") as tfile: - tfile.extractall(".") + 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(tfile, ".") # precipitation shapefile name shp = "{}_{}.shp".format(base, ymd)