Changeset 4304 for TI12-security


Ignore:
Timestamp:
08/10/08 14:05:12 (11 years ago)
Author:
pjkersha
Message:

Updated Session Manager parsing. ConfigFileParsers? can now take '.' delimited option names. '.' delimits subsections e.g. sessionManager.wssecurity.signingCertFilePath for X.509 cert used by WS-Security signature handler for Session Manager.

Location:
TI12-security/trunk/python
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/CredWallet.py

    r4293 r4304  
    268268    __metaclass__ = _MetaCredWallet 
    269269 
    270     _propDefs = dict(userId=None, 
    271                      userX509Cert=None, 
    272                      userX509CertFilePath=None, 
    273                      userPriKey=None, 
    274                      userPriKeyFilePath=None, 
    275                      issuingX509Cert=None, 
    276                      issuingX509CertFilePath=None, 
    277                      caCertFilePathList=None, 
    278                      sslCACertFilePathList=None, 
    279                      attributeAuthorityURI=None, 
    280                      attributeAuthority=None, 
    281                      credentialRepository=None, 
    282                      mapFromTrustedHosts=False, 
    283                      rtnExtAttCertList=True, 
    284                      attCertRefreshElapse=7200, 
    285                      wssCfgFilePath=None, 
    286                      wssCfgSection='DEFAULT', 
    287                      wssCfgKw={}) 
     270    propertyDefaults = dict( 
     271        userId=None, 
     272        userX509Cert=None, 
     273        userX509CertFilePath=None, 
     274        userPriKey=None, 
     275        userPriKeyFilePath=None, 
     276        issuingX509Cert=None, 
     277        issuingX509CertFilePath=None, 
     278        caCertFilePathList=[], 
     279        sslCACertFilePathList=[], 
     280        attributeAuthorityURI=None, 
     281        attributeAuthority=None, 
     282        credentialRepository=None, 
     283        mapFromTrustedHosts=False, 
     284        rtnExtAttCertList=True, 
     285        attCertRefreshElapse=7200, 
     286        wssCfgFilePath=None, 
     287        wssCfgSection='DEFAULT', 
     288        wssCfgKw={}) 
    288289     
    289290    _protectedAttrs = [ 
     
    309310    ] 
    310311     
    311     __slots__ = _propDefs.keys() + _protectedAttrs 
     312    __slots__ = propertyDefaults.keys() + _protectedAttrs 
    312313     
    313314    def __init__(self,  
     
    339340         
    340341        # ... then properties 
    341         attr.update(CredWallet._propDefs) 
     342        attr.update(CredWallet.propertyDefaults) 
    342343        for k, v in attr.items(): 
    343344            try: 
     
    374375                     '"%s"' % self.userId) 
    375376             
    376             if not isinstance(self._credentialRepository,CredentialRepository): 
     377            if not issubclass(self._credentialRepository,CredentialRepository): 
    377378                raise CredWalletError("Input Credential Repository instance " 
    378379                                      "must be of a class derived from " 
     
    383384            try: 
    384385                self._credentialRepository.auditCredentials(self.userId) 
    385                 userCred = self._credentialRepository.getCredentials(self.userId) 
     386                userCred=self._credentialRepository.getCredentials(self.userId) 
    386387     
    387388            except Exception, e: 
     
    429430        prop = readAndValidate(cfgFilePath, 
    430431                               cfg=self._cfg, 
    431                                validKeys=CredWallet._propDefs, 
     432                               validKeys=CredWallet.propertyDefaults, 
    432433                               prefix=prefix, 
    433434                               sections=(section,)) 
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/ConfigFileParsers.py

    r4285 r4304  
    1212__revision__ = '$Id$' 
    1313 
    14 from ConfigParser import SafeConfigParser, InterpolationMissingOptionError 
     14from ConfigParser import SafeConfigParser, InterpolationMissingOptionError, \ 
     15    NoOptionError 
    1516from ndg.security.common.wssecurity import WSSecurityConfig 
    1617# For parsing of properties file 
     
    3839    def optionxform(self, optionstr): 
    3940        return optionstr 
    40  
     41         
    4142class ConfigFileParseError(Exception): 
    4243    """Raise for errors in configuration file formatting""" 
     
    175176            else: 
    176177                if section == wsseSection: 
    177                     keys = WSSecurityConfig.defParam 
     178                    keys = WSSecurityConfig.propertyDefaults 
    178179                else: 
    179180                    keys = validKeys 
     
    261262            subKey = ''.join(splitKey[1:]) 
    262263            if sectionKey in validKeys: 
    263                 val = _parseVal(subKey, val, validKeys[sectionKey]) 
     264                val = _parseVal(cfg, section, key, validKeys[sectionKey], 
     265                                subKey=subKey) 
    264266                if sectionKey in properties: 
    265267                    properties[sectionKey][subKey] = val 
     
    268270        else:  
    269271            # No sub-section present    
    270             val = _parseVal(key, val, validKeys) 
     272            val = _parseVal(cfg, section, key, validKeys) 
    271273         
    272274            # check if key already exists; if so, append to list 
     
    279281    return properties 
    280282 
    281  
    282 def _parseVal(key, val, validKeys):  
    283                
    284     if val: 
    285         # expand out any env vars 
    286         val = expandEnvVars(val) 
    287          
    288         # if the tag contains an integer, convert this appropriately 
    289         if val.isdigit(): 
    290             val = int(val) 
    291          
    292         # ensure it is read in as the correct type 
    293         if key in validKeys and isinstance(validKeys[key], list): 
    294             # Treat as a list of space separated elements 
    295             val = val.split() 
     283def _parseVal(cfg, section, option, validKeys, subKey=None): 
     284    '''Convert option to correct type trying each parser config routine in  
     285    turn.  Convert to a list if validKeys dict item indicates so 
     286     
     287    @type cfg: ndg.security.common.utils.ConfigFileParsers.CaseSensitiveConfigParser 
     288    @param cfg: config file object 
     289    @type section: basestring 
     290    @param section: section in config file to read from 
     291    @type key: basestring 
     292    @param key: section option to read 
     293    @type validKeys: dict 
     294    @param validKeys: key look-up - if item is set to list type then the option 
     295    value in the config file will be split into a list.''' 
     296     
     297    if subKey: 
     298        key = subKey 
    296299    else: 
    297         # NB, the XML parser will return empty vals as None, so ensure  
    298         # consistency here 
    299         val = None 
    300          
    301     return val 
    302  
    303 removePrefix = lambda prop: dict([(k.replace(prefix, ''), v)  
    304                                   for k,v in prop.items()]) 
    305         
     300        key = option 
     301          
     302    conversionFuncs = (cfg.getint, cfg.getfloat, cfg.getboolean, cfg.get) 
     303    for conversionFunc in conversionFuncs: 
     304        try: 
     305            val = conversionFunc(section, option) 
     306            if val == '': 
     307                # NB, the XML parser will return empty vals as None, so ensure  
     308                # consistency here 
     309                val = None 
     310                 
     311            elif isinstance(val, basestring): 
     312                # expand out any env vars 
     313                val = expandEnvVars(val) 
     314                 
     315                # ensure it is read in as the correct type 
     316                if key in validKeys and isinstance(validKeys[key], list): 
     317                    # Treat as a list of space separated string type elements 
     318                    # Nb. lists only cater for string type elements 
     319                    val = val.split() 
     320              
     321            return val 
     322        except ValueError: 
     323            continue 
     324        except Exception, e: 
     325            # TODO: Remove catch - testing only 
     326            pass 
     327 
     328    raise ValueError('Error parsing option "%s" in section "%s"'%(section,key)) 
     329 
     330          
    306331def readXMLPropertyFile(propFilePath, validKeys, rootElem=None): 
    307332    """ 
     
    365390                keys = validKeys 
    366391                if key == 'WS-Security': 
    367                     keys = WSSecurityConfig.defParam 
     392                    keys = WSSecurityConfig.propertyDefaults 
    368393                val = readXMLPropertyFile(propFilePath, keys, rootElem=elem) 
    369394 
     
    413438        # using the properties listed here 
    414439        if key == wsseSection: 
    415             validateProperties(properties[key], WSSecurityConfig.defParam) 
     440            validateProperties(properties[key], WSSecurityConfig.propertyDefaults) 
    416441             
    417442        elif validKeys[key] and isinstance(validKeys[key], dict): 
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/__init__.py

    r4233 r4304  
    2525    convenient interface for access to params. 
    2626    """ 
    27     defParam = dict( 
     27    propertyDefaults = dict( 
    2828             reqBinSecTokValType=OASIS.X509TOKEN.X509, 
    2929             verifyingCert=None, 
     
    5353         
    5454        # Initialise parameters from ref in class var 
    55         self._param = WSSecurityConfig.defParam.copy() 
     55        self._param = WSSecurityConfig.propertyDefaults.copy() 
    5656         
    5757        if isinstance(cfg, basestring): 
     
    8080            raise IOError('Missing config file(s): "%s"' % \ 
    8181                          '", "'.join(missingFilePaths)) 
    82          
    83  
    8482 
    8583    def parse(self, **kw): 
     
    9795            # Options may be omitted and set later 
    9896            if self._cfg.has_option(section, paramName): 
    99                 if isinstance(WSSecurityConfig.defParam[paramName], list): 
     97                if isinstance(WSSecurityConfig.propertyDefaults[paramName],  
     98                              list): 
    10099                    try: 
    101100                        self._param[paramName] = \ 
     
    104103                        raise SecurityConfigError('Setting "%s"' % paramName) 
    105104                     
    106                 elif isinstance(WSSecurityConfig.defParam[paramName], bool):            
     105                elif isinstance(WSSecurityConfig.propertyDefaults[paramName],  
     106                                bool):            
    107107                    self._param[paramName] = self._cfg.getboolean(section,  
    108108                                                                  paramName) 
     
    140140        WSSecurityConfig.__name__ + \ 
    141141        """ behaves as data dictionary of WS-Security properties""" 
    142         if key not in WSSecurityConfig.defParam: 
     142        if key not in WSSecurityConfig.propertyDefaults: 
    143143            raise KeyError("Parameter key '%s' is not recognised" % key) 
    144144         
     
    174174     
    175175    def update(self, seq, *arg): 
    176         badKeys = [i for i in seq if i not in WSSecurityConfig.defParam] 
     176        badKeys=[i for i in seq if i not in WSSecurityConfig.propertyDefaults] 
    177177        if badKeys: 
    178178            raise KeyError("Parameter key(s) %s not recognised" % \ 
     
    181181     
    182182    def fromkeys(self, seq): 
    183         badKeys = [i for i in seq if i not in WSSecurityConfig.defParam] 
     183        badKeys=[i for i in seq if i not in WSSecurityConfig.propertyDefaults] 
    184184        if badKeys: 
    185185            raise KeyError("Parameter key(s) %s not recognised" % \ 
     
    188188     
    189189    def setdefault(self, key, *arg): 
    190         badKeys = [i for i in b if i not in WSSecurityConfig.defParam] 
     190        badKeys = [i for i in b if i not in WSSecurityConfig.propertyDefaults] 
    191191        if badKeys: 
    192192            raise KeyError("Parameter keys '%s' not recognised" % badKeys) 
  • TI12-security/trunk/python/ndg.security.server/ndg/security/server/SessionMgr/__init__.py

    r4279 r4304  
    3939from ndg.security.common.CredWallet import CredWallet, CredentialRepository, \ 
    4040    CredWalletError, CredWalletAttributeRequestDenied 
    41  
     41     
     42from ndg.security.common.wssecurity import WSSecurityConfig 
    4243from ndg.security.common.X509 import X500DN, X509Cert, X509CertParse, \ 
    4344                                X509CertExpired, X509CertInvalidNotBeforeTime  
     
    220221    """NDG authentication and session handling 
    221222     
    222     @type _validElem: dict 
    223     @cvar _validElem: list of the valid properties file element names and 
     223    @type propertyDefaults: dict 
     224    @cvar propertyDefaults: list of the valid properties file element names and 
    224225    sub-elements where appropriate 
    225226     
    226227    @type _confDir: string 
    227     @cvar _confDir: configuration directory under $NDGSEC_DIR - default location 
    228     for properties file  
     228    @cvar _confDir: configuration directory under $NDGSEC_DIR - default  
     229    location for properties file  
    229230     
    230231    @type _propFileName: string 
     
    232233    _confDir 
    233234     
    234     @type _credentialRepositoryValidElem: dict 
    235     @cvar _credentialRepositoryValidElem: permitted properties file elements  
    236     for configuring the Crendential Repository.  Those set to NotImplemented  
    237     indicate properties that must be set.  For the others, the value indicates 
    238     the default if not present in the file""" 
     235    @type credentialRepositoryPropertyDefaults: dict 
     236    @cvar credentialRepositoryPropertyDefaults: permitted properties file  
     237    elements for configuring the Crendential Repository.  Those set to  
     238    NotImplemented indicate properties that must be set.  For the others, the  
     239    value indicates the default if not present in the file""" 
    239240 
    240241    # valid configuration property keywords 
    241     WS_SETTINGS_KEY_NAME = 'WS-Security' 
    242     AUTHN_KEY_NAME = 'authNService' 
    243     CRED_REPOS_KEY_NAME = 'credentialRepository' 
    244     CRED_WALLET_KEY_NAME = 'credentialWallet' 
    245      
    246     _credentialRepositoryValidElem = { 
     242    WSSECURITY_KEYNAME = 'wssecurity' 
     243    AUTHN_KEYNAME = 'authNService' 
     244    CREDREPOS_KEYNAME = 'credentialRepository' 
     245    CREDWALLET_KEYNAME = 'credentialWallet' 
     246 
     247    authNServicePropertyDefaults = { 
    247248        'modFilePath': None, 
    248249        'modName': None, 
    249250        'className': None, 
    250         'propFile': None 
     251        'propertiesFile': None         
    251252    } 
    252  
    253     _validElem = { 
     253     
     254    credentialRepositoryPropertyDefaults = { 
     255        'modFilePath': None, 
     256        'modName': None, 
     257        'className': None, 
     258        'propertiesFile': None 
     259    } 
     260 
     261    propertyDefaults = { 
    254262        'portNum':                None, 
    255263        'useSSL':                 False, 
     
    257265        'sslKeyFile':             None, 
    258266        'sslCACertDir':           None, 
    259         AUTHN_KEY_NAME:           None,  
    260         CRED_WALLET_KEY_NAME:     None, 
    261         CRED_REPOS_KEY_NAME:      _credentialRepositoryValidElem, 
     267        AUTHN_KEYNAME:            authNServicePropertyDefaults,  
     268        CREDWALLET_KEYNAME:       CredWallet.propertyDefaults, 
     269        CREDREPOS_KEYNAME:        credentialRepositoryPropertyDefaults, 
     270        WSSECURITY_KEYNAME:       WSSecurityConfig.propertyDefaults 
    262271    } 
    263272 
     
    269278                 propFileSection='DEFAULT', 
    270279                 propPrefix='', 
    271                  credentialRepositoryPPhrase=None, **prop):        
     280                 credentialRepositoryPPhrase=None,  
     281                 **prop):        
    272282        """Create a new session manager to manager NDG User Sessions 
    273283         
    274         propFilePath:        path to properties file 
    275         credentialRepositoryPPhrase:    for credential repository if not set in 
    276                              properties file 
    277         **prop:              set any other properties corresponding to the 
    278                              tags in the properties file"""         
     284        @type propFilePath: basestring 
     285        @param propFilePath: path to properties file 
     286        @type propFileSection: basestring 
     287        @param propFileSection: applies to ini format config files only - the  
     288        section to read the Session Managers settings from 
     289        @type credentialRepositoryPPhrase: basestring 
     290        @param credentialRepositoryPPhrase: for credential repository if not  
     291        set in properties file 
     292        @type prop: dict 
     293        @param **prop: set any other properties corresponding to the tags in  
     294        the properties file as keywords"""         
    279295 
    280296        log.info("Initialising service ...") 
     
    308324        # Instantiate the authentication service to use with the session manager 
    309325        self.__authNService = instantiateClass( 
    310                 self.__prop[self.AUTHN_KEY_NAME].get('moduleName'), 
    311                 self.__prop[self.AUTHN_KEY_NAME].get('className'), 
    312                 moduleFilePath=self.__prop[self.AUTHN_KEY_NAME].get('moduleFilePath'), 
     326                self.__prop[self.AUTHN_KEYNAME].get('moduleName'), 
     327                self.__prop[self.AUTHN_KEYNAME].get('className'), 
     328                moduleFilePath=self.__prop[self.AUTHN_KEYNAME].get('moduleFilePath'), 
    313329                objectType=AbstractAuthNService,  
    314                 classProperties=self.__prop[self.AUTHN_KEY_NAME]) 
     330                classProperties=self.__prop[self.AUTHN_KEYNAME]) 
    315331        # Call here as we can safely expect that all Credential Repository 
    316332        # parameters have been set above 
    317         credentialRepositoryModule = self.__prop[self.CRED_REPOS_KEY_NAME].get('modName') 
    318         credentialRepositoryClassName = self.__prop[self.CRED_REPOS_KEY_NAME].get('className') 
     333        credentialRepositoryModule = self.__prop[self.CREDREPOS_KEYNAME].get('modName') 
     334        credentialRepositoryClassName = self.__prop[self.CREDREPOS_KEYNAME].get('className') 
    319335        if credentialRepositoryModule is None or credentialRepositoryClassName is None: 
    320336            self._credentialRepository = NullCredentialRepository() 
    321337        else: 
    322338            credentialRepositoryModuleFilePath = \ 
    323                 self.__prop[self.CRED_REPOS_KEY_NAME].get('modFilePath') 
     339                self.__prop[self.CREDREPOS_KEYNAME].get('modFilePath') 
    324340                 
    325341            self._credentialRepository = instantiateClass( 
     
    328344                        moduleFilePath=credentialRepositoryModuleFilePath, 
    329345                        objectType=CredentialRepository, 
    330                         classProperties=self.__prop[self.CRED_REPOS_KEY_NAME]) 
     346                        classProperties=self.__prop[self.CREDREPOS_KEYNAME]) 
    331347         
    332348        # Set any properties that were provided by keyword input 
     
    538554        # Configuration file properties are held together in a dictionary 
    539555        self.__prop = readAndValidateProperties(self.propFilePath, 
    540                                             validKeys=SessionMgr._validElem, 
    541                                             prefix=prefix, 
    542                                             sections=(section,), 
    543                                             wsseSection=self.WS_SETTINGS_KEY_NAME) 
    544          
    545         # add the WS-security properties to the main properties 
    546         if self.__prop.has_key(self.WS_SETTINGS_KEY_NAME): 
    547             self.__prop.update(self.__prop[self.WS_SETTINGS_KEY_NAME]) 
    548  
    549         missingElem = [] 
    550          
    551         # Further process the input config detail - to ensure subelement  
    552         # details are properly set up - NB, these are vals which are  
    553         # dictionaries; can ignore other vals here 
    554         for key, val in self.__prop.items(): 
    555             if not isinstance(val, dict): 
    556                 continue 
    557              
    558             if key == self.CRED_REPOS_KEY_NAME: 
    559                 # Check for missing elements 
    560                 missingElem.extend(getMissingElem( 
    561                                    self._validElem[self.CRED_REPOS_KEY_NAME], 
    562                                    self.__prop[self.CRED_REPOS_KEY_NAME]))                     
    563  
    564         missingElem.extend(getMissingElem(self._validElem, self.__prop)) 
    565         errMsg = '' 
    566          
    567         if missingElem: 
    568             raise SessionMgrError('Missing elements: "%s"\n' %  
    569                                   '", "'.join(missingElem) + \ 
    570                                   " for properties file") 
     556                                        validKeys=SessionMgr.propertyDefaults, 
     557                                        prefix=prefix, 
     558                                        sections=(section,), 
     559                                        wsseSection=self.WSSECURITY_KEYNAME) 
    571560 
    572561        log.info('Loaded properties from "%s"' % self._propFilePath) 
     
    579568         
    580569        for key in prop.keys(): 
    581             if key not in self._validElem: 
     570            if key not in self.propertyDefaults: 
    582571                raise SessionMgrError("Property name \"%s\" is invalid" % key) 
    583572        for key, value in prop.items(): 
     
    586575                self.__authNService.setProperties(prop[key]) 
    587576     
    588             elif key == self.CRED_REPOS_KEY_NAME: 
    589                 self.__prop[self.CRED_REPOS_KEY_NAME] = prop[key].copy() 
    590  
    591             elif key in self._validElem: 
     577            elif key == self.CREDREPOS_KEYNAME: 
     578                self.__prop[self.CREDREPOS_KEYNAME] = prop[key].copy() 
     579 
     580            elif key in self.propertyDefaults: 
    592581                # Only update other keys if they are not None or "" 
    593582                if value: 
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/credwallet/credWallet.cfg

    r4293 r4304  
    1515issuingX509Cert= 
    1616 
    17 # CA certificates for Attribute Certificate signautre validation 
     17# CA certificates for Attribute Certificate signature validation 
    1818caCertFilePathList=$NDGSEC_CREDWALLET_UNITTEST_DIR/ca/ndg-test-ca.crt 
    1919 
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/sessionMgr/sessionMgr.cfg

    r4294 r4304  
    1111# 
    1212[DEFAULT] 
     13# ALL the settings from this point to the Credential Wallet settings heading 
     14# are not actually used in these unit tests because the Session Manager is not 
     15# being run as a service, it's being run as a local instance within the tests. 
     16# The settings are included to ensure that they're correctly parsed by the  
     17# config file reader 
     18 
    1319# the port number the service is to run on - for convenience only may be  
    1420# ignored by web application server container - e.g. Paste - see ini file 
     
    1824useSSL: False 
    1925 
    20 # X.509 certificate for SSL connections - ignored if useSSL is blank  
    21 #sslCertFile: $NDGSEC_SM_UNITTEST_DIR/host.crt 
     26# X.509 certificate for SSL connections - ignored if useSSL is blank - Nb. 
     27sslCertFile: $NDGSEC_SM_UNITTEST_DIR/sm.crt 
    2228 
    2329# Private key file for SSL  - ignored if useSSL is blank  
    24 #sslKeyFile: $NDGSEC_SM_UNITTEST_DIR/host.key 
     30sslKeyFile: $NDGSEC_SM_UNITTEST_DIR/sm.key 
    2531 
    2632# Directory containing CA cert.s to verify SSL peer cert against - ignored if  
     
    4955# Refresh an Attribute Certificate, if an existing one in the wallet has only 
    5056# this length of time left before it expires 
    51 attCertRefreshElapse=7200 
     57credentialWallet.attCertRefreshElapse=7200 
     58 
     59# Settings for Credential Repository plugin 
     60# File path to plugin module - may be left blank if module is included in the  
     61# current PYTHONPATH 
     62#credentialRepository.modFilePath: 
     63 
     64# 
     65# Module name - the default is an empty stub 
     66credentialRepository.modName: ndg.security.common.CredWallet 
     67 
     68# Name of class in module to instantiate  
     69credentialRepository.className: NullCredRepos 
     70 
     71# Optional Properties file argument to Credential Repository class.  This is  
     72# include to enable custom settings to be defined from an external  
     73# configuration file 
     74credentialRepository.propertiesFile: 
     75 
     76 
     77# Authentication service properties  
     78authNService.moduleFilePath:  
     79authNService.moduleName: ndg.security.server.authenservice.session_mgr_my_proxy_client 
     80authNService.className: SessionMgrMyProxyClient 
     81authNService.propertiesFile: 
     82 
     83# MyProxy AuthNService Plugin specific settings 
     84# Delete this element and take setting from MYPROXY_SERVER environment  
     85# variable if required 
     86#hostname: localhost 
     87 
     88#  
     89# Delete this element to take default setting 7512 or read  
     90# MYPROXY_SERVER_PORT setting 
     91authNService.port: 7512 
     92 
     93# Useful if hostname and certificate CN don't match correctly.  Globus  
     94# host DN is set to "host/<fqdn: ".  Delete this element and set from  
     95# MYPROXY_SERVER_DN environment variable if prefered 
     96authNService.serverDN: 
     97 
     98# Set "host/" prefix to host cert CN as is default with globus 
     99authNService.serverCNprefix: host/  
     100  
     101# This directory path is used to locate the OpenSSL configuration file 
     102# 
     103# The settings are used to set up the defaults for the Distinguished Name of 
     104# the new proxy cert. issued  
     105#  
     106# GLOBUS_LOCATION or GRID_SECURITY_DIR environment variables may be used 
     107# but the settings can be independent of any Globus installation 
     108authNService.openSSLConfFilePath: $NDGSEC_DIR/conf/openssl.conf 
     109authNService.tmpDir: /tmp 
     110 
     111# Limit on maximum lifetime (in seconds) any proxy certificate can have -  
     112# specified when a certificate is first created by store() method 
     113authNService.proxyCertMaxLifetime: 43200 
     114 
     115# Life time of a proxy certificate (seconds) when issued from the Proxy Server  
     116# with ndg.security.server.MyProxy.getDelegation() method 
     117authNService.proxyCertLifetime: 43200 
     118  
     119# CA certificate applied to verify peer certificate against in 
     120# SSL connection to MyProxy server 
     121authNService.caCertFile: $NDGSEC_DIR/conf/certs/cacert.pem 
    52122 
    53123# 
    54124# SOAP Signature Handler settings 
    55 # Leave blank for NO SOAP signature 
    56 [WS-Security] 
    57125# 
    58126# OUTBOUND MESSAGE CONFIG 
     
    61129# The CA certificates of other NDG trusted sites should go here.  NB, multiple 
    62130# values should be delimited by a space 
    63 caCertFilePathList: $NDGSEC_DIR/conf/certs/ca/cacert.pem   
     131wssecurity.caCertFilePathList: $NDGSEC_DIR/conf/certs/ca/cacert.pem   
    64132 
    65133# Signature of an outbound message 
     
    71139 
    72140# PEM encoded cert 
    73 signingCertFilePath: $NDGSEC_DIR/conf/certs/sm-cert.pem 
     141wssecurity.signingCertFilePath: $NDGSEC_DIR/conf/certs/sm-cert.pem 
    74142 
    75143# ... or provide file path to PEM encoded private key file 
    76 signingPriKeyFilePath: $NDGSEC_DIR/conf/certs/sm-key.pem 
     144wssecurity.signingPriKeyFilePath: $NDGSEC_DIR/conf/certs/sm-key.pem 
    77145 
    78146# Password protecting private key.  Leave blank if there is no password. 
    79 signingPriKeyPwd= 
    80  
    81 # Pass a list of certificates ',' separated PEM encoded certs constituting a  
    82 # chain of trust from the certificate used to verifying the signature backward  
    83 # to the CA cert.  The CA cert need not be included.  To use this option,  
    84 # reqBinSecTokValType must be set to the X509PKIPathv1 
    85 signingCertChain= 
     147wssecurity.signingPriKeyPwd= 
    86148 
    87149# Provide a space separated list of file paths 
    88 caCertFilePathList: $NDGSEC_DIR/conf/certs/ca/cacert.pem 
     150wssecurity.caCertFilePathList: $NDGSEC_DIR/conf/certs/ca/cacert.pem 
    89151 
    90152# Set the ValueType for the BinarySecurityToken added to the WSSE header for a 
     
    96158# binSecTokValType determines whether signingCert or signingCertChain  
    97159# attributes will be used. 
    98 reqBinSecTokValType: X509v3 
     160wssecurity.reqBinSecTokValType: X509v3 
    99161 
    100162# Add a timestamp element to an outbound message 
    101 addTimestamp: True 
     163wssecurity.addTimestamp: True 
    102164 
    103165# For WSSE 1.1 - service returns signature confirmation containing signature  
    104166# value sent by client 
    105 applySignatureConfirmation: True 
     167wssecurity.applySignatureConfirmation: True 
    106168 
    107169# Inclusive namespace prefixes - for Exclusive Canonicalisation only 
     
    110172# Inclusive namespace prefixes Canonicalisation of reference elements -  
    111173# space separated list e.g. refC14nInclNS=wsse ds ns1 
    112 refC14nInclNS: 
     174wssecurity.refC14nInclNS: 
    113175 
    114176# Inclusive namespaces prefixes for Canonicalisation of SignedInfo element - 
    115177# same format as the above 
    116 signedInfoC14nInclNS: 
     178wssecurity.signedInfoC14nInclNS: 
    117179 
    118180# 
     
    125187 
    126188# ... or provide file path PEM encode cert here 
    127 verifyingCertFilePath:  
     189wssecurity.verifyingCertFilePath:  
    128190 
    129  
    130 # authentication service properties  
    131 [authNServiceProp] 
    132 moduleFilePath:  
    133 moduleName: ndg.security.server.authenservice.session_mgr_my_proxy_client 
    134 className: SessionMgrMyProxyClient 
    135 propertiesFile: 
    136 # Delete this element and take setting from MYPROXY_SERVER environment  
    137 # variable if required 
    138  
    139 # hostname: localhost 
    140 #  
    141 # Delete this element to take default setting 7512 or read  
    142 # MYPROXY_SERVER_PORT setting 
    143 port: 7512 
    144  
    145 # Useful if hostname and certificate CN don't match correctly.  Globus  
    146 # host DN is set to "host/<fqdn: ".  Delete this element and set from  
    147 # MYPROXY_SERVER_DN environment variable if prefered 
    148 serverDN: 
    149  
    150 # Set "host/" prefix to host cert CN as is default with globus 
    151 serverCNprefix: host/  
    152   
    153 # This directory path is used to locate the OpenSSL configuration file 
    154 # 
    155 # The settings are used to set up the defaults for the Distinguished Name of 
    156 # the new proxy cert. issued  
    157 #  
    158 # GLOBUS_LOCATION or GRID_SECURITY_DIR environment variables may be used 
    159 # but the settings can be independent of any Globus installation 
    160 openSSLConfFilePath: $NDGSEC_DIR/conf/openssl.conf 
    161 tmpDir: /tmp 
    162  
    163 # Limit on maximum lifetime any proxy certificate can have -  
    164 # specified when a certificate is first created by store() method 
    165 proxyCertMaxLifetime: 43200 # in seconds 
    166  
    167 # Life time of a proxy certificate (seconds) when issued from the Proxy Server  
    168 # with ndg.security.server.MyProxy.getDelegation() method 
    169 proxyCertLifetime: 43200 
    170   
    171 # CA certificate applied to verify peer certificate against in 
    172 # SSL connection to MyProxy server 
    173 caCertFile: $NDGSEC_DIR/conf/certs/cacert.pem 
    174  
    175  
    176 # Settings for Credential Repository plugin 
    177 [credReposProp] 
    178 # File path to plugin module - may be left blank if module is included in the  
    179 # current PYTHONPATH 
    180 #modFilePath: 
    181  
    182 # 
    183 # Module name - the default is an empty stub 
    184 modName: ndg.security.common.CredWallet 
    185  
    186 # Name of class in module to instantiate  
    187 className: NullCredRepos 
    188  
    189 # Optional Properties file argument to Credential Repository class.  This is  
    190 # include to enable custom settings to be defined from an external  
    191 # configuration file 
    192 propFile: 
    193  
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/sessionMgr/sessionMgrTest.cfg

    r4158 r4304  
    1010# $Id:$ 
    1111[setUp] 
    12 propFilePath = $NDGSEC_SM_UNITTEST_DIR/sessionMgrProperties.xml 
     12# Test with INI file - use of XML file likely to be deprecated 
     13#propFilePath = $NDGSEC_SM_UNITTEST_DIR/sessionMgrProperties.xml 
     14propFilePath = $NDGSEC_SM_UNITTEST_DIR/sessionMgr.cfg 
    1315 
    1416[test1Connect] 
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/sessionMgr/test_sessionMgr.py

    r4294 r4304  
    2020import traceback 
    2121 
     22from ndg.security.common.utils.ConfigFileParsers import \ 
     23                                                    CaseSensitiveConfigParser 
    2224from ndg.security.common.X509 import X509CertParse 
    2325from ndg.security.server.SessionMgr import * 
    24 from ndg.security.server.MyProxy import MyProxyClient 
    2526 
    2627from os.path import expandvars as xpdVars 
     
    5051                os.path.abspath(os.path.dirname(__file__)) 
    5152         
    52         self.cfg = SafeConfigParser() 
     53        self.cfg = CaseSensitiveConfigParser() 
    5354        configFilePath = jnPath(os.environ['NDGSEC_SM_UNITTEST_DIR'], 
    5455                                "sessionMgrTest.cfg") 
     
    5758        # Initialise the Session Manager client connection 
    5859        # Omit traceFile keyword to leave out SOAP debug info 
    59         propFilePath = xpdVars(self.cfg.get('setUp', 'propFilePath')) 
    60         self.sm = SessionMgr(propFilePath=propFilePath) 
    61  
    62     def sessionMgrConnect(self): 
     60        self.propFilePath = xpdVars(self.cfg.get('setUp', 'propFilePath')) 
     61#        self.sm = SessionMgr(propFilePath=propFilePath) 
     62 
     63    def test0Init(self): 
     64        sm = SessionMgr(propFilePath=self.propFilePath) 
     65         
     66    def _sessionMgrConnect(self): 
     67        '''Helper method to set up connections''' 
    6368        print "Connecting to session manager..." 
    6469        username = self.cfg.get('test1Connect', 'username') 
    6570        if SessionMgrTestCase.test1Passphrase is None and \ 
    6671           self.cfg.has_option('test1Connect', 'passphrase'): 
    67             SessionMgrTestCase.test1Passphrase = \ 
    68                                     self.cfg.get('test1Connect', 'passphrase') 
     72            SessionMgrTestCase.test1Passphrase = self.cfg.get('test1Connect',  
     73                                                              'passphrase') 
    6974         
    7075        if not SessionMgrTestCase.test1Passphrase: 
    7176            SessionMgrTestCase.test1Passphrase = getpass.getpass(\ 
     77                prompt="\ntest1Connect pass-phrase for user %s: " % username) 
     78 
     79        print "Connecting to session manager as user: %s..." % username 
     80        userCert, self.userPriKey, self.issuingCert, self.sessID = \ 
     81            self.sm.connect(username=username,  
     82                            passphrase=SessionMgrTestCase.test1Passphrase) 
     83        self.userCert = X509CertParse(userCert) 
     84         
     85        print "User '%s' connected to Session Manager:\n%s" % (username,  
     86                                                               self.sessID) 
     87        creds='\n'.join((self.issuingCert or '', 
     88                         self.userCert.asPEM().strip(), 
     89                         self.userPriKey)) 
     90        open(mkPath("user.creds"), "w").write(creds) 
     91        print "Finished setting up connection" 
     92         
     93                                   
     94    def test1Connect(self): 
     95        """test1Connect: make a new session""" 
     96         
     97        username = self.cfg.get('test1Connect', 'username') 
     98        if SessionMgrTestCase.test1Passphrase is None and \ 
     99           self.cfg.has_option('test1Connect', 'passphrase'): 
     100            SessionMgrTestCase.test1Passphrase = self.cfg.get('test1Connect',  
     101                                                              'passphrase') 
     102         
     103        if not SessionMgrTestCase.test1Passphrase: 
     104            SessionMgrTestCase.test1Passphrase = getpass.getpass( 
    72105                prompt="\ntest1Connect pass-phrase for user %s: " % username) 
    73106 
     
    84117                         self.userPriKey)) 
    85118        open(mkPath("user.creds"), "w").write(creds) 
    86         print "Finished setting up connection" 
    87          
    88                                    
    89     def test1Connect(self): 
    90         """test1Connect: make a new session""" 
    91          
    92         username = self.cfg.get('test1Connect', 'username') 
    93         if SessionMgrTestCase.test1Passphrase is None and \ 
    94            self.cfg.has_option('test1Connect', 'passphrase'): 
    95             SessionMgrTestCase.test1Passphrase = \ 
    96                                     self.cfg.get('test1Connect', 'passphrase') 
    97          
    98         if not SessionMgrTestCase.test1Passphrase: 
    99             SessionMgrTestCase.test1Passphrase = getpass.getpass(\ 
    100                 prompt="\ntest1Connect pass-phrase for user %s: " % username) 
    101  
    102         print "Connecting to session manager as user: %s..." %username 
    103         userCert, self.userPriKey, self.issuingCert, self.sessID = \ 
    104             self.sm.connect(username=username,  
    105                             passphrase=SessionMgrTestCase.test1Passphrase) 
    106         self.userCert = X509CertParse(userCert) 
    107          
    108         print "User '%s' connected to Session Manager:\n%s" % \ 
    109                                                         (username, self.sessID) 
    110         creds='\n'.join((self.issuingCert or '', 
    111                          self.userCert.asPEM().strip(), 
    112                          self.userPriKey)) 
    113         open(mkPath("user.creds"), "w").write(creds) 
    114119     
    115120             
     
    117122        """test2GetSessionStatus: check a session is alive""" 
    118123         
    119         self.sessionMgrConnect() 
     124        self._sessionMgrConnect() 
    120125        assert self.sm.getSessionStatus(sessID=self.sessID), "Session is dead" 
    121126        print "User connected to Session Manager with sessID=%s" % self.sessID 
     
    129134        """test3ConnectNoCreateServerSess: Connect as a non browser client -  
    130135        sessID should be None""" 
    131  
    132         username = self.cfg.get('test3ConnectNoCreateServerSess', 'username') 
     136        section = 'test3ConnectNoCreateServerSess' 
     137        username = self.cfg.get(section, 'username') 
    133138 
    134139        if SessionMgrTestCase.test3Passphrase is None and \ 
    135            self.cfg.has_option('test3ConnectNoCreateServerSess',  
    136                                'passphrase'): 
    137             SessionMgrTestCase.test3Passphrase = \ 
    138                 self.cfg.get('test3ConnectNoCreateServerSess', 'passphrase') 
     140           self.cfg.has_option(section, passphrase): 
     141            SessionMgrTestCase.test3Passphrase = self.cfg.get(section,  
     142                                                              'passphrase') 
    139143         
    140144        if not SessionMgrTestCase.test3Passphrase: 
    141             SessionMgrTestCase.test3Passphrase = getpass.getpass(\ 
    142         prompt="\ntest3ConnectNoCreateServerSess pass-phrase for user %s: " % \ 
    143             username) 
     145            SessionMgrTestCase.test3Passphrase = getpass.getpass(prompt=\ 
     146                                            "\ntest3ConnectNoCreateServerSess " 
     147                                            "pass-phrase for user %s: " %  
     148                                            username) 
    144149 
    145150        self.userCert, self.userPriKey, self.issuingCert, sessID = \ 
     
    151156        assert not sessID, "Expecting a null session ID!" 
    152157           
    153         print "User '%s' retrieved creds. from Session Manager:\n%s" % \ 
    154                                                     (username, self.userCert) 
     158        print("User '%s' retrieved creds. from Session Manager:\n%s" %  
     159                                                    (username, self.userCert)) 
    155160             
    156161 
    157162    def test4DisconnectWithSessID(self): 
    158         """test4DisconnectWithSessID: disconnect as if acting as a browser client  
     163        """test4DisconnectWithSessID: disconnect as if acting as a browser  
     164        client  
    159165        """ 
    160166         
    161         self.sessionMgrConnect()         
     167        self._sessionMgrConnect()         
    162168        self.sm.deleteUserSession(sessID=self.sessID) 
    163169         
     
    169175        """ 
    170176         
    171         self.sessionMgrConnect() 
     177        self._sessionMgrConnect() 
    172178         
    173179        # Proxy cert in signature determines ID of session to 
     
    181187        a session ID as authentication credential""" 
    182188 
    183         self.sessionMgrConnect() 
    184          
     189        self._sessionMgrConnect() 
     190         
     191        section = 'test6GetAttCertWithSessID' 
    185192        attCert, errMsg, extAttCertList = self.sm.getAttCert(\ 
    186             sessID=self.sessID,  
    187             aaURI=self.cfg.get('test6GetAttCertWithSessID', 'aauri')) 
     193                                        sessID=self.sessID,  
     194                                        aaURI=self.cfg.get(section, 'aaURI')) 
    188195        if errMsg: 
    189196            self.fail(errMsg) 
    190197             
    191198        print "Attribute Certificate:\n%s" % attCert  
    192         attCert.filePath = \ 
    193             xpdVars(self.cfg.get('test6GetAttCertWithSessID', 'acoutfilepath'))  
     199        attCert.filePath = xpdVars(self.cfg.get(section, 'acoutfilepath'))  
    194200        attCert.write() 
    195201         
     
    202208        Attribute Authority where the user is NOT registered""" 
    203209 
    204         self.sessionMgrConnect() 
    205          
    206         aaURI = self.cfg.get('test6aGetAttCertRefusedWithSessID', 'aauri') 
    207          
    208         attCert, errMsg, extAttCertList = self.sm.getAttCert(sessID=self.sessID,  
    209                                          aaURI=aaURI, 
    210                                          mapFromTrustedHosts=False) 
     210        self._sessionMgrConnect() 
     211         
     212        aaURI = self.cfg.get('test6aGetAttCertRefusedWithSessID', 'aaURI') 
     213         
     214        attCert, errMsg, extAttCertList=self.sm.getAttCert(sessID=self.sessID,  
     215                                                     aaURI=aaURI, 
     216                                                     mapFromTrustedHosts=False) 
    211217        if errMsg: 
    212218            print "SUCCESS - obtained expected result: %s" % errMsg 
     
    220226        a session ID as authentication credential""" 
    221227 
    222         self.sessionMgrConnect() 
     228        self._sessionMgrConnect() 
    223229         
    224230        # Attribute Certificate cached in test 6 can be used to get a mapped 
     
    226232        self.sm = self.test6GetAttCertWithSessID() 
    227233 
    228         aaURI = self.cfg.get('test6bGetMappedAttCertWithSessID', 'aauri') 
     234        aaURI = self.cfg.get('test6bGetMappedAttCertWithSessID', 'aaURI') 
    229235         
    230236        attCert, errMsg, extAttCertList=self.sm.getAttCert(sessID=self.sessID, 
     
    241247        a session ID as authentication credential""" 
    242248         
    243         self.sessionMgrConnect() 
    244          
    245         aaURI = \ 
    246             self.cfg.get('test6cGetAttCertWithExtAttCertListWithSessID', 'aauri') 
     249        self._sessionMgrConnect() 
     250        section = 'test6cGetAttCertWithExtAttCertListWithSessID' 
     251        aaURI = self.cfg.get(section, 'aaURI') 
    247252         
    248253        # Use output from test6GetAttCertWithSessID! 
    249         extACFilePath = \ 
    250         xpdVars(self.cfg.get('test6cGetAttCertWithExtAttCertListWithSessID',  
    251                              'extacfilepath'))    
     254        extACFilePath = xpdVars(self.cfg.get(section, 'extACFilePath'))    
    252255        extAttCert = open(extACFilePath).read() 
    253256         
     
    265268        """test7GetAttCertWithUserCert: make an attribute request using 
    266269        a user cert as authentication credential""" 
    267         self.sessionMgrConnect() 
     270        self._sessionMgrConnect() 
    268271 
    269272        # Request an attribute certificate from an Attribute Authority  
    270273        # using the userCert returned from connect() 
    271274         
    272         aaURI = self.cfg.get('test7GetAttCertWithUserCert', 'aauri') 
    273         attCert, errMsg, extAttCertList = self.sm.getAttCert(\ 
     275        aaURI = self.cfg.get('test7GetAttCertWithUserCert', 'aaURI') 
     276        attCert, errMsg, extAttCertList = self.sm.getAttCert( 
    274277                                     userCert=self.userCert, aaURI=aaURI) 
    275278        if errMsg: 
Note: See TracChangeset for help on using the changeset viewer.