Development of an internal social media platform with personalised dashboards for students
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

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