You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

csrf.py 13KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 logging
  7. import re
  8. import string
  9. from urllib.parse import urlparse
  10. from django.conf import settings
  11. from django.core.exceptions import DisallowedHost, ImproperlyConfigured
  12. from django.urls import get_callable
  13. from django.utils.cache import patch_vary_headers
  14. from django.utils.crypto import constant_time_compare, get_random_string
  15. from django.utils.deprecation import MiddlewareMixin
  16. from django.utils.http import is_same_domain
  17. from django.utils.log import log_response
  18. logger = logging.getLogger('django.security.csrf')
  19. REASON_NO_REFERER = "Referer checking failed - no Referer."
  20. REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
  21. REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
  22. REASON_BAD_TOKEN = "CSRF token missing or incorrect."
  23. REASON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
  24. REASON_INSECURE_REFERER = "Referer checking failed - Referer is insecure while host is secure."
  25. CSRF_SECRET_LENGTH = 32
  26. CSRF_TOKEN_LENGTH = 2 * CSRF_SECRET_LENGTH
  27. CSRF_ALLOWED_CHARS = string.ascii_letters + string.digits
  28. CSRF_SESSION_KEY = '_csrftoken'
  29. def _get_failure_view():
  30. """Return the view to be used for CSRF rejections."""
  31. return get_callable(settings.CSRF_FAILURE_VIEW)
  32. def _get_new_csrf_string():
  33. return get_random_string(CSRF_SECRET_LENGTH, allowed_chars=CSRF_ALLOWED_CHARS)
  34. def _salt_cipher_secret(secret):
  35. """
  36. Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
  37. token by adding a salt and using it to encrypt the secret.
  38. """
  39. salt = _get_new_csrf_string()
  40. chars = CSRF_ALLOWED_CHARS
  41. pairs = zip((chars.index(x) for x in secret), (chars.index(x) for x in salt))
  42. cipher = ''.join(chars[(x + y) % len(chars)] for x, y in pairs)
  43. return salt + cipher
  44. def _unsalt_cipher_token(token):
  45. """
  46. Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
  47. CSRF_TOKEN_LENGTH, and that its first half is a salt), use it to decrypt
  48. the second half to produce the original secret.
  49. """
  50. salt = token[:CSRF_SECRET_LENGTH]
  51. token = token[CSRF_SECRET_LENGTH:]
  52. chars = CSRF_ALLOWED_CHARS
  53. pairs = zip((chars.index(x) for x in token), (chars.index(x) for x in salt))
  54. secret = ''.join(chars[x - y] for x, y in pairs) # Note negative values are ok
  55. return secret
  56. def _get_new_csrf_token():
  57. return _salt_cipher_secret(_get_new_csrf_string())
  58. def get_token(request):
  59. """
  60. Return the CSRF token required for a POST form. The token is an
  61. alphanumeric value. A new token is created if one is not already set.
  62. A side effect of calling this function is to make the csrf_protect
  63. decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
  64. header to the outgoing response. For this reason, you may need to use this
  65. function lazily, as is done by the csrf context processor.
  66. """
  67. if "CSRF_COOKIE" not in request.META:
  68. csrf_secret = _get_new_csrf_string()
  69. request.META["CSRF_COOKIE"] = _salt_cipher_secret(csrf_secret)
  70. else:
  71. csrf_secret = _unsalt_cipher_token(request.META["CSRF_COOKIE"])
  72. request.META["CSRF_COOKIE_USED"] = True
  73. return _salt_cipher_secret(csrf_secret)
  74. def rotate_token(request):
  75. """
  76. Change the CSRF token in use for a request - should be done on login
  77. for security purposes.
  78. """
  79. request.META.update({
  80. "CSRF_COOKIE_USED": True,
  81. "CSRF_COOKIE": _get_new_csrf_token(),
  82. })
  83. request.csrf_cookie_needs_reset = True
  84. def _sanitize_token(token):
  85. # Allow only ASCII alphanumerics
  86. if re.search('[^a-zA-Z0-9]', token):
  87. return _get_new_csrf_token()
  88. elif len(token) == CSRF_TOKEN_LENGTH:
  89. return token
  90. elif len(token) == CSRF_SECRET_LENGTH:
  91. # Older Django versions set cookies to values of CSRF_SECRET_LENGTH
  92. # alphanumeric characters. For backwards compatibility, accept
  93. # such values as unsalted secrets.
  94. # It's easier to salt here and be consistent later, rather than add
  95. # different code paths in the checks, although that might be a tad more
  96. # efficient.
  97. return _salt_cipher_secret(token)
  98. return _get_new_csrf_token()
  99. def _compare_salted_tokens(request_csrf_token, csrf_token):
  100. # Assume both arguments are sanitized -- that is, strings of
  101. # length CSRF_TOKEN_LENGTH, all CSRF_ALLOWED_CHARS.
  102. return constant_time_compare(
  103. _unsalt_cipher_token(request_csrf_token),
  104. _unsalt_cipher_token(csrf_token),
  105. )
  106. class CsrfViewMiddleware(MiddlewareMixin):
  107. """
  108. Require a present and correct csrfmiddlewaretoken for POST requests that
  109. have a CSRF cookie, and set an outgoing CSRF cookie.
  110. This middleware should be used in conjunction with the {% csrf_token %}
  111. template tag.
  112. """
  113. # The _accept and _reject methods currently only exist for the sake of the
  114. # requires_csrf_token decorator.
  115. def _accept(self, request):
  116. # Avoid checking the request twice by adding a custom attribute to
  117. # request. This will be relevant when both decorator and middleware
  118. # are used.
  119. request.csrf_processing_done = True
  120. return None
  121. def _reject(self, request, reason):
  122. response = _get_failure_view()(request, reason=reason)
  123. log_response(
  124. 'Forbidden (%s): %s', reason, request.path,
  125. response=response,
  126. request=request,
  127. logger=logger,
  128. )
  129. return response
  130. def _get_token(self, request):
  131. if settings.CSRF_USE_SESSIONS:
  132. try:
  133. return request.session.get(CSRF_SESSION_KEY)
  134. except AttributeError:
  135. raise ImproperlyConfigured(
  136. 'CSRF_USE_SESSIONS is enabled, but request.session is not '
  137. 'set. SessionMiddleware must appear before CsrfViewMiddleware '
  138. 'in MIDDLEWARE%s.' % ('_CLASSES' if settings.MIDDLEWARE is None else '')
  139. )
  140. else:
  141. try:
  142. cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
  143. except KeyError:
  144. return None
  145. csrf_token = _sanitize_token(cookie_token)
  146. if csrf_token != cookie_token:
  147. # Cookie token needed to be replaced;
  148. # the cookie needs to be reset.
  149. request.csrf_cookie_needs_reset = True
  150. return csrf_token
  151. def _set_token(self, request, response):
  152. if settings.CSRF_USE_SESSIONS:
  153. if request.session.get(CSRF_SESSION_KEY) != request.META['CSRF_COOKIE']:
  154. request.session[CSRF_SESSION_KEY] = request.META['CSRF_COOKIE']
  155. else:
  156. response.set_cookie(
  157. settings.CSRF_COOKIE_NAME,
  158. request.META['CSRF_COOKIE'],
  159. max_age=settings.CSRF_COOKIE_AGE,
  160. domain=settings.CSRF_COOKIE_DOMAIN,
  161. path=settings.CSRF_COOKIE_PATH,
  162. secure=settings.CSRF_COOKIE_SECURE,
  163. httponly=settings.CSRF_COOKIE_HTTPONLY,
  164. samesite=settings.CSRF_COOKIE_SAMESITE,
  165. )
  166. # Set the Vary header since content varies with the CSRF cookie.
  167. patch_vary_headers(response, ('Cookie',))
  168. def process_request(self, request):
  169. csrf_token = self._get_token(request)
  170. if csrf_token is not None:
  171. # Use same token next time.
  172. request.META['CSRF_COOKIE'] = csrf_token
  173. def process_view(self, request, callback, callback_args, callback_kwargs):
  174. if getattr(request, 'csrf_processing_done', False):
  175. return None
  176. # Wait until request.META["CSRF_COOKIE"] has been manipulated before
  177. # bailing out, so that get_token still works
  178. if getattr(callback, 'csrf_exempt', False):
  179. return None
  180. # Assume that anything not defined as 'safe' by RFC7231 needs protection
  181. if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
  182. if getattr(request, '_dont_enforce_csrf_checks', False):
  183. # Mechanism to turn off CSRF checks for test suite.
  184. # It comes after the creation of CSRF cookies, so that
  185. # everything else continues to work exactly the same
  186. # (e.g. cookies are sent, etc.), but before any
  187. # branches that call reject().
  188. return self._accept(request)
  189. if request.is_secure():
  190. # Suppose user visits http://example.com/
  191. # An active network attacker (man-in-the-middle, MITM) sends a
  192. # POST form that targets https://example.com/detonate-bomb/ and
  193. # submits it via JavaScript.
  194. #
  195. # The attacker will need to provide a CSRF cookie and token, but
  196. # that's no problem for a MITM and the session-independent
  197. # secret we're using. So the MITM can circumvent the CSRF
  198. # protection. This is true for any HTTP connection, but anyone
  199. # using HTTPS expects better! For this reason, for
  200. # https://example.com/ we need additional protection that treats
  201. # http://example.com/ as completely untrusted. Under HTTPS,
  202. # Barth et al. found that the Referer header is missing for
  203. # same-domain requests in only about 0.2% of cases or less, so
  204. # we can use strict Referer checking.
  205. referer = request.META.get('HTTP_REFERER')
  206. if referer is None:
  207. return self._reject(request, REASON_NO_REFERER)
  208. referer = urlparse(referer)
  209. # Make sure we have a valid URL for Referer.
  210. if '' in (referer.scheme, referer.netloc):
  211. return self._reject(request, REASON_MALFORMED_REFERER)
  212. # Ensure that our Referer is also secure.
  213. if referer.scheme != 'https':
  214. return self._reject(request, REASON_INSECURE_REFERER)
  215. # If there isn't a CSRF_COOKIE_DOMAIN, require an exact match
  216. # match on host:port. If not, obey the cookie rules (or those
  217. # for the session cookie, if CSRF_USE_SESSIONS).
  218. good_referer = (
  219. settings.SESSION_COOKIE_DOMAIN
  220. if settings.CSRF_USE_SESSIONS
  221. else settings.CSRF_COOKIE_DOMAIN
  222. )
  223. if good_referer is not None:
  224. server_port = request.get_port()
  225. if server_port not in ('443', '80'):
  226. good_referer = '%s:%s' % (good_referer, server_port)
  227. else:
  228. try:
  229. # request.get_host() includes the port.
  230. good_referer = request.get_host()
  231. except DisallowedHost:
  232. pass
  233. # Create a list of all acceptable HTTP referers, including the
  234. # current host if it's permitted by ALLOWED_HOSTS.
  235. good_hosts = list(settings.CSRF_TRUSTED_ORIGINS)
  236. if good_referer is not None:
  237. good_hosts.append(good_referer)
  238. if not any(is_same_domain(referer.netloc, host) for host in good_hosts):
  239. reason = REASON_BAD_REFERER % referer.geturl()
  240. return self._reject(request, reason)
  241. csrf_token = request.META.get('CSRF_COOKIE')
  242. if csrf_token is None:
  243. # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
  244. # and in this way we can avoid all CSRF attacks, including login
  245. # CSRF.
  246. return self._reject(request, REASON_NO_CSRF_COOKIE)
  247. # Check non-cookie token for match.
  248. request_csrf_token = ""
  249. if request.method == "POST":
  250. try:
  251. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  252. except IOError:
  253. # Handle a broken connection before we've completed reading
  254. # the POST data. process_view shouldn't raise any
  255. # exceptions, so we'll ignore and serve the user a 403
  256. # (assuming they're still listening, which they probably
  257. # aren't because of the error).
  258. pass
  259. if request_csrf_token == "":
  260. # Fall back to X-CSRFToken, to make things easier for AJAX,
  261. # and possible for PUT/DELETE.
  262. request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')
  263. request_csrf_token = _sanitize_token(request_csrf_token)
  264. if not _compare_salted_tokens(request_csrf_token, csrf_token):
  265. return self._reject(request, REASON_BAD_TOKEN)
  266. return self._accept(request)
  267. def process_response(self, request, response):
  268. if not getattr(request, 'csrf_cookie_needs_reset', False):
  269. if getattr(response, 'csrf_cookie_set', False):
  270. return response
  271. if not request.META.get("CSRF_COOKIE_USED", False):
  272. return response
  273. # Set the CSRF cookie even if it's already set, so we renew
  274. # the expiry timer.
  275. self._set_token(request, response)
  276. response.csrf_cookie_set = True
  277. return response