2009-10-27 08:36:34 +08:00
|
|
|
"""
|
|
|
|
Cross Site Request Forgery Middleware.
|
|
|
|
|
|
|
|
This module provides a middleware that implements protection
|
|
|
|
against request forgeries from other sites.
|
|
|
|
"""
|
2012-08-13 17:34:40 +08:00
|
|
|
from __future__ import unicode_literals
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2012-09-21 03:03:24 +08:00
|
|
|
import logging
|
2009-10-27 08:36:34 +08:00
|
|
|
import re
|
|
|
|
|
|
|
|
from django.conf import settings
|
2015-12-30 23:51:16 +08:00
|
|
|
from django.urls import get_callable
|
2009-10-27 08:36:34 +08:00
|
|
|
from django.utils.cache import patch_vary_headers
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.crypto import constant_time_compare, get_random_string
|
2012-08-13 17:34:40 +08:00
|
|
|
from django.utils.encoding import force_text
|
2015-03-17 17:52:55 +08:00
|
|
|
from django.utils.http import is_same_domain
|
|
|
|
from django.utils.six.moves.urllib.parse import urlparse
|
2012-09-21 03:03:24 +08:00
|
|
|
|
|
|
|
logger = logging.getLogger('django.request')
|
2010-10-04 23:12:39 +08:00
|
|
|
|
2010-09-04 00:28:10 +08:00
|
|
|
REASON_NO_REFERER = "Referer checking failed - no Referer."
|
2015-09-01 10:32:03 +08:00
|
|
|
REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
|
2010-09-04 00:28:10 +08:00
|
|
|
REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
|
|
|
|
REASON_BAD_TOKEN = "CSRF token missing or incorrect."
|
2015-03-17 17:52:55 +08:00
|
|
|
REASON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
|
|
|
|
REASON_INSECURE_REFERER = "Referer checking failed - Referer is insecure while host is secure."
|
2010-09-04 00:28:10 +08:00
|
|
|
|
2012-02-11 12:18:15 +08:00
|
|
|
CSRF_KEY_LENGTH = 32
|
2010-09-04 00:28:10 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2009-10-27 08:36:34 +08:00
|
|
|
def _get_failure_view():
|
|
|
|
"""
|
|
|
|
Returns the view to be used for CSRF rejections
|
|
|
|
"""
|
|
|
|
return get_callable(settings.CSRF_FAILURE_VIEW)
|
|
|
|
|
2010-09-04 00:28:10 +08:00
|
|
|
|
2009-10-27 08:36:34 +08:00
|
|
|
def _get_new_csrf_key():
|
2012-02-11 12:18:15 +08:00
|
|
|
return get_random_string(CSRF_KEY_LENGTH)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2010-09-04 00:28:10 +08:00
|
|
|
|
2009-10-27 08:36:34 +08:00
|
|
|
def get_token(request):
|
|
|
|
"""
|
2013-01-29 23:45:40 +08:00
|
|
|
Returns the CSRF token required for a POST form. The token is an
|
2015-04-24 14:24:38 +08:00
|
|
|
alphanumeric value. A new token is created if one is not already set.
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2013-01-29 23:45:40 +08:00
|
|
|
A side effect of calling this function is to make the csrf_protect
|
2009-10-27 08:36:34 +08:00
|
|
|
decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
|
|
|
|
header to the outgoing response. For this reason, you may need to use this
|
|
|
|
function lazily, as is done by the csrf context processor.
|
|
|
|
"""
|
2015-04-24 14:24:38 +08:00
|
|
|
if "CSRF_COOKIE" not in request.META:
|
|
|
|
request.META["CSRF_COOKIE"] = _get_new_csrf_key()
|
2009-10-27 08:36:34 +08:00
|
|
|
request.META["CSRF_COOKIE_USED"] = True
|
2015-04-24 14:24:38 +08:00
|
|
|
return request.META["CSRF_COOKIE"]
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2010-09-04 00:28:10 +08:00
|
|
|
|
2013-05-23 23:14:27 +08:00
|
|
|
def rotate_token(request):
|
|
|
|
"""
|
|
|
|
Changes the CSRF token in use for a request - should be done on login
|
|
|
|
for security purposes.
|
|
|
|
"""
|
2013-10-18 07:51:45 +08:00
|
|
|
request.META.update({
|
|
|
|
"CSRF_COOKIE_USED": True,
|
|
|
|
"CSRF_COOKIE": _get_new_csrf_key(),
|
|
|
|
})
|
2013-05-23 23:14:27 +08:00
|
|
|
|
|
|
|
|
2010-09-11 06:56:56 +08:00
|
|
|
def _sanitize_token(token):
|
2012-08-13 17:34:40 +08:00
|
|
|
# Allow only alphanum
|
2012-02-11 12:18:15 +08:00
|
|
|
if len(token) > CSRF_KEY_LENGTH:
|
|
|
|
return _get_new_csrf_key()
|
2012-08-13 17:34:40 +08:00
|
|
|
token = re.sub('[^a-zA-Z0-9]+', '', force_text(token))
|
2010-09-11 06:56:56 +08:00
|
|
|
if token == "":
|
|
|
|
# In case the cookie has been truncated to nothing at some point.
|
|
|
|
return _get_new_csrf_key()
|
2012-02-11 12:18:15 +08:00
|
|
|
return token
|
2010-09-11 06:56:56 +08:00
|
|
|
|
|
|
|
|
2009-10-27 08:36:34 +08:00
|
|
|
class CsrfViewMiddleware(object):
|
|
|
|
"""
|
|
|
|
Middleware that requires a present and correct csrfmiddlewaretoken
|
|
|
|
for POST requests that have a CSRF cookie, and sets an outgoing
|
|
|
|
CSRF cookie.
|
|
|
|
|
|
|
|
This middleware should be used in conjunction with the csrf_token template
|
|
|
|
tag.
|
|
|
|
"""
|
2010-10-28 19:47:15 +08:00
|
|
|
# The _accept and _reject methods currently only exist for the sake of the
|
|
|
|
# requires_csrf_token decorator.
|
|
|
|
def _accept(self, request):
|
|
|
|
# Avoid checking the request twice by adding a custom attribute to
|
|
|
|
# request. This will be relevant when both decorator and middleware
|
|
|
|
# are used.
|
|
|
|
request.csrf_processing_done = True
|
|
|
|
return None
|
|
|
|
|
|
|
|
def _reject(self, request, reason):
|
2013-11-02 16:30:39 +08:00
|
|
|
logger.warning('Forbidden (%s): %s', reason, request.path,
|
2013-05-18 19:09:38 +08:00
|
|
|
extra={
|
|
|
|
'status_code': 403,
|
|
|
|
'request': request,
|
|
|
|
}
|
|
|
|
)
|
2010-10-28 19:47:15 +08:00
|
|
|
return _get_failure_view()(request, reason=reason)
|
|
|
|
|
2009-10-27 08:36:34 +08:00
|
|
|
def process_view(self, request, callback, callback_args, callback_kwargs):
|
2011-02-09 10:06:27 +08:00
|
|
|
|
2009-10-27 08:36:34 +08:00
|
|
|
if getattr(request, 'csrf_processing_done', False):
|
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
2012-02-11 12:18:15 +08:00
|
|
|
csrf_token = _sanitize_token(
|
|
|
|
request.COOKIES[settings.CSRF_COOKIE_NAME])
|
2011-03-31 01:34:14 +08:00
|
|
|
# Use same token next time
|
|
|
|
request.META['CSRF_COOKIE'] = csrf_token
|
2009-10-27 08:36:34 +08:00
|
|
|
except KeyError:
|
2011-03-31 01:34:14 +08:00
|
|
|
csrf_token = None
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2010-06-08 22:35:48 +08:00
|
|
|
# Wait until request.META["CSRF_COOKIE"] has been manipulated before
|
|
|
|
# bailing out, so that get_token still works
|
|
|
|
if getattr(callback, 'csrf_exempt', False):
|
|
|
|
return None
|
|
|
|
|
2012-09-10 23:11:24 +08:00
|
|
|
# Assume that anything not defined as 'safe' by RFC2616 needs protection
|
2011-05-10 07:45:54 +08:00
|
|
|
if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
|
2009-10-27 08:36:34 +08:00
|
|
|
if getattr(request, '_dont_enforce_csrf_checks', False):
|
2012-02-11 12:18:15 +08:00
|
|
|
# Mechanism to turn off CSRF checks for test suite.
|
|
|
|
# It comes after the creation of CSRF cookies, so that
|
|
|
|
# everything else continues to work exactly the same
|
2012-02-18 04:04:11 +08:00
|
|
|
# (e.g. cookies are sent, etc.), but before any
|
|
|
|
# branches that call reject().
|
2010-10-28 19:47:15 +08:00
|
|
|
return self._accept(request)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
|
|
|
if request.is_secure():
|
2010-07-01 06:30:37 +08:00
|
|
|
# Suppose user visits http://example.com/
|
2012-02-18 04:04:11 +08:00
|
|
|
# An active network attacker (man-in-the-middle, MITM) sends a
|
|
|
|
# POST form that targets https://example.com/detonate-bomb/ and
|
|
|
|
# submits it via JavaScript.
|
2010-07-01 06:30:37 +08:00
|
|
|
#
|
|
|
|
# The attacker will need to provide a CSRF cookie and token, but
|
2012-02-18 04:04:11 +08:00
|
|
|
# that's no problem for a MITM and the session-independent
|
|
|
|
# nonce we're using. So the MITM can circumvent the CSRF
|
2010-07-01 06:30:37 +08:00
|
|
|
# protection. This is true for any HTTP connection, but anyone
|
2012-02-18 04:04:11 +08:00
|
|
|
# using HTTPS expects better! For this reason, for
|
2010-07-01 06:30:37 +08:00
|
|
|
# https://example.com/ we need additional protection that treats
|
2012-02-18 04:04:11 +08:00
|
|
|
# http://example.com/ as completely untrusted. Under HTTPS,
|
2010-07-01 06:30:37 +08:00
|
|
|
# Barth et al. found that the Referer header is missing for
|
|
|
|
# same-domain requests in only about 0.2% of cases or less, so
|
|
|
|
# we can use strict Referer checking.
|
2015-01-06 01:23:57 +08:00
|
|
|
referer = force_text(
|
|
|
|
request.META.get('HTTP_REFERER'),
|
|
|
|
strings_only=True,
|
|
|
|
errors='replace'
|
|
|
|
)
|
2009-10-27 08:36:34 +08:00
|
|
|
if referer is None:
|
2010-10-28 19:47:15 +08:00
|
|
|
return self._reject(request, REASON_NO_REFERER)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2015-03-17 17:52:55 +08:00
|
|
|
referer = urlparse(referer)
|
|
|
|
|
|
|
|
# Make sure we have a valid URL for Referer.
|
|
|
|
if '' in (referer.scheme, referer.netloc):
|
|
|
|
return self._reject(request, REASON_MALFORMED_REFERER)
|
|
|
|
|
|
|
|
# Ensure that our Referer is also secure.
|
|
|
|
if referer.scheme != 'https':
|
|
|
|
return self._reject(request, REASON_INSECURE_REFERER)
|
|
|
|
|
|
|
|
# If there isn't a CSRF_COOKIE_DOMAIN, assume we need an exact
|
|
|
|
# match on host:port. If not, obey the cookie rules.
|
|
|
|
if settings.CSRF_COOKIE_DOMAIN is None:
|
|
|
|
# request.get_host() includes the port.
|
|
|
|
good_referer = request.get_host()
|
|
|
|
else:
|
|
|
|
good_referer = settings.CSRF_COOKIE_DOMAIN
|
|
|
|
server_port = request.META['SERVER_PORT']
|
|
|
|
if server_port not in ('443', '80'):
|
|
|
|
good_referer = '%s:%s' % (good_referer, server_port)
|
|
|
|
|
2015-09-01 10:32:03 +08:00
|
|
|
# Here we generate a list of all acceptable HTTP referers,
|
|
|
|
# including the current host since that has been validated
|
|
|
|
# upstream.
|
|
|
|
good_hosts = list(settings.CSRF_TRUSTED_ORIGINS)
|
2015-03-17 17:52:55 +08:00
|
|
|
good_hosts.append(good_referer)
|
|
|
|
|
|
|
|
if not any(is_same_domain(referer.netloc, host) for host in good_hosts):
|
|
|
|
reason = REASON_BAD_REFERER % referer.geturl()
|
2010-10-28 19:47:15 +08:00
|
|
|
return self._reject(request, reason)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2011-03-31 01:34:14 +08:00
|
|
|
if csrf_token is None:
|
|
|
|
# No CSRF cookie. For POST requests, we insist on a CSRF cookie,
|
|
|
|
# and in this way we can avoid all CSRF attacks, including login
|
|
|
|
# CSRF.
|
|
|
|
return self._reject(request, REASON_NO_CSRF_COOKIE)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2012-02-18 04:04:11 +08:00
|
|
|
# Check non-cookie token for match.
|
2011-05-10 07:45:54 +08:00
|
|
|
request_csrf_token = ""
|
|
|
|
if request.method == "POST":
|
2014-06-25 18:52:25 +08:00
|
|
|
try:
|
|
|
|
request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
|
|
|
|
except IOError:
|
|
|
|
# Handle a broken connection before we've completed reading
|
|
|
|
# the POST data. process_view shouldn't raise any
|
|
|
|
# exceptions, so we'll ignore and serve the user a 403
|
|
|
|
# (assuming they're still listening, which they probably
|
|
|
|
# aren't because of the error).
|
|
|
|
pass
|
2011-05-10 07:45:54 +08:00
|
|
|
|
2011-02-09 10:06:27 +08:00
|
|
|
if request_csrf_token == "":
|
2011-05-10 07:45:54 +08:00
|
|
|
# Fall back to X-CSRFToken, to make things easier for AJAX,
|
2012-02-18 04:04:11 +08:00
|
|
|
# and possible for PUT/DELETE.
|
2015-02-22 05:57:02 +08:00
|
|
|
request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')
|
2011-02-09 10:06:27 +08:00
|
|
|
|
Fixed #14445 - Use HMAC and constant-time comparison functions where needed.
All adhoc MAC applications have been updated to use HMAC, using SHA1 to
generate unique keys for each application based on the SECRET_KEY, which is
common practice for this situation. In all cases, backwards compatibility
with existing hashes has been maintained, aiming to phase this out as per
the normal deprecation process. In this way, under most normal
circumstances the old hashes will have expired (e.g. by session expiration
etc.) before they become invalid.
In the case of the messages framework and the cookie backend, which was
already using HMAC, there is the possibility of a backwards incompatibility
if the SECRET_KEY is shorter than the default 50 bytes, but the low
likelihood and low impact meant compatibility code was not worth it.
All known instances where tokens/hashes were compared using simple string
equality, which could potentially open timing based attacks, have also been
fixed using a constant-time comparison function.
There are no known practical attacks against the existing implementations,
so these security improvements will not be backported.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@14218 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2010-10-15 04:54:30 +08:00
|
|
|
if not constant_time_compare(request_csrf_token, csrf_token):
|
2011-03-31 01:34:14 +08:00
|
|
|
return self._reject(request, REASON_BAD_TOKEN)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2010-10-28 19:47:15 +08:00
|
|
|
return self._accept(request)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
|
|
|
def process_response(self, request, response):
|
|
|
|
if getattr(response, 'csrf_processing_done', False):
|
|
|
|
return response
|
|
|
|
|
|
|
|
if not request.META.get("CSRF_COOKIE_USED", False):
|
|
|
|
return response
|
|
|
|
|
2012-02-11 12:18:15 +08:00
|
|
|
# Set the CSRF cookie even if it's already set, so we renew
|
|
|
|
# the expiry timer.
|
2009-10-27 08:36:34 +08:00
|
|
|
response.set_cookie(settings.CSRF_COOKIE_NAME,
|
2011-05-10 07:00:22 +08:00
|
|
|
request.META["CSRF_COOKIE"],
|
2014-03-04 08:52:28 +08:00
|
|
|
max_age=settings.CSRF_COOKIE_AGE,
|
2011-05-10 07:00:22 +08:00
|
|
|
domain=settings.CSRF_COOKIE_DOMAIN,
|
|
|
|
path=settings.CSRF_COOKIE_PATH,
|
2013-02-07 16:48:08 +08:00
|
|
|
secure=settings.CSRF_COOKIE_SECURE,
|
|
|
|
httponly=settings.CSRF_COOKIE_HTTPONLY
|
2011-05-10 07:00:22 +08:00
|
|
|
)
|
2009-10-27 08:36:34 +08:00
|
|
|
# Content varies with the CSRF cookie, so set the Vary header.
|
|
|
|
patch_vary_headers(response, ('Cookie',))
|
|
|
|
response.csrf_processing_done = True
|
|
|
|
return response
|