Skip to content

Commit

Permalink
[1.7.x] Fixed #23815 -- Prevented UnicodeDecodeError in CSRF middleware
Browse files Browse the repository at this point in the history
Thanks codeitloadit for the report, living180 for investigations
and Tim Graham for the review.
Backport of 27dd7e7 from master.
  • Loading branch information
claudep committed Jan 6, 2015
1 parent 0e21fd4 commit d8fb557
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
6 changes: 5 additions & 1 deletion django/middleware/csrf.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,11 @@ def process_view(self, request, callback, callback_args, callback_kwargs):
# Barth et al. found that the Referer header is missing for
# same-domain requests in only about 0.2% of cases or less, so
# we can use strict Referer checking.
referer = request.META.get('HTTP_REFERER')
referer = force_text(
request.META.get('HTTP_REFERER'),
strings_only=True,
errors='replace'
)
if referer is None:
return self._reject(request, REASON_NO_REFERER)

Expand Down
3 changes: 3 additions & 0 deletions docs/releases/1.7.3.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,6 @@ Bugfixes
affect users who have subclassed
``django.contrib.auth.hashers.PBKDF2PasswordHasher`` to change the
default value.

* Fixed a crash in the CSRF middleware when handling non-ASCII referer header
(:ticket:`23815`).
5 changes: 5 additions & 0 deletions tests/csrf_tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,11 @@ def test_https_malformed_referer(self):
req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {})
self.assertNotEqual(None, req2)
self.assertEqual(403, req2.status_code)
# Non-ASCII
req.META['HTTP_REFERER'] = b'\xd8B\xf6I\xdf'
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):
Expand Down

0 comments on commit d8fb557

Please sign in to comment.