From e100a14fd4a7112ccd714d30cd2c9ea12858fb76 Mon Sep 17 00:00:00 2001 From: Adam Hopkins Date: Sun, 31 Jul 2022 08:49:02 +0300 Subject: [PATCH] Use pathlib for path resolution (#2506) --- codecov.yml | 1 + sanic/mixins/routes.py | 61 +++++++++++++++++++++--------------------- tests/test_static.py | 9 ++++--- 3 files changed, 37 insertions(+), 34 deletions(-) diff --git a/codecov.yml b/codecov.yml index 5905afd5..f4256866 100644 --- a/codecov.yml +++ b/codecov.yml @@ -4,6 +4,7 @@ coverage: default: target: auto threshold: 0.75 + informational: true project: default: target: auto diff --git a/sanic/mixins/routes.py b/sanic/mixins/routes.py index 8a5f10cc..efb522f4 100644 --- a/sanic/mixins/routes.py +++ b/sanic/mixins/routes.py @@ -3,8 +3,8 @@ from contextlib import suppress from functools import partial, wraps from inspect import getsource, signature from mimetypes import guess_type -from os import path, sep -from pathlib import PurePath +from os import path +from pathlib import Path, PurePath from textwrap import dedent from time import gmtime, strftime from typing import ( @@ -26,12 +26,7 @@ from sanic.base.meta import SanicMeta from sanic.compat import stat_async from sanic.constants import DEFAULT_HTTP_CONTENT_TYPE, HTTP_METHODS from sanic.errorpages import RESPONSE_MAPPING -from sanic.exceptions import ( - BadRequest, - FileNotFound, - HeaderNotFound, - RangeNotSatisfiable, -) +from sanic.exceptions import FileNotFound, HeaderNotFound, RangeNotSatisfiable from sanic.handlers import ContentRangeHandler from sanic.log import error_logger from sanic.models.futures import FutureRoute, FutureStatic @@ -806,31 +801,39 @@ class RouteMixin(metaclass=SanicMeta): __file_uri__=None, ): # Merge served directory and requested file if provided - root_path = file_path = path.abspath(unquote(file_or_directory)) + file_path_raw = Path(unquote(file_or_directory)) + root_path = file_path = file_path_raw.resolve() + not_found = FileNotFound( + "File not found", + path=file_or_directory, + relative_url=__file_uri__, + ) if __file_uri__: # Strip all / that in the beginning of the URL to help prevent # python from herping a derp and treating the uri as an # absolute path unquoted_file_uri = unquote(__file_uri__).lstrip("/") + file_path_raw = Path(file_or_directory, unquoted_file_uri) + file_path = file_path_raw.resolve() + if ( + file_path < root_path and not file_path_raw.is_symlink() + ) or file_path_raw.match("../**/*"): + error_logger.exception( + f"File not found: path={file_or_directory}, " + f"relative_url={__file_uri__}" + ) + raise not_found - segments = unquoted_file_uri.split("/") - if ".." in segments or any(sep in segment for segment in segments): - raise BadRequest("Invalid URL") - - file_path = path.join(file_or_directory, unquoted_file_uri) - file_path = path.abspath(file_path) - - if not file_path.startswith(root_path): - error_logger.exception( - f"File not found: path={file_or_directory}, " - f"relative_url={__file_uri__}" - ) - raise FileNotFound( - "File not found", - path=file_or_directory, - relative_url=__file_uri__, - ) + try: + file_path.relative_to(root_path) + except ValueError: + if not file_path_raw.is_symlink(): + error_logger.exception( + f"File not found: path={file_or_directory}, " + f"relative_url={__file_uri__}" + ) + raise not_found try: headers = {} # Check if the client has been sent this file before @@ -898,11 +901,7 @@ class RouteMixin(metaclass=SanicMeta): except RangeNotSatisfiable: raise except FileNotFoundError: - raise FileNotFound( - "File not found", - path=file_or_directory, - relative_url=__file_uri__, - ) + raise not_found except Exception: error_logger.exception( f"Exception in static request handler: " diff --git a/tests/test_static.py b/tests/test_static.py index aeb625b7..c51e7e7e 100644 --- a/tests/test_static.py +++ b/tests/test_static.py @@ -616,8 +616,11 @@ def test_dotted_dir_ok( def test_breakout(app: Sanic, static_file_directory: str): app.static("/foo", static_file_directory) + _, response = app.test_client.get("/foo/..%2Ffake/server.py") + assert response.status == 404 + _, response = app.test_client.get("/foo/..%2Fstatic/test.file") - assert response.status == 400 + assert response.status == 404 @pytest.mark.skipif( @@ -629,6 +632,6 @@ def test_double_backslash_prohibited_on_win32( app.static("/foo", static_file_directory) _, response = app.test_client.get("/foo/static/..\\static/test.file") - assert response.status == 400 + assert response.status == 404 _, response = app.test_client.get("/foo/static\\../static/test.file") - assert response.status == 400 + assert response.status == 404