| 1 |
from django.conf import settings |
| 2 |
from django.utils.inspect import signature |
| 3 |
|
| 4 |
from .. import Error, Tags, Warning, register |
| 5 |
|
| 6 |
W003 = Warning( |
| 7 |
"You don't appear to be using Django's built-in " |
| 8 |
"cross-site request forgery protection via the middleware " |
| 9 |
"('django.middleware.csrf.CsrfViewMiddleware' is not in your " |
| 10 |
"MIDDLEWARE). Enabling the middleware is the safest approach " |
| 11 |
"to ensure you don't leave any holes.", |
| 12 |
id="security.W003", |
| 13 |
) |
| 14 |
|
| 15 |
W016 = Warning( |
| 16 |
"You have 'django.middleware.csrf.CsrfViewMiddleware' in your " |
| 17 |
"MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. " |
| 18 |
"Using a secure-only CSRF cookie makes it more difficult for network " |
| 19 |
"traffic sniffers to steal the CSRF token.", |
| 20 |
id="security.W016", |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
def _csrf_middleware(): |
| 25 |
return "django.middleware.csrf.CsrfViewMiddleware" in settings.MIDDLEWARE |
| 26 |
|
| 27 |
|
| 28 |
@register(Tags.security, deploy=True) |
| 29 |
def check_csrf_middleware(app_configs, **kwargs): |
| 30 |
passed_check = _csrf_middleware() |
| 31 |
return [] if passed_check else [W003] |
| 32 |
|
| 33 |
|
| 34 |
@register(Tags.security, deploy=True) |
| 35 |
def check_csrf_cookie_secure(app_configs, **kwargs): |
| 36 |
passed_check = ( |
| 37 |
settings.CSRF_USE_SESSIONS |
| 38 |
or not _csrf_middleware() |
| 39 |
or settings.CSRF_COOKIE_SECURE is True |
| 40 |
) |
| 41 |
return [] if passed_check else [W016] |
| 42 |
|
| 43 |
|
| 44 |
@register(Tags.security) |
| 45 |
def check_csrf_failure_view(app_configs, **kwargs): |
| 46 |
from django.middleware.csrf import _get_failure_view |
| 47 |
|
| 48 |
errors = [] |
| 49 |
try: |
| 50 |
view = _get_failure_view() |
| 51 |
except ImportError: |
| 52 |
msg = ( |
| 53 |
"The CSRF failure view '%s' could not be imported." |
| 54 |
% settings.CSRF_FAILURE_VIEW |
| 55 |
) |
| 56 |
errors.append(Error(msg, id="security.E102")) |
| 57 |
else: |
| 58 |
try: |
| 59 |
signature(view).bind(None, reason=None) |
| 60 |
except TypeError: |
| 61 |
msg = ( |
| 62 |
"The CSRF failure view '%s' does not take the correct number of " |
| 63 |
"arguments." % settings.CSRF_FAILURE_VIEW |
| 64 |
) |
| 65 |
errors.append(Error(msg, id="security.E101")) |
| 66 |
return errors |