2006-05-09 07:03:08 +08:00
|
|
|
"""
|
|
|
|
Cross Site Request Forgery Middleware.
|
|
|
|
|
|
|
|
This module provides a middleware that implements protection
|
2008-08-02 13:56:57 +08:00
|
|
|
against request forgeries from other sites.
|
2006-05-09 07:03:08 +08:00
|
|
|
"""
|
2008-08-02 13:56:57 +08:00
|
|
|
|
|
|
|
import re
|
|
|
|
import itertools
|
2008-12-03 08:34:18 +08:00
|
|
|
try:
|
|
|
|
from functools import wraps
|
|
|
|
except ImportError:
|
|
|
|
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
|
2008-08-02 13:56:57 +08:00
|
|
|
|
2006-05-09 07:03:08 +08:00
|
|
|
from django.conf import settings
|
|
|
|
from django.http import HttpResponseForbidden
|
2008-08-02 13:56:57 +08:00
|
|
|
from django.utils.hashcompat import md5_constructor
|
2007-11-14 20:58:53 +08:00
|
|
|
from django.utils.safestring import mark_safe
|
2006-05-09 07:03:08 +08:00
|
|
|
|
2007-11-14 20:58:53 +08:00
|
|
|
_ERROR_MSG = mark_safe('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"><body><h1>403 Forbidden</h1><p>Cross Site Request Forgery detected. Request aborted.</p></body></html>')
|
2006-05-09 07:03:08 +08:00
|
|
|
|
|
|
|
_POST_FORM_RE = \
|
|
|
|
re.compile(r'(<form\W[^>]*\bmethod=(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)
|
2008-08-02 13:56:57 +08:00
|
|
|
|
|
|
|
_HTML_TYPES = ('text/html', 'application/xhtml+xml')
|
2006-05-09 07:03:08 +08:00
|
|
|
|
|
|
|
def _make_token(session_id):
|
2008-08-02 13:56:57 +08:00
|
|
|
return md5_constructor(settings.SECRET_KEY + session_id).hexdigest()
|
2006-05-12 06:32:47 +08:00
|
|
|
|
2008-12-03 08:31:31 +08:00
|
|
|
class CsrfViewMiddleware(object):
|
2006-05-09 07:03:08 +08:00
|
|
|
"""
|
2008-12-03 08:31:31 +08:00
|
|
|
Middleware that requires a present and correct csrfmiddlewaretoken
|
|
|
|
for POST requests that have an active session.
|
|
|
|
"""
|
|
|
|
def process_view(self, request, callback, callback_args, callback_kwargs):
|
2007-09-03 14:18:48 +08:00
|
|
|
if request.method == 'POST':
|
2008-12-03 08:34:18 +08:00
|
|
|
if getattr(callback, 'csrf_exempt', False):
|
|
|
|
return None
|
|
|
|
|
|
|
|
if request.is_ajax():
|
|
|
|
return None
|
|
|
|
|
2006-05-09 07:03:08 +08:00
|
|
|
try:
|
|
|
|
session_id = request.COOKIES[settings.SESSION_COOKIE_NAME]
|
|
|
|
except KeyError:
|
|
|
|
# No session, no check required
|
|
|
|
return None
|
|
|
|
|
|
|
|
csrf_token = _make_token(session_id)
|
|
|
|
# check incoming token
|
|
|
|
try:
|
|
|
|
request_csrf_token = request.POST['csrfmiddlewaretoken']
|
|
|
|
except KeyError:
|
|
|
|
return HttpResponseForbidden(_ERROR_MSG)
|
2008-08-02 13:56:57 +08:00
|
|
|
|
2006-05-09 07:03:08 +08:00
|
|
|
if request_csrf_token != csrf_token:
|
|
|
|
return HttpResponseForbidden(_ERROR_MSG)
|
2008-08-02 13:56:57 +08:00
|
|
|
|
2006-05-09 07:03:08 +08:00
|
|
|
return None
|
2006-05-12 06:32:47 +08:00
|
|
|
|
2008-12-03 08:31:31 +08:00
|
|
|
class CsrfResponseMiddleware(object):
|
|
|
|
"""
|
|
|
|
Middleware that post-processes a response to add a
|
|
|
|
csrfmiddlewaretoken if the response/request have an active
|
|
|
|
session.
|
|
|
|
"""
|
2006-05-09 07:03:08 +08:00
|
|
|
def process_response(self, request, response):
|
|
|
|
csrf_token = None
|
|
|
|
try:
|
|
|
|
cookie = response.cookies[settings.SESSION_COOKIE_NAME]
|
|
|
|
csrf_token = _make_token(cookie.value)
|
|
|
|
except KeyError:
|
2008-08-02 13:56:57 +08:00
|
|
|
# No outgoing cookie to set session, but
|
2006-05-09 07:03:08 +08:00
|
|
|
# a session might already exist.
|
|
|
|
try:
|
|
|
|
session_id = request.COOKIES[settings.SESSION_COOKIE_NAME]
|
|
|
|
csrf_token = _make_token(session_id)
|
|
|
|
except KeyError:
|
|
|
|
# no incoming or outgoing cookie
|
|
|
|
pass
|
2008-08-02 13:56:57 +08:00
|
|
|
|
2006-05-09 07:03:08 +08:00
|
|
|
if csrf_token is not None and \
|
2006-05-12 06:32:47 +08:00
|
|
|
response['Content-Type'].split(';')[0] in _HTML_TYPES:
|
2008-08-02 13:56:57 +08:00
|
|
|
|
2006-05-12 06:32:47 +08:00
|
|
|
# ensure we don't add the 'id' attribute twice (HTML validity)
|
2008-08-02 13:56:57 +08:00
|
|
|
idattributes = itertools.chain(("id='csrfmiddlewaretoken'",),
|
2006-05-12 06:32:47 +08:00
|
|
|
itertools.repeat(''))
|
|
|
|
def add_csrf_field(match):
|
|
|
|
"""Returns the matched <form> tag plus the added <input> element"""
|
2007-11-14 20:58:53 +08:00
|
|
|
return mark_safe(match.group() + "<div style='display:none;'>" + \
|
2006-05-12 06:32:47 +08:00
|
|
|
"<input type='hidden' " + idattributes.next() + \
|
|
|
|
" name='csrfmiddlewaretoken' value='" + csrf_token + \
|
2007-11-14 20:58:53 +08:00
|
|
|
"' /></div>")
|
2006-05-12 06:32:47 +08:00
|
|
|
|
2006-05-09 07:03:08 +08:00
|
|
|
# Modify any POST forms
|
2006-05-12 06:32:47 +08:00
|
|
|
response.content = _POST_FORM_RE.sub(add_csrf_field, response.content)
|
2006-05-09 07:03:08 +08:00
|
|
|
return response
|
2008-12-03 08:31:31 +08:00
|
|
|
|
|
|
|
class CsrfMiddleware(CsrfViewMiddleware, CsrfResponseMiddleware):
|
|
|
|
"""Django middleware that adds protection against Cross Site
|
|
|
|
Request Forgeries by adding hidden form fields to POST forms and
|
|
|
|
checking requests for the correct value.
|
|
|
|
|
|
|
|
In the list of middlewares, SessionMiddleware is required, and
|
|
|
|
must come after this middleware. CsrfMiddleWare must come after
|
|
|
|
compression middleware.
|
|
|
|
|
|
|
|
If a session ID cookie is present, it is hashed with the
|
|
|
|
SECRET_KEY setting to create an authentication token. This token
|
|
|
|
is added to all outgoing POST forms and is expected on all
|
|
|
|
incoming POST requests that have a session ID cookie.
|
|
|
|
|
|
|
|
If you are setting cookies directly, instead of using Django's
|
|
|
|
session framework, this middleware will not work.
|
|
|
|
|
|
|
|
CsrfMiddleWare is composed of two middleware, CsrfViewMiddleware
|
|
|
|
and CsrfResponseMiddleware which can be used independently.
|
|
|
|
"""
|
|
|
|
pass
|
2008-12-03 08:34:18 +08:00
|
|
|
|
|
|
|
def csrf_exempt(view_func):
|
|
|
|
"""
|
|
|
|
Marks a view function as being exempt from the CSRF checks
|
|
|
|
"""
|
|
|
|
def wrapped_view(*args, **kwargs):
|
|
|
|
return view_func(*args, **kwargs)
|
|
|
|
# We could just do view.csrf_exempt = True, but decorators are
|
|
|
|
# nicer if they don't have side-effects.
|
|
|
|
wrapped_view.csrf_exempt = True
|
|
|
|
return wraps(view_func)(wrapped_view)
|