csrf.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. from django.conf import settings
  2. from .. import register, Tags, Warning
  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_CLASSES). 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_CLASSES, 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. W017 = Warning(
  19. "You have 'django.middleware.csrf.CsrfViewMiddleware' in your "
  20. "MIDDLEWARE_CLASSES, but you have not set CSRF_COOKIE_HTTPONLY to True. "
  21. "Using an HttpOnly CSRF cookie makes it more difficult for cross-site "
  22. "scripting attacks to steal the CSRF token.",
  23. id='security.W017',
  24. )
  25. def _csrf_middleware():
  26. return "django.middleware.csrf.CsrfViewMiddleware" in settings.MIDDLEWARE_CLASSES
  27. @register(Tags.security, deploy=True)
  28. def check_csrf_middleware(app_configs, **kwargs):
  29. passed_check = _csrf_middleware()
  30. return [] if passed_check else [W003]
  31. @register(Tags.security, deploy=True)
  32. def check_csrf_cookie_secure(app_configs, **kwargs):
  33. passed_check = (
  34. not _csrf_middleware() or
  35. settings.CSRF_COOKIE_SECURE
  36. )
  37. return [] if passed_check else [W016]
  38. @register(Tags.security, deploy=True)
  39. def check_csrf_cookie_httponly(app_configs, **kwargs):
  40. passed_check = (
  41. not _csrf_middleware() or
  42. settings.CSRF_COOKIE_HTTPONLY
  43. )
  44. return [] if passed_check else [W017]