diff --git a/django/middleware/csrf.py b/django/middleware/csrf.py
index 37f92b1..fb2dbde 100644
|
a
|
b
|
else:
|
| 25 | 25 | randrange = random.randrange |
| 26 | 26 | _MAX_CSRF_KEY = 18446744073709551616L # 2 << 63 |
| 27 | 27 | |
| | 28 | CSRF_KEY_LENGTH = 32 # implied from using MD5 hash |
| | 29 | |
| 28 | 30 | REASON_NO_REFERER = "Referer checking failed - no Referer." |
| 29 | 31 | REASON_BAD_REFERER = "Referer checking failed - %s does not match %s." |
| 30 | 32 | REASON_NO_CSRF_COOKIE = "CSRF cookie not set." |
| … |
… |
def get_token(request):
|
| 59 | 61 | def _sanitize_token(token): |
| 60 | 62 | # Allow only alphanum, and ensure we return a 'str' for the sake of the post |
| 61 | 63 | # processing middleware. |
| 62 | | token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore'))) |
| | 64 | if len(token) >= CSRF_KEY_LENGTH: |
| | 65 | token = "" |
| | 66 | else: |
| | 67 | token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore'))) |
| 63 | 68 | if token == "": |
| 64 | 69 | # In case the cookie has been truncated to nothing at some point. |
| 65 | 70 | return _get_new_csrf_key() |
diff --git a/tests/regressiontests/csrf_tests/tests.py b/tests/regressiontests/csrf_tests/tests.py
index 6e6c87a..07bbfdb 100644
|
a
|
b
|
from __future__ import with_statement
|
| 4 | 4 | from django.conf import settings |
| 5 | 5 | from django.core.context_processors import csrf |
| 6 | 6 | from django.http import HttpRequest, HttpResponse |
| 7 | | from django.middleware.csrf import CsrfViewMiddleware |
| | 7 | from django.middleware.csrf import CsrfViewMiddleware, CSRF_KEY_LENGTH |
| 8 | 8 | from django.template import RequestContext, Template |
| 9 | 9 | from django.test import TestCase |
| 10 | 10 | from django.views.decorators.csrf import csrf_exempt, requires_csrf_token, ensure_csrf_cookie |
| … |
… |
class CsrfViewMiddlewareTest(TestCase):
|
| 100 | 100 | self.assertEqual(csrf_cookie['path'], '/test/') |
| 101 | 101 | self.assertTrue('Cookie' in resp2.get('Vary','')) |
| 102 | 102 | |
| | 103 | def test_process_view_token_too_long(self): |
| | 104 | u""" |
| | 105 | Check that if the token is longer than expected, it is ignored and |
| | 106 | a new token is created. |
| | 107 | """ |
| | 108 | req = self._get_GET_no_csrf_cookie_request() |
| | 109 | req.COOKIES[settings.CSRF_COOKIE_NAME] = 'x' * 10000000 |
| | 110 | CsrfViewMiddleware().process_view(req, token_view, (), {}) |
| | 111 | resp = token_view(req) |
| | 112 | resp2 = CsrfViewMiddleware().process_response(req, resp) |
| | 113 | csrf_cookie = resp2.cookies.get(settings.CSRF_COOKIE_NAME, False) |
| | 114 | self.assertEqual(len(csrf_cookie.value), CSRF_KEY_LENGTH) |
| | 115 | |
| 103 | 116 | def test_process_response_get_token_not_used(self): |
| 104 | 117 | """ |
| 105 | 118 | Check that if get_token() is not called, the view middleware does not |