From 051cb1f4c60ac8e7087d92ef34ed41e6684d8b9b Mon Sep 17 00:00:00 2001 From: Florian Apolloner Date: Sat, 18 May 2013 12:32:47 +0200 Subject: [PATCH] Fixed #20411 -- Don't let invalid referers blow up CSRF same origin checks. Thanks to edevil for the report and saz for the patch. --- django/utils/http.py | 5 ++++- tests/csrf_tests/tests.py | 13 +++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/django/utils/http.py b/django/utils/http.py index 15fac6bfca..9897df4fb0 100644 --- a/django/utils/http.py +++ b/django/utils/http.py @@ -226,7 +226,10 @@ def same_origin(url1, url2): Checks if two URLs are 'same-origin' """ p1, p2 = urllib_parse.urlparse(url1), urllib_parse.urlparse(url2) - return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port) + try: + return (p1.scheme, p1.hostname, p1.port) == (p2.scheme, p2.hostname, p2.port) + except ValueError: + return False def is_safe_url(url, host=None): """ diff --git a/tests/csrf_tests/tests.py b/tests/csrf_tests/tests.py index 5300b2172a..b9e8cb5f75 100644 --- a/tests/csrf_tests/tests.py +++ b/tests/csrf_tests/tests.py @@ -283,6 +283,19 @@ class CsrfViewMiddlewareTest(TestCase): self.assertNotEqual(None, req2) self.assertEqual(403, req2.status_code) + @override_settings(ALLOWED_HOSTS=['www.example.com']) + def test_https_malformed_referer(self): + """ + Test that a POST HTTPS request with a bad referer is rejected + """ + req = self._get_POST_request_with_token() + req._is_secure_override = True + req.META['HTTP_HOST'] = 'www.example.com' + req.META['HTTP_REFERER'] = 'http://http://www.example.com/' + req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {}) + self.assertNotEqual(None, req2) + self.assertEqual(403, req2.status_code) + @override_settings(ALLOWED_HOSTS=['www.example.com']) def test_https_good_referer(self): """