PageRenderTime 796ms CodeModel.GetById 20ms RepoModel.GetById 23ms app.codeStats 0ms

/django/middleware/csrf.py

https://code.google.com/p/mango-py/
Python | 326 lines | 228 code | 28 blank | 70 comment | 19 complexity | aab9305924a206418844938b6c53a6c4 MD5 | raw file
Possible License(s): BSD-3-Clause
  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. import itertools
  7. import re
  8. import random
  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.hashcompat import md5_constructor
  13. from django.utils.http import same_origin
  14. from django.utils.log import getLogger
  15. from django.utils.safestring import mark_safe
  16. from django.utils.crypto import constant_time_compare
  17. _POST_FORM_RE = \
  18. re.compile(r'(<form\W[^>]*\bmethod\s*=\s*(\'|"|)POST(\'|"|)\b[^>]*>)', re.IGNORECASE)
  19. _HTML_TYPES = ('text/html', 'application/xhtml+xml')
  20. logger = getLogger('django.request')
  21. # Use the system (hardware-based) random number generator if it exists.
  22. if hasattr(random, 'SystemRandom'):
  23. randrange = random.SystemRandom().randrange
  24. else:
  25. randrange = random.randrange
  26. _MAX_CSRF_KEY = 18446744073709551616L # 2 << 63
  27. REASON_NO_REFERER = "Referer checking failed - no Referer."
  28. REASON_BAD_REFERER = "Referer checking failed - %s does not match %s."
  29. REASON_NO_COOKIE = "No CSRF or session cookie."
  30. REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
  31. REASON_BAD_TOKEN = "CSRF token missing or incorrect."
  32. def _get_failure_view():
  33. """
  34. Returns the view to be used for CSRF rejections
  35. """
  36. return get_callable(settings.CSRF_FAILURE_VIEW)
  37. def _get_new_csrf_key():
  38. return md5_constructor("%s%s"
  39. % (randrange(0, _MAX_CSRF_KEY), settings.SECRET_KEY)).hexdigest()
  40. def _make_legacy_session_token(session_id):
  41. return md5_constructor(settings.SECRET_KEY + session_id).hexdigest()
  42. def get_token(request):
  43. """
  44. Returns the the CSRF token required for a POST form. The token is an
  45. alphanumeric value.
  46. A side effect of calling this function is to make the the csrf_protect
  47. decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
  48. header to the outgoing response. For this reason, you may need to use this
  49. function lazily, as is done by the csrf context processor.
  50. """
  51. request.META["CSRF_COOKIE_USED"] = True
  52. return request.META.get("CSRF_COOKIE", None)
  53. def _sanitize_token(token):
  54. # Allow only alphanum, and ensure we return a 'str' for the sake of the post
  55. # processing middleware.
  56. token = re.sub('[^a-zA-Z0-9]', '', str(token.decode('ascii', 'ignore')))
  57. if token == "":
  58. # In case the cookie has been truncated to nothing at some point.
  59. return _get_new_csrf_key()
  60. else:
  61. return token
  62. class CsrfViewMiddleware(object):
  63. """
  64. Middleware that requires a present and correct csrfmiddlewaretoken
  65. for POST requests that have a CSRF cookie, and sets an outgoing
  66. CSRF cookie.
  67. This middleware should be used in conjunction with the csrf_token template
  68. tag.
  69. """
  70. # The _accept and _reject methods currently only exist for the sake of the
  71. # requires_csrf_token decorator.
  72. def _accept(self, request):
  73. # Avoid checking the request twice by adding a custom attribute to
  74. # request. This will be relevant when both decorator and middleware
  75. # are used.
  76. request.csrf_processing_done = True
  77. return None
  78. def _reject(self, request, reason):
  79. return _get_failure_view()(request, reason=reason)
  80. def process_view(self, request, callback, callback_args, callback_kwargs):
  81. if getattr(request, 'csrf_processing_done', False):
  82. return None
  83. # If the user doesn't have a CSRF cookie, generate one and store it in the
  84. # request, so it's available to the view. We'll store it in a cookie when
  85. # we reach the response.
  86. try:
  87. # In case of cookies from untrusted sources, we strip anything
  88. # dangerous at this point, so that the cookie + token will have the
  89. # same, sanitized value.
  90. request.META["CSRF_COOKIE"] = _sanitize_token(request.COOKIES[settings.CSRF_COOKIE_NAME])
  91. cookie_is_new = False
  92. except KeyError:
  93. # No cookie, so create one. This will be sent with the next
  94. # response.
  95. request.META["CSRF_COOKIE"] = _get_new_csrf_key()
  96. # Set a flag to allow us to fall back and allow the session id in
  97. # place of a CSRF cookie for this request only.
  98. cookie_is_new = True
  99. # Wait until request.META["CSRF_COOKIE"] has been manipulated before
  100. # bailing out, so that get_token still works
  101. if getattr(callback, 'csrf_exempt', False):
  102. return None
  103. if request.method == 'POST':
  104. if getattr(request, '_dont_enforce_csrf_checks', False):
  105. # Mechanism to turn off CSRF checks for test suite. It comes after
  106. # the creation of CSRF cookies, so that everything else continues to
  107. # work exactly the same (e.g. cookies are sent etc), but before the
  108. # any branches that call reject()
  109. return self._accept(request)
  110. if request.is_secure():
  111. # Suppose user visits http://example.com/
  112. # An active network attacker,(man-in-the-middle, MITM) sends a
  113. # POST form which targets https://example.com/detonate-bomb/ and
  114. # submits it via javascript.
  115. #
  116. # The attacker will need to provide a CSRF cookie and token, but
  117. # that is no problem for a MITM and the session independent
  118. # nonce we are using. So the MITM can circumvent the CSRF
  119. # protection. This is true for any HTTP connection, but anyone
  120. # using HTTPS expects better! For this reason, for
  121. # https://example.com/ we need additional protection that treats
  122. # http://example.com/ as completely untrusted. Under HTTPS,
  123. # Barth et al. found that the Referer header is missing for
  124. # same-domain requests in only about 0.2% of cases or less, so
  125. # we can use strict Referer checking.
  126. referer = request.META.get('HTTP_REFERER')
  127. if referer is None:
  128. logger.warning('Forbidden (%s): %s' % (REASON_NO_REFERER, request.path),
  129. extra={
  130. 'status_code': 403,
  131. 'request': request,
  132. }
  133. )
  134. return self._reject(request, REASON_NO_REFERER)
  135. # Note that request.get_host() includes the port
  136. good_referer = 'https://%s/' % request.get_host()
  137. if not same_origin(referer, good_referer):
  138. reason = REASON_BAD_REFERER % (referer, good_referer)
  139. logger.warning('Forbidden (%s): %s' % (reason, request.path),
  140. extra={
  141. 'status_code': 403,
  142. 'request': request,
  143. }
  144. )
  145. return self._reject(request, reason)
  146. # If the user didn't already have a CSRF cookie, then fall back to
  147. # the Django 1.1 method (hash of session ID), so a request is not
  148. # rejected if the form was sent to the user before upgrading to the
  149. # Django 1.2 method (session independent nonce)
  150. if cookie_is_new:
  151. try:
  152. session_id = request.COOKIES[settings.SESSION_COOKIE_NAME]
  153. csrf_token = _make_legacy_session_token(session_id)
  154. except KeyError:
  155. # No CSRF cookie and no session cookie. For POST requests,
  156. # we insist on a CSRF cookie, and in this way we can avoid
  157. # all CSRF attacks, including login CSRF.
  158. logger.warning('Forbidden (%s): %s' % (REASON_NO_COOKIE, request.path),
  159. extra={
  160. 'status_code': 403,
  161. 'request': request,
  162. }
  163. )
  164. return self._reject(request, REASON_NO_COOKIE)
  165. else:
  166. csrf_token = request.META["CSRF_COOKIE"]
  167. # check incoming token
  168. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  169. if request_csrf_token == "":
  170. # Fall back to X-CSRFToken, to make things easier for AJAX
  171. request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')
  172. if not constant_time_compare(request_csrf_token, csrf_token):
  173. if cookie_is_new:
  174. # probably a problem setting the CSRF cookie
  175. logger.warning('Forbidden (%s): %s' % (REASON_NO_CSRF_COOKIE, request.path),
  176. extra={
  177. 'status_code': 403,
  178. 'request': request,
  179. }
  180. )
  181. return self._reject(request, REASON_NO_CSRF_COOKIE)
  182. else:
  183. logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path),
  184. extra={
  185. 'status_code': 403,
  186. 'request': request,
  187. }
  188. )
  189. return self._reject(request, REASON_BAD_TOKEN)
  190. return self._accept(request)
  191. def process_response(self, request, response):
  192. if getattr(response, 'csrf_processing_done', False):
  193. return response
  194. # If CSRF_COOKIE is unset, then CsrfViewMiddleware.process_view was
  195. # never called, probaby because a request middleware returned a response
  196. # (for example, contrib.auth redirecting to a login page).
  197. if request.META.get("CSRF_COOKIE") is None:
  198. return response
  199. if not request.META.get("CSRF_COOKIE_USED", False):
  200. return response
  201. # Set the CSRF cookie even if it's already set, so we renew the expiry timer.
  202. response.set_cookie(settings.CSRF_COOKIE_NAME,
  203. request.META["CSRF_COOKIE"], max_age = 60 * 60 * 24 * 7 * 52,
  204. domain=settings.CSRF_COOKIE_DOMAIN)
  205. # Content varies with the CSRF cookie, so set the Vary header.
  206. patch_vary_headers(response, ('Cookie',))
  207. response.csrf_processing_done = True
  208. return response
  209. class CsrfResponseMiddleware(object):
  210. """
  211. DEPRECATED
  212. Middleware that post-processes a response to add a csrfmiddlewaretoken.
  213. This exists for backwards compatibility and as an interim measure until
  214. applications are converted to using use the csrf_token template tag
  215. instead. It will be removed in Django 1.4.
  216. """
  217. def __init__(self):
  218. import warnings
  219. warnings.warn(
  220. "CsrfResponseMiddleware and CsrfMiddleware are deprecated; use CsrfViewMiddleware and the template tag instead (see CSRF documentation).",
  221. DeprecationWarning
  222. )
  223. def process_response(self, request, response):
  224. if getattr(response, 'csrf_exempt', False):
  225. return response
  226. if response['Content-Type'].split(';')[0] in _HTML_TYPES:
  227. csrf_token = get_token(request)
  228. # If csrf_token is None, we have no token for this request, which probably
  229. # means that this is a response from a request middleware.
  230. if csrf_token is None:
  231. return response
  232. # ensure we don't add the 'id' attribute twice (HTML validity)
  233. idattributes = itertools.chain(("id='csrfmiddlewaretoken'",),
  234. itertools.repeat(''))
  235. def add_csrf_field(match):
  236. """Returns the matched <form> tag plus the added <input> element"""
  237. return mark_safe(match.group() + "<div style='display:none;'>" + \
  238. "<input type='hidden' " + idattributes.next() + \
  239. " name='csrfmiddlewaretoken' value='" + csrf_token + \
  240. "' /></div>")
  241. # Modify any POST forms
  242. response.content, n = _POST_FORM_RE.subn(add_csrf_field, response.content)
  243. if n > 0:
  244. # Content varies with the CSRF cookie, so set the Vary header.
  245. patch_vary_headers(response, ('Cookie',))
  246. # Since the content has been modified, any Etag will now be
  247. # incorrect. We could recalculate, but only if we assume that
  248. # the Etag was set by CommonMiddleware. The safest thing is just
  249. # to delete. See bug #9163
  250. del response['ETag']
  251. return response
  252. class CsrfMiddleware(object):
  253. """
  254. Django middleware that adds protection against Cross Site
  255. Request Forgeries by adding hidden form fields to POST forms and
  256. checking requests for the correct value.
  257. CsrfMiddleware uses two middleware, CsrfViewMiddleware and
  258. CsrfResponseMiddleware, which can be used independently. It is recommended
  259. to use only CsrfViewMiddleware and use the csrf_token template tag in
  260. templates for inserting the token.
  261. """
  262. # We can't just inherit from CsrfViewMiddleware and CsrfResponseMiddleware
  263. # because both have process_response methods.
  264. def __init__(self):
  265. self.response_middleware = CsrfResponseMiddleware()
  266. self.view_middleware = CsrfViewMiddleware()
  267. def process_response(self, request, resp):
  268. # We must do the response post-processing first, because that calls
  269. # get_token(), which triggers a flag saying that the CSRF cookie needs
  270. # to be sent (done in CsrfViewMiddleware.process_response)
  271. resp2 = self.response_middleware.process_response(request, resp)
  272. return self.view_middleware.process_response(request, resp2)
  273. def process_view(self, request, callback, callback_args, callback_kwargs):
  274. return self.view_middleware.process_view(request, callback, callback_args,
  275. callback_kwargs)