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.

sessions.py 2.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. from django.conf import settings
  2. from .. import Tags, Warning, register
  3. def add_session_cookie_message(message):
  4. return message + (
  5. " Using a secure-only session cookie makes it more difficult for "
  6. "network traffic sniffers to hijack user sessions."
  7. )
  8. W010 = Warning(
  9. add_session_cookie_message(
  10. "You have 'django.contrib.sessions' in your INSTALLED_APPS, "
  11. "but you have not set SESSION_COOKIE_SECURE to True."
  12. ),
  13. id='security.W010',
  14. )
  15. W011 = Warning(
  16. add_session_cookie_message(
  17. "You have 'django.contrib.sessions.middleware.SessionMiddleware' "
  18. "in your MIDDLEWARE, but you have not set "
  19. "SESSION_COOKIE_SECURE to True."
  20. ),
  21. id='security.W011',
  22. )
  23. W012 = Warning(
  24. add_session_cookie_message("SESSION_COOKIE_SECURE is not set to True."),
  25. id='security.W012',
  26. )
  27. def add_httponly_message(message):
  28. return message + (
  29. " Using an HttpOnly session cookie makes it more difficult for "
  30. "cross-site scripting attacks to hijack user sessions."
  31. )
  32. W013 = Warning(
  33. add_httponly_message(
  34. "You have 'django.contrib.sessions' in your INSTALLED_APPS, "
  35. "but you have not set SESSION_COOKIE_HTTPONLY to True.",
  36. ),
  37. id='security.W013',
  38. )
  39. W014 = Warning(
  40. add_httponly_message(
  41. "You have 'django.contrib.sessions.middleware.SessionMiddleware' "
  42. "in your MIDDLEWARE, but you have not set "
  43. "SESSION_COOKIE_HTTPONLY to True."
  44. ),
  45. id='security.W014',
  46. )
  47. W015 = Warning(
  48. add_httponly_message("SESSION_COOKIE_HTTPONLY is not set to True."),
  49. id='security.W015',
  50. )
  51. @register(Tags.security, deploy=True)
  52. def check_session_cookie_secure(app_configs, **kwargs):
  53. errors = []
  54. if not settings.SESSION_COOKIE_SECURE:
  55. if _session_app():
  56. errors.append(W010)
  57. if _session_middleware():
  58. errors.append(W011)
  59. if len(errors) > 1:
  60. errors = [W012]
  61. return errors
  62. @register(Tags.security, deploy=True)
  63. def check_session_cookie_httponly(app_configs, **kwargs):
  64. errors = []
  65. if not settings.SESSION_COOKIE_HTTPONLY:
  66. if _session_app():
  67. errors.append(W013)
  68. if _session_middleware():
  69. errors.append(W014)
  70. if len(errors) > 1:
  71. errors = [W015]
  72. return errors
  73. def _session_middleware():
  74. return 'django.contrib.sessions.middleware.SessionMiddleware' in settings.MIDDLEWARE
  75. def _session_app():
  76. return "django.contrib.sessions" in settings.INSTALLED_APPS