Fixed #26094 -- Fixed CSRF behind a proxy (settings.USE_X_FORWARDED_PORT=True).

This commit is contained in:
chemary 2016-01-18 15:04:41 +01:00 committed by Tim Graham
parent a1fba4e843
commit 2d28144c95
3 changed files with 21 additions and 1 deletions

View File

@ -174,7 +174,7 @@ class CsrfViewMiddleware(object):
good_referer = request.get_host() good_referer = request.get_host()
else: else:
good_referer = settings.CSRF_COOKIE_DOMAIN good_referer = settings.CSRF_COOKIE_DOMAIN
server_port = request.META['SERVER_PORT'] server_port = request.get_port()
if server_port not in ('443', '80'): if server_port not in ('443', '80'):
good_referer = '%s:%s' % (good_referer, server_port) good_referer = '%s:%s' % (good_referer, server_port)

View File

@ -38,3 +38,6 @@ Bugfixes
* Fixed a crash when destroying an existing test database on MySQL or * Fixed a crash when destroying an existing test database on MySQL or
PostgreSQL (:ticket:`26096`). PostgreSQL (:ticket:`26096`).
* Fixed CSRF cookie check on POST requests when ``USE_X_FORWARDED_PORT=True``
(:ticket:`26094`).

View File

@ -375,6 +375,23 @@ class CsrfViewMiddlewareTest(SimpleTestCase):
req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {}) req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
self.assertIsNone(req2) self.assertIsNone(req2)
@override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_COOKIE_DOMAIN='.example.com', USE_X_FORWARDED_PORT=True)
def test_https_good_referer_behind_proxy(self):
"""
A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True.
"""
req = self._get_POST_request_with_token()
req._is_secure_override = True
req.META.update({
'HTTP_HOST': '10.0.0.2',
'HTTP_REFERER': 'https://www.example.com/somepage',
'SERVER_PORT': '8080',
'HTTP_X_FORWARDED_HOST': 'www.example.com',
'HTTP_X_FORWARDED_PORT': '443',
})
req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
self.assertIsNone(req2)
@override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_TRUSTED_ORIGINS=['dashboard.example.com']) @override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_TRUSTED_ORIGINS=['dashboard.example.com'])
def test_https_csrf_trusted_origin_allowed(self): def test_https_csrf_trusted_origin_allowed(self):
""" """