csrf.py 19 KB

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