PageRenderTime 47ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/python/lib/Lib/site-packages/django/middleware/csrf.py

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