Changeset 1549


Ignore:
Timestamp:
05/10/06 12:02:51 (13 years ago)
Author:
pjkersha
Message:

Tests/SessionMgrTest?.py: unit test for Session.SessionMgr?. Test new interface to dynamically load
CredentialRepository? class. This will enable data providers to plug in their own interface to their
prefered database.

Tests/MyProxyClient?/m2CryptoMyPxClnt.py: experimented using M2Crypto for a MyProxy? client. Working version
for MyProxy? logon and store but latter needs more work to validate.

NDG/SQLObject: contains CredentialRepository? implemented with the SQLObject Object Relational Mapper. Supports
MySQL, Postgres and others dbs. Session.SessionMgr? can now be configured to pick up the required
CredentialRepository? plugin.

NDG/Session:

  • adapted so that CredentialRepository? interface class is picked up from properties file settings.
  • added some epydoc text to some methods
  • simplified exception classes - they should merely inherit from Exception no customisation code is

necessary.

Other files - updated copyright to 2006.

Location:
TI12-security/trunk/python
Files:
2 added
19 edited

Legend:

Unmodified
Added
Removed
  • TI12-security/trunk/python/NDG/AttAuthority.py

    r1314 r1549  
    55P J Kershaw 15/04/05 
    66 
    7 Copyright (C) 2005 CCLRC & NERC 
     7Copyright (C) 2006 CCLRC & NERC 
    88 
    99This software may be distributed under the terms of the Q Public License, 
     
    103103         
    104104        if not isinstance(propFilePath, basestring): 
    105             raise AttAuthorityError("Input Properties file path " + \ 
    106                                     "must be a valid string.") 
     105            raise AttAuthorityError, "Input Properties file path " + \ 
     106                                     "must be a valid string." 
    107107 
    108108 
     
    132132             
    133133        except Exception, e: 
    134             raise AttAuthorityError(\ 
    135                     "Attribute Authority's certificate is invalid: " + str(e)) 
     134            raise AttAuthorityError, \ 
     135                    "Attribute Authority's certificate is invalid: " + str(e) 
    136136         
    137137        # Check CA certificate 
     
    143143             
    144144        except Exception, e: 
    145             raise AttAuthorityError("CA certificate is invalid: " + str(e)) 
     145            raise AttAuthorityError, "CA certificate is invalid: " + str(e) 
    146146         
    147147        # Issuer details - serialise using the separator string set in the 
     
    172172                                 
    173173        except Exception, e: 
    174             raise AttAuthorityError('Importing User Roles module: %s' % e) 
     174            raise AttAuthorityError,'Importing User Roles module: %s' % str(e) 
    175175 
    176176        # Check class inherits from AAUserRoles abstract base class 
    177177        if not issubclass(usrRolesClass, AAUserRoles): 
    178             raise AttAuthorityError(\ 
     178            raise AttAuthorityError, \ 
    179179                "User Roles class %s must be derived from AAUserRoles" % \ 
    180                 self.__prop['usrRolesClassName']) 
     180                self.__prop['usrRolesClassName'] 
    181181 
    182182 
     
    186186             
    187187        except Exception, e: 
    188             raise AttAuthorityError(\ 
    189                 "Error instantiating User Roles interface: " + str(e)) 
     188            raise AttAuthorityError, \ 
     189                "Error instantiating User Roles interface: " + str(e) 
    190190      
    191191         
     
    194194    def __delitem__(self, key): 
    195195        self.__class__.__name__ + " keys cannot be removed"         
    196         raise KeyError('Keys cannot be deleted from '+self.__class__.__name__) 
     196        raise KeyError, 'Keys cannot be deleted from '+self.__class__.__name__ 
    197197 
    198198 
     
    202202        """ 
    203203        if key not in self.__prop: 
    204             raise KeyError("Invalid key " + key) 
     204            raise KeyError, "Invalid key " + key 
    205205         
    206206        return self.__prop[key] 
     
    208208 
    209209    def clear(self): 
    210         raise KeyError("Data cannot be cleared from "+self.__class__.__name__) 
     210        raise KeyError, "Data cannot be cleared from "+self.__class__.__name__ 
    211211    
    212212    def keys(self): 
  • TI12-security/trunk/python/NDG/AttAuthorityIO.py

    r1340 r1549  
    66P J Kershaw 14/12/05 
    77 
    8 Copyright (C) 2005 CCLRC & NERC 
     8Copyright (C) 2006 CCLRC & NERC 
    99 
    1010This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/AttCert.py

    r1177 r1549  
    55P J Kershaw 05/04/05 
    66 
    7 Copyright (C) 2005 CCLRC & NERC 
     7Copyright (C) 2006 CCLRC & NERC 
    88 
    99This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/CertReq.py

    r930 r1549  
    55P J Kershaw 08/08/05 
    66 
    7 Copyright (C) 2005 CCLRC & NERC 
     7Copyright (C) 2006 CCLRC & NERC 
    88 
    99This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/CredWallet.py

    r1307 r1549  
    5656class CredWalletError(Exception):     
    5757    """Exception handling for NDG CredentialWallet class.""" 
    58      
    59     def __init__(self, msg): 
    60         self.__msg = msg 
    61           
    62     def __str__(self): 
    63         return self.__msg 
    64  
    65  
     58    pass 
    6659 
    6760 
     
    10341027class CredReposError(Exception):    
    10351028    """Exception handling for NDG Credential Repository class.""" 
    1036      
    1037     def __init__(self, msg): 
    1038         self.__msg = msg 
    1039           
    1040     def __str__(self): 
    1041         return self.__msg  
    1042   
    1043  
     1029    pass  
    10441030 
    10451031 
     
    10991085        raise NotImplementedError( 
    11001086            self.addCredentials.__doc__.replace('\n       ','')) 
    1101  
    1102  
    1103  
    1104             
    1105 if __name__ == "__main__": 
    1106     proxyCertTxt = open('../x509up_u25157').read() 
    1107     credWallet = CredWallet(proxyCertTxt) 
  • TI12-security/trunk/python/NDG/MyProxy.py

    r930 r1549  
    66P J Kershaw 02/06/05 
    77 
    8 Copyright (C) 2005 CCLRC & NERC 
     8Copyright (C) 2006 CCLRC & NERC 
    99 
    1010This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/Session.py

    r1517 r1549  
    66P J Kershaw 02/06/05 
    77 
    8 Copyright (C) 2005 CCLRC & NERC 
     8Copyright (C) 2006 CCLRC & NERC 
    99 
    1010This software may be distributed under the terms of the Q Public License, 
     
    1313 
    1414reposID = '$Id$' 
    15  
    16 # SQLObject Database interface 
    17 from sqlobject import * 
    1815 
    1916# Placing of session ID on client 
     
    6259class UserSessionError(Exception):     
    6360    """Exception handling for NDG User Session class.""" 
    64      
    65     def __init__(self, msg): 
    66         self.__msg = msg 
    67           
    68     def __str__(self): 
    69         return self.__msg 
     61    pass 
    7062     
    7163     
     
    424416class SessionMgrError(Exception):     
    425417    """Exception handling for NDG Session Manager class.""" 
    426      
    427     def __init__(self, msg): 
    428         self.__msg = msg 
    429           
    430     def __str__(self): 
    431         return self.__msg 
    432  
     418    pass 
    433419 
    434420#_____________________________________________________________________________ 
     
    437423 
    438424    # valid configuration property keywords 
    439     __validKeys = [    'caCertFile', 
    440                        'certFile', 
    441                        'keyFile', 
    442                        'keyPPhrase',  
    443                        'sessMgrEncrKey',  
    444                        'sessMgrWSDLuri', 
    445                        'cookieDomain',  
    446                        'myProxyProp',  
    447                        'credReposProp'] 
     425    __validElem = \ 
     426    { 
     427        'caCertFile':     None, 
     428        'certFile':       None, 
     429        'keyFile':        None, 
     430        'keyPPhrase':     None,  
     431        'sessMgrEncrKey': None,  
     432        'sessMgrWSDLuri': None, 
     433        'cookieDomain':   None,  
     434        'myProxyProp':    None,  
     435        'credReposProp':  ('modFilePath', 'modName', 'className', 'propFile') 
     436    } 
    448437 
    449438     
     
    463452        # Base class initialisation 
    464453        dict.__init__(self) 
    465          
    466  
    467         # MyProxy interface 
    468         try: 
    469             self.__myPx = MyProxy() 
    470              
    471         except Exception, e: 
    472             raise SessionMgrError, "Creating MyProxy interface: %s" % e 
    473  
    474          
    475         # Credentials repository - permanent stroe of user credentials 
    476         try: 
    477             self.__credRepos = SessionMgrCredRepos() 
    478              
    479         except Exception, e: 
    480             raise SessionMgrError, \ 
    481                             "Creating credential repository interface: %s" % e 
    482454 
    483455        # Key user sessions by session ID 
     
    486458        # Key user sessions by user DN 
    487459        self.__dnDict = {} 
    488          
    489          
    490         # Dictionary to hold properties 
     460 
     461        # Credential Repository interface only set if properties file is set 
     462        # otherwise explict calls are necessary to set credReposProp via 
     463        # setProperties/readProperties and then loadCredReposInterface 
     464        self.__credRepos = None 
     465         
     466 
     467        # MyProxy interface 
     468        try: 
     469            self.__myPx = MyProxy() 
     470             
     471        except Exception, e: 
     472            raise SessionMgrError, "Creating MyProxy interface: %s" % e 
     473 
     474                 
     475        # Dictionary to hold properties       
    491476        self.__prop = {} 
    492477         
     
    494479        # Set properties from file 
    495480        if propFilePath is not None: 
    496             self.readProperties(propFilePath, 
    497                                 credReposPPhrase=credReposPPhrase) 
    498  
    499  
     481            self.readProperties(propFilePath) 
     482 
     483            # Call here as we can safely expect that all Credential Repository 
     484            # parameters have been set above 
     485            self.loadCredReposInterface() 
     486 
     487         
    500488        # Set any properties that were provided by keyword input 
    501489        # 
    502490        # Nb. If any are duplicated with tags in the properties file they 
    503491        # will overwrite the latter 
     492        # 
     493        # loadCredReposInterface must be called explicitly if propFilePath 
     494        # wasn't set.  This is because if properties are passed by keyword  
     495        # alone there is no guarantee that those needed to load the interface 
     496        # will be present.  readProperties however, requires that all the 
     497        # required parameters are present in the properties file. 
    504498        self.setProperties(**prop) 
     499         
     500         
     501    #_________________________________________________________________________ 
     502    def loadCredReposInterface(self, credReposPPhrase=None, Force=False): 
     503        """ 
     504        Pick up and instantiate Credential Repository interface class from  
     505        properties file settings/keywords set by setProperties/__init__ 
     506         
     507        @param credReposPPhrase: password for CredentialRepository database 
     508            This is passed into the Credential Repository object but may not 
     509            be needed.  e.g. the custom class could pick up a password from 
     510            the properties file for it - ['credRepos']['propFilePath'] 
     511        @type credReposPPhrase: string 
     512        @param Force: flag to force reload of Credential Repository instance 
     513        @type Force: boolean 
     514        @return: None 
     515        """ 
     516         
     517        # Don't bother if object has already been created.  Use Force=True 
     518        # to override and force reload 
     519        if Force is False and self.__credRepos is not None: 
     520            return 
     521         
     522        # Credentials repository - permanent store of user credentials 
     523        try: 
     524            try: 
     525                # Temporarily extend system path ready for import 
     526                sysPathBak = sys.path[:] 
     527                sys.path.append(self.__prop['credReposProp']['modFilePath']) 
     528                 
     529                # Import module name specified in properties file 
     530                credReposMod = \ 
     531                    __import__(self.__prop['credReposProp']['modName'], 
     532                               globals(), 
     533                               locals(), 
     534                               [self.__prop['credReposProp']['className']]) 
     535     
     536                credReposClass = eval(\ 
     537                'credReposMod.' + self.__prop['credReposProp']['className']) 
     538            finally: 
     539                sys.path[:] = sysPathBak 
     540 
     541        except KeyError, e: 
     542            raise SessionMgrError, \ 
     543        'Missing %s element for credential repository module import' % str(e) 
     544                         
     545        except Exception, e: 
     546            raise SessionMgrError, \ 
     547                        'Importing credential repository module: %s' % str(e) 
     548 
     549        # Check class inherits from CredWallet.CredRepos abstract base class 
     550        if not issubclass(credReposClass, CredRepos): 
     551            raise SessionMgrError, \ 
     552                "Credential Repository class %s must be inherited from %s" % \ 
     553                (credReposClass, CredRepos) 
     554 
     555 
     556        # Instantiate custom class 
     557        try: 
     558            self.__credRepos = credReposClass(\ 
     559                      propFilePath=self.__prop['credReposProp']['propFile'], 
     560                      dbPPhrase=credReposPPhrase) 
     561             
     562        except Exception, e: 
     563            raise SessionMgrError, \ 
     564            "Error instantiating Credential Repository interface: " + str(e) 
    505565      
    506566         
     
    548608 
    549609    #_________________________________________________________________________ 
    550     def readProperties(self, 
    551                        propFilePath=None, 
    552                        propElem=None, 
    553                        credReposPPhrase=None): 
     610    def readProperties(self, propFilePath=None, propElem=None): 
    554611        """Read Session Manager properties from an XML file or cElementTree 
    555         node""" 
     612        node 
     613         
     614        @param propFilePath: file path for XML properties file 
     615        @type propFilePath: string 
     616        @param propElem: pass in existing ElementTree treeroot 
     617        @type propElem: Element 
     618        @ruturn: None""" 
    556619 
    557620        if propFilePath is not None: 
    558  
    559621            try: 
    560622                tree = ElementTree.parse(propFilePath) 
     
    577639 
    578640 
    579         missingKeys = [] 
     641        filtElemTxt = lambda elem: os.path.expandvars(elem.text).strip() 
     642         
     643        missingElem = [] 
     644        getMissingElem = lambda targ, ref: [e for e in targ if e not in ref] 
     645        invalidElem = [] 
    580646        try: 
    581647            for elem in propElem: 
     
    584650     
    585651                elif elem.tag == 'credReposProp': 
    586                     self.__credRepos.readProperties(propElem=elem, 
    587                                                 dbPPhrase=credReposPPhrase) 
    588                 elif elem.tag in self.__validKeys: 
     652                    self.__prop['credReposProp'] = \ 
     653                                dict([(e.tag, filtElemTxt(e)) for e in elem]) 
     654                             
     655                    # Check for missing elements 
     656                    missingElem.extend(getMissingElem(\ 
     657                                           self.__validElem['credReposProp'], 
     658                                           self.__prop['credReposProp'])) 
     659                         
     660                elif elem.tag in self.__validElem: 
    589661                    # Strip white space but not in the case of pass-phrase  
    590662                    # field as pass-phrase might contain leading or  
     
    593665                         
    594666                        # Check for environment variables in file paths 
    595                         self.__prop[elem.tag] = \ 
    596                                         os.path.expandvars(elem.text).strip() 
     667                        self.__prop[elem.tag] = filtElemTxt(elem) 
    597668                    else: 
    598669                        self.__prop[elem.tag] = elem.text                                          
    599670                else: 
    600                     missingKeys.append(elem.tag) 
     671                    invalidElem.append(elem.tag) 
    601672                 
    602673        except Exception, e: 
     
    605676                (elem.tag, propFilePath, e) 
    606677 
    607  
    608         if missingKeys != []: 
    609             raise SessionMgrError, "The following properties are " + \ 
    610                                    "missing from the properties file: " + \ 
    611                                    ', '.join(missingKeys) 
    612  
     678        missingElem.extend(getMissingElem(self.__prop, self.__validElem)) 
     679        errMsg = '' 
     680         
     681        if invalidElem != []: 
     682            errMsg = 'Invalid elements: "%s"\n' % '", "'.join(invalidElem) 
     683 
     684        if missingElem != []: 
     685            errMsg += 'Missing elements: "%s"\n' % '", "'.join(missingElem) 
     686 
     687        if errMsg: 
     688            raise SessionMgrError, errMsg +  "for properties file \"%s\"" % \ 
     689                                                                propFilePath 
     690         
    613691 
    614692    #_________________________________________________________________________ 
     
    618696         
    619697        for key in prop.keys(): 
    620             if key not in self.__validKeys: 
    621                 raise SessionMgrError("Property name \"%s\" is invalid" % key) 
     698            if key not in self.__validElem: 
     699                raise SessionMgrError, "Property name \"%s\" is invalid" % key 
    622700 
    623701 
     
    628706     
    629707            elif key == 'credReposProp': 
    630                 self.__credRepos.setProperties(prop[key]) 
    631  
    632             elif key in self.__validKeys: 
     708                self.__prop['credReposProp'] = prop[key].copy() 
     709 
     710            elif key in self.__validElem: 
    633711                # Only update other keys if they are not None or "" 
    634712                if value: 
    635713                    self.__prop[key] = value                 
    636714            else: 
    637                 raise SessionMgrError(\ 
    638                     "Key \"%s\" is not a valid Session Manager property" % 
    639                     key) 
     715                raise SessionMgrError, \ 
     716                "Key \"%s\" is not a valid Session Manager property" % key 
    640717 
    641718 
    642719    #_________________________________________________________________________ 
    643720    def addUser(self, caConfigFilePath=None, caPassPhrase=None, **reqKeys):         
    644         """Register a new user with NDG data centre 
     721        """Register a new user with an NDG data centre 
    645722         
    646723        addUser([caConfigFilePath, ]|[, caPassPhrase] 
     
    11131190        Repository""" 
    11141191        self.__credRepos.auditCredentials() 
    1115  
    1116  
    1117 #_____________________________________________________________________________ 
    1118 class SessionMgrCredRepos(CredRepos): 
    1119     """Interface to Credential Repository Database 
    1120      
    1121     Nb. inherits from CredWallet.CredRepos to ensure correct interface 
    1122     to the wallet""" 
    1123  
    1124     # valid configuration property keywords 
    1125     __validKeys = ['dbURI'] 
    1126      
    1127      
    1128     #_________________________________________________________________________     
    1129     def __init__(self, propFilePath=None, dbPPhrase=None, **prop): 
    1130         """Initialise Credentials Repository Database object. 
    1131  
    1132         If the connection string or properties file is set a connection 
    1133         will be made 
    1134  
    1135         dbURI:              <db type>://<username>:<passwd>@<hostname>/dbname 
    1136         propFilePath: file path to properties file 
    1137  
    1138         Nb. propFilePath setting overrides input dbURI 
    1139         """ 
    1140              
    1141         self.__con = None 
    1142         self.__prop = {} 
    1143          
    1144         if propFilePath is not None: 
    1145              
    1146             # Read database URI set in file 
    1147             self.readProperties(propFilePath, dbPPhrase=dbPPhrase) 
    1148              
    1149         elif prop != {}: 
    1150              
    1151             # Database URI may have been set as an input keyword argument 
    1152             self.setProperties(dbPPhrase=dbPPhrase, **prop) 
    1153  
    1154  
    1155     #_________________________________________________________________________     
    1156     def __setConnection(self, 
    1157                         dbType=None, 
    1158                         dbUserName=None, 
    1159                         dbPPhrase=None, 
    1160                         dbHostname=None, 
    1161                         dbName=None, 
    1162                         dbURI=None, 
    1163                         chkConnection=True): 
    1164         """Establish a database connection from a database URI 
    1165  
    1166         pass a URI OR the parameters to construct the URI 
    1167              
    1168         dbURI: "<db type>://<username>:<passwd>:<hostname>/dbname" 
    1169  
    1170         or 
    1171  
    1172         dbURI: "<db type>://<username>:%PPHRASE%:<hostname>/dbname" 
    1173         + passPhrase 
    1174  
    1175         - %PPHRASE% is substituted with the input passPhrase keyword 
    1176          
    1177         or 
    1178          
    1179         dbType:         database type e.g. 'mysql' 
    1180         dbUserName:     username 
    1181         dbPPhrase:      pass-phrase 
    1182         dbHostname:     name of host where database resides 
    1183         dbName:         name of the database 
    1184  
    1185  
    1186         chkConnection:  check that the URI is able to connect to the  
    1187         """ 
    1188  
    1189         try: 
    1190             if dbURI: 
    1191                 # Check for pass-phrase variable set in URI '%PPHRASE%' 
    1192                 dbURIspl = dbURI.split('%') 
    1193                 if len(dbURIspl) == 3: 
    1194                      
    1195                     if dbPPhrase is None: 
    1196                         raise CredReposError, "No database pass-phrase set" 
    1197                      
    1198                     dbURI = dbURIspl[0] + dbPPhrase + dbURIspl[2] 
    1199                  
    1200             else: 
    1201                 # Construct URI from individual inputs 
    1202                 dbURI = dbType + '://' + dbUserName + ':' + dbPPhrase + \ 
    1203                         ':' + dbHostname + '/' + dbName 
    1204         except Exception, e: 
    1205             # Checking form missing keywords 
    1206             raise CredReposError, "Error creating database URI: %s" % e 
    1207  
    1208         try: 
    1209             self.__con = connectionForURI(dbURI) 
    1210         except Exception, e: 
    1211             raise CredReposError, "Error creating database connection: %s" % e 
    1212  
    1213         if chkConnection: 
    1214             try: 
    1215                 self.__con.makeConnection() 
    1216                  
    1217             except Exception, e: 
    1218                 raise CredReposError, \ 
    1219                         "Error connecting to Credential Repository: %s" % e 
    1220  
    1221              
    1222         # Copy the connection object into the table classes 
    1223         SessionMgrCredRepos.UserID._connection = self.__con 
    1224         SessionMgrCredRepos.UserCredential._connection = self.__con 
    1225            
    1226  
    1227     #_________________________________________________________________________     
    1228     def setProperties(self, dbPPhrase=None, **prop): 
    1229         """Update existing properties from an input dictionary 
    1230         Check input keys are valid names""" 
    1231          
    1232         for key in prop.keys(): 
    1233             if key not in self.__validKeys: 
    1234                 raise CredReposError, "Property name \"%s\" is invalid" % key 
    1235                  
    1236         self.__prop.update(prop) 
    1237  
    1238  
    1239         # Update connection setting 
    1240         if 'dbURI' in prop: 
    1241             self.__setConnection(dbURI=prop['dbURI'], dbPPhrase=dbPPhrase) 
    1242  
    1243  
    1244     #_________________________________________________________________________     
    1245     def readProperties(self, 
    1246                        propFilePath=None, 
    1247                        propElem=None, 
    1248                        dbPPhrase=None): 
    1249         """Read the configuration properties for the CredentialRepository 
    1250  
    1251         propFilePath|propElem 
    1252  
    1253         propFilePath: set to read from the specified file 
    1254         propElem:     set to read beginning from a cElementTree node""" 
    1255  
    1256         if propFilePath is not None: 
    1257  
    1258             try: 
    1259                 tree = ElementTree.parse(propFilePath) 
    1260                 propElem = tree.getroot() 
    1261                  
    1262             except IOError, e: 
    1263                 raise CredReposError, \ 
    1264                                 "Error parsing properties file \"%s\": %s" % \ 
    1265                                 (e.filename, e.strerror) 
    1266  
    1267             except Exception, e: 
    1268                 raise CredReposError, \ 
    1269                                 "Error parsing properties file \"%s\": %s" % \ 
    1270                                 (propFilePath, str(e)) 
    1271  
    1272         if propElem is None: 
    1273             raise CredReposError, \ 
    1274     "Error parsing properties file \"%s\": root element is not defined" % \ 
    1275                                 propFilePath 
    1276  
    1277  
    1278         # Read properties into a dictionary 
    1279         prop = {} 
    1280         for elem in propElem: 
    1281                      
    1282             # Check for environment variables in file paths 
    1283             tagCaps = elem.tag.upper() 
    1284             if 'FILE' in tagCaps or 'PATH' in tagCaps or 'DIR' in tagCaps: 
    1285                 elem.text = os.path.expandvars(elem.text) 
    1286  
    1287             prop[elem.tag] = elem.text 
    1288              
    1289         self.setProperties(dbPPhrase=dbPPhrase, **prop) 
    1290  
    1291              
    1292     #_________________________________________________________________________     
    1293     def addUser(self, userName, dn): 
    1294         """A new user to Credentials Repository""" 
    1295         try: 
    1296             self.UserID(userName=userName, dn=dn) 
    1297  
    1298         except Exception, e: 
    1299             raise CredReposError, "Error adding new user '%s': %s" % \ 
    1300                                                                 (userName, e) 
    1301  
    1302  
    1303     #_________________________________________________________________________     
    1304     def auditCredentials(self, dn=None, **attCertValidKeys): 
    1305         """Check the attribute certificates held in the repository and delete 
    1306         any that have expired 
    1307  
    1308         dn:                Only audit for the given user distinguished Name. 
    1309                            if not set, all records are audited 
    1310         attCertValidKeys:  keywords which set how to check the Attribute 
    1311                            Certificate e.g. check validity time, XML 
    1312                            signature, version etc.  Default is check 
    1313                            validity time only""" 
    1314  
    1315         if attCertValidKeys == {}: 
    1316             # Default to check only the validity time 
    1317             attCertValidKeys = {    'chkTime':          True, 
    1318                                     'chkVersion':       False, 
    1319                                     'chkProvenance':    False, 
    1320                                     'chkSig':           False } 
    1321              
    1322         try: 
    1323             if dn: 
    1324                 # Only audit for the given user distinguished Name 
    1325                 credList = self.UserCredential.selectBy(dn=dn) 
    1326             else: 
    1327                 # Audit all credentials 
    1328                 credList = self.UserCredential.select() 
    1329              
    1330         except Exception, e: 
    1331             raise CredReposError,"Selecting credentials from repository: " + \ 
    1332                                  str(e) 
    1333  
    1334         # Iterate through list of credentials deleting records where the 
    1335         # certificate is invalid 
    1336         try: 
    1337             for cred in credList: 
    1338                 attCert = AttCertParse(cred.attCert) 
    1339                  
    1340                 if not attCert.isValid(**attCertValidKeys): 
    1341                     self.UserCredential.delete(cred.id) 
    1342                      
    1343         except Exception, e: 
    1344             try: 
    1345                 raise CredReposError, "Deleting credentials for '%s': %s" % \ 
    1346                                                        (cred.dn, e) 
    1347             except: 
    1348                 raise CredReposError, "Deleting credentials: %s" % e 
    1349  
    1350  
    1351     #_________________________________________________________________________     
    1352     def getCredentials(self, dn): 
    1353         """Get the list of credentials for a given user's DN""" 
    1354  
    1355         try: 
    1356             return self.UserCredential.selectBy(dn=dn) 
    1357              
    1358         except Exception, e: 
    1359             raise CredReposError, "Selecting credentials for %s: %s" % (dn, e) 
    1360  
    1361  
    1362     #_________________________________________________________________________     
    1363     def addCredentials(self, dn, attCertList): 
    1364         """Add new attribute certificates for a user.  The user must have 
    1365         been previously registered in the repository 
    1366  
    1367         dn:             users Distinguished name 
    1368         attCertList:   list of attribute certificates""" 
    1369          
    1370         try: 
    1371             userCred = self.UserID.selectBy(dn=dn) 
    1372              
    1373             if userCred.count() == 0: 
    1374                 # Add a new user record HERE instead of at user registration 
    1375                 # time.  This decouples CredentialRepository from MyProxy and 
    1376                 # user registration process. Previously, a user not recognised 
    1377                 # exception would have been raised here.  'userName' field 
    1378                 # of UserID table is now perhaps superfluous. 
    1379                 # 
    1380                 # P J Kershaw 26/04/06  
    1381                 self.addUser(X500DN(dn)['CN'], dn) 
    1382  
    1383         except Exception, e: 
    1384             raise CredReposError, "Checking for user \"%s\": %s" % (dn, e) 
    1385  
    1386          
    1387         # Carry out check? - filter out certs in db where a new cert 
    1388         # supercedes it - i.e. expires later and has the same roles 
    1389         # assigned - May be too complicated to implement 
    1390         #uniqAttCertList = [attCert for attCert in attCertList \ 
    1391         #    if min([attCert == cred.attCert for cred in userCred])] 
    1392          
    1393                  
    1394         # Update database with new entries 
    1395         try: 
    1396             for attCert in attCertList: 
    1397                 self.UserCredential(dn=dn, attCert=attCert.asString()) 
    1398  
    1399         except Exception, e: 
    1400             raise CredReposError, "Adding new user credentials for " + \ 
    1401                                   "user %s: %s" % (dn, str(e)) 
    1402  
    1403  
    1404     #_________________________________________________________________________     
    1405     def _initTables(self, prompt=True): 
    1406         """Use with EXTREME caution - this method will initialise the database 
    1407         tables removing any previous records entered""" 
    1408   
    1409         if prompt: 
    1410             resp = raw_input(\ 
    1411         "Are you sure you want to initialise the database tables? (yes/no) ") 
    1412      
    1413             if resp.upper() != "YES": 
    1414                 print "Tables unchanged" 
    1415                 return 
    1416          
    1417         self.UserID.createTable() 
    1418         self.UserCredential.createTable() 
    1419         print "Tables created" 
    1420  
    1421              
    1422     #_________________________________________________________________________ 
    1423     # Database tables defined using SQLObject derived classes 
    1424     # Nb. These are class variables of the SessionMgrCredRepos class 
    1425     class UserID(SQLObject): 
    1426         """SQLObject derived class to define Credentials Repository db table 
    1427         to store user information""" 
    1428  
    1429         # to be assigned to connectionForURI(<db URI>) 
    1430         _connection = None 
    1431  
    1432         # Force table name 
    1433         _table = "UserID" 
    1434  
    1435         userName = StringCol(dbName='userName', length=30) 
    1436         dn = StringCol(dbName='dn', length=128) 
    1437  
    1438  
    1439     class UserCredential(SQLObject): 
    1440         """SQLObject derived class to define Credentials Repository db table 
    1441         to store user credentials information""" 
    1442  
    1443         # to be assigned to connectionForURI(<db URI>) 
    1444         _connection = None 
    1445  
    1446         # Force table name 
    1447         _table = "UserCredential" 
    1448  
    1449          
    1450         # User name field binds with UserCredential table 
    1451         dn = StringCol(dbName='dn', length=128) 
    1452  
    1453         # Store complete attribute certificate text 
    1454         attCert = StringCol(dbName='attCert') 
  • TI12-security/trunk/python/NDG/SessionMgrIO.py

    r1340 r1549  
    66P J Kershaw 14/12/05 
    77 
    8 Copyright (C) 2005 CCLRC & NERC 
     8Copyright (C) 2006 CCLRC & NERC 
    99 
    1010This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/SimpleCAClient.py

    r1301 r1549  
    55P J Kershaw 08/08/05 
    66 
    7 Copyright (C) 2005 CCLRC & NERC 
     7Copyright (C) 2006 CCLRC & NERC 
    88 
    99This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/TestUserRoles.py

    r930 r1549  
    66P J Kershaw 29/07/05 
    77                                                                                 
    8 Copyright (C) 2005 CCLRC & NERC 
     8Copyright (C) 2006 CCLRC & NERC 
    99                                                                                 
    1010This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/X509.py

    r941 r1549  
    55P J Kershaw 05/04/05 
    66 
    7 Copyright (C) 2005 CCLRC & NERC 
     7Copyright (C) 2006 CCLRC & NERC 
    88 
    99This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/XMLMsg.py

    r1176 r1549  
    55P J Kershaw 14/12/05 
    66 
    7 Copyright (C) 2005 CCLRC & NERC 
     7Copyright (C) 2006 CCLRC & NERC 
    88 
    99This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/XMLSecDoc.py

    r1125 r1549  
    77P J Kershaw 05/04/05 
    88 
    9 Copyright (C) 2005 CCLRC & NERC 
     9Copyright (C) 2006 CCLRC & NERC 
    1010 
    1111This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/NDG/sessionMgr_services_server.py

    r751 r1549  
    88P J Kershaw 18/12/05 
    99 
    10 Copyright (C) 2005 CCLRC & NERC 
     10Copyright (C) 2006 CCLRC & NERC 
    1111 
    1212This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/Tests/MyProxyClient/m2CryptoMyPxClnt.py

    r1544 r1549  
    1010import os 
    1111import socket 
    12 from M2Crypto import X509, RSA, EVP, m2 
     12from M2Crypto import X509, RSA, EVP, m2, BIO 
    1313from M2Crypto.SSL.Context import Context 
    1414from M2Crypto.SSL.Connection import Connection 
     
    143143    """ 
    144144    import pdb; pdb.set_trace() 
    145     context = SSL.Context(SSL.SSLv3_METHOD) 
     145    # Set to version 3? 
     146    context = Context() 
    146147     
    147148    # disable for compatibility with myproxy server (er, globus) 
    148149    # globus doesn't handle this case, apparently, and instead 
    149150    # chokes in proxy delegation code 
    150     context.set_options(0x00000800L) 
     151    context.set_options(m2.SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS)#0x00000800L) 
    151152     
    152153    # connect to myproxy server 
    153     if debuglevel(1):    
    154         print "debug: connect to myproxy server" 
    155          
    156     conn = SSL.Connection(context, socket.socket()) 
    157     conn.connect((hostname, port)) 
     154    if debuglevel(1):   print "debug: connect to myproxy server" 
     155    conn = Connection(context, sock=socket.socket()) 
     156     
     157    # Fudge to avoid checking client cert - seems to pick globus  
     158    # host/<hostname> one 
     159    conn.clientPostConnectionCheck = None 
     160    conn.connect((hostname,port)) 
    158161     
    159162    # send globus compatibility stuff 
     
    189192         re.S) 
    190193     
    191     certTxt = pat.findall(open(certFile).read())[0] 
     194    #certTxt = pat.findall(open(certFile).read())[0] 
     195    certTxt = X509.load_cert(certFile).as_pem() 
    192196    keyTxt = open(keyFile).read() 
    193      
    194     conn.send("%s\n%s" % (certTxt, keyTxt)) 
     197#    PwdCB = lambda *ar, **kw: open('../tmp').read().strip()                                           
     198#    keyTxt = EVP.load_key(keyFile, callback=PwdCB).as_pem(callback=PwdCB) 
     199     
     200    conn.send(certTxt + keyTxt) 
    195201 
    196202 
  • TI12-security/trunk/python/Tests/reqAuthorisation.py

    r930 r1549  
    77P J Kershaw 05/05/05 
    88 
    9 Copyright (C) 2005 CCLRC & NERC 
     9Copyright (C) 2006 CCLRC & NERC 
    1010 
    1111This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/bin/AttAuthorityServer.py

    r1236 r1549  
    77P J Kershaw 05/05/05 
    88 
    9 Copyright (C) 2005 CCLRC & NERC 
     9Copyright (C) 2006 CCLRC & NERC 
    1010 
    1111This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/bin/SimpleCAServer.py

    r1236 r1549  
    77P J Kershaw 02/08/05 
    88 
    9 Copyright (C) 2005 CCLRC & NERC 
     9Copyright (C) 2006 CCLRC & NERC 
    1010 
    1111This software may be distributed under the terms of the Q Public License, 
  • TI12-security/trunk/python/conf/sessionMgrProperties.xml

    r964 r1549  
    3535    </myProxyProp> 
    3636    <credReposProp> 
    37         <dbURI></dbURI> 
     37            <modFilePath></modFilePath> 
     38            <modName></modName> 
     39            <className></className> 
     40            <propFile></propFile> 
    3841    </credReposProp> 
    3942</sessMgrProp> 
Note: See TracChangeset for help on using the changeset viewer.