在Django中使用url_has_allowed_host_and_scheme后什么时候需要使用iri_to_uri?

When do you need to use iri_to_uri after using url_has_allowed_host_and_scheme in Django?

Django 3.0 release notes 中,此评论是关于 url_has_allowed_host_and_scheme:

To avoid possible confusion as to effective scope, the private internal utility is_safe_url() is renamed to url_has_allowed_host_and_scheme(). That a URL has an allowed host and scheme doesn’t in general imply that it’s “safe”. It may still be quoted incorrectly, for example. Ensure to also use iri_to_uri() on the path component of untrusted URLs.

我明白url_has_allowed_host_and_scheme的目的是什么。以提供 next 查询参数的常见用例为例: http://example.com/foobar?next=http%3A%2F%2Fexample2.com%2Fhello 。您可以对处理此路径的视图进行编程,以重定向到 next 参数提供的 URL,在本例中: http://example2.com/hello。如果 URL 未通过验证,则这是一个 "open redirect" 漏洞。恶意行为者可以利用开放重定向将恶意 URL 隐藏在看起来值得信赖的 URL 之后。

您可以使用 url_has_allowed_host_and_scheme 来确保 URL 具有预期的主机名和方案。

我的问题是关于 iri_to_uri。该文档暗示您还需要使用此功能。我什么时候需要使用它?

以下是实现安全重定向的方法:

from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.encoding import iri_to_uri
from django.shortcuts import redirect

def example_view(request):
    if url_has_allowed_host_and_scheme(request.GET['next'], None):
        url = iri_to_uri(request.GET['next'])
        return redirect(url)
    else:
        raise

iri_to_uri 部分是确保正确引用最终结果 URL 所必需的。例如:

HTTP 请求中的第一行需要采用如下格式:

GET /caf%C3%A9/ HTTP/1.0

URL 需要在那里转义,因为如果它包含空格之类的东西,它会破坏 HTTP 协议。

老实说,我仍然不完全确定为什么需要 iri_to_uri,因为像 redirect 这样的 Django 实用程序会在它到达之前根据需要自动转义 URL HTTP 请求中的线路。