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 re
|
2008-12-03 06:40:00 +08:00
|
|
|
|
2011-10-14 02:51:33 +08:00
|
|
|
from django.conf import settings
|
2018-09-01 22:32:35 +08:00
|
|
|
from django.contrib.sessions.backends.cache import SessionStore
|
2016-07-01 00:42:11 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2021-07-23 18:26:22 +08:00
|
|
|
from django.http import HttpRequest, HttpResponse, UnreadablePostError
|
2015-04-24 14:24:38 +08:00
|
|
|
from django.middleware.csrf import (
|
2021-06-02 18:32:01 +08:00
|
|
|
CSRF_ALLOWED_CHARS, CSRF_SESSION_KEY, CSRF_TOKEN_LENGTH, REASON_BAD_ORIGIN,
|
2021-05-29 19:49:53 +08:00
|
|
|
REASON_CSRF_TOKEN_MISSING, REASON_NO_CSRF_COOKIE, CsrfViewMiddleware,
|
2021-07-09 13:03:52 +08:00
|
|
|
InvalidTokenFormat, RejectRequest, _does_token_match, _mask_cipher_secret,
|
|
|
|
_sanitize_token, _unmask_cipher_token, get_token, rotate_token,
|
2015-04-24 14:24:38 +08:00
|
|
|
)
|
2015-04-18 05:38:20 +08:00
|
|
|
from django.test import SimpleTestCase, override_settings
|
2016-12-01 01:33:00 +08:00
|
|
|
from django.views.decorators.csrf import csrf_exempt, requires_csrf_token
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2016-12-01 01:33:00 +08:00
|
|
|
from .views import (
|
2021-07-16 22:54:42 +08:00
|
|
|
ensure_csrf_cookie_view, ensured_and_protected_view,
|
|
|
|
non_token_view_using_request_processor, post_form_view, protected_view,
|
|
|
|
sandwiched_rotate_token_view, token_view,
|
2016-12-01 01:33:00 +08:00
|
|
|
)
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
|
2021-06-02 18:32:01 +08:00
|
|
|
# This is a test (unmasked) CSRF cookie / secret.
|
|
|
|
TEST_SECRET = 'lcccccccX2kcccccccY2jcccccccssIC'
|
|
|
|
# Two masked versions of TEST_SECRET for testing purposes.
|
|
|
|
MASKED_TEST_SECRET1 = '1bcdefghij2bcdefghij3bcdefghij4bcdefghij5bcdefghij6bcdefghijABCD'
|
|
|
|
MASKED_TEST_SECRET2 = '2JgchWvM1tpxT2lfz9aydoXW9yT1DN3NdLiejYxOOlzzV4nhBbYqmqZYbAV3V5Bf'
|
|
|
|
|
|
|
|
|
|
|
|
class CsrfFunctionTests(SimpleTestCase):
|
|
|
|
|
|
|
|
def test_unmask_cipher_token(self):
|
|
|
|
cases = [
|
|
|
|
(TEST_SECRET, MASKED_TEST_SECRET1),
|
|
|
|
(TEST_SECRET, MASKED_TEST_SECRET2),
|
|
|
|
(
|
|
|
|
32 * 'a',
|
|
|
|
'vFioG3XOLyGyGsPRFyB9iYUs341ufzIEvFioG3XOLyGyGsPRFyB9iYUs341ufzIE',
|
|
|
|
),
|
|
|
|
(32 * 'a', 64 * 'a'),
|
|
|
|
(32 * 'a', 64 * 'b'),
|
|
|
|
(32 * 'b', 32 * 'a' + 32 * 'b'),
|
|
|
|
(32 * 'b', 32 * 'b' + 32 * 'c'),
|
|
|
|
(32 * 'c', 32 * 'a' + 32 * 'c'),
|
|
|
|
]
|
|
|
|
for secret, masked_secret in cases:
|
|
|
|
with self.subTest(masked_secret=masked_secret):
|
|
|
|
actual = _unmask_cipher_token(masked_secret)
|
|
|
|
self.assertEqual(actual, secret)
|
|
|
|
|
|
|
|
# This method depends on _unmask_cipher_token() being correct.
|
|
|
|
def assertMaskedSecretCorrect(self, masked_secret, secret):
|
|
|
|
"""Test that a string is a valid masked version of a secret."""
|
|
|
|
self.assertEqual(len(masked_secret), CSRF_TOKEN_LENGTH)
|
|
|
|
self.assertTrue(
|
|
|
|
set(masked_secret).issubset(set(CSRF_ALLOWED_CHARS)),
|
|
|
|
msg=f'invalid characters in {masked_secret!r}',
|
|
|
|
)
|
|
|
|
actual = _unmask_cipher_token(masked_secret)
|
|
|
|
self.assertEqual(actual, secret)
|
|
|
|
|
|
|
|
def test_mask_cipher_secret(self):
|
|
|
|
cases = [
|
|
|
|
32 * 'a',
|
|
|
|
TEST_SECRET,
|
|
|
|
'da4SrUiHJYoJ0HYQ0vcgisoIuFOxx4ER',
|
|
|
|
]
|
|
|
|
for secret in cases:
|
|
|
|
with self.subTest(secret=secret):
|
|
|
|
masked = _mask_cipher_secret(secret)
|
|
|
|
self.assertMaskedSecretCorrect(masked, secret)
|
|
|
|
|
2021-07-09 13:03:52 +08:00
|
|
|
def test_get_token_csrf_cookie_set(self):
|
|
|
|
request = HttpRequest()
|
|
|
|
request.META['CSRF_COOKIE'] = MASKED_TEST_SECRET1
|
|
|
|
self.assertNotIn('CSRF_COOKIE_NEEDS_UPDATE', request.META)
|
|
|
|
token = get_token(request)
|
|
|
|
self.assertNotEqual(token, MASKED_TEST_SECRET1)
|
|
|
|
self.assertMaskedSecretCorrect(token, TEST_SECRET)
|
|
|
|
# The existing cookie is preserved.
|
|
|
|
self.assertEqual(request.META['CSRF_COOKIE'], MASKED_TEST_SECRET1)
|
|
|
|
self.assertIs(request.META['CSRF_COOKIE_NEEDS_UPDATE'], True)
|
|
|
|
|
|
|
|
def test_get_token_csrf_cookie_not_set(self):
|
|
|
|
request = HttpRequest()
|
|
|
|
self.assertNotIn('CSRF_COOKIE', request.META)
|
|
|
|
self.assertNotIn('CSRF_COOKIE_NEEDS_UPDATE', request.META)
|
|
|
|
token = get_token(request)
|
|
|
|
cookie = request.META['CSRF_COOKIE']
|
|
|
|
self.assertEqual(len(cookie), CSRF_TOKEN_LENGTH)
|
|
|
|
unmasked_cookie = _unmask_cipher_token(cookie)
|
|
|
|
self.assertMaskedSecretCorrect(token, unmasked_cookie)
|
|
|
|
self.assertIs(request.META['CSRF_COOKIE_NEEDS_UPDATE'], True)
|
|
|
|
|
|
|
|
def test_rotate_token(self):
|
|
|
|
request = HttpRequest()
|
|
|
|
request.META['CSRF_COOKIE'] = MASKED_TEST_SECRET1
|
|
|
|
self.assertNotIn('CSRF_COOKIE_NEEDS_UPDATE', request.META)
|
|
|
|
rotate_token(request)
|
|
|
|
# The underlying secret was changed.
|
|
|
|
cookie = request.META['CSRF_COOKIE']
|
|
|
|
self.assertEqual(len(cookie), CSRF_TOKEN_LENGTH)
|
|
|
|
unmasked_cookie = _unmask_cipher_token(cookie)
|
|
|
|
self.assertNotEqual(unmasked_cookie, TEST_SECRET)
|
|
|
|
self.assertIs(request.META['CSRF_COOKIE_NEEDS_UPDATE'], True)
|
|
|
|
|
|
|
|
def test_sanitize_token_masked(self):
|
|
|
|
# Tokens of length CSRF_TOKEN_LENGTH are preserved.
|
|
|
|
cases = [
|
|
|
|
(MASKED_TEST_SECRET1, MASKED_TEST_SECRET1),
|
|
|
|
(64 * 'a', 64 * 'a'),
|
|
|
|
]
|
|
|
|
for token, expected in cases:
|
|
|
|
with self.subTest(token=token):
|
|
|
|
actual = _sanitize_token(token)
|
|
|
|
self.assertEqual(actual, expected)
|
|
|
|
|
|
|
|
def test_sanitize_token_unmasked(self):
|
|
|
|
# A token of length CSRF_SECRET_LENGTH is masked.
|
|
|
|
actual = _sanitize_token(TEST_SECRET)
|
|
|
|
self.assertMaskedSecretCorrect(actual, TEST_SECRET)
|
|
|
|
|
|
|
|
def test_sanitize_token_invalid(self):
|
|
|
|
cases = [
|
|
|
|
(64 * '*', 'has invalid characters'),
|
|
|
|
(16 * 'a', 'has incorrect length'),
|
|
|
|
]
|
|
|
|
for token, expected_message in cases:
|
|
|
|
with self.subTest(token=token):
|
|
|
|
with self.assertRaisesMessage(InvalidTokenFormat, expected_message):
|
|
|
|
_sanitize_token(token)
|
|
|
|
|
|
|
|
def test_does_token_match(self):
|
|
|
|
cases = [
|
|
|
|
((MASKED_TEST_SECRET1, MASKED_TEST_SECRET2), True),
|
|
|
|
((MASKED_TEST_SECRET1, 64 * 'a'), False),
|
|
|
|
]
|
|
|
|
for (token1, token2), expected in cases:
|
|
|
|
with self.subTest(token1=token1, token2=token2):
|
|
|
|
actual = _does_token_match(token1, token2)
|
|
|
|
self.assertIs(actual, expected)
|
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2021-07-04 14:29:52 +08:00
|
|
|
class TestingSessionStore(SessionStore):
|
|
|
|
"""
|
|
|
|
A version of SessionStore that stores what cookie values are passed to
|
|
|
|
set_cookie() when CSRF_USE_SESSIONS=True.
|
|
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
# This is a list of the cookie values passed to set_cookie() over
|
|
|
|
# the course of the request-response.
|
|
|
|
self._cookies_set = []
|
|
|
|
|
|
|
|
def __setitem__(self, key, value):
|
|
|
|
super().__setitem__(key, value)
|
|
|
|
self._cookies_set.append(value)
|
|
|
|
|
|
|
|
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
class TestingHttpRequest(HttpRequest):
|
|
|
|
"""
|
2021-07-04 14:29:52 +08:00
|
|
|
A version of HttpRequest that lets one track and change some things more
|
|
|
|
easily.
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
"""
|
2016-07-01 00:42:11 +08:00
|
|
|
def __init__(self):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__()
|
2021-07-04 14:29:52 +08:00
|
|
|
self.session = TestingSessionStore()
|
2016-07-01 00:42:11 +08:00
|
|
|
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
def is_secure(self):
|
2011-12-17 08:17:26 +08:00
|
|
|
return getattr(self, '_is_secure_override', False)
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
|
2013-11-03 12:36:09 +08:00
|
|
|
|
2021-07-23 18:13:31 +08:00
|
|
|
class PostErrorRequest(TestingHttpRequest):
|
|
|
|
"""
|
|
|
|
TestingHttpRequest that can raise errors when accessing POST data.
|
|
|
|
"""
|
|
|
|
post_error = None
|
|
|
|
|
|
|
|
def _get_post(self):
|
|
|
|
if self.post_error is not None:
|
|
|
|
raise self.post_error
|
|
|
|
return self._post
|
|
|
|
|
|
|
|
def _set_post(self, post):
|
|
|
|
self._post = post
|
|
|
|
|
|
|
|
POST = property(_get_post, _set_post)
|
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class CsrfViewMiddlewareTestMixin:
|
2016-07-01 00:42:11 +08:00
|
|
|
"""
|
|
|
|
Shared methods and tests for session-based and cookie-based tokens.
|
|
|
|
"""
|
|
|
|
|
2021-06-02 18:32:01 +08:00
|
|
|
_csrf_id_cookie = MASKED_TEST_SECRET1
|
2021-06-02 18:34:47 +08:00
|
|
|
_csrf_id_token = MASKED_TEST_SECRET2
|
2008-12-03 06:40:00 +08:00
|
|
|
|
2021-06-23 22:16:40 +08:00
|
|
|
def _set_csrf_cookie(self, req, cookie):
|
|
|
|
raise NotImplementedError('This method must be implemented by a subclass.')
|
|
|
|
|
2021-06-29 22:07:28 +08:00
|
|
|
def _read_csrf_cookie(self, req, resp):
|
|
|
|
"""
|
|
|
|
Return the CSRF cookie as a string, or False if no cookie is present.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError('This method must be implemented by a subclass.')
|
|
|
|
|
2021-07-04 14:29:52 +08:00
|
|
|
def _get_cookies_set(self, req, resp):
|
|
|
|
"""
|
|
|
|
Return a list of the cookie values passed to set_cookie() over the
|
|
|
|
course of the request-response.
|
|
|
|
"""
|
|
|
|
raise NotImplementedError('This method must be implemented by a subclass.')
|
|
|
|
|
|
|
|
def assertCookiesSet(self, req, resp, expected_secrets):
|
|
|
|
"""
|
|
|
|
Assert that set_cookie() was called with the given sequence of secrets.
|
|
|
|
"""
|
|
|
|
cookies_set = self._get_cookies_set(req, resp)
|
|
|
|
secrets_set = [_unmask_cipher_token(cookie) for cookie in cookies_set]
|
|
|
|
self.assertEqual(secrets_set, expected_secrets)
|
|
|
|
|
2021-07-23 18:13:31 +08:00
|
|
|
def _get_request(self, method=None, cookie=None, request_class=None):
|
2021-06-23 22:02:07 +08:00
|
|
|
if method is None:
|
|
|
|
method = 'GET'
|
2021-07-23 18:13:31 +08:00
|
|
|
if request_class is None:
|
|
|
|
request_class = TestingHttpRequest
|
|
|
|
req = request_class()
|
2021-06-23 22:02:07 +08:00
|
|
|
req.method = method
|
|
|
|
if cookie is not None:
|
|
|
|
self._set_csrf_cookie(req, cookie)
|
2021-03-22 15:22:58 +08:00
|
|
|
return req
|
2008-12-03 06:40:00 +08:00
|
|
|
|
2021-06-23 22:34:48 +08:00
|
|
|
def _get_csrf_cookie_request(
|
|
|
|
self, method=None, cookie=None, post_token=None, meta_token=None,
|
2021-07-23 18:13:31 +08:00
|
|
|
token_header=None, request_class=None,
|
2021-06-11 01:20:08 +08:00
|
|
|
):
|
|
|
|
"""
|
2021-06-23 22:34:48 +08:00
|
|
|
The method argument defaults to "GET". The cookie argument defaults to
|
|
|
|
this class's default test cookie. The post_token and meta_token
|
|
|
|
arguments are included in the request's req.POST and req.META headers,
|
|
|
|
respectively, when that argument is provided and non-None. The
|
|
|
|
token_header argument is the header key to use for req.META, defaults
|
|
|
|
to "HTTP_X_CSRFTOKEN".
|
2021-06-11 01:20:08 +08:00
|
|
|
"""
|
2021-06-23 22:34:48 +08:00
|
|
|
if cookie is None:
|
|
|
|
cookie = self._csrf_id_cookie
|
2021-06-11 01:20:08 +08:00
|
|
|
if token_header is None:
|
|
|
|
token_header = 'HTTP_X_CSRFTOKEN'
|
2021-07-23 18:13:31 +08:00
|
|
|
req = self._get_request(
|
|
|
|
method=method,
|
|
|
|
cookie=cookie,
|
|
|
|
request_class=request_class,
|
|
|
|
)
|
2021-06-11 01:20:08 +08:00
|
|
|
if post_token is not None:
|
|
|
|
req.POST['csrfmiddlewaretoken'] = post_token
|
|
|
|
if meta_token is not None:
|
|
|
|
req.META[token_header] = meta_token
|
2008-12-03 07:00:06 +08:00
|
|
|
return req
|
|
|
|
|
2021-06-23 22:34:48 +08:00
|
|
|
def _get_POST_csrf_cookie_request(
|
|
|
|
self, cookie=None, post_token=None, meta_token=None, token_header=None,
|
2021-07-23 18:13:31 +08:00
|
|
|
request_class=None,
|
2021-06-23 22:34:48 +08:00
|
|
|
):
|
|
|
|
return self._get_csrf_cookie_request(
|
|
|
|
method='POST', cookie=cookie, post_token=post_token,
|
|
|
|
meta_token=meta_token, token_header=token_header,
|
2021-07-23 18:13:31 +08:00
|
|
|
request_class=request_class,
|
2021-06-23 22:34:48 +08:00
|
|
|
)
|
|
|
|
|
2021-07-23 18:13:31 +08:00
|
|
|
def _get_POST_request_with_token(self, cookie=None, request_class=None):
|
2021-06-02 19:02:52 +08:00
|
|
|
"""The cookie argument defaults to this class's default test cookie."""
|
2021-07-23 18:13:31 +08:00
|
|
|
return self._get_POST_csrf_cookie_request(
|
|
|
|
cookie=cookie,
|
|
|
|
post_token=self._csrf_id_token,
|
|
|
|
request_class=request_class,
|
|
|
|
)
|
2008-12-03 07:00:06 +08:00
|
|
|
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
def _check_token_present(self, response, csrf_id=None):
|
2016-12-29 23:27:49 +08:00
|
|
|
text = str(response.content, response.charset)
|
2018-05-03 14:57:18 +08:00
|
|
|
match = re.search('name="csrfmiddlewaretoken" value="(.*?)"', text)
|
2021-06-02 18:34:47 +08:00
|
|
|
csrf_token = csrf_id or self._csrf_id_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
|
|
|
self.assertTrue(
|
2021-07-01 00:17:58 +08:00
|
|
|
match and _does_token_match(csrf_token, match[1]),
|
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
|
|
|
"Could not find csrfmiddlewaretoken to match %s" % csrf_token
|
|
|
|
)
|
2008-12-03 08:31:31 +08:00
|
|
|
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
def test_process_response_get_token_not_used(self):
|
2008-12-03 06:40:00 +08:00
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
If get_token() is not called, the view middleware does not
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
add a cookie.
|
2008-12-03 06:40:00 +08:00
|
|
|
"""
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
# This is important to make pages cacheable. Pages which do call
|
|
|
|
# get_token(), assuming they use the token, are not cacheable because
|
|
|
|
# the token is specific to the user
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
# non_token_view_using_request_processor does not call get_token(), but
|
|
|
|
# does use the csrf request processor. By using this, we are testing
|
|
|
|
# that the view processor is properly lazy and doesn't call get_token()
|
|
|
|
# until needed.
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(non_token_view_using_request_processor)
|
|
|
|
mw.process_request(req)
|
|
|
|
mw.process_view(req, non_token_view_using_request_processor, (), {})
|
|
|
|
resp = mw(req)
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
|
2021-06-29 22:07:28 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
2016-06-17 02:19:18 +08:00
|
|
|
self.assertIs(csrf_cookie, False)
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
|
2021-05-31 19:24:02 +08:00
|
|
|
def _check_bad_or_missing_cookie(self, cookie, expected):
|
|
|
|
"""Passing None for cookie includes no cookie."""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request(method='POST', cookie=cookie)
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
2018-04-28 21:20:27 +08:00
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
2019-09-27 01:06:35 +08:00
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertEqual(403, resp.status_code)
|
2021-05-31 19:24:02 +08:00
|
|
|
self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % expected)
|
|
|
|
|
|
|
|
def test_no_csrf_cookie(self):
|
|
|
|
"""
|
|
|
|
If no CSRF cookies is present, the middleware rejects the incoming
|
|
|
|
request. This will stop login CSRF.
|
|
|
|
"""
|
|
|
|
self._check_bad_or_missing_cookie(None, REASON_NO_CSRF_COOKIE)
|
2008-12-03 07:00:06 +08:00
|
|
|
|
2021-06-08 17:19:24 +08:00
|
|
|
def _check_bad_or_missing_token(
|
|
|
|
self, expected, post_token=None, meta_token=None, token_header=None,
|
|
|
|
):
|
|
|
|
req = self._get_POST_csrf_cookie_request(
|
|
|
|
post_token=post_token,
|
|
|
|
meta_token=meta_token,
|
|
|
|
token_header=token_header,
|
|
|
|
)
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
2018-04-28 21:20:27 +08:00
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
2019-09-27 01:06:35 +08:00
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertEqual(403, resp.status_code)
|
2021-05-31 17:44:07 +08:00
|
|
|
self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % expected)
|
|
|
|
|
2021-06-11 01:14:14 +08:00
|
|
|
def test_csrf_cookie_bad_or_missing_token(self):
|
2021-05-31 17:44:07 +08:00
|
|
|
"""
|
2021-06-11 01:14:14 +08:00
|
|
|
If a CSRF cookie is present but the token is missing or invalid, the
|
2021-05-31 17:44:07 +08:00
|
|
|
middleware rejects the incoming request.
|
|
|
|
"""
|
2021-06-11 01:14:14 +08:00
|
|
|
cases = [
|
2021-06-08 17:19:24 +08:00
|
|
|
(None, None, REASON_CSRF_TOKEN_MISSING),
|
2021-06-09 00:33:26 +08:00
|
|
|
(16 * 'a', None, 'CSRF token from POST has incorrect length.'),
|
|
|
|
(64 * '*', None, 'CSRF token from POST has invalid characters.'),
|
|
|
|
(64 * 'a', None, 'CSRF token from POST incorrect.'),
|
|
|
|
(
|
|
|
|
None,
|
|
|
|
16 * 'a',
|
|
|
|
"CSRF token from the 'X-Csrftoken' HTTP header has incorrect length.",
|
|
|
|
),
|
|
|
|
(
|
|
|
|
None,
|
|
|
|
64 * '*',
|
|
|
|
"CSRF token from the 'X-Csrftoken' HTTP header has invalid characters.",
|
|
|
|
),
|
|
|
|
(
|
|
|
|
None,
|
|
|
|
64 * 'a',
|
|
|
|
"CSRF token from the 'X-Csrftoken' HTTP header incorrect.",
|
|
|
|
),
|
2021-06-11 01:14:14 +08:00
|
|
|
]
|
2021-06-08 17:19:24 +08:00
|
|
|
for post_token, meta_token, expected in cases:
|
|
|
|
with self.subTest(post_token=post_token, meta_token=meta_token):
|
|
|
|
self._check_bad_or_missing_token(
|
|
|
|
expected,
|
|
|
|
post_token=post_token,
|
|
|
|
meta_token=meta_token,
|
|
|
|
)
|
|
|
|
|
|
|
|
@override_settings(CSRF_HEADER_NAME='HTTP_X_CSRFTOKEN_CUSTOMIZED')
|
|
|
|
def test_csrf_cookie_bad_token_custom_header(self):
|
|
|
|
"""
|
|
|
|
If a CSRF cookie is present and an invalid token is passed via a
|
|
|
|
custom CSRF_HEADER_NAME, the middleware rejects the incoming request.
|
|
|
|
"""
|
2021-06-09 00:33:26 +08:00
|
|
|
expected = (
|
|
|
|
"CSRF token from the 'X-Csrftoken-Customized' HTTP header has "
|
|
|
|
"incorrect length."
|
|
|
|
)
|
2021-06-08 17:19:24 +08:00
|
|
|
self._check_bad_or_missing_token(
|
|
|
|
expected,
|
|
|
|
meta_token=16 * 'a',
|
|
|
|
token_header='HTTP_X_CSRFTOKEN_CUSTOMIZED',
|
|
|
|
)
|
2008-12-03 07:00:06 +08:00
|
|
|
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
def test_process_request_csrf_cookie_and_token(self):
|
2008-12-03 07:00:06 +08:00
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
If both a cookie and a token is present, the middleware lets it through.
|
2008-12-03 07:00:06 +08:00
|
|
|
"""
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
req = self._get_POST_request_with_token()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
2008-12-03 08:34:18 +08:00
|
|
|
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
def test_process_request_csrf_cookie_no_token_exempt_view(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
If a CSRF cookie is present and no token, but the csrf_exempt decorator
|
|
|
|
has been applied to the view, the middleware lets it through
|
2008-12-03 08:34:18 +08:00
|
|
|
"""
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
req = self._get_POST_csrf_cookie_request()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, csrf_exempt(post_form_view), (), {})
|
|
|
|
self.assertIsNone(resp)
|
2008-12-03 08:34:18 +08:00
|
|
|
|
2011-02-09 10:06:27 +08:00
|
|
|
def test_csrf_token_in_header(self):
|
2008-12-03 08:34:18 +08:00
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
The token may be passed in a header instead of in the form.
|
2008-12-03 08:34:18 +08:00
|
|
|
"""
|
2021-06-02 18:34:47 +08:00
|
|
|
req = self._get_POST_csrf_cookie_request(meta_token=self._csrf_id_token)
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
2015-02-22 05:57:02 +08:00
|
|
|
|
|
|
|
@override_settings(CSRF_HEADER_NAME='HTTP_X_CSRFTOKEN_CUSTOMIZED')
|
|
|
|
def test_csrf_token_in_header_with_customized_name(self):
|
|
|
|
"""
|
|
|
|
settings.CSRF_HEADER_NAME can be used to customize the CSRF header name
|
|
|
|
"""
|
2021-06-11 01:20:08 +08:00
|
|
|
req = self._get_POST_csrf_cookie_request(
|
2021-06-02 18:34:47 +08:00
|
|
|
meta_token=self._csrf_id_token,
|
2021-06-11 01:20:08 +08:00
|
|
|
token_header='HTTP_X_CSRFTOKEN_CUSTOMIZED',
|
|
|
|
)
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
|
2011-05-10 07:45:54 +08:00
|
|
|
def test_put_and_delete_rejected(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
HTTP PUT and DELETE methods have protection
|
2011-05-10 07:45:54 +08:00
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request(method='PUT')
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
2018-04-28 21:20:27 +08:00
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
2019-09-27 01:06:35 +08:00
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertEqual(403, resp.status_code)
|
2018-04-28 21:20:27 +08:00
|
|
|
self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)
|
2011-05-10 07:45:54 +08:00
|
|
|
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request(method='DELETE')
|
2018-04-28 21:20:27 +08:00
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
2019-09-27 01:06:35 +08:00
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertEqual(403, resp.status_code)
|
2018-04-28 21:20:27 +08:00
|
|
|
self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % REASON_NO_CSRF_COOKIE)
|
2011-05-10 07:45:54 +08:00
|
|
|
|
|
|
|
def test_put_and_delete_allowed(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
HTTP PUT and DELETE can get through with X-CSRFToken and a cookie.
|
2011-05-10 07:45:54 +08:00
|
|
|
"""
|
2021-06-23 22:34:48 +08:00
|
|
|
req = self._get_csrf_cookie_request(method='PUT', meta_token=self._csrf_id_token)
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
2011-05-10 07:45:54 +08:00
|
|
|
|
2021-06-23 22:34:48 +08:00
|
|
|
req = self._get_csrf_cookie_request(method='DELETE', meta_token=self._csrf_id_token)
|
2019-09-27 01:06:35 +08:00
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
2011-05-10 07:45:54 +08:00
|
|
|
|
2021-07-04 14:29:52 +08:00
|
|
|
def test_rotate_token_triggers_second_reset(self):
|
|
|
|
"""
|
|
|
|
If rotate_token() is called after the token is reset in
|
|
|
|
CsrfViewMiddleware's process_response() and before another call to
|
|
|
|
the same process_response(), the cookie is reset a second time.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
resp = sandwiched_rotate_token_view(req)
|
|
|
|
self.assertContains(resp, 'OK')
|
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
actual_secret = _unmask_cipher_token(csrf_cookie)
|
|
|
|
# set_cookie() was called a second time with a different secret.
|
|
|
|
self.assertCookiesSet(req, resp, [TEST_SECRET, actual_secret])
|
|
|
|
self.assertNotEqual(actual_secret, TEST_SECRET)
|
|
|
|
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
# Tests for the template tag method
|
|
|
|
def test_token_node_no_csrf_cookie(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
CsrfTokenNode works when no CSRF cookie is set.
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
resp = token_view(req)
|
2015-04-24 14:24:38 +08:00
|
|
|
|
|
|
|
token = get_token(req)
|
|
|
|
self.assertIsNotNone(token)
|
|
|
|
self._check_token_present(resp, token)
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
|
2010-09-11 06:56:56 +08:00
|
|
|
def test_token_node_empty_csrf_cookie(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
A new token is sent if the csrf_cookie is the empty string.
|
2010-09-11 06:56:56 +08:00
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2021-06-29 22:18:17 +08:00
|
|
|
self._set_csrf_cookie(req, '')
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_view(req, token_view, (), {})
|
2010-09-11 06:56:56 +08:00
|
|
|
resp = token_view(req)
|
|
|
|
|
2015-04-24 14:24:38 +08:00
|
|
|
token = get_token(req)
|
|
|
|
self.assertIsNotNone(token)
|
|
|
|
self._check_token_present(resp, token)
|
2010-09-11 06:56:56 +08:00
|
|
|
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
def test_token_node_with_csrf_cookie(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
CsrfTokenNode works when a CSRF cookie is set.
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
"""
|
2021-06-23 22:34:48 +08:00
|
|
|
req = self._get_csrf_cookie_request()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
mw.process_view(req, token_view, (), {})
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
resp = token_view(req)
|
|
|
|
self._check_token_present(resp)
|
|
|
|
|
2010-06-08 22:35:48 +08:00
|
|
|
def test_get_token_for_exempt_view(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
get_token still works for a view decorated with 'csrf_exempt'.
|
2010-06-08 22:35:48 +08:00
|
|
|
"""
|
2021-06-23 22:34:48 +08:00
|
|
|
req = self._get_csrf_cookie_request()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
mw.process_view(req, csrf_exempt(token_view), (), {})
|
2010-06-08 22:35:48 +08:00
|
|
|
resp = token_view(req)
|
|
|
|
self._check_token_present(resp)
|
|
|
|
|
2010-10-28 19:47:15 +08:00
|
|
|
def test_get_token_for_requires_csrf_token_view(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
get_token() works for a view decorated solely with requires_csrf_token.
|
2010-10-28 19:47:15 +08:00
|
|
|
"""
|
2021-06-23 22:34:48 +08:00
|
|
|
req = self._get_csrf_cookie_request()
|
2010-10-28 19:47:15 +08:00
|
|
|
resp = requires_csrf_token(token_view)(req)
|
|
|
|
self._check_token_present(resp)
|
|
|
|
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
def test_token_node_with_new_csrf_cookie(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
CsrfTokenNode works when a CSRF cookie is created by
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
the middleware (when one was not already present)
|
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_view(req, token_view, (), {})
|
|
|
|
resp = mw(req)
|
2021-06-29 22:07:28 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
self._check_token_present(resp, csrf_id=csrf_cookie)
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +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 test_cookie_not_reset_on_accepted_request(self):
|
|
|
|
"""
|
|
|
|
The csrf token used in posts is changed on every request (although
|
|
|
|
stays equivalent). The csrf cookie should not change on accepted
|
|
|
|
requests. If it appears in the response, it should keep its value.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
mw.process_view(req, token_view, (), {})
|
|
|
|
resp = mw(req)
|
2021-06-29 22:07:28 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
self.assertEqual(
|
|
|
|
csrf_cookie, self._csrf_id_cookie,
|
|
|
|
'CSRF cookie was changed on an accepted request',
|
|
|
|
)
|
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
|
|
|
|
2016-10-18 00:14:49 +08:00
|
|
|
@override_settings(DEBUG=True, ALLOWED_HOSTS=['www.example.com'])
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
def test_https_bad_referer(self):
|
|
|
|
"""
|
2016-10-27 15:53:39 +08:00
|
|
|
A POST HTTPS request with a bad referer is rejected
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
2011-12-17 08:17:26 +08:00
|
|
|
req._is_secure_override = True
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_REFERER'] = 'https://www.evil.org/somepage'
|
2015-03-17 17:52:55 +08:00
|
|
|
req.META['SERVER_PORT'] = '443'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2015-03-17 17:52:55 +08:00
|
|
|
self.assertContains(
|
|
|
|
response,
|
|
|
|
'Referer checking failed - https://www.evil.org/somepage does not '
|
|
|
|
'match any trusted origins.',
|
|
|
|
status_code=403,
|
|
|
|
)
|
|
|
|
|
2021-03-26 17:37:55 +08:00
|
|
|
def _check_referer_rejects(self, mw, req):
|
|
|
|
with self.assertRaises(RejectRequest):
|
|
|
|
mw._check_referer(req)
|
|
|
|
|
2021-04-06 07:51:53 +08:00
|
|
|
@override_settings(DEBUG=True)
|
|
|
|
def test_https_no_referer(self):
|
|
|
|
"""A POST HTTPS request with a missing referer is rejected."""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2021-04-06 07:51:53 +08:00
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertContains(
|
|
|
|
response,
|
|
|
|
'Referer checking failed - no Referer.',
|
|
|
|
status_code=403,
|
|
|
|
)
|
|
|
|
|
2017-10-22 07:56:01 +08:00
|
|
|
def test_https_malformed_host(self):
|
|
|
|
"""
|
|
|
|
CsrfViewMiddleware generates a 403 response if it receives an HTTPS
|
|
|
|
request with a bad host.
|
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request(method='POST')
|
2017-10-22 07:56:01 +08:00
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = '@malformed'
|
|
|
|
req.META['HTTP_REFERER'] = 'https://www.evil.org/somepage'
|
|
|
|
req.META['SERVER_PORT'] = '443'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
expected = (
|
|
|
|
'Referer checking failed - https://www.evil.org/somepage does not '
|
|
|
|
'match any trusted origins.'
|
|
|
|
)
|
|
|
|
with self.assertRaisesMessage(RejectRequest, expected):
|
|
|
|
mw._check_referer(req)
|
2019-09-27 01:06:35 +08:00
|
|
|
response = mw.process_view(req, token_view, (), {})
|
2017-10-22 07:56:01 +08:00
|
|
|
self.assertEqual(response.status_code, 403)
|
|
|
|
|
2021-03-25 15:35:49 +08:00
|
|
|
def test_origin_malformed_host(self):
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request(method='POST')
|
2021-03-25 15:35:49 +08:00
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = '@malformed'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'https://www.evil.org'
|
|
|
|
mw = CsrfViewMiddleware(token_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2021-03-25 15:35:49 +08:00
|
|
|
response = mw.process_view(req, token_view, (), {})
|
|
|
|
self.assertEqual(response.status_code, 403)
|
|
|
|
|
2015-03-17 17:52:55 +08:00
|
|
|
@override_settings(DEBUG=True)
|
2013-05-18 18:32:47 +08:00
|
|
|
def test_https_malformed_referer(self):
|
|
|
|
"""
|
2015-09-05 03:58:15 +08:00
|
|
|
A POST HTTPS request with a bad referer is rejected.
|
2013-05-18 18:32:47 +08:00
|
|
|
"""
|
2015-03-17 17:52:55 +08:00
|
|
|
malformed_referer_msg = 'Referer checking failed - Referer is malformed.'
|
2013-05-18 18:32:47 +08:00
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_REFERER'] = 'http://http://www.example.com/'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2019-09-27 01:06:35 +08:00
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2015-03-17 17:52:55 +08:00
|
|
|
self.assertContains(
|
|
|
|
response,
|
|
|
|
'Referer checking failed - Referer is insecure while host is secure.',
|
|
|
|
status_code=403,
|
|
|
|
)
|
|
|
|
# Empty
|
|
|
|
req.META['HTTP_REFERER'] = ''
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2019-09-27 01:06:35 +08:00
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2015-03-17 17:52:55 +08:00
|
|
|
self.assertContains(response, malformed_referer_msg, status_code=403)
|
2015-01-06 01:23:57 +08:00
|
|
|
# Non-ASCII
|
2017-01-29 21:58:20 +08:00
|
|
|
req.META['HTTP_REFERER'] = 'ØBöIß'
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2019-09-27 01:06:35 +08:00
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2015-03-17 17:52:55 +08:00
|
|
|
self.assertContains(response, malformed_referer_msg, status_code=403)
|
|
|
|
# missing scheme
|
|
|
|
# >>> urlparse('//example.com/')
|
|
|
|
# ParseResult(scheme='', netloc='example.com', path='/', params='', query='', fragment='')
|
|
|
|
req.META['HTTP_REFERER'] = '//example.com/'
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2019-09-27 01:06:35 +08:00
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2015-03-17 17:52:55 +08:00
|
|
|
self.assertContains(response, malformed_referer_msg, status_code=403)
|
|
|
|
# missing netloc
|
|
|
|
# >>> urlparse('https://')
|
|
|
|
# ParseResult(scheme='https', netloc='', path='', params='', query='', fragment='')
|
|
|
|
req.META['HTTP_REFERER'] = 'https://'
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2019-09-27 01:06:35 +08:00
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2015-03-17 17:52:55 +08:00
|
|
|
self.assertContains(response, malformed_referer_msg, status_code=403)
|
2021-03-19 17:42:05 +08:00
|
|
|
# Invalid URL
|
|
|
|
# >>> urlparse('https://[')
|
|
|
|
# ValueError: Invalid IPv6 URL
|
|
|
|
req.META['HTTP_REFERER'] = 'https://['
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2021-03-19 17:42:05 +08:00
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertContains(response, malformed_referer_msg, status_code=403)
|
2013-05-18 18:32:47 +08:00
|
|
|
|
2013-02-10 01:17:01 +08:00
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'])
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
def test_https_good_referer(self):
|
|
|
|
"""
|
2015-09-05 03:58:15 +08:00
|
|
|
A POST HTTPS request with a good referer is accepted.
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
2011-12-17 08:17:26 +08:00
|
|
|
req._is_secure_override = True
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-27 07:23:07 +08:00
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_REFERER'] = 'https://www.example.com/somepage'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
2011-03-16 04:37:09 +08:00
|
|
|
|
2013-02-10 01:17:01 +08:00
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'])
|
2011-03-16 04:37:09 +08:00
|
|
|
def test_https_good_referer_2(self):
|
|
|
|
"""
|
2015-09-05 03:58:15 +08:00
|
|
|
A POST HTTPS request with a good referer is accepted where the referer
|
|
|
|
contains no trailing slash.
|
2011-03-16 04:37:09 +08:00
|
|
|
"""
|
|
|
|
# See ticket #15617
|
|
|
|
req = self._get_POST_request_with_token()
|
2011-12-17 08:17:26 +08:00
|
|
|
req._is_secure_override = True
|
2011-03-16 04:37:09 +08:00
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_REFERER'] = 'https://www.example.com'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
2011-05-10 05:35:24 +08:00
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def _test_https_good_referer_behind_proxy(self):
|
2016-01-18 22:04:41 +08:00
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META.update({
|
|
|
|
'HTTP_HOST': '10.0.0.2',
|
|
|
|
'HTTP_REFERER': 'https://www.example.com/somepage',
|
|
|
|
'SERVER_PORT': '8080',
|
|
|
|
'HTTP_X_FORWARDED_HOST': 'www.example.com',
|
|
|
|
'HTTP_X_FORWARDED_PORT': '443',
|
|
|
|
})
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
2016-01-18 22:04:41 +08:00
|
|
|
|
2021-04-06 07:51:53 +08:00
|
|
|
@override_settings(CSRF_TRUSTED_ORIGINS=['https://dashboard.example.com'])
|
|
|
|
def test_https_good_referer_malformed_host(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request is accepted if it receives a good referer with
|
|
|
|
a bad host.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = '@malformed'
|
|
|
|
req.META['HTTP_REFERER'] = 'https://dashboard.example.com/somepage'
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
|
|
|
|
2021-01-13 08:55:02 +08:00
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_TRUSTED_ORIGINS=['https://dashboard.example.com'])
|
2015-09-01 10:32:03 +08:00
|
|
|
def test_https_csrf_trusted_origin_allowed(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request with a referer added to the CSRF_TRUSTED_ORIGINS
|
|
|
|
setting is accepted.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_REFERER'] = 'https://dashboard.example.com'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
2015-09-01 10:32:03 +08:00
|
|
|
|
2021-01-13 08:55:02 +08:00
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_TRUSTED_ORIGINS=['https://*.example.com'])
|
2015-03-17 17:52:55 +08:00
|
|
|
def test_https_csrf_wildcard_trusted_origin_allowed(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request with a referer that matches a CSRF_TRUSTED_ORIGINS
|
2015-12-03 07:55:50 +08:00
|
|
|
wildcard is accepted.
|
2015-03-17 17:52:55 +08:00
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_REFERER'] = 'https://dashboard.example.com'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2015-03-17 17:52:55 +08:00
|
|
|
self.assertIsNone(response)
|
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def _test_https_good_referer_matches_cookie_domain(self):
|
2015-03-17 17:52:55 +08:00
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_REFERER'] = 'https://foo.example.com/'
|
|
|
|
req.META['SERVER_PORT'] = '443'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2015-03-17 17:52:55 +08:00
|
|
|
self.assertIsNone(response)
|
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def _test_https_good_referer_matches_cookie_domain_with_different_port(self):
|
2015-03-17 17:52:55 +08:00
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_REFERER'] = 'https://foo.example.com:4443/'
|
|
|
|
req.META['SERVER_PORT'] = '4443'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2015-03-17 17:52:55 +08:00
|
|
|
self.assertIsNone(response)
|
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def test_ensures_csrf_cookie_no_logging(self):
|
2015-03-17 17:52:55 +08:00
|
|
|
"""
|
2016-07-01 00:42:11 +08:00
|
|
|
ensure_csrf_cookie() doesn't log warnings (#19436).
|
2015-03-17 17:52:55 +08:00
|
|
|
"""
|
2021-01-08 00:54:40 +08:00
|
|
|
with self.assertNoLogs('django.request', 'WARNING'):
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2021-01-08 00:54:40 +08:00
|
|
|
ensure_csrf_cookie_view(req)
|
2016-07-01 00:42:11 +08:00
|
|
|
|
2021-07-23 18:26:22 +08:00
|
|
|
def test_reading_post_data_raises_unreadable_post_error(self):
|
2016-07-01 00:42:11 +08:00
|
|
|
"""
|
2021-07-23 18:26:22 +08:00
|
|
|
An UnreadablePostError raised while reading the POST data should be
|
|
|
|
handled by the middleware.
|
2016-07-01 00:42:11 +08:00
|
|
|
"""
|
2021-07-23 18:13:31 +08:00
|
|
|
req = self._get_POST_request_with_token()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
2016-07-01 00:42:11 +08:00
|
|
|
self.assertIsNone(resp)
|
|
|
|
|
2021-07-23 18:13:31 +08:00
|
|
|
req = self._get_POST_request_with_token(request_class=PostErrorRequest)
|
2021-07-23 18:26:22 +08:00
|
|
|
req.post_error = UnreadablePostError('Error reading input data.')
|
2019-09-27 01:06:35 +08:00
|
|
|
mw.process_request(req)
|
2018-04-28 21:20:27 +08:00
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
2019-09-27 01:06:35 +08:00
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
2018-04-28 21:20:27 +08:00
|
|
|
self.assertEqual(resp.status_code, 403)
|
2021-05-29 19:49:53 +08:00
|
|
|
self.assertEqual(
|
|
|
|
cm.records[0].getMessage(),
|
|
|
|
'Forbidden (%s): ' % REASON_CSRF_TOKEN_MISSING,
|
|
|
|
)
|
2016-07-01 00:42:11 +08:00
|
|
|
|
2021-07-23 18:26:22 +08:00
|
|
|
def test_reading_post_data_raises_os_error(self):
|
|
|
|
"""
|
|
|
|
An OSError raised while reading the POST data should not be handled by
|
|
|
|
the middleware.
|
|
|
|
"""
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
req = self._get_POST_request_with_token(request_class=PostErrorRequest)
|
|
|
|
req.post_error = OSError('Deleted directories/Missing permissions.')
|
|
|
|
mw.process_request(req)
|
|
|
|
with self.assertRaises(OSError):
|
|
|
|
mw.process_view(req, post_form_view, (), {})
|
|
|
|
|
2021-01-03 07:46:17 +08:00
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'])
|
|
|
|
def test_bad_origin_bad_domain(self):
|
|
|
|
"""A request with a bad origin is rejected."""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'https://www.evil.org'
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2021-01-03 07:46:17 +08:00
|
|
|
self.assertIs(mw._origin_verified(req), False)
|
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertEqual(response.status_code, 403)
|
|
|
|
msg = REASON_BAD_ORIGIN % req.META['HTTP_ORIGIN']
|
|
|
|
self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % msg)
|
|
|
|
|
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'])
|
|
|
|
def test_bad_origin_null_origin(self):
|
|
|
|
"""A request with a null origin is rejected."""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'null'
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2021-01-03 07:46:17 +08:00
|
|
|
self.assertIs(mw._origin_verified(req), False)
|
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertEqual(response.status_code, 403)
|
|
|
|
msg = REASON_BAD_ORIGIN % req.META['HTTP_ORIGIN']
|
|
|
|
self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % msg)
|
|
|
|
|
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'])
|
|
|
|
def test_bad_origin_bad_protocol(self):
|
|
|
|
"""A request with an origin with wrong protocol is rejected."""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'http://example.com'
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2021-01-03 07:46:17 +08:00
|
|
|
self.assertIs(mw._origin_verified(req), False)
|
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertEqual(response.status_code, 403)
|
|
|
|
msg = REASON_BAD_ORIGIN % req.META['HTTP_ORIGIN']
|
|
|
|
self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % msg)
|
|
|
|
|
|
|
|
@override_settings(
|
|
|
|
ALLOWED_HOSTS=['www.example.com'],
|
|
|
|
CSRF_TRUSTED_ORIGINS=[
|
|
|
|
'http://no-match.com',
|
|
|
|
'https://*.example.com',
|
|
|
|
'http://*.no-match.com',
|
|
|
|
'http://*.no-match-2.com',
|
|
|
|
],
|
|
|
|
)
|
|
|
|
def test_bad_origin_csrf_trusted_origin_bad_protocol(self):
|
|
|
|
"""
|
|
|
|
A request with an origin with the wrong protocol compared to
|
|
|
|
CSRF_TRUSTED_ORIGINS is rejected.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'http://foo.example.com'
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2021-01-03 07:46:17 +08:00
|
|
|
self.assertIs(mw._origin_verified(req), False)
|
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertEqual(response.status_code, 403)
|
|
|
|
msg = REASON_BAD_ORIGIN % req.META['HTTP_ORIGIN']
|
|
|
|
self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % msg)
|
|
|
|
self.assertEqual(mw.allowed_origins_exact, {'http://no-match.com'})
|
|
|
|
self.assertEqual(mw.allowed_origin_subdomains, {
|
|
|
|
'https': ['.example.com'],
|
|
|
|
'http': ['.no-match.com', '.no-match-2.com'],
|
|
|
|
})
|
|
|
|
|
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'])
|
|
|
|
def test_bad_origin_cannot_be_parsed(self):
|
|
|
|
"""
|
|
|
|
A POST request with an origin that can't be parsed by urlparse() is
|
|
|
|
rejected.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'https://['
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2021-01-03 07:46:17 +08:00
|
|
|
self.assertIs(mw._origin_verified(req), False)
|
|
|
|
with self.assertLogs('django.security.csrf', 'WARNING') as cm:
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertEqual(response.status_code, 403)
|
|
|
|
msg = REASON_BAD_ORIGIN % req.META['HTTP_ORIGIN']
|
|
|
|
self.assertEqual(cm.records[0].getMessage(), 'Forbidden (%s): ' % msg)
|
|
|
|
|
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'])
|
|
|
|
def test_good_origin_insecure(self):
|
|
|
|
"""A POST HTTP request with a good origin is accepted."""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'http://www.example.com'
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
self.assertIs(mw._origin_verified(req), True)
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(response)
|
|
|
|
|
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'])
|
|
|
|
def test_good_origin_secure(self):
|
|
|
|
"""A POST HTTPS request with a good origin is accepted."""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'https://www.example.com'
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
self.assertIs(mw._origin_verified(req), True)
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(response)
|
|
|
|
|
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_TRUSTED_ORIGINS=['https://dashboard.example.com'])
|
|
|
|
def test_good_origin_csrf_trusted_origin_allowed(self):
|
|
|
|
"""
|
|
|
|
A POST request with an origin added to the CSRF_TRUSTED_ORIGINS
|
|
|
|
setting is accepted.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'https://dashboard.example.com'
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
self.assertIs(mw._origin_verified(req), True)
|
|
|
|
resp = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
|
|
|
self.assertEqual(mw.allowed_origins_exact, {'https://dashboard.example.com'})
|
|
|
|
self.assertEqual(mw.allowed_origin_subdomains, {})
|
|
|
|
|
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_TRUSTED_ORIGINS=['https://*.example.com'])
|
|
|
|
def test_good_origin_wildcard_csrf_trusted_origin_allowed(self):
|
|
|
|
"""
|
|
|
|
A POST request with an origin that matches a CSRF_TRUSTED_ORIGINS
|
|
|
|
wildcard is accepted.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_HOST'] = 'www.example.com'
|
|
|
|
req.META['HTTP_ORIGIN'] = 'https://foo.example.com'
|
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
self.assertIs(mw._origin_verified(req), True)
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
|
|
|
self.assertIsNone(response)
|
|
|
|
self.assertEqual(mw.allowed_origins_exact, set())
|
|
|
|
self.assertEqual(mw.allowed_origin_subdomains, {'https': ['.example.com']})
|
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
|
|
|
|
class CsrfViewMiddlewareTests(CsrfViewMiddlewareTestMixin, SimpleTestCase):
|
|
|
|
|
2021-06-23 22:16:40 +08:00
|
|
|
def _set_csrf_cookie(self, req, cookie):
|
2021-05-31 19:24:02 +08:00
|
|
|
req.COOKIES[settings.CSRF_COOKIE_NAME] = cookie
|
2016-07-01 00:42:11 +08:00
|
|
|
|
2021-06-29 22:07:28 +08:00
|
|
|
def _read_csrf_cookie(self, req, resp):
|
|
|
|
"""
|
|
|
|
Return the CSRF cookie as a string, or False if no cookie is present.
|
|
|
|
"""
|
|
|
|
if settings.CSRF_COOKIE_NAME not in resp.cookies:
|
|
|
|
return False
|
|
|
|
csrf_cookie = resp.cookies[settings.CSRF_COOKIE_NAME]
|
|
|
|
return csrf_cookie.value
|
|
|
|
|
2021-07-04 14:29:52 +08:00
|
|
|
def _get_cookies_set(self, req, resp):
|
|
|
|
return resp._cookies_set
|
|
|
|
|
2011-05-10 05:35:24 +08:00
|
|
|
def test_ensures_csrf_cookie_no_middleware(self):
|
|
|
|
"""
|
2015-09-05 03:58:15 +08:00
|
|
|
The ensure_csrf_cookie() decorator works without middleware.
|
2011-05-10 05:35:24 +08:00
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2016-12-01 01:33:00 +08:00
|
|
|
resp = ensure_csrf_cookie_view(req)
|
2021-06-29 22:18:17 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
self.assertTrue(csrf_cookie)
|
2014-10-28 18:02:56 +08:00
|
|
|
self.assertIn('Cookie', resp.get('Vary', ''))
|
2011-05-10 05:35:24 +08:00
|
|
|
|
|
|
|
def test_ensures_csrf_cookie_with_middleware(self):
|
|
|
|
"""
|
2015-09-05 03:58:15 +08:00
|
|
|
The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware
|
|
|
|
enabled.
|
2011-05-10 05:35:24 +08:00
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(ensure_csrf_cookie_view)
|
|
|
|
mw.process_view(req, ensure_csrf_cookie_view, (), {})
|
|
|
|
resp = mw(req)
|
2021-06-29 22:18:17 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
self.assertTrue(csrf_cookie)
|
2019-09-27 01:06:35 +08:00
|
|
|
self.assertIn('Cookie', resp.get('Vary', ''))
|
2013-05-18 19:09:38 +08:00
|
|
|
|
2014-03-04 08:52:28 +08:00
|
|
|
def test_csrf_cookie_age(self):
|
|
|
|
"""
|
2015-09-05 03:58:15 +08:00
|
|
|
CSRF cookie age can be set using settings.CSRF_COOKIE_AGE.
|
2014-03-04 08:52:28 +08:00
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2014-03-04 08:52:28 +08:00
|
|
|
|
|
|
|
MAX_AGE = 123
|
|
|
|
with self.settings(CSRF_COOKIE_NAME='csrfcookie',
|
|
|
|
CSRF_COOKIE_DOMAIN='.example.com',
|
|
|
|
CSRF_COOKIE_AGE=MAX_AGE,
|
|
|
|
CSRF_COOKIE_PATH='/test/',
|
|
|
|
CSRF_COOKIE_SECURE=True,
|
|
|
|
CSRF_COOKIE_HTTPONLY=True):
|
|
|
|
# token_view calls get_token() indirectly
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_view(req, token_view, (), {})
|
|
|
|
resp = mw(req)
|
|
|
|
max_age = resp.cookies.get('csrfcookie').get('max-age')
|
2014-03-04 08:52:28 +08:00
|
|
|
self.assertEqual(max_age, MAX_AGE)
|
|
|
|
|
|
|
|
def test_csrf_cookie_age_none(self):
|
|
|
|
"""
|
2015-09-05 03:58:15 +08:00
|
|
|
CSRF cookie age does not have max age set and therefore uses
|
|
|
|
session-based cookies.
|
2014-03-04 08:52:28 +08:00
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2014-03-04 08:52:28 +08:00
|
|
|
|
|
|
|
MAX_AGE = None
|
|
|
|
with self.settings(CSRF_COOKIE_NAME='csrfcookie',
|
|
|
|
CSRF_COOKIE_DOMAIN='.example.com',
|
|
|
|
CSRF_COOKIE_AGE=MAX_AGE,
|
|
|
|
CSRF_COOKIE_PATH='/test/',
|
|
|
|
CSRF_COOKIE_SECURE=True,
|
|
|
|
CSRF_COOKIE_HTTPONLY=True):
|
|
|
|
# token_view calls get_token() indirectly
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_view(req, token_view, (), {})
|
|
|
|
resp = mw(req)
|
|
|
|
max_age = resp.cookies.get('csrfcookie').get('max-age')
|
2014-03-04 08:52:28 +08:00
|
|
|
self.assertEqual(max_age, '')
|
2014-06-25 18:52:25 +08:00
|
|
|
|
2018-04-14 08:58:31 +08:00
|
|
|
def test_csrf_cookie_samesite(self):
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2018-04-14 08:58:31 +08:00
|
|
|
with self.settings(CSRF_COOKIE_NAME='csrfcookie', CSRF_COOKIE_SAMESITE='Strict'):
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_view(req, token_view, (), {})
|
|
|
|
resp = mw(req)
|
|
|
|
self.assertEqual(resp.cookies['csrfcookie']['samesite'], 'Strict')
|
2018-04-14 08:58:31 +08:00
|
|
|
|
2021-05-31 19:24:02 +08:00
|
|
|
def test_bad_csrf_cookie_characters(self):
|
|
|
|
"""
|
|
|
|
If the CSRF cookie has invalid characters in a POST request, the
|
|
|
|
middleware rejects the incoming request.
|
|
|
|
"""
|
2021-05-31 19:26:11 +08:00
|
|
|
self._check_bad_or_missing_cookie(64 * '*', 'CSRF cookie has invalid characters.')
|
2021-05-31 19:24:02 +08:00
|
|
|
|
|
|
|
def test_bad_csrf_cookie_length(self):
|
|
|
|
"""
|
|
|
|
If the CSRF cookie has an incorrect length in a POST request, the
|
|
|
|
middleware rejects the incoming request.
|
|
|
|
"""
|
2021-05-31 19:26:11 +08:00
|
|
|
self._check_bad_or_missing_cookie(16 * 'a', 'CSRF cookie has incorrect length.')
|
2021-05-31 19:24:02 +08:00
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def test_process_view_token_too_long(self):
|
2014-06-25 18:52:25 +08:00
|
|
|
"""
|
2016-07-01 00:42:11 +08:00
|
|
|
If the token is longer than expected, it is ignored and a new token is
|
|
|
|
created.
|
2014-06-25 18:52:25 +08:00
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2021-06-29 22:18:17 +08:00
|
|
|
self._set_csrf_cookie(req, 'x' * 100000)
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_view(req, token_view, (), {})
|
|
|
|
resp = mw(req)
|
2021-06-29 22:18:17 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
self.assertEqual(len(csrf_cookie), CSRF_TOKEN_LENGTH)
|
2014-06-25 18:52:25 +08:00
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def test_process_view_token_invalid_chars(self):
|
|
|
|
"""
|
|
|
|
If the token contains non-alphanumeric characters, it is ignored and a
|
|
|
|
new token is created.
|
|
|
|
"""
|
2021-06-02 18:34:47 +08:00
|
|
|
token = ('!@#' + self._csrf_id_token)[:CSRF_TOKEN_LENGTH]
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2021-06-29 22:18:17 +08:00
|
|
|
self._set_csrf_cookie(req, token)
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_view(req, token_view, (), {})
|
|
|
|
resp = mw(req)
|
2021-06-29 22:18:17 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
self.assertEqual(len(csrf_cookie), CSRF_TOKEN_LENGTH)
|
|
|
|
self.assertNotEqual(csrf_cookie, token)
|
2014-06-25 18:52:25 +08:00
|
|
|
|
2021-06-02 19:31:27 +08:00
|
|
|
def test_masked_unmasked_combinations(self):
|
|
|
|
"""
|
|
|
|
All combinations are allowed of (1) masked and unmasked cookies,
|
|
|
|
(2) masked and unmasked tokens, and (3) tokens provided via POST and
|
|
|
|
the X-CSRFToken header.
|
|
|
|
"""
|
|
|
|
cases = [
|
|
|
|
(TEST_SECRET, TEST_SECRET, None),
|
|
|
|
(TEST_SECRET, MASKED_TEST_SECRET2, None),
|
|
|
|
(TEST_SECRET, None, TEST_SECRET),
|
|
|
|
(TEST_SECRET, None, MASKED_TEST_SECRET2),
|
|
|
|
(MASKED_TEST_SECRET1, TEST_SECRET, None),
|
|
|
|
(MASKED_TEST_SECRET1, MASKED_TEST_SECRET2, None),
|
|
|
|
(MASKED_TEST_SECRET1, None, TEST_SECRET),
|
|
|
|
(MASKED_TEST_SECRET1, None, MASKED_TEST_SECRET2),
|
|
|
|
]
|
|
|
|
for args in cases:
|
|
|
|
with self.subTest(args=args):
|
|
|
|
cookie, post_token, meta_token = args
|
|
|
|
req = self._get_POST_csrf_cookie_request(
|
|
|
|
cookie=cookie, post_token=post_token, meta_token=meta_token,
|
|
|
|
)
|
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, token_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
|
|
|
|
2021-07-16 22:54:42 +08:00
|
|
|
def test_cookie_reset_only_once(self):
|
|
|
|
"""
|
|
|
|
A CSRF cookie that needs to be reset is reset only once when the view
|
|
|
|
is decorated with both ensure_csrf_cookie and csrf_protect.
|
|
|
|
"""
|
|
|
|
# Pass an unmasked cookie to trigger a cookie reset.
|
|
|
|
req = self._get_POST_request_with_token(cookie=TEST_SECRET)
|
|
|
|
resp = ensured_and_protected_view(req)
|
|
|
|
self.assertContains(resp, 'OK')
|
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
actual_secret = _unmask_cipher_token(csrf_cookie)
|
|
|
|
self.assertEqual(actual_secret, TEST_SECRET)
|
|
|
|
# set_cookie() was called only once and with the expected secret.
|
|
|
|
self.assertCookiesSet(req, resp, [TEST_SECRET])
|
|
|
|
|
|
|
|
def test_invalid_cookie_replaced_on_GET(self):
|
|
|
|
"""
|
|
|
|
A CSRF cookie with the wrong format is replaced during a GET request.
|
|
|
|
"""
|
|
|
|
req = self._get_request(cookie='badvalue')
|
|
|
|
resp = protected_view(req)
|
|
|
|
self.assertContains(resp, 'OK')
|
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
self.assertTrue(csrf_cookie, msg='No CSRF cookie was sent.')
|
|
|
|
self.assertEqual(len(csrf_cookie), CSRF_TOKEN_LENGTH)
|
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def test_bare_secret_accepted_and_replaced(self):
|
|
|
|
"""
|
|
|
|
The csrf token is reset from a bare secret.
|
|
|
|
"""
|
2021-06-02 19:02:52 +08:00
|
|
|
req = self._get_POST_request_with_token(cookie=TEST_SECRET)
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, token_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
|
|
|
resp = mw(req)
|
2021-06-29 22:18:17 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req, resp)
|
|
|
|
self.assertEqual(len(csrf_cookie), CSRF_TOKEN_LENGTH)
|
|
|
|
self._check_token_present(resp, csrf_id=csrf_cookie)
|
2014-06-25 18:52:25 +08:00
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_COOKIE_DOMAIN='.example.com', USE_X_FORWARDED_PORT=True)
|
|
|
|
def test_https_good_referer_behind_proxy(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True.
|
|
|
|
"""
|
|
|
|
self._test_https_good_referer_behind_proxy()
|
2014-06-25 18:52:25 +08:00
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_COOKIE_DOMAIN='.example.com')
|
|
|
|
def test_https_good_referer_matches_cookie_domain(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request with a good referer should be accepted from a
|
|
|
|
subdomain that's allowed by CSRF_COOKIE_DOMAIN.
|
|
|
|
"""
|
|
|
|
self._test_https_good_referer_matches_cookie_domain()
|
2014-06-25 18:52:25 +08:00
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'], CSRF_COOKIE_DOMAIN='.example.com')
|
|
|
|
def test_https_good_referer_matches_cookie_domain_with_different_port(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request with a good referer should be accepted from a
|
|
|
|
subdomain that's allowed by CSRF_COOKIE_DOMAIN and a non-443 port.
|
|
|
|
"""
|
|
|
|
self._test_https_good_referer_matches_cookie_domain_with_different_port()
|
2014-06-25 18:52:25 +08:00
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
@override_settings(CSRF_COOKIE_DOMAIN='.example.com', DEBUG=True)
|
|
|
|
def test_https_reject_insecure_referer(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request from an insecure referer should be rejected.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_REFERER'] = 'http://example.com/'
|
|
|
|
req.META['SERVER_PORT'] = '443'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
2021-03-26 17:37:55 +08:00
|
|
|
self._check_referer_rejects(mw, req)
|
2019-09-27 01:06:35 +08:00
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2016-07-01 00:42:11 +08:00
|
|
|
self.assertContains(
|
|
|
|
response,
|
|
|
|
'Referer checking failed - Referer is insecure while host is secure.',
|
|
|
|
status_code=403,
|
|
|
|
)
|
2014-06-25 18:52:25 +08:00
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
|
|
|
|
@override_settings(CSRF_USE_SESSIONS=True, CSRF_COOKIE_DOMAIN=None)
|
|
|
|
class CsrfViewMiddlewareUseSessionsTests(CsrfViewMiddlewareTestMixin, SimpleTestCase):
|
|
|
|
"""
|
|
|
|
CSRF tests with CSRF_USE_SESSIONS=True.
|
|
|
|
"""
|
|
|
|
|
2021-06-23 22:16:40 +08:00
|
|
|
def _set_csrf_cookie(self, req, cookie):
|
2021-05-31 19:24:02 +08:00
|
|
|
req.session[CSRF_SESSION_KEY] = cookie
|
2016-07-01 00:42:11 +08:00
|
|
|
|
2021-06-29 22:18:17 +08:00
|
|
|
def _read_csrf_cookie(self, req, resp=None):
|
2021-06-29 22:07:28 +08:00
|
|
|
"""
|
|
|
|
Return the CSRF cookie as a string, or False if no cookie is present.
|
|
|
|
"""
|
|
|
|
if CSRF_SESSION_KEY not in req.session:
|
|
|
|
return False
|
|
|
|
return req.session[CSRF_SESSION_KEY]
|
|
|
|
|
2021-07-04 14:29:52 +08:00
|
|
|
def _get_cookies_set(self, req, resp):
|
|
|
|
return req.session._cookies_set
|
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def test_no_session_on_request(self):
|
|
|
|
msg = (
|
|
|
|
'CSRF_USE_SESSIONS is enabled, but request.session is not set. '
|
|
|
|
'SessionMiddleware must appear before CsrfViewMiddleware in MIDDLEWARE.'
|
|
|
|
)
|
|
|
|
with self.assertRaisesMessage(ImproperlyConfigured, msg):
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(lambda req: HttpResponse())
|
|
|
|
mw.process_request(HttpRequest())
|
2016-07-01 00:42:11 +08:00
|
|
|
|
2021-06-02 19:31:27 +08:00
|
|
|
def test_masked_unmasked_combinations(self):
|
|
|
|
"""
|
|
|
|
Masked and unmasked tokens are allowed both as POST and as the
|
|
|
|
X-CSRFToken header.
|
|
|
|
"""
|
|
|
|
cases = [
|
|
|
|
# Bare secrets are not allowed when CSRF_USE_SESSIONS=True.
|
|
|
|
(MASKED_TEST_SECRET1, TEST_SECRET, None),
|
|
|
|
(MASKED_TEST_SECRET1, MASKED_TEST_SECRET2, None),
|
|
|
|
(MASKED_TEST_SECRET1, None, TEST_SECRET),
|
|
|
|
(MASKED_TEST_SECRET1, None, MASKED_TEST_SECRET2),
|
|
|
|
]
|
|
|
|
for args in cases:
|
|
|
|
with self.subTest(args=args):
|
|
|
|
cookie, post_token, meta_token = args
|
|
|
|
req = self._get_POST_csrf_cookie_request(
|
|
|
|
cookie=cookie, post_token=post_token, meta_token=meta_token,
|
|
|
|
)
|
|
|
|
mw = CsrfViewMiddleware(token_view)
|
|
|
|
mw.process_request(req)
|
|
|
|
resp = mw.process_view(req, token_view, (), {})
|
|
|
|
self.assertIsNone(resp)
|
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def test_process_response_get_token_used(self):
|
|
|
|
"""The ensure_csrf_cookie() decorator works without middleware."""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2016-12-01 01:33:00 +08:00
|
|
|
ensure_csrf_cookie_view(req)
|
2021-06-29 22:18:17 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req)
|
|
|
|
self.assertTrue(csrf_cookie)
|
2016-07-01 00:42:11 +08:00
|
|
|
|
2018-09-01 22:32:35 +08:00
|
|
|
def test_session_modify(self):
|
|
|
|
"""The session isn't saved if the CSRF cookie is unchanged."""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(ensure_csrf_cookie_view)
|
|
|
|
mw.process_view(req, ensure_csrf_cookie_view, (), {})
|
|
|
|
mw(req)
|
2021-06-29 22:18:17 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req)
|
|
|
|
self.assertTrue(csrf_cookie)
|
2018-09-01 22:32:35 +08:00
|
|
|
req.session.modified = False
|
2019-09-27 01:06:35 +08:00
|
|
|
mw.process_view(req, ensure_csrf_cookie_view, (), {})
|
|
|
|
mw(req)
|
2018-09-01 22:32:35 +08:00
|
|
|
self.assertFalse(req.session.modified)
|
|
|
|
|
2016-07-01 00:42:11 +08:00
|
|
|
def test_ensures_csrf_cookie_with_middleware(self):
|
|
|
|
"""
|
|
|
|
The ensure_csrf_cookie() decorator works with the CsrfViewMiddleware
|
|
|
|
enabled.
|
|
|
|
"""
|
2021-06-23 22:02:07 +08:00
|
|
|
req = self._get_request()
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(ensure_csrf_cookie_view)
|
|
|
|
mw.process_view(req, ensure_csrf_cookie_view, (), {})
|
|
|
|
mw(req)
|
2021-06-29 22:18:17 +08:00
|
|
|
csrf_cookie = self._read_csrf_cookie(req)
|
|
|
|
self.assertTrue(csrf_cookie)
|
2016-07-01 00:42:11 +08:00
|
|
|
|
|
|
|
@override_settings(
|
|
|
|
ALLOWED_HOSTS=['www.example.com'],
|
|
|
|
SESSION_COOKIE_DOMAIN='.example.com',
|
|
|
|
USE_X_FORWARDED_PORT=True,
|
|
|
|
DEBUG=True,
|
|
|
|
)
|
|
|
|
def test_https_good_referer_behind_proxy(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request is accepted when USE_X_FORWARDED_PORT=True.
|
|
|
|
"""
|
|
|
|
self._test_https_good_referer_behind_proxy()
|
|
|
|
|
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'], SESSION_COOKIE_DOMAIN='.example.com')
|
|
|
|
def test_https_good_referer_matches_cookie_domain(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request with a good referer should be accepted from a
|
|
|
|
subdomain that's allowed by SESSION_COOKIE_DOMAIN.
|
|
|
|
"""
|
|
|
|
self._test_https_good_referer_matches_cookie_domain()
|
|
|
|
|
|
|
|
@override_settings(ALLOWED_HOSTS=['www.example.com'], SESSION_COOKIE_DOMAIN='.example.com')
|
|
|
|
def test_https_good_referer_matches_cookie_domain_with_different_port(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request with a good referer should be accepted from a
|
|
|
|
subdomain that's allowed by SESSION_COOKIE_DOMAIN and a non-443 port.
|
|
|
|
"""
|
|
|
|
self._test_https_good_referer_matches_cookie_domain_with_different_port()
|
|
|
|
|
|
|
|
@override_settings(SESSION_COOKIE_DOMAIN='.example.com', DEBUG=True)
|
|
|
|
def test_https_reject_insecure_referer(self):
|
|
|
|
"""
|
|
|
|
A POST HTTPS request from an insecure referer should be rejected.
|
|
|
|
"""
|
|
|
|
req = self._get_POST_request_with_token()
|
|
|
|
req._is_secure_override = True
|
|
|
|
req.META['HTTP_REFERER'] = 'http://example.com/'
|
|
|
|
req.META['SERVER_PORT'] = '443'
|
2019-09-27 01:06:35 +08:00
|
|
|
mw = CsrfViewMiddleware(post_form_view)
|
|
|
|
response = mw.process_view(req, post_form_view, (), {})
|
2016-07-01 00:42:11 +08:00
|
|
|
self.assertContains(
|
|
|
|
response,
|
|
|
|
'Referer checking failed - Referer is insecure while host is secure.',
|
|
|
|
status_code=403,
|
|
|
|
)
|
2017-09-18 04:24:05 +08:00
|
|
|
|
|
|
|
|
|
|
|
@override_settings(ROOT_URLCONF='csrf_tests.csrf_token_error_handler_urls', DEBUG=False)
|
|
|
|
class CsrfInErrorHandlingViewsTests(SimpleTestCase):
|
|
|
|
def test_csrf_token_on_404_stays_constant(self):
|
|
|
|
response = self.client.get('/does not exist/')
|
|
|
|
# The error handler returns status code 599.
|
|
|
|
self.assertEqual(response.status_code, 599)
|
|
|
|
token1 = response.content
|
|
|
|
response = self.client.get('/does not exist/')
|
|
|
|
self.assertEqual(response.status_code, 599)
|
|
|
|
token2 = response.content
|
2021-07-01 00:17:58 +08:00
|
|
|
self.assertTrue(_does_token_match(token1.decode('ascii'), token2.decode('ascii')))
|