Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Removed Django 1.1 fallback for CSRF checks.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@15948 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 21ef64e34c1c84bd7beb07531694d3f22fc42ffd 1 parent 4550f95
Luke Plant authored March 30, 2011
75  django/middleware/csrf.py
@@ -34,7 +34,6 @@
34 34
 
35 35
 REASON_NO_REFERER = "Referer checking failed - no Referer."
36 36
 REASON_BAD_REFERER = "Referer checking failed - %s does not match %s."
37  
-REASON_NO_COOKIE = "No CSRF or session cookie."
38 37
 REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
39 38
 REASON_BAD_TOKEN = "CSRF token missing or incorrect."
40 39
 
@@ -105,22 +104,14 @@ def process_view(self, request, callback, callback_args, callback_kwargs):
105 104
         if getattr(request, 'csrf_processing_done', False):
106 105
             return None
107 106
 
108  
-        # If the user doesn't have a CSRF cookie, generate one and store it in the
109  
-        # request, so it's available to the view.  We'll store it in a cookie when
110  
-        # we reach the response.
111 107
         try:
112  
-            # In case of cookies from untrusted sources, we strip anything
113  
-            # dangerous at this point, so that the cookie + token will have the
114  
-            # same, sanitized value.
115  
-            request.META["CSRF_COOKIE"] = _sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME])
116  
-            cookie_is_new = False
  108
+            csrf_token = _sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME])
  109
+            # Use same token next time
  110
+            request.META['CSRF_COOKIE'] = csrf_token
117 111
         except KeyError:
118  
-            # No cookie, so create one.  This will be sent with the next
119  
-            # response.
  112
+            csrf_token = None
  113
+            # Generate token and store it in the request, so it's available to the view.
120 114
             request.META["CSRF_COOKIE"] = _get_new_csrf_key()
121  
-            # Set a flag to allow us to fall back and allow the session id in
122  
-            # place of a CSRF cookie for this request only.
123  
-            cookie_is_new = True
124 115
 
125 116
         # Wait until request.META["CSRF_COOKIE"] has been manipulated before
126 117
         # bailing out, so that get_token still works
@@ -173,27 +164,17 @@ def process_view(self, request, callback, callback_args, callback_kwargs):
173 164
                     )
174 165
                     return self._reject(request, reason)
175 166
 
176  
-            # If the user didn't already have a CSRF cookie, then fall back to
177  
-            # the Django 1.1 method (hash of session ID), so a request is not
178  
-            # rejected if the form was sent to the user before upgrading to the
179  
-            # Django 1.2 method (session independent nonce)
180  
-            if cookie_is_new:
181  
-                try:
182  
-                    session_id = request.COOKIES[settings.SESSION_COOKIE_NAME]
183  
-                    csrf_token = _make_legacy_session_token(session_id)
184  
-                except KeyError:
185  
-                    # No CSRF cookie and no session cookie. For POST requests,
186  
-                    # we insist on a CSRF cookie, and in this way we can avoid
187  
-                    # all CSRF attacks, including login CSRF.
188  
-                    logger.warning('Forbidden (%s): %s' % (REASON_NO_COOKIE, request.path),
189  
-                        extra={
190  
-                            'status_code': 403,
191  
-                            'request': request,
192  
-                        }
193  
-                    )
194  
-                    return self._reject(request, REASON_NO_COOKIE)
195  
-            else:
196  
-                csrf_token = request.META["CSRF_COOKIE"]
  167
+            if csrf_token is None:
  168
+                # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
  169
+                # and in this way we can avoid all CSRF attacks, including login
  170
+                # CSRF.
  171
+                logger.warning('Forbidden (%s): %s' % (REASON_NO_CSRF_COOKIE, request.path),
  172
+                    extra={
  173
+                        'status_code': 403,
  174
+                        'request': request,
  175
+                    }
  176
+                )
  177
+                return self._reject(request, REASON_NO_CSRF_COOKIE)
197 178
 
198 179
             # check incoming token
199 180
             request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
@@ -202,23 +183,13 @@ def process_view(self, request, callback, callback_args, callback_kwargs):
202 183
                 request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')
203 184
 
204 185
             if not constant_time_compare(request_csrf_token, csrf_token):
205  
-                if cookie_is_new:
206  
-                    # probably a problem setting the CSRF cookie
207  
-                    logger.warning('Forbidden (%s): %s' % (REASON_NO_CSRF_COOKIE, request.path),
208  
-                        extra={
209  
-                            'status_code': 403,
210  
-                            'request': request,
211  
-                        }
212  
-                    )
213  
-                    return self._reject(request, REASON_NO_CSRF_COOKIE)
214  
-                else:
215  
-                    logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path),
216  
-                        extra={
217  
-                            'status_code': 403,
218  
-                            'request': request,
219  
-                        }
220  
-                    )
221  
-                    return self._reject(request, REASON_BAD_TOKEN)
  186
+                logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path),
  187
