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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. request.session[CSRF_SESSION_KEY] = request.META['CSRF_COOKIE']
  154. else:
  155. response.set_cookie(
  156. settings.CSRF_COOKIE_NAME,
  157. request.META['CSRF_COOKIE'],
  158. max_age=settings.CSRF_COOKIE_AGE,
  159. domain=settings.CSRF_COOKIE_DOMAIN,
  160. path=settings.CSRF_COOKIE_PATH,
  161. secure=settings.CSRF_COOKIE_SECURE,
  162. httponly=settings.CSRF_COOKIE_HTTPONLY,
  163. samesite=settings.CSRF_COOKIE_SAMESITE,
  164. )
  165. # Set the Vary header since content varies with the CSRF cookie.
  166. patch_vary_headers(response, ('Cookie',))
  167. def process_request(self, request):
  168. csrf_token = self._get_token(request)
  169. if csrf_token is not None:
  170. # Use same token next time.
  171. request.META['CSRF_COOKIE'] = csrf_token
  172. def process_view(self, request, callback, callback_args, callback_kwargs):
  173. if getattr(request, 'csrf_processing_done', False):
  174. return None
  175. # Wait until request.META["CSRF_COOKIE"] has been manipulated before
  176. # bailing out, so that get_token still works
  177. if getattr(callback, 'csrf_exempt', False):
  178. return None
  179. # Assume that anything not defined as 'safe' by RFC7231 needs protection
  180. if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
  181. if getattr(request, '_dont_enforce_csrf_checks', False):
  182. # Mechanism to turn off CSRF checks for test suite.
  183. # It comes after the creation of CSRF cookies, so that
  184. # everything else continues to work exactly the same
  185. # (e.g. cookies are sent, etc.), but before any
  186. # branches that call reject().
  187. return self._accept(request)
  188. if request.is_secure():
  189. # Suppose user visits http://example.com/
  190. # An active network attacker (man-in-the-middle, MITM) sends a
  191. # POST form that targets https://example.com/detonate-bomb/ and
  192. # submits it via JavaScript.
  193. #
  194. # The attacker will need to provide a CSRF cookie and token, but
  195. # that's no problem for a MITM and the session-independent
  196. # secret we're using. So the MITM can circumvent the CSRF
  197. # protection. This is true for any HTTP connection, but anyone
  198. # using HTTPS expects better! For this reason, for
  199. # https://example.com/ we need additional protection that treats
  200. # http://example.com/ as completely untrusted. Under HTTPS,
  201. # Barth et al. found that the Referer header is missing for
  202. # same-domain requests in only about 0.2% of cases or less, so
  203. # we can use strict Referer checking.
  204. referer = request.META.get('HTTP_REFERER')
  205. if referer is None:
  206. return self._reject(request, REASON_NO_REFERER)
  207. referer = urlparse(referer)
  208. # Make sure we have a valid URL for Referer.
  209. if '' in (referer.scheme, referer.netloc):
  210. return self._reject(request, REASON_MALFORMED_REFERER)
  211. # Ensure that our Referer is also secure.
  212. if referer.scheme != 'https':
  213. return self._reject(request, REASON_INSECURE_REFERER)
  214. # If there isn't a CSRF_COOKIE_DOMAIN, require an exact match
  215. # match on host:port. If not, obey the cookie rules (or those
  216. # for the session cookie, if CSRF_USE_SESSIONS).
  217. good_referer = (
  218. settings.SESSION_COOKIE_DOMAIN
  219. if settings.CSRF_USE_SESSIONS
  220. else settings.CSRF_COOKIE_DOMAIN
  221. )
  222. if good_referer is not None:
  223. server_port = request.get_port()
  224. if server_port not in ('443', '80'):
  225. good_referer = '%s:%s' % (good_referer, server_port)
  226. else:
  227. try:
  228. # request.get_host() includes the port.
  229. good_referer = request.get_host()
  230. except DisallowedHost:
  231. pass
  232. # Create a list of all acceptable HTTP referers, including the
  233. # current host if it's permitted by ALLOWED_HOSTS.
  234. good_hosts = list(settings.CSRF_TRUSTED_ORIGINS)
  235. if good_referer is not None:
  236. good_hosts.append(good_referer)
  237. if not any(is_same_domain(referer.netloc, host) for host in good_hosts):
  238. reason = REASON_BAD_REFERER % referer.geturl()
  239. return self._reject(request, reason)
  240. csrf_token = request.META.get('CSRF_COOKIE')
  241. if csrf_token is None:
  242. # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
  243. # and in this way we can avoid all CSRF attacks, including login
  244. # CSRF.
  245. return self._reject(request, REASON_NO_CSRF_COOKIE)
  246. # Check non-cookie token for match.
  247. request_csrf_token = ""
  248. if request.method == "POST":
  249. try:
  250. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  251. except IOError:
  252. # Handle a broken connection before we've completed reading
  253. # the POST data. process_view shouldn't raise any
  254. # exceptions, so we'll ignore and serve the user a 403
  255. # (assuming they're still listening, which they probably
  256. # aren't because of the error).
  257. pass
  258. if request_csrf_token == "":
  259. # Fall back to X-CSRFToken, to make things easier for AJAX,
  260. # and possible for PUT/DELETE.
  261. request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')
  262. request_csrf_token = _sanitize_token(request_csrf_token)
  263. if not _compare_salted_tokens(request_csrf_token, csrf_token):
  264. return self._reject(request, REASON_BAD_TOKEN)
  265. return self._accept(request)
  266. def process_response(self, request, response):
  267. if not getattr(request, 'csrf_cookie_needs_reset', False):
  268. if getattr(response, 'csrf_cookie_set', False):
  269. return response
  270. if not request.META.get("CSRF_COOKIE_USED", False):
  271. return response
  272. # Set the CSRF cookie even if it's already set, so we renew
  273. # the expiry timer.
  274. self._set_token(request, response)
  275. response.csrf_cookie_set = True
  276. return response