From a1244b9e3eb34586b549fc421dfb06d5cba452c6 Mon Sep 17 00:00:00 2001 From: Piero Toffanin Date: Tue, 26 Oct 2021 15:41:14 -0400 Subject: [PATCH] Path traversal check --- app/app.py | 13 +++++++++---- app/security.py | 14 ++++++++++++++ app/templates/index.html | 2 +- 3 files changed, 24 insertions(+), 5 deletions(-) create mode 100644 app/security.py diff --git a/app/app.py b/app/app.py index cd16942..e3a809e 100644 --- a/app/app.py +++ b/app/app.py @@ -12,7 +12,7 @@ from flask_swagger_ui import get_swaggerui_blueprint from translatehtml import translate_html from werkzeug.utils import secure_filename -from app import flood, remove_translated_files +from app import flood, remove_translated_files, security from app.language import detect_languages, transliterate from .api_keys import Database from .suggestions import Database as SuggestionsDatabase @@ -621,10 +621,15 @@ def create_app(args): Download a translated file """ if args.disable_files_translation: - abort(403, description="Files translation are disabled on this server.") - - + abort(400, description="Files translation are disabled on this server.") + filepath = os.path.join(get_upload_dir(), filename) + try: + checked_filepath = security.path_traversal_check(filepath, get_upload_dir()) + if os.path.isfile(checked_filepath): + filepath = checked_filepath + except security.SuspiciousFileOperation: + abort(400, description="Invalid filename") return_data = io.BytesIO() with open(filepath, 'rb') as fo: diff --git a/app/security.py b/app/security.py new file mode 100644 index 0000000..56913ce --- /dev/null +++ b/app/security.py @@ -0,0 +1,14 @@ +import os + +class SuspiciousFileOperation(Exception): + pass + +def path_traversal_check(unsafe_path, known_safe_path): + known_safe_path = os.path.abspath(known_safe_path) + unsafe_path = os.path.abspath(unsafe_path) + + if (os.path.commonprefix([known_safe_path, unsafe_path]) != known_safe_path): + raise SuspiciousFileOperation("{} is not safe".format(unsafe_path)) + + # Passes the check + return unsafe_path \ No newline at end of file diff --git a/app/templates/index.html b/app/templates/index.html index dcbb04c..24bb0f0 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -175,7 +175,7 @@
- Supported file format: [[ supportedFilesFormatFormatted ]] + Supported file formats: [[ supportedFilesFormatFormatted ]]