Ticket #27575: django-27575.diff

File django-27575.diff, 5.4 KB (added by daoyyy7777, 2 weeks ago)

Validate the effective host before URL resolution, with regression tests and documentation.

  • django/core/handlers/base.py

    diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py
    index d65a5ed..302865f 100644
    a b class BaseHandler:  
    311311            resolver = get_resolver(urlconf)
    312312        else:
    313313            resolver = get_resolver()
     314        # Request middleware may have normalized proxy headers. Validate the
     315        # effective host before resolving the URL or calling view middleware.
     316        request.get_host()
    314317        # Resolve the view, and assign the match object back to the request.
    315318        resolver_match = resolver.resolve(request.path_info)
    316319        request.resolver_match = resolver_match
  • docs/ref/settings.txt

    diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt
    index a1ab130..a929780 100644
    a b is validated against ``['.localhost', '127.0.0.1', '[::1]']``.  
    103103``ALLOWED_HOSTS`` is also :ref:`checked when running tests
    104104<topics-testing-advanced-multiple-hosts>`.
    105105
    106 This validation only applies via :meth:`~django.http.HttpRequest.get_host`;
    107 if your code accesses the ``Host`` header directly from ``request.META`` you
    108 are bypassing this security protection.
     106Django calls :meth:`~django.http.HttpRequest.get_host` before resolving the
     107request URL, after middleware has had the opportunity to normalize proxy
     108headers. Middleware that uses the host before calling ``get_response()``,
     109including middleware that returns its own response, should call
     110:meth:`~django.http.HttpRequest.get_host` to obtain the validated host.
     111Reading a header directly from ``request.META`` doesn't validate it.
    109112
    110113.. setting:: APPEND_SLASH
    111114
  • docs/releases/6.2.txt

    diff --git a/docs/releases/6.2.txt b/docs/releases/6.2.txt
    index fc7475a..1e7c400 100644
    a b Models  
    458458Requests and responses
    459459----------------------
    460460
     461* Django now checks :setting:`ALLOWED_HOSTS` before URL resolution even when
     462  no middleware or view calls :meth:`~django.http.HttpRequest.get_host`.
     463  Requests that reach URL resolution with a disallowed host now receive a
     464  400 response. Middleware that returns a response earlier remains responsible
     465  for validating any host it uses.
     466
    461467* Most Django-provided middleware now set ``async_capable = False`` to
    462468  avoid repetitive context switching in ``MiddlewareMixin.__acall__()`` under
    463469  ASGI. For atypical use cases, e.g. high in-process concurrency over non-ORM
  • docs/topics/security.txt

    diff --git a/docs/topics/security.txt b/docs/topics/security.txt
    index 075bc98..471115c 100644
    a b Because even seemingly-secure web server configurations are susceptible to fake  
    225225:setting:`ALLOWED_HOSTS` setting in the
    226226:meth:`django.http.HttpRequest.get_host` method.
    227227
    228 This validation only applies via :meth:`~django.http.HttpRequest.get_host`;
    229 if your code accesses the ``Host`` header directly from ``request.META`` you
    230 are bypassing this security protection.
     228The request handler calls :meth:`~django.http.HttpRequest.get_host` before
     229resolving the URL. Middleware that reads the host earlier should use the same
     230method. Accessing headers directly through ``request.META`` doesn't validate
     231them.
    231232
    232233For more details see the full :setting:`ALLOWED_HOSTS` documentation.
    233234
  • tests/handlers/tests.py

    diff --git a/tests/handlers/tests.py b/tests/handlers/tests.py
    index b1da08f..beedb70 100644
    a b def empty_middleware(get_response):  
    199199    pass
    200200
    201201
     202def last_forwarded_host_middleware(get_response):
     203    def middleware(request):
     204        forwarded = request.META["HTTP_X_FORWARDED_HOST"]
     205        request.META["HTTP_X_FORWARDED_HOST"] = forwarded.split(",")[-1].strip()
     206        return get_response(request)
     207
     208    return middleware
     209
     210
     211@override_settings(
     212    ALLOWED_HOSTS=["example.com"], ROOT_URLCONF="handlers.urls", MIDDLEWARE=[]
     213)
     214class HostValidationTests(SimpleTestCase):
     215    def test_disallowed_host(self):
     216        with self.assertLogs("django.security.DisallowedHost", "ERROR"):
     217            response = self.client.get("/regular/", headers={"host": "other.test"})
     218        self.assertEqual(response.status_code, 400)
     219        self.assertIsNone(response.wsgi_request.resolver_match)
     220
     221    async def test_disallowed_host_async(self):
     222        with self.assertLogs("django.security.DisallowedHost", "ERROR"):
     223            response = await self.async_client.request(
     224                path="/async_regular/", headers=[(b"host", b"other.test")]
     225            )
     226        self.assertEqual(response.status_code, 400)
     227        self.assertIsNone(response.asgi_request.resolver_match)
     228
     229    def test_allowed_host(self):
     230        response = self.client.get("/regular/", headers={"host": "example.com:8080"})
     231        self.assertContains(response, "regular content")
     232
     233    @override_settings(
     234        MIDDLEWARE=["handlers.tests.last_forwarded_host_middleware"],
     235        USE_X_FORWARDED_HOST=True,
     236    )
     237    def test_forwarded_host_after_middleware(self):
     238        for host, status in [("example.com", 200), ("other.test", 400)]:
     239            with self.subTest(host=host):
     240                response = self.client.get(
     241                    "/regular/",
     242                    headers={"x-forwarded-host": f"proxy.internal, {host}"},
     243                )
     244                self.assertEqual(response.status_code, status)
     245
     246
    202247@override_settings(ROOT_URLCONF="handlers.urls")
    203248class HandlerRequestTests(SimpleTestCase):
    204249    request_factory = RequestFactory()
Back to Top