Sanitize the `next` query parameter to avoid malicious redirections

Issue #133 invalid
M G created an issue

In postman/base_write.html, postman/view.html and postman/base_folder.html, some links use a next query parameter.

However, this parameter is not sanitized in the called view and can lead to any redirection.

One should check the redirection URL before emitting the response, for example with the following snippet:

from django.utils.http import url_has_allowed_host_and_scheme
def sanitize_redirection(request, param="next"):
    """Sanitize the redirection URL, only keeping allowed hosts."""
    redirect_to: str = request.GET.get(param, "/")
    if not url_has_allowed_host_and_scheme(
        url=redirect_to,
        allowed_hosts={request.get_host()},
        require_https=request.is_secure(),
    ):
        redirect_to = "/"
    return redirect_to

Comments (3)

  1. Patrick Samson repo owner
    • changed status to open

    The query parameter is transformed by the _get_safe_internal_url() which drops any scheme or domain parts.

    Just for information, do you think of a case where it could be a real security issue (without the function mentioned afore)? I believe that a ?next=https://google.com is at worse just annoying.

  2. M G reporter

    Let’s imagine that our Django app is a public board that checks any link posted by a user (I own such a board, and I use the Google API to checks links).

    A malicious user can explain how to write a private message, posting htt[p]s://my.safe.board/postman/write/?next=htt[p]s://malicous.link/

    This link will be assessed as safe by Google, an innocent user will click it and will be redirected to the malicious link.

  3. Log in to comment