Debian Codegraph @

django/middleware/csrf.py

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