From fc56c15b6ad303c7709b69a5fe84f3ad7dbef17c Mon Sep 17 00:00:00 2001 From: TrellixVulnTeam Date: Thu, 17 Nov 2022 21:06:07 +0000 Subject: [PATCH] Adding tarfile member sanitization to extractall() --- egs/libri360_train/dataprep.py | 21 ++++++++++++++++++++- egs/voxceleb12_train/dataprep.py | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/egs/libri360_train/dataprep.py b/egs/libri360_train/dataprep.py index fc18ade..160d618 100644 --- a/egs/libri360_train/dataprep.py +++ b/egs/libri360_train/dataprep.py @@ -144,7 +144,26 @@ def full_extract(args, fname): print("Extracting %s" % fname) if fname.endswith(".tar.gz"): with tarfile.open(fname, "r:gz") as tar: - tar.extractall(args.save_path) + 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, args.save_path) elif fname.endswith(".zip"): with ZipFile(fname, "r") as zf: zf.extractall(args.save_path) diff --git a/egs/voxceleb12_train/dataprep.py b/egs/voxceleb12_train/dataprep.py index 183e095..9ceb02a 100644 --- a/egs/voxceleb12_train/dataprep.py +++ b/egs/voxceleb12_train/dataprep.py @@ -185,7 +185,26 @@ def full_extract(args, fname): print("Extracting %s" % fname) if fname.endswith(".tar.gz"): with tarfile.open(fname, "r:gz") as tar: - tar.extractall(args.save_path) + 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, args.save_path) elif fname.endswith(".zip"): with ZipFile(fname, "r") as zf: zf.extractall(args.save_path)