base.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import base64
  2. import logging
  3. import string
  4. import warnings
  5. from datetime import datetime, timedelta
  6. from django.conf import settings
  7. from django.contrib.sessions.exceptions import SuspiciousSession
  8. from django.core import signing
  9. from django.core.exceptions import SuspiciousOperation
  10. from django.utils import timezone
  11. from django.utils.crypto import (
  12. constant_time_compare, get_random_string, salted_hmac,
  13. )
  14. from django.utils.deprecation import RemovedInDjango40Warning
  15. from django.utils.module_loading import import_string
  16. from django.utils.translation import LANGUAGE_SESSION_KEY
  17. # session_key should not be case sensitive because some backends can store it
  18. # on case insensitive file systems.
  19. VALID_KEY_CHARS = string.ascii_lowercase + string.digits
  20. class CreateError(Exception):
  21. """
  22. Used internally as a consistent exception type to catch from save (see the
  23. docstring for SessionBase.save() for details).
  24. """
  25. pass
  26. class UpdateError(Exception):
  27. """
  28. Occurs if Django tries to update a session that was deleted.
  29. """
  30. pass
  31. class SessionBase:
  32. """
  33. Base class for all Session classes.
  34. """
  35. TEST_COOKIE_NAME = 'testcookie'
  36. TEST_COOKIE_VALUE = 'worked'
  37. __not_given = object()
  38. def __init__(self, session_key=None):
  39. self._session_key = session_key
  40. self.accessed = False
  41. self.modified = False
  42. self.serializer = import_string(settings.SESSION_SERIALIZER)
  43. def __contains__(self, key):
  44. return key in self._session
  45. def __getitem__(self, key):
  46. if key == LANGUAGE_SESSION_KEY:
  47. warnings.warn(
  48. 'The user language will no longer be stored in '
  49. 'request.session in Django 4.0. Read it from '
  50. 'request.COOKIES[settings.LANGUAGE_COOKIE_NAME] instead.',
  51. RemovedInDjango40Warning, stacklevel=2,
  52. )
  53. return self._session[key]
  54. def __setitem__(self, key, value):
  55. self._session[key] = value
  56. self.modified = True
  57. def __delitem__(self, key):
  58. del self._session[key]
  59. self.modified = True
  60. @property
  61. def key_salt(self):
  62. return 'django.contrib.sessions.' + self.__class__.__qualname__
  63. def get(self, key, default=None):
  64. return self._session.get(key, default)
  65. def pop(self, key, default=__not_given):
  66. self.modified = self.modified or key in self._session
  67. args = () if default is self.__not_given else (default,)
  68. return self._session.pop(key, *args)
  69. def setdefault(self, key, value):
  70. if key in self._session:
  71. return self._session[key]
  72. else:
  73. self.modified = True
  74. self._session[key] = value
  75. return value
  76. def set_test_cookie(self):
  77. self[self.TEST_COOKIE_NAME] = self.TEST_COOKIE_VALUE
  78. def test_cookie_worked(self):
  79. return self.get(self.TEST_COOKIE_NAME) == self.TEST_COOKIE_VALUE
  80. def delete_test_cookie(self):
  81. del self[self.TEST_COOKIE_NAME]
  82. def _hash(self, value):
  83. # RemovedInDjango40Warning: pre-Django 3.1 format will be invalid.
  84. key_salt = "django.contrib.sessions" + self.__class__.__name__
  85. return salted_hmac(key_salt, value).hexdigest()
  86. def encode(self, session_dict):
  87. "Return the given session dictionary serialized and encoded as a string."
  88. # RemovedInDjango40Warning: DEFAULT_HASHING_ALGORITHM will be removed.
  89. if settings.DEFAULT_HASHING_ALGORITHM == 'sha1':
  90. return self._legacy_encode(session_dict)
  91. return signing.dumps(
  92. session_dict, salt=self.key_salt, serializer=self.serializer,
  93. compress=True,
  94. )
  95. def decode(self, session_data):
  96. try:
  97. return signing.loads(session_data, salt=self.key_salt, serializer=self.serializer)
  98. # RemovedInDjango40Warning: when the deprecation ends, handle here
  99. # exceptions similar to what _legacy_decode() does now.
  100. except signing.BadSignature:
  101. try:
  102. # Return an empty session if data is not in the pre-Django 3.1
  103. # format.
  104. return self._legacy_decode(session_data)
  105. except Exception:
  106. logger = logging.getLogger('django.security.SuspiciousSession')
  107. logger.warning('Session data corrupted')
  108. return {}
  109. except Exception:
  110. return self._legacy_decode(session_data)
  111. def _legacy_encode(self, session_dict):
  112. # RemovedInDjango40Warning.
  113. serialized = self.serializer().dumps(session_dict)
  114. hash = self._hash(serialized)
  115. return base64.b64encode(hash.encode() + b':' + serialized).decode('ascii')
  116. def _legacy_decode(self, session_data):
  117. # RemovedInDjango40Warning: pre-Django 3.1 format will be invalid.
  118. encoded_data = base64.b64decode(session_data.encode('ascii'))
  119. try:
  120. # could produce ValueError if there is no ':'
  121. hash, serialized = encoded_data.split(b':', 1)
  122. expected_hash = self._hash(serialized)
  123. if not constant_time_compare(hash.decode(), expected_hash):
  124. raise SuspiciousSession("Session data corrupted")
  125. else:
  126. return self.serializer().loads(serialized)
  127. except Exception as e:
  128. # ValueError, SuspiciousOperation, unpickling exceptions. If any of
  129. # these happen, just return an empty dictionary (an empty session).
  130. if isinstance(e, SuspiciousOperation):
  131. logger = logging.getLogger('django.security.%s' % e.__class__.__name__)
  132. logger.warning(str(e))
  133. return {}
  134. def update(self, dict_):
  135. self._session.update(dict_)
  136. self.modified = True
  137. def has_key(self, key):
  138. return key in self._session
  139. def keys(self):
  140. return self._session.keys()
  141. def values(self):
  142. return self._session.values()
  143. def items(self):
  144. return self._session.items()
  145. def clear(self):
  146. # To avoid unnecessary persistent storage accesses, we set up the
  147. # internals directly (loading data wastes time, since we are going to
  148. # set it to an empty dict anyway).
  149. self._session_cache = {}
  150. self.accessed = True
  151. self.modified = True
  152. def is_empty(self):
  153. "Return True when there is no session_key and the session is empty."
  154. try:
  155. return not self._session_key and not self._session_cache
  156. except AttributeError:
  157. return True
  158. def _get_new_session_key(self):
  159. "Return session key that isn't being used."
  160. while True:
  161. session_key = get_random_string(32, VALID_KEY_CHARS)
  162. if not self.exists(session_key):
  163. return session_key
  164. def _get_or_create_session_key(self):
  165. if self._session_key is None:
  166. self._session_key = self._get_new_session_key()
  167. return self._session_key
  168. def _validate_session_key(self, key):
  169. """
  170. Key must be truthy and at least 8 characters long. 8 characters is an
  171. arbitrary lower bound for some minimal key security.
  172. """
  173. return key and len(key) >= 8
  174. def _get_session_key(self):
  175. return self.__session_key
  176. def _set_session_key(self, value):
  177. """
  178. Validate session key on assignment. Invalid values will set to None.
  179. """
  180. if self._validate_session_key(value):
  181. self.__session_key = value
  182. else:
  183. self.__session_key = None
  184. session_key = property(_get_session_key)
  185. _session_key = property(_get_session_key, _set_session_key)
  186. def _get_session(self, no_load=False):
  187. """
  188. Lazily load session from storage (unless "no_load" is True, when only
  189. an empty dict is stored) and store it in the current instance.
  190. """
  191. self.accessed = True
  192. try:
  193. return self._session_cache
  194. except AttributeError:
  195. if self.session_key is None or no_load:
  196. self._session_cache = {}
  197. else:
  198. self._session_cache = self.load()
  199. return self._session_cache
  200. _session = property(_get_session)
  201. def get_session_cookie_age(self):
  202. return settings.SESSION_COOKIE_AGE
  203. def get_expiry_age(self, **kwargs):
  204. """Get the number of seconds until the session expires.
  205. Optionally, this function accepts `modification` and `expiry` keyword
  206. arguments specifying the modification and expiry of the session.
  207. """
  208. try:
  209. modification = kwargs['modification']
  210. except KeyError:
  211. modification = timezone.now()
  212. # Make the difference between "expiry=None passed in kwargs" and
  213. # "expiry not passed in kwargs", in order to guarantee not to trigger
  214. # self.load() when expiry is provided.
  215. try:
  216. expiry = kwargs['expiry']
  217. except KeyError:
  218. expiry = self.get('_session_expiry')
  219. if not expiry: # Checks both None and 0 cases
  220. return self.get_session_cookie_age()
  221. if not isinstance(expiry, datetime):
  222. return expiry
  223. delta = expiry - modification
  224. return delta.days * 86400 + delta.seconds
  225. def get_expiry_date(self, **kwargs):
  226. """Get session the expiry date (as a datetime object).
  227. Optionally, this function accepts `modification` and `expiry` keyword
  228. arguments specifying the modification and expiry of the session.
  229. """
  230. try:
  231. modification = kwargs['modification']
  232. except KeyError:
  233. modification = timezone.now()
  234. # Same comment as in get_expiry_age
  235. try:
  236. expiry = kwargs['expiry']
  237. except KeyError:
  238. expiry = self.get('_session_expiry')
  239. if isinstance(expiry, datetime):
  240. return expiry
  241. expiry = expiry or self.get_session_cookie_age()
  242. return modification + timedelta(seconds=expiry)
  243. def set_expiry(self, value):
  244. """
  245. Set a custom expiration for the session. ``value`` can be an integer,
  246. a Python ``datetime`` or ``timedelta`` object or ``None``.
  247. If ``value`` is an integer, the session will expire after that many
  248. seconds of inactivity. If set to ``0`` then the session will expire on
  249. browser close.
  250. If ``value`` is a ``datetime`` or ``timedelta`` object, the session
  251. will expire at that specific future time.
  252. If ``value`` is ``None``, the session uses the global session expiry
  253. policy.
  254. """
  255. if value is None:
  256. # Remove any custom expiration for this session.
  257. try:
  258. del self['_session_expiry']
  259. except KeyError:
  260. pass
  261. return
  262. if isinstance(value, timedelta):
  263. value = timezone.now() + value
  264. self['_session_expiry'] = value
  265. def get_expire_at_browser_close(self):
  266. """
  267. Return ``True`` if the session is set to expire when the browser
  268. closes, and ``False`` if there's an expiry date. Use
  269. ``get_expiry_date()`` or ``get_expiry_age()`` to find the actual expiry
  270. date/age, if there is one.
  271. """
  272. if self.get('_session_expiry') is None:
  273. return settings.SESSION_EXPIRE_AT_BROWSER_CLOSE
  274. return self.get('_session_expiry') == 0
  275. def flush(self):
  276. """
  277. Remove the current session data from the database and regenerate the
  278. key.
  279. """
  280. self.clear()
  281. self.delete()
  282. self._session_key = None
  283. def cycle_key(self):
  284. """
  285. Create a new session key, while retaining the current session data.
  286. """
  287. data = self._session
  288. key = self.session_key
  289. self.create()
  290. self._session_cache = data
  291. if key:
  292. self.delete(key)
  293. # Methods that child classes must implement.
  294. def exists(self, session_key):
  295. """
  296. Return True if the given session_key already exists.
  297. """
  298. raise NotImplementedError('subclasses of SessionBase must provide an exists() method')
  299. def create(self):
  300. """
  301. Create a new session instance. Guaranteed to create a new object with
  302. a unique key and will have saved the result once (with empty data)
  303. before the method returns.
  304. """
  305. raise NotImplementedError('subclasses of SessionBase must provide a create() method')
  306. def save(self, must_create=False):
  307. """
  308. Save the session data. If 'must_create' is True, create a new session
  309. object (or raise CreateError). Otherwise, only update an existing
  310. object and don't create one (raise UpdateError if needed).
  311. """
  312. raise NotImplementedError('subclasses of SessionBase must provide a save() method')
  313. def delete(self, session_key=None):
  314. """
  315. Delete the session data under this key. If the key is None, use the
  316. current session key value.
  317. """
  318. raise NotImplementedError('subclasses of SessionBase must provide a delete() method')
  319. def load(self):
  320. """
  321. Load the session data and return a dictionary.
  322. """
  323. raise NotImplementedError('subclasses of SessionBase must provide a load() method')
  324. @classmethod
  325. def clear_expired(cls):
  326. """
  327. Remove expired sessions from the session store.
  328. If this operation isn't possible on a given backend, it should raise
  329. NotImplementedError. If it isn't necessary, because the backend has
  330. a built-in expiration mechanism, it should be a no-op.
  331. """
  332. raise NotImplementedError('This backend does not support clear_expired().')