You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

csrf.py 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from django.conf import settings
  2. from .. import Tags, Warning, register
  3. W003 = Warning(
  4. "You don't appear to be using Django's built-in "
  5. "cross-site request forgery protection via the middleware "
  6. "('django.middleware.csrf.CsrfViewMiddleware' is not in your "
  7. "MIDDLEWARE). Enabling the middleware is the safest approach "
  8. "to ensure you don't leave any holes.",
  9. id='security.W003',
  10. )
  11. W016 = Warning(
  12. "You have 'django.middleware.csrf.CsrfViewMiddleware' in your "
  13. "MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. "
  14. "Using a secure-only CSRF cookie makes it more difficult for network "
  15. "traffic sniffers to steal the CSRF token.",
  16. id='security.W016',
  17. )
  18. def _csrf_middleware():
  19. return 'django.middleware.csrf.CsrfViewMiddleware' in settings.MIDDLEWARE
  20. @register(Tags.security, deploy=True)
  21. def check_csrf_middleware(app_configs, **kwargs):
  22. passed_check = _csrf_middleware()
  23. return [] if passed_check else [W003]
  24. @register(Tags.security, deploy=True)
  25. def check_csrf_cookie_secure(app_configs, **kwargs):
  26. passed_check = (
  27. settings.CSRF_USE_SESSIONS or
  28. not _csrf_middleware() or
  29. settings.CSRF_COOKIE_SECURE
  30. )
  31. return [] if passed_check else [W016]