Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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 19KB

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