diff --git a/bin/individuals_merge.py b/bin/individuals_merge.py index ae0e3ad..8601dfd 100755 --- a/bin/individuals_merge.py +++ b/bin/individuals_merge.py @@ -14,7 +14,26 @@ def compress(archive, input_dir): def extract_all(archive, output_dir): with tarfile.open(archive, "r:*") as f: - f.extractall(os.path.basename(output_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(f, os.path.basename(output_dir)) flist = f.getnames() if flist[0] == '': flist = flist[1:] diff --git a/bin/individuals_merge_mpi.py b/bin/individuals_merge_mpi.py index 4982591..52365ef 100755 --- a/bin/individuals_merge_mpi.py +++ b/bin/individuals_merge_mpi.py @@ -18,7 +18,26 @@ def compress(archive, input_dir): def extract_all(archive, output_dir): with tarfile.open(archive, "r:*") as file: - file.extractall(os.path.basename(output_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(file, os.path.basename(output_dir)) flist = file.getnames() if flist[0] == '': flist = flist[1:]