Fixed #32571 -- Made CsrfViewMiddleware handle invalid URLs in Referer header.

This commit is contained in:
Adam Donaghy 2021-03-19 20:42:05 +11:00 committed by Mariusz Felisiak
parent 474cc420bf
commit e49fdfa405
2 changed files with 10 additions and 1 deletions

View File

@ -298,7 +298,10 @@ class CsrfViewMiddleware(MiddlewareMixin):
if referer is None:
return self._reject(request, REASON_NO_REFERER)
referer = urlparse(referer)
try:
referer = urlparse(referer)
except ValueError:
return self._reject(request, REASON_MALFORMED_REFERER)
# Make sure we have a valid URL for Referer.
if '' in (referer.scheme, referer.netloc):

View File

@ -353,6 +353,12 @@ class CsrfViewMiddlewareTestMixin:
req.META['HTTP_REFERER'] = 'https://'
response = mw.process_view(req, post_form_view, (), {})
self.assertContains(response, malformed_referer_msg, status_code=403)
# Invalid URL
# >>> urlparse('https://[')
# ValueError: Invalid IPv6 URL
req.META['HTTP_REFERER'] = 'https://['
response = mw.process_view(req, post_form_view, (), {})
self.assertContains(response, malformed_referer_msg, status_code=403)
@override_settings(ALLOWED_HOSTS=['www.example.com'])
def test_https_good_referer(self):