Ticket #14235: 14235.diff

File 14235.diff, 3.8 KB (added by Luke Plant, 14 years ago)

Patch. Fixed typo in comment in last patch.

  • django/middleware/csrf.py

     
    1313from django.core.urlresolvers import get_callable
    1414from django.utils.cache import patch_vary_headers
    1515from django.utils.hashcompat import md5_constructor
    16 from django.utils.html import escape
    1716from django.utils.safestring import mark_safe
    1817
    1918_POST_FORM_RE = \
     
    6564    return request.META.get("CSRF_COOKIE", None)
    6665
    6766
     67def _sanitise_token(token):
     68    # Allow only alphanum, and ensure we return a 'str' for the sake of the post
     69    # processing middleware.
     70    return re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore')))
     71
     72
    6873class CsrfViewMiddleware(object):
    6974    """
    7075    Middleware that requires a present and correct csrfmiddlewaretoken
     
    9095        # request, so it's available to the view.  We'll store it in a cookie when
    9196        # we reach the response.
    9297        try:
    93             request.META["CSRF_COOKIE"] = request.COOKIES[settings.CSRF_COOKIE_NAME]
     98            # In case of cookies from untrusted sources, we strip anything
     99            # dangerous at this point, so that the cookie + token will have the
     100            # same, sanitised value.
     101            request.META["CSRF_COOKIE"] = _sanitise_token(request.COOKIES[settings.CSRF_COOKIE_NAME])
    94102            cookie_is_new = False
    95103        except KeyError:
    96104            # No cookie, so create one.  This will be sent with the next
     
    249257                """Returns the matched <form> tag plus the added <input> element"""
    250258                return mark_safe(match.group() + "<div style='display:none;'>" + \
    251259                "<input type='hidden' " + idattributes.next() + \
    252                 " name='csrfmiddlewaretoken' value='" + escape(csrf_token) + \
     260                " name='csrfmiddlewaretoken' value='" + csrf_token + \
    253261                "' /></div>")
    254262
    255263            # Modify any POST forms
  • tests/regressiontests/csrf_tests/tests.py

     
    1313
    1414# Response/views used for CsrfResponseMiddleware and CsrfViewMiddleware tests
    1515def post_form_response():
    16     resp = HttpResponse(content="""
    17 <html><body><form method="post"><input type="text" /></form></body></html>
     16    resp = HttpResponse(content=u"""
     17<html><body><h1>\u00a1Unicode!<form method="post"><input type="text" /></form></body></html>
    1818""", mimetype="text/html")
    1919    return resp
    2020
     
    5858
    5959class CsrfMiddlewareTest(TestCase):
    6060    # The csrf token is potentially from an untrusted source, so could have
    61     # characters that need escaping
    62     _csrf_id = "<1>"
     61    # characters that need dealing with.
     62    _csrf_id_cookie = "<1>\xc2\xa1"
     63    _csrf_id = "1"
    6364
    6465    # This is a valid session token for this ID and secret key.  This was generated using
    6566    # the old code that we're to be backwards-compatible with.  Don't use the CSRF code
     
    7475
    7576    def _get_GET_csrf_cookie_request(self):
    7677        req = TestingHttpRequest()
    77         req.COOKIES[settings.CSRF_COOKIE_NAME] = self._csrf_id
     78        req.COOKIES[settings.CSRF_COOKIE_NAME] = self._csrf_id_cookie
    7879        return req
    7980
    8081    def _get_POST_csrf_cookie_request(self):
     
    104105        return req
    105106
    106107    def _check_token_present(self, response, csrf_id=None):
    107         self.assertContains(response, "name='csrfmiddlewaretoken' value='%s'" % escape(csrf_id or self._csrf_id))
     108        self.assertContains(response, "name='csrfmiddlewaretoken' value='%s'" % (csrf_id or self._csrf_id))
    108109
    109110    # Check the post processing and outgoing cookie
    110111    def test_process_response_no_csrf_cookie(self):
Back to Top