csrf.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 string
  8. from collections import defaultdict
  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.functional import cached_property
  17. from django.utils.http import is_same_domain
  18. from django.utils.log import log_response
  19. from django.utils.regex_helper import _lazy_re_compile
  20. logger = logging.getLogger('django.security.csrf')
  21. # This matches if any character is not in CSRF_ALLOWED_CHARS.
  22. invalid_token_chars_re = _lazy_re_compile('[^a-zA-Z0-9]')
  23. REASON_BAD_ORIGIN = "Origin checking failed - %s does not match any trusted origins."
  24. REASON_NO_REFERER = "Referer checking failed - no Referer."
  25. REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
  26. REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
  27. REASON_CSRF_TOKEN_INCORRECT = 'CSRF token incorrect.'
  28. REASON_CSRF_TOKEN_MISSING = 'CSRF token missing.'
  29. REASON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
  30. REASON_INSECURE_REFERER = "Referer checking failed - Referer is insecure while host is secure."
  31. # The reason strings below are for passing to InvalidTokenFormat. They are
  32. # phrases without a subject because they can be in reference to either the CSRF
  33. # cookie or non-cookie token.
  34. REASON_INCORRECT_LENGTH = 'has incorrect length'
  35. REASON_INVALID_CHARACTERS = 'has invalid characters'
  36. CSRF_SECRET_LENGTH = 32
  37. CSRF_TOKEN_LENGTH = 2 * CSRF_SECRET_LENGTH
  38. CSRF_ALLOWED_CHARS = string.ascii_letters + string.digits
  39. CSRF_SESSION_KEY = '_csrftoken'
  40. def _get_failure_view():
  41. """Return the view to be used for CSRF rejections."""
  42. return get_callable(settings.CSRF_FAILURE_VIEW)
  43. def _get_new_csrf_string():
  44. return get_random_string(CSRF_SECRET_LENGTH, allowed_chars=CSRF_ALLOWED_CHARS)
  45. def _mask_cipher_secret(secret):
  46. """
  47. Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
  48. token by adding a mask and applying it to the secret.
  49. """
  50. mask = _get_new_csrf_string()
  51. chars = CSRF_ALLOWED_CHARS
  52. pairs = zip((chars.index(x) for x in secret), (chars.index(x) for x in mask))
  53. cipher = ''.join(chars[(x + y) % len(chars)] for x, y in pairs)
  54. return mask + cipher
  55. def _unmask_cipher_token(token):
  56. """
  57. Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
  58. CSRF_TOKEN_LENGTH, and that its first half is a mask), use it to decrypt
  59. the second half to produce the original secret.
  60. """
  61. mask = token[:CSRF_SECRET_LENGTH]
  62. token = token[CSRF_SECRET_LENGTH:]
  63. chars = CSRF_ALLOWED_CHARS
  64. pairs = zip((chars.index(x) for x in token), (chars.index(x) for x in mask))
  65. return ''.join(chars[x - y] for x, y in pairs) # Note negative values are ok
  66. def _get_new_csrf_token():
  67. return _mask_cipher_secret(_get_new_csrf_string())
  68. def get_token(request):
  69. """
  70. Return the CSRF token required for a POST form. The token is an
  71. alphanumeric value. A new token is created if one is not already set.
  72. A side effect of calling this function is to make the csrf_protect
  73. decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
  74. header to the outgoing response. For this reason, you may need to use this
  75. function lazily, as is done by the csrf context processor.
  76. """
  77. if "CSRF_COOKIE" not in request.META:
  78. csrf_secret = _get_new_csrf_string()
  79. request.META["CSRF_COOKIE"] = _mask_cipher_secret(csrf_secret)
  80. else:
  81. csrf_secret = _unmask_cipher_token(request.META["CSRF_COOKIE"])
  82. request.META["CSRF_COOKIE_USED"] = True
  83. return _mask_cipher_secret(csrf_secret)
  84. def rotate_token(request):
  85. """
  86. Change the CSRF token in use for a request - should be done on login
  87. for security purposes.
  88. """
  89. request.META.update({
  90. "CSRF_COOKIE_USED": True,
  91. "CSRF_COOKIE": _get_new_csrf_token(),
  92. })
  93. request.csrf_cookie_needs_reset = True
  94. class InvalidTokenFormat(Exception):
  95. def __init__(self, reason):
  96. self.reason = reason
  97. def _sanitize_token(token):
  98. if len(token) not in (CSRF_TOKEN_LENGTH, CSRF_SECRET_LENGTH):
  99. raise InvalidTokenFormat(REASON_INCORRECT_LENGTH)
  100. # Make sure all characters are in CSRF_ALLOWED_CHARS.
  101. if invalid_token_chars_re.search(token):
  102. raise InvalidTokenFormat(REASON_INVALID_CHARACTERS)
  103. if len(token) == CSRF_SECRET_LENGTH:
  104. # Older Django versions set cookies to values of CSRF_SECRET_LENGTH
  105. # alphanumeric characters. For backwards compatibility, accept
  106. # such values as unmasked secrets.
  107. # It's easier to mask here and be consistent later, rather than add
  108. # different code paths in the checks, although that might be a tad more
  109. # efficient.
  110. return _mask_cipher_secret(token)
  111. return token
  112. def _compare_masked_tokens(request_csrf_token, csrf_token):
  113. # Assume both arguments are sanitized -- that is, strings of
  114. # length CSRF_TOKEN_LENGTH, all CSRF_ALLOWED_CHARS.
  115. return constant_time_compare(
  116. _unmask_cipher_token(request_csrf_token),
  117. _unmask_cipher_token(csrf_token),
  118. )
  119. class RejectRequest(Exception):
  120. def __init__(self, reason):
  121. self.reason = reason
  122. class CsrfViewMiddleware(MiddlewareMixin):
  123. """
  124. Require a present and correct csrfmiddlewaretoken for POST requests that
  125. have a CSRF cookie, and set an outgoing CSRF cookie.
  126. This middleware should be used in conjunction with the {% csrf_token %}
  127. template tag.
  128. """
  129. @cached_property
  130. def csrf_trusted_origins_hosts(self):
  131. return [
  132. urlparse(origin).netloc.lstrip('*')
  133. for origin in settings.CSRF_TRUSTED_ORIGINS
  134. ]
  135. @cached_property
  136. def allowed_origins_exact(self):
  137. return {
  138. origin for origin in settings.CSRF_TRUSTED_ORIGINS
  139. if '*' not in origin
  140. }
  141. @cached_property
  142. def allowed_origin_subdomains(self):
  143. """
  144. A mapping of allowed schemes to list of allowed netlocs, where all
  145. subdomains of the netloc are allowed.
  146. """
  147. allowed_origin_subdomains = defaultdict(list)
  148. for parsed in (urlparse(origin) for origin in settings.CSRF_TRUSTED_ORIGINS if '*' in origin):
  149. allowed_origin_subdomains[parsed.scheme].append(parsed.netloc.lstrip('*'))
  150. return allowed_origin_subdomains
  151. # The _accept and _reject methods currently only exist for the sake of the
  152. # requires_csrf_token decorator.
  153. def _accept(self, request):
  154. # Avoid checking the request twice by adding a custom attribute to
  155. # request. This will be relevant when both decorator and middleware
  156. # are used.
  157. request.csrf_processing_done = True
  158. return None
  159. def _reject(self, request, reason):
  160. response = _get_failure_view()(request, reason=reason)
  161. log_response(
  162. 'Forbidden (%s): %s', reason, request.path,
  163. response=response,
  164. request=request,
  165. logger=logger,
  166. )
  167. return response
  168. def _get_token(self, request):
  169. if settings.CSRF_USE_SESSIONS:
  170. try:
  171. return request.session.get(CSRF_SESSION_KEY)
  172. except AttributeError:
  173. raise ImproperlyConfigured(
  174. 'CSRF_USE_SESSIONS is enabled, but request.session is not '
  175. 'set. SessionMiddleware must appear before CsrfViewMiddleware '
  176. 'in MIDDLEWARE.'
  177. )
  178. else:
  179. try:
  180. cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
  181. except KeyError:
  182. return None
  183. # This can raise InvalidTokenFormat.
  184. csrf_token = _sanitize_token(cookie_token)
  185. if csrf_token != cookie_token:
  186. # Then the cookie token had length CSRF_SECRET_LENGTH, so flag
  187. # to replace it with the masked version.
  188. request.csrf_cookie_needs_reset = True
  189. return csrf_token
  190. def _set_token(self, request, response):
  191. if settings.CSRF_USE_SESSIONS:
  192. if request.session.get(CSRF_SESSION_KEY) != request.META['CSRF_COOKIE']:
  193. request.session[CSRF_SESSION_KEY] = request.META['CSRF_COOKIE']
  194. else:
  195. response.set_cookie(
  196. settings.CSRF_COOKIE_NAME,
  197. request.META['CSRF_COOKIE'],
  198. max_age=settings.CSRF_COOKIE_AGE,
  199. domain=settings.CSRF_COOKIE_DOMAIN,
  200. path=settings.CSRF_COOKIE_PATH,
  201. secure=settings.CSRF_COOKIE_SECURE,
  202. httponly=settings.CSRF_COOKIE_HTTPONLY,
  203. samesite=settings.CSRF_COOKIE_SAMESITE,
  204. )
  205. # Set the Vary header since content varies with the CSRF cookie.
  206. patch_vary_headers(response, ('Cookie',))
  207. def _origin_verified(self, request):
  208. request_origin = request.META['HTTP_ORIGIN']
  209. try:
  210. good_host = request.get_host()
  211. except DisallowedHost:
  212. pass
  213. else:
  214. good_origin = '%s://%s' % (
  215. 'https' if request.is_secure() else 'http',
  216. good_host,
  217. )
  218. if request_origin == good_origin:
  219. return True
  220. if request_origin in self.allowed_origins_exact:
  221. return True
  222. try:
  223. parsed_origin = urlparse(request_origin)
  224. except ValueError:
  225. return False
  226. request_scheme = parsed_origin.scheme
  227. request_netloc = parsed_origin.netloc
  228. return any(
  229. is_same_domain(request_netloc, host)
  230. for host in self.allowed_origin_subdomains.get(request_scheme, ())
  231. )
  232. def _check_referer(self, request):
  233. referer = request.META.get('HTTP_REFERER')
  234. if referer is None:
  235. raise RejectRequest(REASON_NO_REFERER)
  236. try:
  237. referer = urlparse(referer)
  238. except ValueError:
  239. raise RejectRequest(REASON_MALFORMED_REFERER)
  240. # Make sure we have a valid URL for Referer.
  241. if '' in (referer.scheme, referer.netloc):
  242. raise RejectRequest(REASON_MALFORMED_REFERER)
  243. # Ensure that our Referer is also secure.
  244. if referer.scheme != 'https':
  245. raise RejectRequest(REASON_INSECURE_REFERER)
  246. if any(
  247. is_same_domain(referer.netloc, host)
  248. for host in self.csrf_trusted_origins_hosts
  249. ):
  250. return
  251. # Allow matching the configured cookie domain.
  252. good_referer = (
  253. settings.SESSION_COOKIE_DOMAIN
  254. if settings.CSRF_USE_SESSIONS
  255. else settings.CSRF_COOKIE_DOMAIN
  256. )
  257. if good_referer is None:
  258. # If no cookie domain is configured, allow matching the current
  259. # host:port exactly if it's permitted by ALLOWED_HOSTS.
  260. try:
  261. # request.get_host() includes the port.
  262. good_referer = request.get_host()
  263. except DisallowedHost:
  264. raise RejectRequest(REASON_BAD_REFERER % referer.geturl())
  265. else:
  266. server_port = request.get_port()
  267. if server_port not in ('443', '80'):
  268. good_referer = '%s:%s' % (good_referer, server_port)
  269. if not is_same_domain(referer.netloc, good_referer):
  270. raise RejectRequest(REASON_BAD_REFERER % referer.geturl())
  271. def process_request(self, request):
  272. try:
  273. csrf_token = self._get_token(request)
  274. except InvalidTokenFormat:
  275. csrf_token = _get_new_csrf_token()
  276. request.csrf_cookie_needs_reset = True
  277. if csrf_token is not None:
  278. # Use same token next time.
  279. request.META['CSRF_COOKIE'] = csrf_token
  280. def process_view(self, request, callback, callback_args, callback_kwargs):
  281. if getattr(request, 'csrf_processing_done', False):
  282. return None
  283. # Wait until request.META["CSRF_COOKIE"] has been manipulated before
  284. # bailing out, so that get_token still works
  285. if getattr(callback, 'csrf_exempt', False):
  286. return None
  287. # Assume that anything not defined as 'safe' by RFC7231 needs protection
  288. if request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
  289. return self._accept(request)
  290. if getattr(request, '_dont_enforce_csrf_checks', False):
  291. # Mechanism to turn off CSRF checks for test suite. It comes after
  292. # the creation of CSRF cookies, so that everything else continues
  293. # to work exactly the same (e.g. cookies are sent, etc.), but
  294. # before any branches that call reject().
  295. return self._accept(request)
  296. # Reject the request if the Origin header doesn't match an allowed
  297. # value.
  298. if 'HTTP_ORIGIN' in request.META:
  299. if not self._origin_verified(request):
  300. return self._reject(request, REASON_BAD_ORIGIN % request.META['HTTP_ORIGIN'])
  301. elif request.is_secure():
  302. # If the Origin header wasn't provided, reject HTTPS requests if
  303. # the Referer header doesn't match an allowed value.
  304. #
  305. # Suppose user visits http://example.com/
  306. # An active network attacker (man-in-the-middle, MITM) sends a
  307. # POST form that targets https://example.com/detonate-bomb/ and
  308. # submits it via JavaScript.
  309. #
  310. # The attacker will need to provide a CSRF cookie and token, but
  311. # that's no problem for a MITM and the session-independent secret
  312. # we're using. So the MITM can circumvent the CSRF protection. This
  313. # is true for any HTTP connection, but anyone using HTTPS expects
  314. # better! For this reason, for https://example.com/ we need
  315. # additional protection that treats http://example.com/ as
  316. # completely untrusted. Under HTTPS, Barth et al. found that the
  317. # Referer header is missing for same-domain requests in only about
  318. # 0.2% of cases or less, so we can use strict Referer checking.
  319. try:
  320. self._check_referer(request)
  321. except RejectRequest as exc:
  322. return self._reject(request, exc.reason)
  323. # Access csrf_token via self._get_token() as rotate_token() may have
  324. # been called by an authentication middleware during the
  325. # process_request() phase.
  326. try:
  327. csrf_token = self._get_token(request)
  328. except InvalidTokenFormat as exc:
  329. return self._reject(request, f'CSRF cookie {exc.reason}.')
  330. if csrf_token is None:
  331. # No CSRF cookie. For POST requests, we insist on a CSRF cookie,
  332. # and in this way we can avoid all CSRF attacks, including login
  333. # CSRF.
  334. return self._reject(request, REASON_NO_CSRF_COOKIE)
  335. # Check non-cookie token for match.
  336. request_csrf_token = ''
  337. if request.method == 'POST':
  338. try:
  339. request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
  340. except OSError:
  341. # Handle a broken connection before we've completed reading the
  342. # POST data. process_view shouldn't raise any exceptions, so
  343. # we'll ignore and serve the user a 403 (assuming they're still
  344. # listening, which they probably aren't because of the error).
  345. pass
  346. if request_csrf_token == '':
  347. # Fall back to X-CSRFToken, to make things easier for AJAX, and
  348. # possible for PUT/DELETE.
  349. try:
  350. request_csrf_token = request.META[settings.CSRF_HEADER_NAME]
  351. except KeyError:
  352. return self._reject(request, REASON_CSRF_TOKEN_MISSING)
  353. try:
  354. request_csrf_token = _sanitize_token(request_csrf_token)
  355. except InvalidTokenFormat as exc:
  356. return self._reject(request, f'CSRF token {exc.reason}.')
  357. if not _compare_masked_tokens(request_csrf_token, csrf_token):
  358. return self._reject(request, REASON_CSRF_TOKEN_INCORRECT)
  359. return self._accept(request)
  360. def process_response(self, request, response):
  361. if not getattr(request, 'csrf_cookie_needs_reset', False):
  362. if getattr(response, 'csrf_cookie_set', False):
  363. return response
  364. if not request.META.get("CSRF_COOKIE_USED", False):
  365. return response
  366. # Set the CSRF cookie even if it's already set, so we renew
  367. # the expiry timer.
  368. self._set_token(request, response)
  369. response.csrf_cookie_set = True
  370. return response