source: TI12-security/trunk/python/ndg.security.server/ndg/security/server/sessionmanager.py @ 4839

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.server/ndg/security/server/sessionmanager.py@4839
Revision 4839, 47.2 KB checked in by pjkersha, 11 years ago (diff)

Changed licence from Q Public to BSD

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1"""NDG Security server side session management and security includes
2UserSession and SessionManager classes.
3
4NERC Data Grid Project
5"""
6__author__ = "P J Kershaw"
7__date__ = "02/06/05"
8__copyright__ = "(C) 2009 Science and Technology Facilities Council"
9__license__ = "BSD - see LICENSE file in top-level directory"__contact__ = "Philip.Kershaw@stfc.ac.uk"
10__revision__ = '$Id:sessionmanager.py 4367 2008-10-29 09:27:59Z pjkersha $'
11import logging
12log = logging.getLogger(__name__)
13
14# Modify sys.path when carrying out dynamic import for Credential Repository
15import sys, os
16
17# Base 64 encode session IDs if returned in strings - urandom's output may
18# not be suitable for printing!
19import base64
20
21# Time module for use with cookie expiry
22from time import strftime
23from datetime import datetime
24
25# For parsing of properties file
26try: # python 2.5
27    from xml.etree import cElementTree as ElementTree
28except ImportError:
29    # if you've installed it yourself it comes this way
30    import cElementTree as ElementTree
31
32# Session Manager URI in cookie
33from Crypto.Cipher import AES
34
35# Credential Wallet
36from ndg.security.common.credentialwallet import CredentialWallet, \
37    CredentialRepository, CredentialWalletError, \
38    CredentialWalletAttributeRequestDenied, NullCredentialRepository
39   
40from ndg.security.common.wssecurity import WSSecurityConfig
41from ndg.security.common.X509 import X500DN, X509Cert, X509CertParse, \
42                                X509CertExpired, X509CertInvalidNotBeforeTime
43
44# Use client package to allow redirection of authorisation requests and
45# to retrieve Attribute Authority public key
46from ndg.security.common.sessionmanager import SessionManagerClient
47
48# generic parser to read INI/XML properties file
49from ndg.security.common.utils.configfileparsers import \
50                                                INIPropertyFileWithValidation
51
52# utility to instantiate classes dynamically
53from ndg.security.common.utils.classfactory import instantiateClass
54
55
56class _SessionException(Exception):
57    """Base class for all Exceptions in this module.  Overrides Exception to
58    enable writing to the log"""
59    def __init__(self, msg):
60        log.error(msg)
61        Exception.__init__(self, msg)
62
63class UserSessionError(_SessionException):   
64    """Exception handling for NDG User Session class."""
65
66class InvalidUserSession(UserSessionError):   
67    """Problem with a session's validity"""
68
69class UserSessionExpired(UserSessionError):   
70    """Raise when session's X.509 cert. has expired"""
71
72class UserSessionX509CertNotBeforeTimeError(UserSessionError):   
73    """Raise when session's X.509 cert. not before time is before the current
74    system time"""
75   
76
77# Inheriting from 'object' allows Python 'new-style' class with Get/Set
78# access methods
79class UserSession(object):
80    """Session details - created when a user logs into NDG"""
81    sessIdLen = 32
82   
83    def __init__(self, **credentialWalletKeys):
84        """Initialise UserSession with keywords to CredentialWallet"""
85               
86        log.debug("UserSession.__init__ ...")
87       
88        # Each User Session has one or more browser sessions associated with
89        # it.  These are stored in a list
90        self.__sessIdList = []
91        self.addNewSessID()
92        self.__credentialWallet = CredentialWallet(**credentialWalletKeys)
93
94        log.info("Created a session with ID = %s" % self.__sessIdList[-1])
95
96    def __getCredentialWallet(self):
97        """Get Credential Wallet instance"""
98        return self.__credentialWallet
99   
100    credentialWallet = property(fget=__getCredentialWallet,
101                          doc="Read-only access to CredentialWallet instance")
102
103    def __getSessIdList(self):
104        """Get Session ID list - last item is latest allocated for this
105        session"""
106        return self.__sessIdList
107   
108    sessIdList = property(fget=__getSessIdList,
109                          doc="Read-only access to Session ID list")
110
111    def __latestSessID(self):
112        """Get the session ID most recently allocated"""
113        return self.__sessIdList[-1]
114   
115    # Publish as an attribute
116    latestSessID = property(fget=__latestSessID,
117                            doc="Latest Session ID allocated")
118
119    def addNewSessID(self):
120        """Add a new session ID to be associated with this UserSession
121        instance"""
122
123        # base 64 encode output from urandom - raw output from urandom is
124        # causes problems when passed over SOAP.  A consequence of this is
125        # that the string length of the session ID will almost certainly be
126        # longer than UserSession.sessIdLen
127        sessID = base64.urlsafe_b64encode(os.urandom(UserSession.sessIdLen))
128        self.__sessIdList.append(sessID)
129
130    @staticmethod
131    def encodeTxt(txt, encrKey=None):
132        """Encode Session Manager URI to allow inclusion in a web browser
133        session cookie
134       
135        The address is optionally encrypted and then base 64 encoded use a
136        URL safe encoding
137       
138        @type encrKey: string
139        @param encrKey: 16 char encryption key used to encrypt the URI.  If
140        omitted or set None, the URI is not encrypted but merely base 64
141        encoded"""
142       
143        if encrKey is not None:
144            # Text length must be a multiple of 16 for AES encryption
145            try:
146                mod = len(txt) % 16
147                nPad = mod and 16 - mod or 0
148                   
149                # Add padding
150                paddedURI = txt + ''.join(' '*nPad)
151            except Exception, e:
152                raise UserSessionError("Padding text for encryption: %s" % e)
153       
154            # Encrypt
155            try:
156                txt = AES.new(encrKey, AES.MODE_ECB).encrypt(paddedURI)
157           
158            except Exception, e:
159                raise UserSessionError("Encrypting text: %s" % e)
160
161        try:
162            return base64.urlsafe_b64encode(txt)
163       
164        except Exception, e:
165            raise UserSessionError("Encoding Session Manager URI: %s" % e)
166       
167    @staticmethod                                   
168    def decodeTxt(txt, encrKey=None):
169        """Decode the URI from cookie set by another Session Manager.  This
170        is required when reading a session cookie to find out which
171        Session Manager holds the client's session
172       
173        @type txt: string
174        @param txt: base 64 encoded encrypted text
175       
176        @type encrKey: string
177        @param encrKey: 16 char encryption key used to encrypt the URI.  If
178        omitted or set None, the URI is assumed to be unencrypted"""
179
180        try:
181            # Convert if unicode type - unicode causes TypeError with
182            # base64.urlsafe_b64decode
183            if isinstance(txt, unicode):
184                txt = str(txt)
185               
186            # Decode from base 64
187            b64DecodedEncrTxt = base64.urlsafe_b64decode(txt)
188           
189        except Exception, e:
190            raise SessionManagerError("Decoding text: %s" % e)         
191        if encrKey is not None:
192            try:
193                aes = AES.new(encrKey, AES.MODE_ECB)
194               
195                # Decrypt and strip trailing spaces
196                return aes.decrypt(b64DecodedEncrTxt).strip()
197           
198            except Exception, e:
199                raise SessionManagerError("Decrypting Session Manager URI: %s" % e)           
200        else:
201            return b64DecodedEncrTxt
202       
203class SessionManagerError(_SessionException):   
204    """Exception handling for NDG Session Manager class."""
205
206class SessionNotFound(SessionManagerError):
207    """Raise from SessionManager._connect2UserSession when session ID is not
208    found in the Session dictionary"""
209
210
211class SessionManager(dict):
212    """NDG authentication and session handling
213   
214    @type propertyDefaults: dict
215    @cvar propertyDefaults: list of the valid properties file element names and
216    sub-elements where appropriate
217   
218    @type _confDir: string
219    @cvar _confDir: configuration directory under $NDGSEC_DIR - default
220    location for properties file
221   
222    @type _propFileName: string
223    @cvar _propFileName: default file name for properties file under
224    _confDir
225   
226    @type credentialRepositoryPropertyDefaults: dict
227    @cvar credentialRepositoryPropertyDefaults: permitted properties file
228    elements for configuring the Crendential Repository.  Those set to
229    NotImplemented indicate properties that must be set.  For the others, the
230    value indicates the default if not present in the file"""
231
232    # Valid configuration property keywords
233    AUTHN_KEYNAME = 'authNService'   
234    CREDREPOS_KEYNAME = 'credentialRepository'   
235    CREDWALLET_KEYNAME = 'credentialWallet'
236    defaultSectionName = 'sessionManager'
237   
238    authNServicePropertyDefaults = {
239        'moduleFilePath': None,
240        'moduleName': None,
241        'className': None,
242    }
243   
244    credentialRepositoryPropertyDefaults = {
245        'moduleFilePath': None,
246        'moduleName': None,
247        'className': 'NullCredentialRepository',
248    }
249
250    propertyDefaults = {
251        'portNum':                None,
252        'useSSL':                 False,
253        'sslCertFile':            None,
254        'sslKeyFile':             None,
255        'sslCACertDir':           None,
256        AUTHN_KEYNAME:            authNServicePropertyDefaults, 
257        CREDREPOS_KEYNAME:        credentialRepositoryPropertyDefaults
258    }
259
260    _confDir = "conf"
261    _propFileName = "sessionMgrProperties.xml"
262   
263    def __init__(self, 
264                 propFilePath=None, 
265                 propFileSection='DEFAULT',
266                 propPrefix='',
267                 **prop):       
268        """Create a new session manager to manager NDG User Sessions
269       
270        @type propFilePath: basestring
271        @param propFilePath: path to properties file
272        @type propFileSection: basestring
273        @param propFileSection: applies to ini format config files only - the
274        section to read the Session Managers settings from
275        set in properties file
276        @type prop: dict
277        @param **prop: set any other properties corresponding to the tags in
278        the properties file as keywords"""       
279
280        log.info("Initialising service ...")
281       
282        # Base class initialisation
283        dict.__init__(self)
284
285        # Key user sessions by session ID
286        self.__sessDict = {}
287
288        # Key user sessions by user DN
289        self.__dnDict = {}
290
291        # Finally, also key by username
292        self.__usernameDict = {}
293       
294        # Credential Repository interface only set if properties file is set
295        # otherwise explicit calls are necessary to set credentialRepositoryProp via
296        # setProperties/readProperties and then loadCredentialRepositoryInterface
297        self._credentialRepository = None
298   
299        # Set from input or use defaults based or environment variables
300        self.propFilePath = propFilePath
301       
302        self.propFileSection = propFileSection
303        self.propPrefix = propPrefix
304        self._cfg = None
305       
306        # Set properties from file
307        self.readProperties()
308
309       
310        # Set any properties that were provided by keyword input
311        # NB If any are duplicated with tags in the properties file they
312        # will overwrite the latter
313        self.setProperties(**prop)
314
315        # Instantiate the authentication service to use with the session
316        # manager
317        self.initAuthNService()
318       
319        # Call here as we can safely expect that all Credential Repository
320        # parameters have been set above
321        self.initCredentialRepository()   
322       
323       
324    def initAuthNService(self):
325        '''Load Authentication Service Interface from property settings'''
326        authNProp = self.__prop[SessionManager.AUTHN_KEYNAME]
327        authNModFilePath = authNProp.pop('moduleFilePath', None)
328       
329        self.__authNService = instantiateClass(authNProp.pop('moduleName'),
330                                               authNProp.pop('className'),
331                                               moduleFilePath=authNModFilePath,
332                                               objectType=AbstractAuthNService, 
333                                               classProperties=authNProp)           
334       
335    def initCredentialRepository(self):
336        '''Load Credential Repository instance from property settings
337        If non module or class name were set a null interface is loaded by
338        default'''
339       
340        credReposProp = self.__prop.get(SessionManager.CREDREPOS_KEYNAME, {})
341
342        credentialRepositoryModule = credReposProp.get('moduleName')
343        credentialRepositoryClassName = credReposProp.get('className')
344           
345        if credentialRepositoryModule is None or \
346           credentialRepositoryClassName is None:
347            # Default to NullCredentialRepository if no settings have been made
348            self._credentialRepository = NullCredentialRepository()
349        else:
350            credReposModuleFilePath = credReposProp.get('moduleFilePath')
351               
352            self._credentialRepository = instantiateClass(
353                                        credentialRepositoryModule,
354                                        credentialRepositoryClassName,
355                                        moduleFilePath=credReposModuleFilePath,
356                                        objectType=CredentialRepository,
357                                        classProperties=credReposProp)
358
359    def __delitem__(self, key):
360        "Session Manager keys cannot be removed"       
361        raise KeyError('Keys cannot be deleted from '+self.__class__.__name__)
362   
363    def __getitem__(self, key):
364        """Enables behaviour as data dictionary of Session Manager properties
365        """
366        if key not in self.__prop:
367            raise KeyError("Invalid key '%s'" % key)
368       
369        return self.__prop[key]
370   
371    def __setitem__(self, key, item):
372        self.__class__.__name__ + """ behaves as data dictionary of Session
373        Manager properties"""
374        self.setProperties(**{key: item})
375           
376    def get(self, kw):
377        return self.__prop.get(kw)
378
379    def clear(self):
380        raise KeyError("Data cannot be cleared from "+SessionManager.__name__)
381   
382    def keys(self):
383        return self.__prop.keys()
384
385    def items(self):
386        return self.__prop.items()
387
388    def values(self):
389        return self.__prop.values()
390
391    def has_key(self, key):
392        return self.__prop.has_key(key)
393
394    # 'in' operator
395    def __contains__(self, key):
396        return key in self.__prop
397   
398    def setPropFilePath(self, val=None):
399        """Set properties file from input or based on environment variable
400        settings"""
401        log.debug("Setting property file path")
402        if not val:
403            if 'NDGSEC_SM_PROPFILEPATH' in os.environ:
404                val = os.environ['NDGSEC_SM_PROPFILEPATH']
405               
406                log.debug('Set properties file path "%s" from '
407                          '"NDGSEC_SM_PROPFILEPATH"' % val)
408
409            elif 'NDGSEC_DIR' in os.environ:
410                val = os.path.join(os.environ['NDGSEC_DIR'], 
411                                   self.__class__._confDir,
412                                   self.__class__._propFileName)
413
414                log.debug('Set properties file path %s from "NDGSEC_DIR"'%val)
415            else:
416                raise AttributeError('Unable to set default Session '
417                                     'Manager properties file path: neither ' 
418                                     '"NDGSEC_SM_PROPFILEPATH" or "NDGSEC_DIR"'
419                                     ' environment variables are set')
420        else:
421             log.debug('Set properties file path %s from user input' % val)       
422
423        if not isinstance(val, basestring):
424            raise AttributeError("Input Properties file path must be a valid "
425                                 "string.")
426     
427        self._propFilePath = os.path.expandvars(val)
428        log.debug("Path set to: %s" % val)
429       
430    def getPropFilePath(self):
431        log.debug("Getting property file path")
432        if hasattr(self, '_propFilePath'):
433            return self._propFilePath
434        else:
435            return ""
436       
437    # Also set up as a property
438    propFilePath = property(fset=setPropFilePath,
439                            fget=getPropFilePath,
440                            doc="Set the path to the properties file")   
441       
442    def getPropFileSection(self):
443        '''Get the section name to extract properties from an ini file -
444        DOES NOT apply to XML file properties
445       
446        @rtype: basestring
447        @return: section name'''
448        log.debug("Getting property file section name")
449        if hasattr(self, '_propFileSection'):
450            return self._propFileSection
451        else:
452            return ""   
453   
454    def setPropFileSection(self, val=None):
455        """Set section name to read properties from ini file.  This is set from
456        input or based on environment variable setting
457        NDGSEC_SM_PROPFILESECTION
458       
459        @type val: basestring
460        @param val: section name"""
461        log.debug("Setting property file section name")
462        if not val:
463            val = os.environ.get('NDGSEC_SM_PROPFILESECTION', 'DEFAULT')
464               
465        if not isinstance(val, basestring):
466            raise AttributeError("Input Properties file section name "
467                                 "must be a valid string.")
468     
469        self._propFileSection = val
470        log.debug("Properties file section set to: %s" % val)
471       
472    # Also set up as a property
473    propFileSection = property(fset=setPropFileSection,
474                    fget=getPropFileSection,
475                    doc="Set the file section name for ini file properties")   
476   
477    def setPropPrefix(self, val=None):
478        """Set prefix for properties read from ini file.  This is set from
479        input or based on environment variable setting
480        NDGSEC_AA_PROPFILEPREFIX
481       
482        DOES NOT apply to XML file properties
483       
484        @type val: basestring
485        @param val: section name"""
486        log.debug("Setting property file section name")
487        if val is None:
488            val = os.environ.get('NDGSEC_AA_PROPFILEPREFIX', 'DEFAULT')
489               
490        if not isinstance(val, basestring):
491            raise AttributeError("Input Properties file section name "
492                                 "must be a valid string.")
493     
494        self._propPrefix = val
495        log.debug("Properties file section set to: %s" % val)
496           
497    def setPropPrefix(self, val=None):
498        """Set prefix for properties read from ini file.  This is set from
499        input or based on environment variable setting
500        NDGSEC_SM_PROPFILEPREFIX
501       
502        DOES NOT apply to XML file properties
503       
504        @type val: basestring
505        @param val: section name"""
506        log.debug("Setting property file section name")
507        if val is None:
508            val = os.environ.get('NDGSEC_SM_PROPFILEPREFIX', 'DEFAULT')
509               
510        if not isinstance(val, basestring):
511            raise AttributeError("Input Properties file section name "
512                                 "must be a valid string.")
513     
514        self._propPrefix = val
515        log.debug("Properties file section set to: %s" % val)
516       
517    def getPropPrefix(self):
518        '''Get the prefix name used for properties in an ini file -
519        DOES NOT apply to XML file properties
520       
521        @rtype: basestring
522        @return: section name'''
523        log.debug("Getting property file prefix")
524        if hasattr(self, '_propPrefix'):
525            return self._propPrefix
526        else:
527            return ""   
528       
529    # Also set up as a property
530    propPrefix = property(fset=setPropPrefix,
531                          fget=getPropPrefix,
532                          doc="Set a prefix for ini file properties")   
533
534    def readProperties(self, section=None, prefix=None):
535        '''Read the properties files and do some checking/converting of input
536        values
537         
538        @type section: basestring
539        @param section: ini file section to read properties from - doesn't
540        apply to XML format properties files.  section setting defaults to
541        current propFileSection attribute
542       
543        @type prefix: basestring
544        @param prefix: apply prefix to ini file properties - doesn't
545        apply to XML format properties files.  This enables filtering of
546        properties so that only those relevant to this class are read in
547        '''
548        if section is None:
549            section = self.propFileSection
550       
551        if prefix is None:
552            prefix = self.propPrefix
553           
554        # Configuration file properties are held together in a dictionary
555        readPropertiesFile = INIPropertyFileWithValidation()
556        fileProp=readPropertiesFile(self.propFilePath,
557                                    validKeys=SessionManager.propertyDefaults,
558                                    prefix=prefix,
559                                    sections=(section,))
560       
561        # Keep a copy of the config file for the CredentialWallet to reference
562        # so that it can retrieve WS-Security settings
563        self._cfg = readPropertiesFile.cfg
564       
565        # Allow for section and prefix names which will nest the Attribute
566        # Authority properties in a hierarchy
567        propBranch = fileProp
568        if section != 'DEFAULT':
569            propBranch = propBranch[section]
570           
571        self.__prop = propBranch
572
573        log.info('Loaded properties from "%s"' % self.propFilePath)
574
575    @staticmethod
576    def _setProperty(value):
577        if value and isinstance(value, basestring):
578            return os.path.expandvars(value).strip()
579        else:
580            return value             
581       
582    def setProperties(self, **prop):
583        """Update existing properties from an input dictionary
584        Check input keys are valid names"""
585       
586        log.debug("Calling SessionManager.setProperties with kw = %s" % prop)
587       
588        for key in prop.keys():
589            if key not in self.propertyDefaults:
590                raise SessionManagerError('Property name "%s" is invalid'%key)
591           
592        for key, value in prop.iteritems():
593                       
594            if key == SessionManager.AUTHN_KEYNAME:
595                for subKey, subVal in prop[key].iteritems():
596#                    if subKey not in \
597#                       SessionManager.authNServicePropertyDefaults:
598#                        raise SessionManagerError('Key "%s" is not a valid '
599#                                            'Session Manager AuthNService '
600#                                            'property' % subKey)
601#                       
602                    if subVal:
603                        self.__prop[key][subKey] = SessionManager._setProperty(
604                                                                        subVal)
605   
606            elif key == SessionManager.CREDREPOS_KEYNAME:
607                for subKey, subVal in self.__prop[key].iteritems():
608#                    if subKey not in \
609#                       SessionManager.credentialRepositoryPropertyDefaults:
610#                        raise SessionManagerError('Key "%s" is not a valid '
611#                                        'Session Manager credentialRepository '
612#                                        'property' % subKey)
613#                       
614                    if subVal:
615                        self.__prop[key][subKey] = SessionManager._setProperty(
616                                                                        subVal)
617
618            elif key in SessionManager.propertyDefaults:
619                # Only update other keys if they are not None or ""
620                if value:
621                    self.__prop[key] = SessionManager._setProperty(value)             
622            else:
623                raise SessionManagerError('Key "%s" is not a valid Session '
624                                          'Manager property' % key)
625       
626    def getSessionStatus(self, sessID=None, userDN=None):
627        """Check the status of a given session identified by sessID or
628        user Distinguished Name
629       
630        @type sessID: string
631        @param sessID: session identifier as returned from a call to connect()
632        @type userDN: string
633        @param userDN: user Distinguished Name of session to check
634        @rtype: bool
635        @return: True if session is active, False if no session found"""
636
637        log.debug("Calling SessionManager.getSessionStatus ...")
638       
639        # Look for a session corresponding to this ID
640        if sessID and userDN:
641            raise SessionManagerError('Only "SessID" or "userDN" keywords may '
642                                      'be set')
643        elif sessID:
644            if sessID in self.__sessDict:               
645                log.info("Session found with ID = %s" % sessID)
646                return True
647            else:
648                # User session not found with given ID
649                log.info("No user session found matching input ID = %s"%sessID)
650                return False
651                         
652        elif userDN:
653            try:
654                # Enables re-ordering of DN fields for following dict search
655                userDN = str(X500DN(userDN))
656               
657            except Exception, e:
658                log.error("Parsing input user certificate DN for "
659                          "getSessionStatus: %s" % e)
660                raise
661           
662            if userDN in self.__dnDict:
663                log.info("Session found with DN = %s" % userDN)
664                return True                       
665            else:
666                # User session not found with given proxy cert
667                log.info("No user session found matching input userDN = %s" %
668                         userDN)
669                return False
670
671    def connect(self, 
672                createServerSess=True,
673                username=None,
674                passphrase=None, 
675                userX509Cert=None, 
676                sessID=None):       
677        """Create a new user session or connect to an existing one:
678
679        connect([createServerSess=True/False, ]|[, username=u, passphrase=p]|
680                [, userX509Cert=px]|[, sessID=id])
681
682        @type createUserSess: bool
683        @param createServerSess: If set to True, the SessionManager will create
684        and manage a session for the user.  For command line case, it's
685        possible to choose to have a client or server side session using this
686        keyword.
687       
688        @type username: string
689        @param username: username of account to connect to
690
691        @type passphrase: string
692        @param passphrase: pass-phrase - user with username arg
693       
694        @type userX509Cert: string
695        @param userX509Cert: connect to existing session with proxy certificate
696        corresponding to user.  username/pass-phrase not required
697       
698        @type sessID: string
699        @param sessID: connect to existing session corresponding to this ID.
700        username/pass-phrase not required.
701       
702        @rtype: tuple
703        @return user certificate, private key, issuing certificate and
704        session ID respectively.  Session ID will be none if createUserSess
705        keyword is set to False
706       
707        @raise AuthNServiceError: error with response from Authentication
708        service.  An instance of this class or derived class instance may be
709        raised.
710        """
711       
712        log.debug("Calling SessionManager.connect ...")
713       
714        # Initialise proxy cert to be returned
715        userX509Cert = None
716       
717        if sessID is not None:           
718            # Connect to an existing session identified by a session ID and
719            # return equivalent proxy cert
720            userSess = self._connect2UserSession(sessID=sessID)
721            userX509Cert = userSess.credentialWallet.userX509Cert
722           
723        elif userX509Cert is not None:
724            # Connect to an existing session identified by a proxy
725            # certificate
726            userSess = self._connect2UserSession(userX509Cert=userX509Cert)
727            sessID = userSess.latestSessID
728           
729        else:
730            # Create a fresh session
731            try:
732                # Get a proxy certificate to represent users ID for the new
733                # session
734                userCreds = self.__authNService.logon(username, passphrase)
735            except AuthNServiceError:
736                # Filter out known AuthNService exceptions
737                raise
738            except Exception, e:
739                # Catch all here for AuthNService but the particular
740                # implementation should make full use of AuthN* exception
741                # types
742                raise AuthNServiceError("Authentication Service: %s" % e)
743                           
744            # Unpack output
745            if userCreds is None:
746                nUserCreds = 0
747            else:
748                nUserCreds = len(userCreds)
749               
750            if nUserCreds > 1:
751                userX509Cert = userCreds[0]
752                userPriKey = userCreds[1]
753            else:
754                userX509Cert = userPriKey = None
755               
756            # Issuing cert is needed only if userX509Cert is a proxy
757            issuingCert = nUserCreds > 2 and userCreds[2] or None       
758
759            if createServerSess:
760                # Session Manager creates and manages user's session
761                userSess = self._createUserSession(username, 
762                                                   passphrase,
763                                                   userCreds)
764                sessID = userSess.latestSessID
765            else:
766                sessID = None
767                               
768        # Return proxy details and cookie
769        return userX509Cert, userPriKey, issuingCert, sessID       
770       
771       
772    def _createUserSession(self, username, userPriKeyPwd=None, userCreds=None):
773        """Create a new user session from input user credentials       
774        and return
775       
776        @type username: basestring
777        @param username: username user logged in with
778        @type userPriKeyPwd: basestring
779        @param userPriKeyPwd: password protecting the private key if set.
780        @type userCreds: tuple
781        @param userCreds: tuple containing user certificate, private key
782        and optionally an issuing certificate.  An issuing certificate is
783        present if user certificate is a proxy and therefore it's issuer is
784        other than the CA. userCreds may default to None if no user certificate
785        is available.  In this case, the Session Manager server certificate
786        is used to secure connections to Attribute Authorities and other
787        services where required
788       
789        @raise SessionManagerError: session ID added already exists in session
790        list"""
791       
792        log.debug("Calling SessionManager._createUserSession ...")
793       
794        # Check for an existing session for the same user
795        if username in self.__usernameDict:
796            # Update existing session with user cert and add a new
797            # session ID to access it - a single session can be accessed
798            # via multiple session IDs e.g. a user may wish to access the
799            # same session from the their desktop PC and their laptop.
800            # Different session IDs are allocated in each case.
801            userSess = self.__usernameDict[username]
802            userSess.addNewSessID()           
803        else:
804            # Create a new user session using the username, session ID and
805            # X.509 credentials
806
807            # Copy global Credential Wallet settings into specific set for this
808            # user
809            if self.propPrefix:
810                credentialWalletPropPfx = '.'.join((self.propPrefix, 
811                                            SessionManager.CREDWALLET_KEYNAME))
812            else:
813                credentialWalletPropPfx = SessionManager.CREDWALLET_KEYNAME
814               
815            # Include cfg setting to enable WS-Security Signature handler to
816            # pick up settings
817            credentialWalletProp = {
818                'cfg': self._cfg,
819                'userId': username,
820                'userPriKeyPwd': userPriKeyPwd,
821                'credentialRepository': self._credentialRepository,
822                'cfgPrefix': credentialWalletPropPfx
823            }
824                                                   
825   
826            # Update user PKI settings if any are present
827            if userCreds is None:
828                nUserCreds = 0
829            else:
830                nUserCreds = len(userCreds)
831               
832            if nUserCreds > 1:
833                credentialWalletProp['userX509Cert'] = userCreds[0]
834                credentialWalletProp['userPriKey'] = userCreds[1]
835           
836            if nUserCreds == 3:
837                credentialWalletProp['issuingX509Cert'] = userCreds[2]
838               
839            try:   
840                userSess = UserSession(**credentialWalletProp)     
841            except Exception, e:
842                log.error("Error occurred whilst creating User Session: %s"%e)
843                raise 
844           
845            # Also allow access by user DN if individual user PKI credentials
846            # have been passed in
847            if userCreds is not None:
848                try:
849                    userDN = str(X509CertParse(userCreds[0]).dn)
850                   
851                except Exception, e:
852                    log.error("Parsing input certificate DN for session "
853                              "create: %s" % e)
854                    raise
855
856                self.__dnDict[userDN] = userSess
857       
858        newSessID = userSess.latestSessID
859       
860        # Check for unique session ID
861        if newSessID in self.__sessDict:
862            raise SessionManagerError("New Session ID is already in use:\n\n "
863                                      "%s" % newSessID)
864
865        # Add new session to list                 
866        self.__sessDict[newSessID] = userSess
867                       
868        # Return new session
869        return userSess
870
871
872    def _connect2UserSession(self,username=None,userX509Cert=None,sessID=None):
873        """Connect to an existing session by providing a valid session ID or
874        proxy certificate
875
876        _connect2UserSession([username|userX509Cert]|[sessID])
877
878        @type username: string
879        @param username: username
880       
881        @type userX509Cert: string
882        @param userX509Cert: user's X.509 certificate corresponding to an
883        existing session to connect to.
884       
885        @type sessID: string
886        @param sessID: similiarly, a web browser session ID linking to an
887        an existing session.
888       
889        @raise SessionNotFound: no matching session to the inputs
890        @raise UserSessionExpired: existing session has expired
891        @raise InvalidUserSession: user credential wallet is invalid
892        @raise UserSessionX509CertNotBeforeTimeError: """
893       
894        log.debug("Calling SessionManager._connect2UserSession ...")
895           
896        # Look for a session corresponding to this ID
897        if username:
898            userSess = self.__usernameDict.get(username)
899            if userSess is None:
900                log.error("Session not found for username=%s" % username)
901                raise SessionNotFound("No user session found matching the "
902                                      "input username")
903
904            if userSess.credentialWallet.userX509Cert:
905                userDN = userSess.credentialWallet.userX509Cert.dn
906            else:
907                userDN = None
908               
909            log.info("Connecting to session userDN=%s; sessID=%s using "
910                     "username=%s" % (userDN, userSess.sessIdList, username))           
911        elif sessID:
912            userSess = self.__sessDict.get(sessID)
913            if userSess is None: 
914                log.error("Session not found for sessID=%s" % sessID)
915                raise SessionNotFound("No user session found matching input "
916                                      "session ID")
917               
918            if userSess.credentialWallet.userX509Cert:
919                userDN = userSess.credentialWallet.userX509Cert.dn
920            else:
921                userDN = None
922               
923            log.info("Connecting to session userDN=%s; username=%s using "
924                     "sessID=%s" % (userDN, username, userSess.sessIdList))
925
926        elif userX509Cert is not None:
927            if isinstance(userX509Cert, basestring):
928                try:
929                    userDN = str(X509CertParse(userX509Cert).dn)
930                   
931                except Exception, e:
932                    log.error("Parsing input user certificate DN for session "
933                              "connect: %s" %e)
934                    raise
935            else:
936                try:
937                    userDN = str(userX509Cert.dn)
938                   
939                except Exception, e:
940                    log.error("Parsing input user certificate DN for session "
941                              "connect: %s" % e)
942                    raise
943               
944            userSess = self.__dnDict.get(userDN)
945            if userSess is None:
946                log.error("Session not found for userDN=%s" % userDN)
947                raise SessionNotFound("No user session found matching input "
948                                      "user X.509 certificate")
949           
950            log.info("Connecting to session sessID=%s; username=%s using "
951                     "userDN=%s" % (userSess.sessIdList, 
952                                    userSess.credentialWallet.userId, 
953                                    userDN))
954        else:
955            raise KeyError('"username", "sessID" or "userX509Cert" keywords '
956                           'must be set')
957           
958        # Check that the Credentials held in the wallet are still valid           
959        try:
960            userSess.credentialWallet.isValid(raiseExcep=True)
961            return userSess
962       
963        except X509CertInvalidNotBeforeTime, e:
964            # ! Delete user session since it's user certificate is invalid
965            self.deleteUserSession(userSess=userSess)
966            raise UserSessionX509CertNotBeforeTimeError(
967                                    "User session is invalid: %s" % e)       
968   
969        except X509CertExpired, e:
970            # ! Delete user session since it's user certificate is invalid
971            self.deleteUserSession(userSess=userSess)
972            raise UserSessionExpired("User session is invalid: %s" % e)       
973       
974        except Exception, e:
975            raise InvalidUserSession("User session is invalid: %s" % e)
976               
977
978    def deleteUserSession(self, sessID=None, userX509Cert=None, userSess=None):
979        """Delete an existing session by providing a valid session ID or
980        proxy certificate - use for user logout
981
982        deleteUserSession([userX509Cert]|[sessID]|[userSess])
983       
984        @type userX509Cert: ndg.security.common.X509.X509Cert
985        @param userX509Cert: proxy certificate corresponding to an existing
986        session to connect to.
987       
988        @type sessID: string
989        @param sessID: similiarly, a web browser session ID linking to an
990        an existing session.
991       
992        @type userSess: UserSession
993        @param userSess: user session object to be deleted
994        """
995       
996        log.debug("Calling SessionManager.deleteUserSession ...")
997       
998        # Look for a session corresponding to the session ID/proxy cert.
999        if sessID:
1000            try:
1001                userSess = self.__sessDict[sessID]
1002               
1003            except KeyError:
1004                raise SessionManagerError("Deleting user session - "
1005                                          "no matching session ID exists")
1006
1007            # Get associated user Distinguished Name if a certificate has been
1008            # set
1009            if userSess.credentialWallet.userX509Cert is None:
1010                userDN = None
1011            else:
1012                userDN = str(userSess.credentialWallet.userX509Cert.dn)
1013           
1014        elif userX509Cert:
1015            try:
1016                userDN = str(userX509Cert.dn)
1017               
1018            except Exception, e:
1019                raise SessionManagerError("Parsing input user certificate "
1020                                          "DN for session connect: %s" % e)
1021            try:
1022                userSess = self.__dnDict[userDN]
1023                       
1024            except KeyError:
1025                # User session not found with given proxy cert
1026                raise SessionManagerError("No user session found matching "
1027                                          "input user certificate")       
1028        elif userSess:
1029            if userSess.credentialWallet.userX509Cert is None:
1030                userDN = None
1031            else:
1032                userDN = str(userSess.credentialWallet.userX509Cert.dn)
1033        else:
1034            # User session not found with given ID
1035            raise SessionManagerError('"sessID", "userX509Cert" or "userSess" '
1036                                      'keywords must be set')
1037 
1038        # Delete associated sessions
1039        try:
1040            # Each session may have a number of session IDs allocated to
1041            # it. 
1042            #
1043            # Use pop rather than del so that key errors are ignored
1044            for userSessID in userSess.sessIdList:
1045                self.__sessDict.pop(userSessID, None)
1046
1047            self.__dnDict.pop(userDN, None)
1048       
1049        except Exception, e:
1050            raise SessionManagerError("Deleting user session: %s" % e) 
1051
1052        log.info("Deleted user session: user DN = %s, sessID = %s" %
1053                 (userDN, userSess.sessIdList))
1054
1055
1056    def getAttCert(self,
1057                   username=None,
1058                   userX509Cert=None,
1059                   sessID=None,
1060                   **credentialWalletKw):
1061        """For a given user, request Attribute Certificate from an Attribute
1062        Authority given by service URI.  If sucessful, an attribute
1063        certificate is added to the user session credential wallet and also
1064        returned from this method
1065       
1066        A user identifier must be provided in the form of a user ID, user X.509
1067        certificate or a user session ID
1068
1069        @type username: string
1070        @param username: username to key into their session
1071
1072        @type userX509Cert: string
1073        @param userX509Cert: user's X.509 certificate to key into their session
1074       
1075        @type sessID: string
1076        @param sessID: user's ID to key into their session
1077       
1078        @type credentialWalletKw: dict
1079        @param **credentialWalletKw: keywords to CredentialWallet.getAttCert
1080        """
1081       
1082        log.debug("Calling SessionManager.getAttCert ...")
1083       
1084        # Retrieve session corresponding to user's session ID using relevant
1085        # input credential
1086        userSess = self._connect2UserSession(username=username, sessID=sessID, 
1087                                             userX509Cert=userX509Cert)
1088       
1089        # The user's Credential Wallet carries out an attribute request to the
1090        # Attribute Authority
1091        attCert = userSess.credentialWallet.getAttCert(**credentialWalletKw)
1092        return attCert
1093
1094       
1095    def auditCredentialRepository(self):
1096        """Remove expired Attribute Certificates from the Credential
1097        Repository"""
1098        log.debug("Calling SessionManager.auditCredentialRepository ...")
1099        self._credentialRepository.auditCredentials()
1100       
1101
1102class AuthNServiceError(Exception):
1103    """Base class for AbstractAuthNService exceptions
1104   
1105    A standard message is raised set by the msg class variable but the actual
1106    exception details are logged to the error log.  The use of a standard
1107    message enbales callers to use its content for user error messages.
1108   
1109    @type msg: basestring
1110    @cvar msg: standard message to be raised for this exception"""
1111    msg = "An error occured with login"
1112    def __init__(self, *arg, **kw):
1113        Exception.__init__(self, AuthNServiceError.msg, *arg, **kw)
1114        if len(arg) > 0:
1115            msg = arg[0]
1116        else:
1117            msg = AuthNServiceError.msg
1118           
1119        log.error(msg)
1120       
1121class AuthNServiceInvalidCredentials(AuthNServiceError):
1122    """User has provided incorrect username/password.  Raise from logon"""
1123    msg = "Invalid username/password provided"
1124   
1125class AuthNServiceRetrieveError(AuthNServiceError):
1126    """Error with retrieval of information to authenticate user e.g. error with
1127    database look-up.  Raise from logon"""
1128    msg = \
1129    "An error occured retrieving information to check the login credentials"
1130
1131class AuthNServiceInitError(AuthNServiceError):
1132    """Error with initialisation of AuthNService.  Raise from __init__"""
1133    msg = "An error occured with the initialisation of the Session " + \
1134        "Manager's Authentication Service"
1135   
1136class AuthNServiceConfigError(AuthNServiceError):
1137    """Error with Authentication configuration.  Raise from __init__"""
1138    msg = "An error occured with the Session Manager's Authentication " + \
1139        "Service configuration"
1140
1141
1142class AbstractAuthNService(object):
1143    """
1144    An abstract base class to define the authentication service interface for
1145    use with a SessionManager service
1146    """
1147
1148    def __init__(self, propertiesFile=None, **prop):
1149        """Make any initial settings
1150       
1151        Settings are held in a dictionary which can be set from **prop,
1152        a call to setProperties() or by passing settings in an XML file
1153        given by propFilePath
1154       
1155        @type propertiesFile: basestring
1156        @param propertiesFile: set properties via a configuration file
1157        @type **prop: dict
1158        @param **prop: set properties via keywords - see __validKeys
1159        class variable for a list of these
1160        @raise AuthNServiceInitError: error with initialisation
1161        @raise AuthNServiceConfigError: error with configuration
1162        @raise AuthNServiceError: generic exception not described by the other
1163        specific exception types.
1164        """
1165   
1166    def setProperties(self, **prop):
1167        """Update existing properties from an input dictionary
1168        Check input keys are valid names"""
1169        raise NotImplementedError(
1170                            self.setProperties.__doc__.replace('\n       ',''))
1171       
1172    def logon(self, username, passphrase):
1173        """Interface login method
1174       
1175        @type username: basestring
1176        @param username: username of credential
1177       
1178        @type passphrase: basestring
1179        @param passphrase: passphrase corresponding to username
1180        @raise AuthNServiceInvalidCredentials: invalid username/passphrase
1181        @raise AuthNServiceError: error
1182        @raise AuthNServiceRetrieveError: error with retrieval of information
1183        to authenticate user e.g. error with database look-up.
1184        @raise AuthNServiceError: generic exception not described by the other
1185        specific exception types.
1186        @rtype: tuple
1187        @return: this may be either user PKI credentials or an empty tuple
1188        depending on the nature of the authentication service.  The UserSession
1189        object in the Session Manager instance can receive an individual user
1190        certificate and private key as returned by for example MyProxy.  In
1191        this case, the tuple consists of strings in PEM format:
1192         - the user certificate
1193         - corresponding private key
1194         - the issuing certificate. 
1195        The issuing certificate is optional.  It is only set if the user
1196        certificate is a proxy certificate
1197        """
1198        raise NotImplementedError(self.logon.__doc__.replace('\n       ',''))
1199           
Note: See TracBrowser for help on using the repository browser.