diff --git a/Chapter06/extract_contents.py b/Chapter06/extract_contents.py index 3e1b060..ce6ef1b 100644 --- a/Chapter06/extract_contents.py +++ b/Chapter06/extract_contents.py @@ -2,5 +2,27 @@ os.mkdir('work') with tarfile.open('work.tar', 'r') as t: - t.extractall('work') + +import os + +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, "work") print(os.listdir('work'))