Permalink
Browse files

bug 591034, Escaping Needed to Prevent Stored XSS via Django's CSRF T…

…oken
  • Loading branch information...
1 parent 4b7608b commit a6b96d02340388e903910369a4a5dcb26aa7cbdd Alex Buchanan committed Sep 8, 2010
Showing with 20 additions and 1 deletion.
  1. +18 −0 libs/csrf_context.py
  2. +2 −1 settings.py
View
18 libs/csrf_context.py
@@ -0,0 +1,18 @@
+"""
+Replacement for django.core.context_processors.csrf that escapes the CSRF
+token.
+"""
+from django.core import context_processors
+from django.utils import functional, html
+
+
+def csrf(request):
+ # Use lazy() because getting the token triggers Set-Cookie: csrftoken.
+ def _get_val():
+ token = context_processors.csrf(request)['csrf_token']
+ # This should be an md5 string so any broken Unicode is an attacker.
+ try:
+ return html.escape(unicode(token))
+ except UnicodeDecodeError:
+ return u''
+ return {'csrf_token': functional.lazy(_get_val, unicode)()}
View
3 settings.py
@@ -72,12 +72,13 @@
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.auth',
'django.core.context_processors.request',
+ 'csrf_context.csrf',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
- #'django.middleware.csrf.CsrfViewMiddleware',
+ 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)

0 comments on commit a6b96d0

Please sign in to comment.