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.
 
 
 
 

356 lines
12 KiB

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