diff --git a/_MISC/misc-examples/python3-book-examples/tarfile/tarfile_extractall.py b/_MISC/misc-examples/python3-book-examples/tarfile/tarfile_extractall.py index c663929e0..a952e4a35 100644 --- a/_MISC/misc-examples/python3-book-examples/tarfile/tarfile_extractall.py +++ b/_MISC/misc-examples/python3-book-examples/tarfile/tarfile_extractall.py @@ -10,5 +10,24 @@ os.mkdir('outdir') with tarfile.open('example.tar', 'r') as t: - t.extractall('outdir') + 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(t, "outdir") print(os.listdir('outdir')) diff --git a/_MISC/misc-examples/python3-book-examples/tarfile/tarfile_extractall_members.py b/_MISC/misc-examples/python3-book-examples/tarfile/tarfile_extractall_members.py index d95424974..6ed69df3a 100644 --- a/_MISC/misc-examples/python3-book-examples/tarfile/tarfile_extractall_members.py +++ b/_MISC/misc-examples/python3-book-examples/tarfile/tarfile_extractall_members.py @@ -10,7 +10,26 @@ os.mkdir('outdir') with tarfile.open('example.tar', 'r') as t: - t.extractall('outdir', + 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(t, "outdir", members=[t.getmember("README.txt")]) members=[t.getmember('README.txt')], ) print(os.listdir('outdir'))