2009-10-27 08:36:34 +08:00
|
|
|
"""
|
|
|
|
Cross Site Request Forgery Middleware.
|
|
|
|
|
|
|
|
This module provides a middleware that implements protection
|
|
|
|
against request forgeries from other sites.
|
|
|
|
"""
|
2012-09-21 03:03:24 +08:00
|
|
|
import logging
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
import string
|
2021-01-03 07:46:17 +08:00
|
|
|
from collections import defaultdict
|
2017-01-07 19:11:46 +08:00
|
|
|
from urllib.parse import urlparse
|
2009-10-27 08:36:34 +08:00
|
|
|
|
|
|
|
from django.conf import settings
|
2017-10-22 07:56:01 +08:00
|
|
|
from django.core.exceptions import DisallowedHost, ImproperlyConfigured
|
2015-12-30 23:51:16 +08:00
|
|
|
from django.urls import get_callable
|
2009-10-27 08:36:34 +08:00
|
|
|
from django.utils.cache import patch_vary_headers
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.utils.crypto import constant_time_compare, get_random_string
|
2015-11-07 23:12:37 +08:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2021-01-13 08:55:02 +08:00
|
|
|
from django.utils.functional import cached_property
|
2015-03-17 17:52:55 +08:00
|
|
|
from django.utils.http import is_same_domain
|
2017-07-13 12:09:18 +08:00
|
|
|
from django.utils.log import log_response
|
2021-05-25 00:34:48 +08:00
|
|
|
from django.utils.regex_helper import _lazy_re_compile
|
2012-09-21 03:03:24 +08:00
|
|
|
|
2016-06-03 08:24:48 +08:00
|
|
|
logger = logging.getLogger('django.security.csrf')
|
2021-05-29 18:53:50 +08:00
|
|
|
# This matches if any character is not in CSRF_ALLOWED_CHARS.
|
|
|
|
invalid_token_chars_re = _lazy_re_compile('[^a-zA-Z0-9]')
|
2010-10-04 23:12:39 +08:00
|
|
|
|
2021-01-03 07:46:17 +08:00
|
|
|
REASON_BAD_ORIGIN = "Origin checking failed - %s does not match any trusted origins."
|
2010-09-04 00:28:10 +08:00
|
|
|
REASON_NO_REFERER = "Referer checking failed - no Referer."
|
2015-09-01 10:32:03 +08:00
|
|
|
REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
|
2010-09-04 00:28:10 +08:00
|
|
|
REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
|
2021-05-29 19:49:53 +08:00
|
|
|
REASON_CSRF_TOKEN_INCORRECT = 'CSRF token incorrect.'
|
|
|
|
REASON_CSRF_TOKEN_MISSING = 'CSRF token missing.'
|
2015-03-17 17:52:55 +08:00
|
|
|
REASON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
|
|
|
|
REASON_INSECURE_REFERER = "Referer checking failed - Referer is insecure while host is secure."
|
2021-05-29 19:49:53 +08:00
|
|
|
# The reason strings below are for passing to InvalidTokenFormat. They are
|
|
|
|
# phrases without a subject because they can be in reference to either the CSRF
|
|
|
|
# cookie or non-cookie token.
|
|
|
|
REASON_INCORRECT_LENGTH = 'has incorrect length'
|
|
|
|
REASON_INVALID_CHARACTERS = 'has invalid characters'
|
2010-09-04 00:28:10 +08:00
|
|
|
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
CSRF_SECRET_LENGTH = 32
|
|
|
|
CSRF_TOKEN_LENGTH = 2 * CSRF_SECRET_LENGTH
|
|
|
|
CSRF_ALLOWED_CHARS = string.ascii_letters + string.digits
|
2016-07-01 00:42:11 +08:00
|
|
|
CSRF_SESSION_KEY = '_csrftoken'
|
2010-09-04 00:28:10 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2009-10-27 08:36:34 +08:00
|
|
|
def _get_failure_view():
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Return the view to be used for CSRF rejections."""
|
2009-10-27 08:36:34 +08:00
|
|
|
return get_callable(settings.CSRF_FAILURE_VIEW)
|
|
|
|
|
2010-09-04 00:28:10 +08:00
|
|
|
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
def _get_new_csrf_string():
|
|
|
|
return get_random_string(CSRF_SECRET_LENGTH, allowed_chars=CSRF_ALLOWED_CHARS)
|
|
|
|
|
|
|
|
|
2020-02-25 21:16:19 +08:00
|
|
|
def _mask_cipher_secret(secret):
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
"""
|
|
|
|
Given a secret (assumed to be a string of CSRF_ALLOWED_CHARS), generate a
|
2020-02-25 21:16:19 +08:00
|
|
|
token by adding a mask and applying it to the secret.
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
"""
|
2020-02-25 21:16:19 +08:00
|
|
|
mask = _get_new_csrf_string()
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
chars = CSRF_ALLOWED_CHARS
|
2020-02-25 21:16:19 +08:00
|
|
|
pairs = zip((chars.index(x) for x in secret), (chars.index(x) for x in mask))
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
cipher = ''.join(chars[(x + y) % len(chars)] for x, y in pairs)
|
2020-02-25 21:16:19 +08:00
|
|
|
return mask + cipher
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
|
|
|
|
|
2020-02-25 21:16:19 +08:00
|
|
|
def _unmask_cipher_token(token):
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
"""
|
|
|
|
Given a token (assumed to be a string of CSRF_ALLOWED_CHARS, of length
|
2020-02-25 21:16:19 +08:00
|
|
|
CSRF_TOKEN_LENGTH, and that its first half is a mask), use it to decrypt
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
the second half to produce the original secret.
|
|
|
|
"""
|
2020-02-25 21:16:19 +08:00
|
|
|
mask = token[:CSRF_SECRET_LENGTH]
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
token = token[CSRF_SECRET_LENGTH:]
|
|
|
|
chars = CSRF_ALLOWED_CHARS
|
2020-02-25 21:16:19 +08:00
|
|
|
pairs = zip((chars.index(x) for x in token), (chars.index(x) for x in mask))
|
2019-04-24 19:09:29 +08:00
|
|
|
return ''.join(chars[x - y] for x, y in pairs) # Note negative values are ok
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
|
|
|
|
|
|
|
|
def _get_new_csrf_token():
|
2020-02-25 21:16:19 +08:00
|
|
|
return _mask_cipher_secret(_get_new_csrf_string())
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2010-09-04 00:28:10 +08:00
|
|
|
|
2009-10-27 08:36:34 +08:00
|
|
|
def get_token(request):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Return the CSRF token required for a POST form. The token is an
|
2015-04-24 14:24:38 +08:00
|
|
|
alphanumeric value. A new token is created if one is not already set.
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2013-01-29 23:45:40 +08:00
|
|
|
A side effect of calling this function is to make the csrf_protect
|
2009-10-27 08:36:34 +08:00
|
|
|
decorator and the CsrfViewMiddleware add a CSRF cookie and a 'Vary: Cookie'
|
|
|
|
header to the outgoing response. For this reason, you may need to use this
|
|
|
|
function lazily, as is done by the csrf context processor.
|
|
|
|
"""
|
2015-04-24 14:24:38 +08:00
|
|
|
if "CSRF_COOKIE" not in request.META:
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
csrf_secret = _get_new_csrf_string()
|
2020-02-25 21:16:19 +08:00
|
|
|
request.META["CSRF_COOKIE"] = _mask_cipher_secret(csrf_secret)
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
else:
|
2020-02-25 21:16:19 +08:00
|
|
|
csrf_secret = _unmask_cipher_token(request.META["CSRF_COOKIE"])
|
2009-10-27 08:36:34 +08:00
|
|
|
request.META["CSRF_COOKIE_USED"] = True
|
2020-02-25 21:16:19 +08:00
|
|
|
return _mask_cipher_secret(csrf_secret)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2010-09-04 00:28:10 +08:00
|
|
|
|
2013-05-23 23:14:27 +08:00
|
|
|
def rotate_token(request):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Change the CSRF token in use for a request - should be done on login
|
2013-05-23 23:14:27 +08:00
|
|
|
for security purposes.
|
|
|
|
"""
|
2013-10-18 07:51:45 +08:00
|
|
|
request.META.update({
|
|
|
|
"CSRF_COOKIE_USED": True,
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
"CSRF_COOKIE": _get_new_csrf_token(),
|
2013-10-18 07:51:45 +08:00
|
|
|
})
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
request.csrf_cookie_needs_reset = True
|
2013-05-23 23:14:27 +08:00
|
|
|
|
|
|
|
|
2021-05-29 19:49:53 +08:00
|
|
|
class InvalidTokenFormat(Exception):
|
|
|
|
def __init__(self, reason):
|
|
|
|
self.reason = reason
|
|
|
|
|
|
|
|
|
2010-09-11 06:56:56 +08:00
|
|
|
def _sanitize_token(token):
|
2021-05-29 19:49:53 +08:00
|
|
|
if len(token) not in (CSRF_TOKEN_LENGTH, CSRF_SECRET_LENGTH):
|
|
|
|
raise InvalidTokenFormat(REASON_INCORRECT_LENGTH)
|
2021-05-29 18:53:50 +08:00
|
|
|
# Make sure all characters are in CSRF_ALLOWED_CHARS.
|
|
|
|
if invalid_token_chars_re.search(token):
|
2021-05-29 19:49:53 +08:00
|
|
|
raise InvalidTokenFormat(REASON_INVALID_CHARACTERS)
|
|
|
|
if len(token) == CSRF_SECRET_LENGTH:
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
# Older Django versions set cookies to values of CSRF_SECRET_LENGTH
|
|
|
|
# alphanumeric characters. For backwards compatibility, accept
|
2020-02-25 21:16:19 +08:00
|
|
|
# such values as unmasked secrets.
|
|
|
|
# It's easier to mask here and be consistent later, rather than add
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
# different code paths in the checks, although that might be a tad more
|
|
|
|
# efficient.
|
2020-02-25 21:16:19 +08:00
|
|
|
return _mask_cipher_secret(token)
|
2021-05-29 19:49:53 +08:00
|
|
|
return token
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
|
|
|
|
|
2020-02-25 21:16:19 +08:00
|
|
|
def _compare_masked_tokens(request_csrf_token, csrf_token):
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
# Assume both arguments are sanitized -- that is, strings of
|
|
|
|
# length CSRF_TOKEN_LENGTH, all CSRF_ALLOWED_CHARS.
|
|
|
|
return constant_time_compare(
|
2020-02-25 21:16:19 +08:00
|
|
|
_unmask_cipher_token(request_csrf_token),
|
|
|
|
_unmask_cipher_token(csrf_token),
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
)
|
2010-09-11 06:56:56 +08:00
|
|
|
|
|
|
|
|
2021-03-26 17:37:55 +08:00
|
|
|
class RejectRequest(Exception):
|
|
|
|
def __init__(self, reason):
|
|
|
|
self.reason = reason
|
|
|
|
|
|
|
|
|
2015-11-07 23:12:37 +08:00
|
|
|
class CsrfViewMiddleware(MiddlewareMixin):
|
2009-10-27 08:36:34 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Require a present and correct csrfmiddlewaretoken for POST requests that
|
|
|
|
have a CSRF cookie, and set an outgoing CSRF cookie.
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
This middleware should be used in conjunction with the {% csrf_token %}
|
|
|
|
template tag.
|
2009-10-27 08:36:34 +08:00
|
|
|
"""
|
2021-01-13 08:55:02 +08:00
|
|
|
@cached_property
|
|
|
|
def csrf_trusted_origins_hosts(self):
|
|
|
|
return [
|
|
|
|
urlparse(origin).netloc.lstrip('*')
|
|
|
|
for origin in settings.CSRF_TRUSTED_ORIGINS
|
|
|
|
]
|
|
|
|
|
2021-01-03 07:46:17 +08:00
|
|
|
@cached_property
|
|
|
|
def allowed_origins_exact(self):
|
|
|
|
return {
|
|
|
|
origin for origin in settings.CSRF_TRUSTED_ORIGINS
|
|
|
|
if '*' not in origin
|
|
|
|
}
|
|
|
|
|
|
|
|
@cached_property
|
|
|
|
def allowed_origin_subdomains(self):
|
|
|
|
"""
|
|
|
|
A mapping of allowed schemes to list of allowed netlocs, where all
|
|
|
|
subdomains of the netloc are allowed.
|
|
|
|
"""
|
|
|
|
allowed_origin_subdomains = defaultdict(list)
|
|
|
|
for parsed in (urlparse(origin) for origin in settings.CSRF_TRUSTED_ORIGINS if '*' in origin):
|
|
|
|
allowed_origin_subdomains[parsed.scheme].append(parsed.netloc.lstrip('*'))
|
|
|
|
return allowed_origin_subdomains
|
|
|
|
|
2010-10-28 19:47:15 +08:00
|
|
|
# The _accept and _reject methods currently only exist for the sake of the
|
|
|
|
# requires_csrf_token decorator.
|
|
|
|
def _accept(self, request):
|
|
|
|
# Avoid checking the request twice by adding a custom attribute to
|
|
|
|
# request. This will be relevant when both decorator and middleware
|
|
|
|
# are used.
|
|
|
|
request.csrf_processing_done = True
|
|
|
|
return None
|
|
|
|
|
|
|
|
def _reject(self, request, reason):
|
2017-07-13 12:09:18 +08:00
|
|
|
response = _get_failure_view()(request, reason=reason)
|
|
|
|
log_response(
|
2016-03-29 06:33:29 +08:00
|
|
|
'Forbidden (%s): %s', reason, request.path,
|
2017-07-13 12:09:18 +08:00
|
|
|
response=response,
|
|
|
|
request=request,
|
|
|
|
logger=logger,
|
2013-05-18 19:09:38 +08:00
|
|
|
)
|
2017-07-13 12:09:18 +08:00
|
|
|
return response
|
2010-10-28 19:47:15 +08:00
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def _get_token(self, request):
|
|
|
|
if settings.CSRF_USE_SESSIONS:
|
|
|
|
try:
|
|
|
|
return request.session.get(CSRF_SESSION_KEY)
|
|
|
|
except AttributeError:
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
'CSRF_USE_SESSIONS is enabled, but request.session is not '
|
|
|
|
'set. SessionMiddleware must appear before CsrfViewMiddleware '
|
2019-10-22 19:01:14 +08:00
|
|
|
'in MIDDLEWARE.'
|
2016-07-01 00:42:11 +08:00
|
|
|
)
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
else:
|
2016-07-01 00:42:11 +08:00
|
|
|
try:
|
|
|
|
cookie_token = request.COOKIES[settings.CSRF_COOKIE_NAME]
|
|
|
|
except KeyError:
|
|
|
|
return None
|
|
|
|
|
2021-05-31 19:26:11 +08:00
|
|
|
# This can raise InvalidTokenFormat.
|
|
|
|
csrf_token = _sanitize_token(cookie_token)
|
2021-05-29 19:49:53 +08:00
|
|
|
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
if csrf_token != cookie_token:
|
2021-05-31 19:26:11 +08:00
|
|
|
# Then the cookie token had length CSRF_SECRET_LENGTH, so flag
|
|
|
|
# to replace it with the masked version.
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
request.csrf_cookie_needs_reset = True
|
2016-07-01 00:42:11 +08:00
|
|
|
return csrf_token
|
|
|
|
|
|
|
|
def _set_token(self, request, response):
|
|
|
|
if settings.CSRF_USE_SESSIONS:
|
2018-09-01 22:32:35 +08:00
|
|
|
if request.session.get(CSRF_SESSION_KEY) != request.META['CSRF_COOKIE']:
|
|
|
|
request.session[CSRF_SESSION_KEY] = request.META['CSRF_COOKIE']
|
2016-07-01 00:42:11 +08:00
|
|
|
else:
|
|
|
|
response.set_cookie(
|
|
|
|
settings.CSRF_COOKIE_NAME,
|
|
|
|
request.META['CSRF_COOKIE'],
|
|
|
|
max_age=settings.CSRF_COOKIE_AGE,
|
|
|
|
domain=settings.CSRF_COOKIE_DOMAIN,
|
|
|
|
path=settings.CSRF_COOKIE_PATH,
|
|
|
|
secure=settings.CSRF_COOKIE_SECURE,
|
|
|
|
httponly=settings.CSRF_COOKIE_HTTPONLY,
|
2018-04-14 08:58:31 +08:00
|
|
|
samesite=settings.CSRF_COOKIE_SAMESITE,
|
2016-07-01 00:42:11 +08:00
|
|
|
)
|
|
|
|
# Set the Vary header since content varies with the CSRF cookie.
|
|
|
|
patch_vary_headers(response, ('Cookie',))
|
|
|
|
|
2021-01-03 07:46:17 +08:00
|
|
|
def _origin_verified(self, request):
|
|
|
|
request_origin = request.META['HTTP_ORIGIN']
|
2021-03-25 15:35:49 +08:00
|
|
|
try:
|
|
|
|
good_host = request.get_host()
|
|
|
|
except DisallowedHost:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
good_origin = '%s://%s' % (
|
|
|
|
'https' if request.is_secure() else 'http',
|
|
|
|
good_host,
|
|
|
|
)
|
|
|
|
if request_origin == good_origin:
|
|
|
|
return True
|
2021-01-03 07:46:17 +08:00
|
|
|
if request_origin in self.allowed_origins_exact:
|
|
|
|
return True
|
|
|
|
try:
|
|
|
|
parsed_origin = urlparse(request_origin)
|
|
|
|
except ValueError:
|
|
|
|
return False
|
|
|
|
request_scheme = parsed_origin.scheme
|
|
|
|
request_netloc = parsed_origin.netloc
|
|
|
|
return any(
|
|
|
|
is_same_domain(request_netloc, host)
|
|
|
|
for host in self.allowed_origin_subdomains.get(request_scheme, ())
|
|
|
|
)
|
|
|
|
|
2021-03-26 17:37:55 +08:00
|
|
|
def _check_referer(self, request):
|
|
|
|
referer = request.META.get('HTTP_REFERER')
|
|
|
|
if referer is None:
|
|
|
|
raise RejectRequest(REASON_NO_REFERER)
|
|
|
|
|
|
|
|
try:
|
|
|
|
referer = urlparse(referer)
|
|
|
|
except ValueError:
|
|
|
|
raise RejectRequest(REASON_MALFORMED_REFERER)
|
|
|
|
|
|
|
|
# Make sure we have a valid URL for Referer.
|
|
|
|
if '' in (referer.scheme, referer.netloc):
|
|
|
|
raise RejectRequest(REASON_MALFORMED_REFERER)
|
|
|
|
|
|
|
|
# Ensure that our Referer is also secure.
|
|
|
|
if referer.scheme != 'https':
|
|
|
|
raise RejectRequest(REASON_INSECURE_REFERER)
|
|
|
|
|
2021-03-26 17:47:32 +08:00
|
|
|
if any(
|
|
|
|
is_same_domain(referer.netloc, host)
|
|
|
|
for host in self.csrf_trusted_origins_hosts
|
|
|
|
):
|
|
|
|
return
|
|
|
|
# Allow matching the configured cookie domain.
|
2021-03-26 17:37:55 +08:00
|
|
|
good_referer = (
|
|
|
|
settings.SESSION_COOKIE_DOMAIN
|
|
|
|
if settings.CSRF_USE_SESSIONS
|
|
|
|
else settings.CSRF_COOKIE_DOMAIN
|
|
|
|
)
|
|
|
|
if good_referer is None:
|
|
|
|
# If no cookie domain is configured, allow matching the current
|
|
|
|
# host:port exactly if it's permitted by ALLOWED_HOSTS.
|
|
|
|
try:
|
|
|
|
# request.get_host() includes the port.
|
|
|
|
good_referer = request.get_host()
|
|
|
|
except DisallowedHost:
|
2021-03-26 17:47:32 +08:00
|
|
|
raise RejectRequest(REASON_BAD_REFERER % referer.geturl())
|
2021-03-26 17:37:55 +08:00
|
|
|
else:
|
|
|
|
server_port = request.get_port()
|
|
|
|
if server_port not in ('443', '80'):
|
|
|
|
good_referer = '%s:%s' % (good_referer, server_port)
|
|
|
|
|
2021-03-26 17:47:32 +08:00
|
|
|
if not is_same_domain(referer.netloc, good_referer):
|
2021-03-26 17:37:55 +08:00
|
|
|
raise RejectRequest(REASON_BAD_REFERER % referer.geturl())
|
|
|
|
|
2017-09-18 04:24:05 +08:00
|
|
|
def process_request(self, request):
|
2021-05-31 19:26:11 +08:00
|
|
|
try:
|
|
|
|
csrf_token = self._get_token(request)
|
|
|
|
except InvalidTokenFormat:
|
|
|
|
csrf_token = _get_new_csrf_token()
|
|
|
|
request.csrf_cookie_needs_reset = True
|
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
if csrf_token is not None:
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
# Use same token next time.
|
|
|
|
request.META['CSRF_COOKIE'] = csrf_token
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2017-09-18 04:24:05 +08:00
|
|
|
def process_view(self, request, callback, callback_args, callback_kwargs):
|
|
|
|
if getattr(request, 'csrf_processing_done', False):
|
|
|
|
return None
|
|
|
|
|
2010-06-08 22:35:48 +08:00
|
|
|
# Wait until request.META["CSRF_COOKIE"] has been manipulated before
|
|
|
|
# bailing out, so that get_token still works
|
|
|
|
if getattr(callback, 'csrf_exempt', False):
|
|
|
|
return None
|
|
|
|
|
2016-05-02 20:35:05 +08:00
|
|
|
# Assume that anything not defined as 'safe' by RFC7231 needs protection
|
2021-04-03 17:02:47 +08:00
|
|
|
if request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'):
|
|
|
|
return self._accept(request)
|
|
|
|
|
|
|
|
if getattr(request, '_dont_enforce_csrf_checks', False):
|
|
|
|
# Mechanism to turn off CSRF checks for test suite. It comes after
|
|
|
|
# the creation of CSRF cookies, so that everything else continues
|
|
|
|
# to work exactly the same (e.g. cookies are sent, etc.), but
|
|
|
|
# before any branches that call reject().
|
|
|
|
return self._accept(request)
|
|
|
|
|
|
|
|
# Reject the request if the Origin header doesn't match an allowed
|
|
|
|
# value.
|
|
|
|
if 'HTTP_ORIGIN' in request.META:
|
|
|
|
if not self._origin_verified(request):
|
|
|
|
return self._reject(request, REASON_BAD_ORIGIN % request.META['HTTP_ORIGIN'])
|
|
|
|
elif request.is_secure():
|
|
|
|
# If the Origin header wasn't provided, reject HTTPS requests if
|
|
|
|
# the Referer header doesn't match an allowed value.
|
|
|
|
#
|
|
|
|
# Suppose user visits http://example.com/
|
|
|
|
# An active network attacker (man-in-the-middle, MITM) sends a
|
|
|
|
# POST form that targets https://example.com/detonate-bomb/ and
|
|
|
|
# submits it via JavaScript.
|
|
|
|
#
|
|
|
|
# The attacker will need to provide a CSRF cookie and token, but
|
|
|
|
# that's no problem for a MITM and the session-independent secret
|
|
|
|
# we're using. So the MITM can circumvent the CSRF protection. This
|
|
|
|
# is true for any HTTP connection, but anyone using HTTPS expects
|
|
|
|
# better! For this reason, for https://example.com/ we need
|
|
|
|
# additional protection that treats http://example.com/ as
|
|
|
|
# completely untrusted. Under HTTPS, Barth et al. found that the
|
|
|
|
# Referer header is missing for same-domain requests in only about
|
|
|
|
# 0.2% of cases or less, so we can use strict Referer checking.
|
|
|
|
try:
|
|
|
|
self._check_referer(request)
|
|
|
|
except RejectRequest as exc:
|
|
|
|
return self._reject(request, exc.reason)
|
|
|
|
|
|
|
|
# Access csrf_token via self._get_token() as rotate_token() may have
|
|
|
|
# been called by an authentication middleware during the
|
|
|
|
# process_request() phase.
|
2021-05-31 19:26:11 +08:00
|
|
|
try:
|
|
|
|
csrf_token = self._get_token(request)
|
|
|
|
except InvalidTokenFormat as exc:
|
|
|
|
return self._reject(request, f'CSRF cookie {exc.reason}.')
|
|
|
|
|
2021-04-03 17:02:47 +08:00
|
|
|
if csrf_token is None:
|
|
|
|
# No CSRF cookie. For POST requests, we insist on a CSRF cookie,
|
|
|
|
# and in this way we can avoid all CSRF attacks, including login
|
|
|
|
# CSRF.
|
|
|
|
return self._reject(request, REASON_NO_CSRF_COOKIE)
|
|
|
|
|
|
|
|
# Check non-cookie token for match.
|
|
|
|
request_csrf_token = ''
|
|
|
|
if request.method == 'POST':
|
|
|
|
try:
|
|
|
|
request_csrf_token = request.POST.get('csrfmiddlewaretoken', '')
|
|
|
|
except OSError:
|
|
|
|
# Handle a broken connection before we've completed reading the
|
|
|
|
# POST data. process_view shouldn't raise any exceptions, so
|
|
|
|
# we'll ignore and serve the user a 403 (assuming they're still
|
|
|
|
# listening, which they probably aren't because of the error).
|
|
|
|
pass
|
|
|
|
|
|
|
|
if request_csrf_token == '':
|
|
|
|
# Fall back to X-CSRFToken, to make things easier for AJAX, and
|
|
|
|
# possible for PUT/DELETE.
|
2021-05-29 19:49:53 +08:00
|
|
|
try:
|
|
|
|
request_csrf_token = request.META[settings.CSRF_HEADER_NAME]
|
|
|
|
except KeyError:
|
|
|
|
return self._reject(request, REASON_CSRF_TOKEN_MISSING)
|
|
|
|
|
|
|
|
try:
|
|
|
|
request_csrf_token = _sanitize_token(request_csrf_token)
|
|
|
|
except InvalidTokenFormat as exc:
|
|
|
|
return self._reject(request, f'CSRF token {exc.reason}.')
|
2021-04-03 17:02:47 +08:00
|
|
|
|
|
|
|
if not _compare_masked_tokens(request_csrf_token, csrf_token):
|
2021-05-29 19:49:53 +08:00
|
|
|
return self._reject(request, REASON_CSRF_TOKEN_INCORRECT)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
2010-10-28 19:47:15 +08:00
|
|
|
return self._accept(request)
|
2009-10-27 08:36:34 +08:00
|
|
|
|
|
|
|
def process_response(self, request, response):
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
if not getattr(request, 'csrf_cookie_needs_reset', False):
|
|
|
|
if getattr(response, 'csrf_cookie_set', False):
|
|
|
|
return response
|
2009-10-27 08:36:34 +08:00
|
|
|
|
|
|
|
if not request.META.get("CSRF_COOKIE_USED", False):
|
|
|
|
return response
|
|
|
|
|
2012-02-11 12:18:15 +08:00
|
|
|
# Set the CSRF cookie even if it's already set, so we renew
|
|
|
|
# the expiry timer.
|
2016-07-01 00:42:11 +08:00
|
|
|
self._set_token(request, response)
|
Fixed #20869 -- made CSRF tokens change every request by salt-encrypting them
Note that the cookie is not changed every request, just the token retrieved
by the `get_token()` method (used also by the `{% csrf_token %}` tag).
While at it, made token validation strict: Where, before, any length was
accepted and non-ASCII chars were ignored, we now treat anything other than
`[A-Za-z0-9]{64}` as invalid (except for 32-char tokens, which, for
backwards-compatibility, are accepted and replaced by 64-char ones).
Thanks Trac user patrys for reporting, github user adambrenecki
for initial patch, Tim Graham for help, and Curtis Maloney,
Collin Anderson, Florian Apolloner, Markus Holtermann & Jon Dufresne
for reviews.
2015-11-08 00:35:45 +08:00
|
|
|
response.csrf_cookie_set = True
|
2009-10-27 08:36:34 +08:00
|
|
|
return response
|