csrf.py 19 KB

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