Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion netpyne_ui/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from notebook.base.handlers import IPythonHandler
from netpyne_ui.constants import ALLOWED_EXTENSIONS, UPLOAD_FOLDER_PATH


def allowed_file(filename, allowed_extensions=ALLOWED_EXTENSIONS):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in allowed_extensions
Expand Down Expand Up @@ -43,6 +44,23 @@ def get_file_paths(handler):
return file_paths


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(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)


class NetPyNEController: # pytest: no cover

@post('/uploads')
Expand Down Expand Up @@ -74,7 +92,7 @@ def uploads(handler: IPythonHandler):

elif filename.endswith('.tar.gz'):
with tarfile.open(file_path, mode='r:gz') as tar:
tar.extractall(UPLOAD_FOLDER_PATH)
safe_extract_tar(tar, UPLOAD_FOLDER_PATH)

elif filename.endswith('.gz'):
with gzip.open(file_path, "rb") as gz, open(file_path.replace('.gz', ''), 'wb') as ff:
Expand Down