csrf.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. """
  2. Cross Site Request Forgery Middleware.
  3. This module provides a middleware that implements protection
  4. against request forgeries from other sites.
  5. """
  6. from __future__ import unicode_literals
  7. import logging
  8. import re
  9. from django.conf import settings
  10. from django.core.urlresolvers import get_callable
  11. from django.utils.cache import patch_vary_headers
  12. from django.utils.encoding import force_text
  13. from django.utils.http import same_origin
  14. from django.utils.crypto import constant_time_compare, get_random_string
  15. logger = logging.getLogger('django.request')
  16. REASON_NO_REFERER = "Referer checking failed - no Referer."
  17. REASON_BAD_REFERER = "Referer checking failed - %s does not match %s."
  18. REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
  19. REASON_BAD_TOKEN = "CSRF token missing or incorrect."
  20. CSRF_KEY_LENGTH = 32
  21. def _get_failure_view():
  22. """
  23. Returns the view to be used for CSRF rejections
  24. """
  25. return get_callable(settings.CSRF_FAILURE_VIEW)
  26. def _get_new_csrf_key():
  27. return get_random_string(CSRF_KEY_LENGTH)
  28. def get_token(request):
  29. """
  30. Returns the CSRF token required for a POST form. The token is an
  31. alphanumeric value.
  32. A side effect of calling this function is to make the csrf_protect
  33. decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
  34. header to the outgoing response. For this reason, you may need to use this
  35. function lazily, as is done by the csrf context processor.
  36. """
  37. request.META["CSRF_COOKIE_USED"] = True
  38. return request.META.get("CSRF_COOKIE", None)
  39. def rotate_token(request):
  40. """
  41. Changes the CSRF token in use for a request - should be done on login
  42. for security purposes.
  43. """
  44. request.META.update({
  45. "CSRF_COOKIE_USED": True,
  46. "CSRF_COOKIE": _get_new_csrf_key(),
  47. })
  48. def _sanitize_token(token):
  49. # Allow only alphanum
  50. if len(token) > CSRF_KEY_LENGTH:
  51. return _get_new_csrf_key()
  52. token = re.sub('[^a-zA-Z0-9]+', '', force_text(token))
  53. if token == "":
  54. # In case the cookie has been truncated to nothing at some point.
  55. return _get_new_csrf_key()
  56. return token
  57. class CsrfViewMiddleware(object):
  58. """
  59. Middleware that requires a present and correct csrfmiddlewaretoken
  60. for POST requests that have a CSRF cookie, and sets an outgoing
  61. CSRF cookie.
  62. This middleware should be used in conjunction with the csrf_token template
  63. tag.
  64. """
  65. # The _accept and _reject methods currently only exist for the sake of the
  66. # requires_csrf_token decorator.
  67. def _accept(self, request):
  68. # Avoid checking the request twice by adding a custom attribute to
  69. # request. This will be relevant when both decorator and middleware
  70. # are used.
  71. request.csrf_processing_done = True
  72. return None
  73. def _reject(self, request, reason):
  74. logger.warning('Forbidden (%s): %s', reason, request.path,
  75. extra={
  76. 'status_code': 403,
  77. 'request': request,
  78. }
  79. )
  80. return _get_failure_view()(request, reason=reason)
  81. def process_view(self, request, callback, callback_args, callback_kwargs):
  82. if getattr(request, 'csrf_processing_done', False):
  83. return None
  84. try:
  85. csrf_token = _sanitize_token(
  86. request.COOKIES[settings.CSRF_COOKIE_NAME])
  87. # Use same token next time
  88. request.META['CSRF_COOKIE'] = csrf_token
  89. except KeyError:
  90. csrf_token = None
  91. # Generate token and store it in the request, so it's
  92. # available to the view.
  93. request.META["CSRF_COOKIE"] = _get_new_csrf_key()
  94. # Wait until request.META["CSRF_COOKIE"] has been manipulated before
  95. # bailing out, so that get_token still works
  96. if getattr(callback, 'csrf_exempt', False):
  97. return None
  98. # Assume that anything not defined as 'safe' by RFC2616 needs protection
  99. if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
  100. if getattr(request, '_dont_enforce_csrf_checks', False):
  101. # Mechanism to turn off CSRF checks for test suite.
  102. # It comes after the creation of CSRF cookies, so that
  103. # everything else continues to work exactly the same
  104. # (e.g. cookies are sent, etc.), but before any
  105. # branches that call reject().
  106. return self._accept(request)
  107. if request.is_secure():
  108. # Suppose user visits http://example.com/
  109. # An active network attacker (man-in-the-middle, MITM) sends a
  110. # POST form that targets https://example.com/detonate-bomb/ and
  111. # submits it via JavaScript.
  112. #
  113. # The attacker will need to provide a CSRF cookie and token, but
  114. # that's no problem for a MITM and the session-independent
  115. # nonce we're using. So the MITM can circumvent the CSRF
  116. # protection. This is true for any HTTP connection, but anyone
  117. # using HTTPS expects better! For this reason, for
  118. # https://example.com/ we need additional protection that treats
  119. # http://example.com/ as completely untrusted. Under HTTPS,
  120. # Barth et al. found that the Referer header is missing for
  121. # same-domain requests in only about 0.2% of cases or less, so
  122. # we can use strict Referer checking.
  123. referer = request.META.get('HTTP_REFERER')
  124. if referer is None:
  125. return self._reject(request, REASON_NO_REFERER)
  126. # Note that request.get_host() includes the port.
  127. good_referer = 'https://%s/' % request.get_host()
  128. if not same_origin(referer, good_referer):
  129. reason = REASON_BAD_REFERER % (referer, good_referer)
  130. return self._reject(request, reason)
  131. if csrf_token is None:
  132. # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
  133. # and in this way we can avoid all CSRF attacks, including login
  134. # CSRF.
  135. return self._reject(request, REASON_NO_CSRF_COOKIE)
  136. # Check non-cookie token for match.
  137. request_csrf_token = ""
  138. if request.method == "POST":
  139. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  140. if request_csrf_token == "":
  141. # Fall back to X-CSRFToken, to make things easier for AJAX,
  142. # and possible for PUT/DELETE.
  143. request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')
  144. if not constant_time_compare(request_csrf_token, csrf_token):
  145. return self._reject(request, REASON_BAD_TOKEN)
  146. return self._accept(request)
  147. def process_response(self, request, response):
  148. if getattr(response, 'csrf_processing_done', False):
  149. return response
  150. # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was
  151. # never called, probably because a request middleware returned a response
  152. # (for example, contrib.auth redirecting to a login page).
  153. if request.META.get("CSRF_COOKIE") is None:
  154. return response
  155. if not request.META.get("CSRF_COOKIE_USED", False):
  156. return response
  157. # Set the CSRF cookie even if it's already set, so we renew
  158. # the expiry timer.
  159. response.set_cookie(settings.CSRF_COOKIE_NAME,
  160. request.META["CSRF_COOKIE"],
  161. max_age=settings.CSRF_COOKIE_AGE,
  162. domain=settings.CSRF_COOKIE_DOMAIN,
  163. path=settings.CSRF_COOKIE_PATH,
  164. secure=settings.CSRF_COOKIE_SECURE,
  165. httponly=settings.CSRF_COOKIE_HTTPONLY
  166. )
  167. # Content varies with the CSRF cookie, so set the Vary header.
  168. patch_vary_headers(response, ('Cookie',))
  169. response.csrf_processing_done = True
  170. return response