This file is indexed.

/usr/share/pyshared/pyweblib/session.py is in python-weblib 1.3.9-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
"""
pyweblib.session - server-side web session handling
(C) 2001 by Michael Stroeder <michael@stroeder.com>

This module implements server side session handling stored in
arbitrary string-keyed dictionary objects

This module is distributed under the terms of the
GPL (GNU GENERAL PUBLIC LICENSE) Version 2
(see http://www.gnu.org/copyleft/gpl.html)

$Id: session.py,v 1.28 2010/10/27 08:27:10 michael Exp $
"""

__version__ = '0.3.5'

import string,re,random,time,pickle

SESSION_ID_CHARS=string.letters+string.digits+'-._'

SESSION_CROSSCHECKVARS = (
  """
  List of environment variables assumed to be constant throughout
  web sessions with the same ID if existent.
  These env vars are cross-checked each time when restoring an
  web session to reduce the risk of session-hijacking.

  Note: REMOTE_ADDR and REMOTE_HOST might not be constant if the client
  access comes through a network of web proxy siblings.
  """
  # REMOTE_ADDR and REMOTE_HOST might not be constant if the client
  # access comes through a network of web proxy siblings.
  'REMOTE_ADDR','REMOTE_HOST',
  'REMOTE_IDENT','REMOTE_USER',
  # If the proxy sets them but can be easily spoofed
  'FORWARDED_FOR','HTTP_X_FORWARDED_FOR',
  # These two are not really secure
  'HTTP_USER_AGENT','HTTP_ACCEPT_CHARSET',
  # SSL session ID if running on SSL server capable
  # of reusing SSL sessions
  'SSL_SESSION_ID',
  # env vars of client certs used for SSL strong authentication
  'SSL_CLIENT_V_START','SSL_CLIENT_V_END',
  'SSL_CLIENT_I_DN','SSL_CLIENT_IDN',
  'SSL_CLIENT_S_DN','SSL_CLIENT_SDN',
  'SSL_CLIENT_M_SERIAL','SSL_CLIENT_CERT_SERIAL',
)

##############################################################################
# Exception classes
##############################################################################

class SessionException(Exception):
  """Raised if """
  def __init__(self, *args):
    self.args = args

class CorruptData(SessionException):
  """Raised if data was corrupt, e.g. UnpicklingError occured"""
  def __str__(self):
    return "Error during retrieving corrupted session data. Session deleted."

class GenerateIDError(SessionException):
  """Raised if generation of unique session ID failed."""
  def __init__(self, maxtry):
    self.maxtry = maxtry
  def __str__(self):
    return "Could not create new session id. Tried %d times." % (self.maxtry)

class SessionExpired(SessionException):
  """Raised if session is expired."""
  def __init__(self, timestamp, session_data):
    self.timestamp = timestamp
    self.session_data = session_data
  def __str__(self):
    return "Session expired %s." % (time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime(self.timestamp)))

class SessionHijacked(SessionException):
  """Raised if hijacking of session was detected."""
  def __init__(self, failed_vars):
    self.failed_vars = failed_vars
  def __str__(self):
    return "Crosschecking of the following env vars failed: %s." % (
      self.failed_vars
    )

class MaxSessionCountExceeded(SessionException):
  """Raised if maximum number of sessions is exceeded."""
  def __init__(self, max_session_count):
    self.max_session_count = max_session_count
  def __str__(self):
    return "Maximum number of sessions exceeded. Limit is %d." % (
      self.max_session_count
    )

class BadSessionId(SessionException):
  """Raised if session ID not found in session dictionary."""
  def __init__(self, session_id):
    self.session_id = session_id
  def __str__(self):
    return "No session with key %s." % (self.session_id)

class InvalidSessionId(SessionException):
  """Raised if session ID not found in session dictionary."""
  def __init__(self, session_id):
    self.session_id = session_id
  def __str__(self):
    return "No session with key %s." % (self.session_id)

try:
  import threading
  from threading import Lock as ThreadingLock

except ImportError:
  # Python installation has no thread support
  class ThreadingLock:
    """
    mimikri for threading.Lock()
    """
    def acquire(self):
      pass
    def release(self):
      pass

