Ticket #14235: 14235.2.diff

File 14235.2.diff, 5.7 KB (added by Luke Plant, 14 years ago)

Updates for Karen's comments.

  • django/template/defaulttags.py

     
    99from django.template import get_library, Library, InvalidTemplateLibrary
    1010from django.template.smartif import IfParser, Literal
    1111from django.conf import settings
    12 from django.utils.html import escape
    1312from django.utils.encoding import smart_str, smart_unicode
    1413from django.utils.safestring import mark_safe
    1514
     
    4342            if csrf_token == 'NOTPROVIDED':
    4443                return mark_safe(u"")
    4544            else:
    46                 return mark_safe(u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % escape(csrf_token))
     45                return mark_safe(u"<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='%s' /></div>" % csrf_token)
    4746        else:
    4847            # It's very probable that the token is missing because of
    4948            # misconfiguration, so we raise a warning
  • 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 = \
     
    5352
    5453def get_token(request):
    5554    """
    56     Returns the the CSRF token required for a POST form. No assumptions should
    57     be made about what characters might be in the CSRF token.
     55    Returns the the CSRF token required for a POST form. The token is an
     56    alphanumeric value.
    5857
    5958    A side effect of calling this function is to make the the csrf_protect
    6059    decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
     
    6564    return request.META.get("CSRF_COOKIE", None)
    6665
    6766
     67def _sanitize_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, sanitized value.
     101            request.META["CSRF_COOKIE"] = _sanitize_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

     
    66from django.views.decorators.csrf import csrf_exempt, csrf_view_exempt
    77from django.core.context_processors import csrf
    88from django.contrib.sessions.middleware import SessionMiddleware
    9 from django.utils.html import escape
    109from django.utils.importlib import import_module
    1110from django.conf import settings
    1211from django.template import RequestContext, Template
    1312
    1413# Response/views used for CsrfResponseMiddleware and CsrfViewMiddleware tests
    1514def post_form_response():
    16     resp = HttpResponse(content="""
    17 <html><body><form method="post"><input type="text" /></form></body></html>
     15    resp = HttpResponse(content=u"""
     16<html><body><h1>\u00a1Unicode!<form method="post"><input type="text" /></form></body></html>
    1817""", mimetype="text/html")
    1918    return resp
    2019
     
    5857
    5958class CsrfMiddlewareTest(TestCase):
    6059    # The csrf token is potentially from an untrusted source, so could have
    61     # characters that need escaping
    62     _csrf_id = "<1>"
     60    # characters that need dealing with.
     61    _csrf_id_cookie = "<1>\xc2\xa1"
     62    _csrf_id = "1"
    6363
    6464    # This is a valid session token for this ID and secret key.  This was generated using
    6565    # the old code that we're to be backwards-compatible with.  Don't use the CSRF code
     
    7474
    7575    def _get_GET_csrf_cookie_request(self):
    7676        req = TestingHttpRequest()
    77         req.COOKIES[settings.CSRF_COOKIE_NAME] = self._csrf_id
     77        req.COOKIES[settings.CSRF_COOKIE_NAME] = self._csrf_id_cookie
    7878        return req
    7979
    8080    def _get_POST_csrf_cookie_request(self):
     
    104104        return req
    105105
    106106    def _check_token_present(self, response, csrf_id=None):
    107         self.assertContains(response, "name='csrfmiddlewaretoken' value='%s'" % escape(csrf_id or self._csrf_id))
     107        self.assertContains(response, "name='csrfmiddlewaretoken' value='%s'" % (csrf_id or self._csrf_id))
    108108
    109109    # Check the post processing and outgoing cookie
    110110    def test_process_response_no_csrf_cookie(self):
Back to Top