Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent directory traversion with static files #2495

Merged
merged 15 commits into from Jul 28, 2022
Merged
26 changes: 13 additions & 13 deletions sanic/mixins/routes.py
Expand Up @@ -5,7 +5,6 @@
from mimetypes import guess_type
from os import path
from pathlib import PurePath
from re import sub
from textwrap import dedent
from time import gmtime, strftime
from typing import (
Expand Down Expand Up @@ -806,23 +805,24 @@ async def _static_request_handler(
content_type=None,
__file_uri__=None,
):
# Using this to determine if the URL is trying to break out of the path
# served. os.path.realpath seems to be very slow
if __file_uri__ and "../" in __file_uri__:
raise BadRequest("Invalid URL")
# Merge served directory and requested file if provided
# 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
root_path = file_path = file_or_directory
root_path = file_path = unquote(file_or_directory)

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

segments = unquoted_file_uri.split("/")
if any(segment == ".." for segment in segments):
raise BadRequest("Invalid URL")

file_path = path.join(
file_or_directory, sub("^[/]*", "", __file_uri__)
file_or_directory, unquoted_file_uri
)

# URL decode the path sent by the browser otherwise we won't be able to
# match filenames which got encoded (filenames with spaces etc)
file_path = path.abspath(unquote(file_path))
if not file_path.startswith(path.abspath(unquote(root_path))):
file_path = path.abspath(file_path)
if not file_path.startswith(path.abspath(root_path)):
error_logger.exception(
f"File not found: path={file_or_directory}, "
f"relative_url={__file_uri__}"
Expand Down