else:

  class CleanUpThread(threading.Thread):
    """
    Thread class for clean-up thread
    """
    def __init__(self,sessionInstance,interval=60):
      self._sessionInstance = sessionInstance
      self._interval = interval
      self._stop_event = threading.Event()
      self._removed = 0
      threading.Thread.__init__(self,name=self.__class__.__module__+self.__class__.__name__)

    def run(self):
      """Thread function for cleaning up session database"""
      while not self._stop_event.isSet():
        self._removed += self._sessionInstance.cleanUp()
        self._stop_event.wait(self._interval)

    def __repr__(self):
      return '%s: %d sessions removed' % (
        self.getName(),self._removed
      )

    def join(self,timeout=0.0):
      self._stop_event.set()
      threading.Thread.join(self,timeout)


class WebSession:
  """
  The session class which handles storing and retrieving of session data
  in a dictionary-like sessiondict object.
  """

  def __init__(
    self,
    dictobj=None,
    expireDeactivate=0,
    expireRemove=0,
    crossCheckVars=None,
    maxSessionCount=None,
    sessionIDLength=12,
    sessionIDChars=None,
  ):
    """
    dictobj
        has to be a instance of a dictionary-like object
        (e.g. derived from UserDict or shelve)
    expireDeactivate
        amount of time (secs) after which a session
        expires and a SessionExpired exception is
        raised which contains the session data.
    expireRemove
        Amount of time (secs) after which a session
        expires and the session data is silently deleted.
        A InvalidSessionId exception is raised in this case if
        the application trys to access the session ID again.
    crossCheckVars
        List of keys of variables cross-checked for each
        retrieval of session data in retrieveSession(). If None
        SESSION_CROSSCHECKVARS is used.
    maxSessionCount
        Maximum number of valid sessions. This affects
        behaviour of retrieveSession() which raises.
        None means unlimited number of sessions.
    sessionIDLength
        Exact integer length of the session ID generated
    sessionIDChars
        String containing the valid chars for session IDs
        (if this is zero-value the default is SESSION_ID_CHARS)
    """
    if dictobj is None:
      self.sessiondict = {}
    else:
      self.sessiondict = dictobj
    self.expireDeactivate = expireDeactivate
    self.expireRemove = expireRemove
    self._session_lock = ThreadingLock()
    if crossCheckVars is None:
      crossCheckVars = SESSION_CROSSCHECKVARS
    self.crossCheckVars = crossCheckVars
    self.maxSessionCount = maxSessionCount
    self.sessionCounter = 0
    self.session_id_len = sessionIDLength
    self.session_id_chars = sessionIDChars or SESSION_ID_CHARS
    self.session_id_re = re.compile('^[%s]+$' % (re.escape(self.session_id_chars)))
    return # __init__()

  def sync(self):
    """
    Call sync if self.sessiondict has .sync() method
    """
    if hasattr(self.sessiondict,'sync'):
      self.sessiondict.sync()

  def close(self):
    """
    Call close() if self.sessiondict has .close() method
    """
    if hasattr(self.sessiondict,'close'):
      # Close e.g. a database
      self.sessiondict.close()
    else:
      # Make sessiondict inaccessible
      self.sessiondict = None

  def _validateSessionIdFormat(self,session_id):
    """
    Validate the format of session_id. Implementation
    has to match IDs produced in method _generateSessionID()
    """
    if len(session_id)!=self.session_id_len or self.session_id_re.match(session_id) is None:
      raise BadSessionId(session_id)
    return

  def _crosscheckSessionEnv(self,stored_env,current_env):
    """
    Returns a list of keys of items which differ in
    stored_env and current_env.
    """
    return [
      k
      for k in stored_env.keys()
      if stored_env[k]!=current_env.get(k,None)
    ]

  def _generateCrosscheckEnv(self,current_env):
    """
    Generate a dictionary of env vars for session cross-checking
    """
    crosscheckenv = {}
    for k in self.crossCheckVars:
      if current_env.has_key(k):
        crosscheckenv[k] = current_env[k]
    return crosscheckenv

  def _generateSessionID(self,maxtry=1):
    """
    Generate a new random and unique session id string
    """
    def choice_id():
      return ''.join([ random.choice(SESSION_ID_CHARS) for i in range(self.session_id_len) ])
    newid = choice_id()
    tried = 0
    while self.sessiondict.has_key(newid) and (not maxtry or tried<maxtry):
      newid = choice_id()
      tried = tried+1
    if maxtry and tried>=maxtry:
      raise GenerateIDError(maxtry)
    else:
      return newid

  def storeSession(self,session_id,session_data):
    """
    Store session_data under session_id.
    """
    self._session_lock.acquire()
    try:
      # Store session data with timestamp
      self.sessiondict[session_id] = (time.time(),session_data)
      self.sync()
    finally:
      self._session_lock.release()
    return session_id

  def deleteSession(self,session_id):
    """
    Delete session_data referenced by session_id.
    """
    # Delete the session data
    self._session_lock.acquire()
    try:
      if self.sessiondict.has_key(session_id):
        del self.sessiondict[session_id]
      if self.sessiondict.has_key('__session_checkvars__'+session_id):
        del self.sessiondict['__session_checkvars__'+session_id]
      self.sync()
    finally:
      self._session_lock.release()
    return session_id

  def retrieveSession(self,session_id,env={}):
    """
    Retrieve session data
    """
    self._validateSessionIdFormat(session_id)
    session_vars_key = '__session_checkvars__'+session_id
    # Check if session id exists
    if not (
      self.sessiondict.has_key(session_id) and \
      self.sessiondict.has_key(session_vars_key)
    ):
      raise InvalidSessionId(session_id)
    # Read the timestamped session data
    try:
      self._session_lock.acquire()
      try:
        session_checkvars = self.sessiondict[session_vars_key]
        timestamp,session_data = self.sessiondict[session_id]
      finally:
        self._session_lock.release()
    except pickle.UnpicklingError:
      self.deleteSession(session_id)
      raise CorruptData
    current_time = time.time()
    # Check if session data is already expired
    if self.expireDeactivate and \
       (current_time>timestamp+self.expireDeactivate):
      # Remove session entry
      self.deleteSession(session_id)
      # Check if application should be able to allow relogin
      if self.expireRemove and \
         (current_time>timestamp+self.expireRemove):
        raise InvalidSessionId(session_id)
      else:
        raise SessionExpired(timestamp,session_data)
    failed_vars = self._crosscheckSessionEnv(session_checkvars,env)
    if failed_vars:
      # Remove session entry
      raise SessionHijacked(failed_vars)
    # Everything's ok => return the session data
    return session_data

  def newSession(self,env={}):
    """
    Store session data under session id
    """
    if self.maxSessionCount and len(self.sessiondict)/2+1>self.maxSessionCount:
      raise MaxSessionCountExceeded(self.maxSessionCount)
    self._session_lock.acquire()
    try:
      # generate completely new session data entry
      session_id=self._generateSessionID(maxtry=3)
      # Store session data with timestamp if session ID
      # was created successfully
      self.sessiondict[session_id] = (
        # Current time
        time.time(),
        # Store a dummy string first
        '_created_',
      )
      self.sessiondict['__session_checkvars__'+session_id] = self._generateCrosscheckEnv(env)
      self.sync()
      self.sessionCounter += 1
    finally:
      self._session_lock.release()
    return session_id

  def cleanUp(self):
    """
    Search for expired session entries and delete them.

    Returns integer counter of deleted sessions as result.
    """
    current_time = time.time()
    result = 0
    for session_id in self.sessiondict.keys():
      if not session_id.startswith('__'):
        try:
          session_timestamp = self.sessiondict[session_id][0]
        except InvalidSessionId:
          # Avoid race condition. The session might have been
          # deleted in the meantime. But make sure everything is deleted.
          self.deleteSession(session_id)
        else:
          # Check expiration time
          if session_timestamp+self.expireRemove<current_time:
            self.deleteSession(session_id)
            result += 1
    return result

# Initialization
random.seed()