PageRenderTime 64ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/packages/django/middleware/csrf.py

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