+                    extra={
  188
+                        'status_code': 403,
  189
+                        'request': request,
  190
+                    }
  191
+                )
  192
+                return self._reject(request, REASON_BAD_TOKEN)
222 193
 
223 194
         return self._accept(request)
224 195
 
50  tests/regressiontests/csrf_tests/tests.py
@@ -6,8 +6,6 @@
6 6
 from django.middleware.csrf import CsrfMiddleware, CsrfViewMiddleware
7 7
 from django.views.decorators.csrf import csrf_exempt, csrf_view_exempt, requires_csrf_token
8 8
 from django.core.context_processors import csrf
9  
-from django.contrib.sessions.middleware import SessionMiddleware
10  
-from django.utils.importlib import import_module
11 9
 from django.conf import settings
12 10
 from django.template import RequestContext, Template
13 11
 
@@ -62,14 +60,6 @@ class CsrfMiddlewareTest(TestCase):
62 60
     _csrf_id_cookie = "<1>\xc2\xa1"
63 61
     _csrf_id = "1"
64 62
 
65  
-    # This is a valid session token for this ID and secret key.  This was generated using
66  
-    # the old code that we're to be backwards-compatible with.  Don't use the CSRF code
67  
-    # to generate this hash, or we're merely testing the code against itself and not
68  
-    # checking backwards-compatibility.  This is also the output of (echo -n test1 | md5sum).
69  
-    _session_token = "5a105e8b9d40e1329780d62ea2265d8a"
70  
-    _session_id = "1"
71  
-    _secret_key_for_session_test= "test"
72  
-
73 63
     def setUp(self):
74 64
         self.save_warnings_state()
75 65
         warnings.filterwarnings('ignore', category=DeprecationWarning,
@@ -101,17 +91,6 @@ def _get_POST_request_with_token(self):
101 91
         req.POST['csrfmiddlewaretoken'] = self._csrf_id
102 92
         return req
103 93
 
104  
-    def _get_POST_session_request_with_token(self):
105  
-        req = self._get_POST_no_csrf_cookie_request()
106  
-        req.COOKIES[settings.SESSION_COOKIE_NAME] = self._session_id
107  
-        req.POST['csrfmiddlewaretoken'] = self._session_token
108  
-        return req
109  
-
110  
-    def _get_POST_session_request_no_token(self):
111  
-        req = self._get_POST_no_csrf_cookie_request()
112  
-        req.COOKIES[settings.SESSION_COOKIE_NAME] = self._session_id
113  
-        return req
114  
-
115 94
     def _check_token_present(self, response, csrf_id=None):
116 95
         self.assertContains(response, "name='csrfmiddlewaretoken' value='%s'" % (csrf_id or self._csrf_id))
117 96
 
@@ -226,10 +205,10 @@ def test_process_response_exempt_view(self):
226 205
         self.assertEqual(resp_content, resp2.content)
227 206
 
228 207
     # Check the request processing
229  
-    def test_process_request_no_session_no_csrf_cookie(self):
  208
+    def test_process_request_no_csrf_cookie(self):
230 209
         """
231  
-        Check that if neither a CSRF cookie nor a session cookie are present,
232  
-        the middleware rejects the incoming request.  This will stop login CSRF.
  210
+        Check that if no CSRF cookies is present, the middleware rejects the
  211
+        incoming request.  This will stop login CSRF.
233 212
         """
234 213
         req = self._get_POST_no_csrf_cookie_request()
235 214
         req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
@@ -252,29 +231,6 @@ def test_process_request_csrf_cookie_and_token(self):
252 231
         req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
253 232
         self.assertEqual(None, req2)
254 233
 
255  
-    def test_process_request_session_cookie_no_csrf_cookie_token(self):
256  
-        """
257  
-        When no CSRF cookie exists, but the user has a session, check that a token
258  
-        using the session cookie as a legacy CSRF cookie is accepted.
259  
-        """
260  
-        orig_secret_key = settings.SECRET_KEY
261  
-        settings.SECRET_KEY = self._secret_key_for_session_test
262  
-        try:
263  
-            req = self._get_POST_session_request_with_token()
264  
-            req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
265  
-            self.assertEqual(None, req2)
266  
-        finally:
267  
-            settings.SECRET_KEY = orig_secret_key
268  
-
269  
-    def test_process_request_session_cookie_no_csrf_cookie_no_token(self):
270  
-        """
271  
-        Check that if a session cookie is present but no token and no CSRF cookie,
272  
-        the request is rejected.
273  
-        """
274  
-        req = self._get_POST_session_request_no_token()
275  
-        req2 = CsrfMiddleware().process_view(req, post_form_view, (), {})
276  
-        self.assertEqual(403, req2.status_code)
277  
-
278 234
     def test_process_request_csrf_cookie_no_token_exempt_view(self):
279 235
         """
280 236
         Check that if a CSRF cookie is present and no token, but the csrf_exempt

0 notes on commit 21ef64e

Please sign in to comment.
Something went wrong with that request. Please try again.