diff --git a/assignment2/hw2/imdb_sentiment_data.py b/assignment2/hw2/imdb_sentiment_data.py index 3b8a77a..656deb6 100644 --- a/assignment2/hw2/imdb_sentiment_data.py +++ b/assignment2/hw2/imdb_sentiment_data.py @@ -26,7 +26,26 @@ def extract_data(filename): if not os.path.exists(os.path.join(os.path.dirname(__file__), 'data2/')): with tarfile.open(filename, "r") as tarball: dir = os.path.dirname(__file__) - tarball.extractall(os.path.join(dir, 'data2/')) + 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(tarball, os.path.join(dir,"data2/")) return def read_data(): diff --git a/assignment2/hw2sent/implementation.py b/assignment2/hw2sent/implementation.py index e25b381..0a67a3d 100644 --- a/assignment2/hw2sent/implementation.py +++ b/assignment2/hw2sent/implementation.py @@ -48,7 +48,26 @@ def extract_data(filename): if not os.path.exists(os.path.join(os.path.dirname(__file__), 'review_data/')): with tarfile.open(filename, "r") as tarball: dir = os.path.dirname(__file__) - tarball.extractall(os.path.join(dir, 'review_data/')) + 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(tarball, os.path.join(dir,"review_data/")) return # Read all movie reivews from extracted data