Changeset 4285 for TI12-security/trunk


Ignore:
Timestamp:
06/10/08 13:34:17 (11 years ago)
Author:
pjkersha
Message:

Refactoring of CredWallet? - first working unit tests for new version + fixes to Attribute Authority ZSI WSDL gen code interface.

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

Legend:

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

    r4262 r4285  
    4343log = logging.getLogger(__name__) 
    4444 
    45 #_____________________________________________________________________________ 
    4645class AttAuthorityClientError(Exception): 
    4746    """Exception handling for AttributeAuthorityClient class""" 
     
    5857    trusted hosts for the given input role name""" 
    5958 
    60 #_____________________________________________________________________________ 
     59 
    6160class AttAuthorityClient(object): 
    6261    """Client interface to Attribute Authority web service 
     
    7170        } 
    7271     
    73     #_________________________________________________________________________ 
    7472    def __init__(self,  
    7573                 uri=None,  
     
    145143            self.initService() 
    146144         
    147  
    148     #_________________________________________________________________________ 
    149145    def __setURI(self, uri): 
    150146        """Set URI for service 
     
    167163            self._transport = ProxyHTTPConnection 
    168164 
    169  
    170     #_________________________________________________________________________ 
    171165    def __getURI(self): 
    172166        """Get URI for service 
     
    177171    uri = property(fset=__setURI, fget=__getURI,doc="Attribute Authority URI") 
    178172 
    179  
    180     #_________________________________________________________________________ 
    181173    def __setHTTPProxyHost(self, val): 
    182174        """Set a HTTP Proxy host overriding any http_proxy environment variable 
     
    192184        doc="HTTP Proxy hostname - overrides any http_proxy env var setting") 
    193185 
    194  
    195     #_________________________________________________________________________ 
    196186    def __setNoHttpProxyList(self, val): 
    197187        """Set to list of hosts for which to ignore the HTTP Proxy setting""" 
     
    206196    doc="Set to list of hosts for which to ignore the HTTP Proxy setting") 
    207197 
    208  
    209     #_________________________________________________________________________ 
    210198    def __setSSLPeerCertCN(self, cn): 
    211199        """For use with HTTPS connections only.  Specify the Common 
     
    223211doc="for https connections, set CN of peer cert if other than peer hostname") 
    224212 
    225  
    226     #_________________________________________________________________________ 
    227213    def __setSSLCACertList(self, caCertList): 
    228214        """For use with HTTPS connections only.  Specify CA certs to one of  
     
    240226doc="for https connections, set list of CA certs from which to verify peer cert") 
    241227 
    242  
    243     #_________________________________________________________________________ 
    244228    def __setSSLCACertFilePathList(self, caCertFilePathList): 
    245229        """For use with HTTPS connections only.  Specify CA certs to one of  
     
    258242doc="for https connections, set list of CA cert files from which to verify peer cert") 
    259243 
    260      
    261     #_________________________________________________________________________ 
    262244    def __setSignatureHandler(self, signatureHandler): 
    263245        """Set SignatureHandler object property method - set to None to for no 
     
    271253        self.__signatureHandler = signatureHandler 
    272254     
    273  
    274     #_________________________________________________________________________ 
    275255    def __getSignatureHandler(self): 
    276256        "Get SignatureHandler object property method" 
     
    281261                                doc="SignatureHandler object") 
    282262     
    283          
    284     #_________________________________________________________________________ 
    285263    def initService(self, uri=None): 
    286264        """Set the WS proxy for the Attribute Authority 
     
    305283                (self.__uri, e.status, e.reason) 
    306284 
    307                                      
    308     #_________________________________________________________________________ 
    309285    def getHostInfo(self): 
    310286        """Get host information for the data provider which the  
     
    348324        return hostInfo 
    349325 
    350                                      
    351     #_________________________________________________________________________ 
    352326    def getTrustedHostInfo(self, role=None): 
    353327        """Get list of trusted hosts for an Attribute Authority 
     
    398372        return trustedHostInfo 
    399373 
    400                                      
    401     #_________________________________________________________________________ 
    402374    def getAllHostsInfo(self): 
    403375        """Get list of all hosts for an Attribute Authority i.e. itself and 
     
    445417        return allHostInfo    
    446418 
    447  
    448     #_________________________________________________________________________ 
    449419    def getAttCert(self, userId=None, userCert=None, userAttCert=None): 
    450420        """Request attribute certificate from NDG Attribute Authority Web  
     
    506476            return AttCertParse(sAttCert) 
    507477        else: 
    508             raise AttributeRequestDenied, msg 
    509  
     478            raise AttributeRequestDenied(msg) 
    510479                                     
    511     #_________________________________________________________________________ 
    512480    def getX509Cert(self): 
    513481        """Retrieve the X.509 certificate of the Attribute Authority 
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/CredWallet.py

    r4279 r4285  
    6464# generic parser to read INI/XML properties file 
    6565from ndg.security.common.utils.ConfigFileParsers import \ 
    66                                                     readAndValidateProperties 
     66                                                INIPropertyFileWithValidation 
    6767 
    6868 
     
    161161    """Volatile store of user credentials associated with a user session 
    162162     
    163     @type __credentialRepository: ndg.security.common.CredentialRepository or  
     163    @type userX509Cert: string / M2Crypto.X509.X509 / 
     164    ndg.security.common.X509.X509Cert 
     165    @ivar userX509Cert: X.509 certificate for user (property attribute) 
     166     
     167    @type userPriKey: string / M2Crypto.RSA.RSA  
     168    @ivar userPriKey: private key for user cert (property attribute) 
     169     
     170    @type issuingX509Cert: string / ndg.security.common.X509.X509Cert 
     171    @ivar issuingX509Cert: X.509 cert for issuer of user cert (property  
     172    attribute) 
     173     
     174    @type attributeAuthorityURI: string 
     175    @ivar attributeAuthorityURI: URI of Attribute Authority to make  
     176    requests to.  Setting this ALSO creates an AttAuthorityClient instance  
     177    self._attributeAuthorityClnt.  - See attributeAuthorityURI property for 
     178    details. (property attribute) 
     179     
     180    @type attributeAuthority: ndg.security.server.AttAuthority.AttAuthority 
     181    @ivar attributeAuthority: Attribute Authority to make requests to.   
     182    attributeAuthorityURI takes precedence over this keyword i.e. if an 
     183    attributeAuthorityURI has been set, then calls are made to the AA web  
     184    service at this location rather to any self.attributeAuthority running  
     185    locally. (property attribute) 
     186     
     187    @type caCertFilePathList: string (for single file), list or tuple 
     188    @ivar caCertFilePathList: Certificate Authority's certificates - used 
     189    in validation of signed Attribute Certificates and WS-Security  
     190    signatures of incoming messages.  If not set here, it must 
     191    be input in call to getAttCert. (property attribute) 
     192             
     193    @type credentialRepository: instance of CredentialRepository derived  
     194    class 
     195    @ivar credentialRepository: Credential Repository instance.   (property  
     196    attribute).  If not set, defaults to NullCredentialRepository type - see  
     197    class below... 
     198 
     199     
     200    @type mapFromTrustedHosts: bool 
     201    @ivar mapFromTrustedHosts sets behaviour for getAttCert().  If 
     202    set True and authorisation fails with the given Attribute Authority,  
     203    attempt to get authorisation using Attribute Certificates issued by  
     204    other trusted AAs. (property attribute) 
     205     
     206    @type rtnExtAttCertList: bool 
     207    @ivar rtnExtAttCertList: behaviour for getAttCert().  If True, and  
     208    authorisation fails with the given Attribute Authority, return a list  
     209    of Attribute Certificates from other trusted AAs which could be used  
     210    to obtain a mapped Attribute Certificate on a subsequent authorisation 
     211    attempt. (property attribute) 
     212     
     213    @type attCertRefreshElapse: float / int 
     214    @ivar attCertRefreshElapse: used by getAttCert to determine  
     215    whether to replace an existing AC in the cache with a fresh one.  If  
     216    the existing one has less than attCertRefreshElapse time in seconds 
     217    left before expiry then replace it. (property attribute) 
     218     
     219    @type wssCfgKw: dict 
     220    @ivar wssCfgKw: keywords to WS-Security SignatureHandler 
     221    used for Credential Wallet's SOAP interface to Attribute Authorities. 
     222    (property attribute) 
     223             
     224    @type _credentialRepository: ndg.security.common.CredentialRepository or  
    164225    derivative 
    165     @ivar __credentialRepository: reference to Credential Repository object.   
     226    @ivar _credentialRepository: reference to Credential Repository object.   
    166227    An optional non-volatile cache for storage of wallet info which can be 
    167     later restored  
     228    later restored. (Don't reference directly - see equivalent property  
     229    attribute) 
    168230 
    169231    @type _mapFromTrustedHosts: bool 
    170232    @ivar _mapFromTrustedHosts: if true, allow a mapped attribute certificate 
    171233    to obtained in a getAttCert call.  Set false to prevent mappings. 
     234    (Don't reference directly - see equivalent property attribute) 
    172235 
    173236    @type _rtnExtAttCertList: bool 
    174237    @ivar _rtnExtAttCertList: if true, return a list of external attribute  
    175     certificates from getAttCert call 
     238    certificates from getAttCert call. (Don't reference directly - see  
     239    equivalent property attribute) 
    176240 
    177241    @type __dn: ndg.security.common.X509.X500DN 
    178     @ivar __dn: distinguished name from user certificate 
     242    @ivar __dn: distinguished name from user certificate.  (Don't reference  
     243    directly - see equivalent property attribute) 
    179244 
    180245    @type _credentials: dict        
    181246    @ivar _credentials: Credentials are stored as a dictionary one element per 
    182     attribute certificate held and indexed by certificate issuer name 
     247    attribute certificate held and indexed by certificate issuer name. 
     248    (Don't reference directly - see equivalent property attribute) 
    183249 
    184250    @type _caCertFilePathList: basestring, list, tuple or None 
    185251    @ivar _caCertFilePathList: file path(s) to CA certificates.  If None 
    186     then the input is quietly ignored.  See caCertFilePathList property 
     252    then the input is quietly ignored.  See caCertFilePathList property. 
     253    (Don't reference directly - see equivalent property attribute) 
    187254 
    188255    @type _userX509Cert: ndg.security.common.X509.X509Cert 
    189     @ivar _userX509Cert: X.509 user certificate instance 
     256    @ivar _userX509Cert: X.509 user certificate instance. 
     257    (Don't reference directly - see equivalent property attribute) 
    190258 
    191259    @type _issuingX509Cert: ndg.security.common.X509.X509Cert 
    192     @ivar _issuingX509Cert: X.509 user certificate instance 
     260    @ivar _issuingX509Cert: X.509 user certificate instance. 
     261    (Don't reference directly - see equivalent property attribute) 
    193262  
    194263    @type _userPriKey: M2Crypto.RSA.RSA 
    195     @ivar _userPriKey: Private key used to sign outbound message 
     264    @ivar _userPriKey: Private key used to sign outbound message. 
     265    (Don't reference directly - see equivalent property attribute) 
    196266    """ 
    197267 
    198268    __metaclass__ = _MetaCredWallet 
    199269 
    200     _defParam = dict(username=None, 
    201                      userCreds=None, 
     270    _defParam = dict(userId=None, 
     271                     userX509Cert=None, 
     272                     userPriKey=None, 
     273                     issuingX509Cert=None, 
    202274                     caCertFilePathList=None, 
     275                     sslCACertFilePathList=None, 
    203276                     attributeAuthorityURI=None, 
    204277                     attributeAuthority=None, 
     
    207280                     rtnExtAttCertList=True, 
    208281                     attCertRefreshElapse=7200, 
    209                      wssSignatureHandlerKw={}) 
     282                     wssCfgFilePath=None, 
     283                     wssCfgSection='DEFAULT', 
     284                     wssCfgKw={}) 
    210285     
    211286    __slots__ = _defParam.keys() + [ 
    212         'accessDenied', 
    213287        '_userX509Cert', 
    214288        '_userPriKey', 
     
    217291        '_attributeAuthority', 
    218292        '_caCertFilePathList', 
    219          
     293        '_sslCACertFilePathList', 
     294        '_credentialRepository', 
     295        '_attCertRefreshElapse', 
     296        '_cfg', 
     297        '_credentials', 
     298        '_dn' 
    220299    ] 
    221300     
    222     def __init__(self, cfg=None, cfgFileSection='DEFAULT', cfgPrefix='', **kw): 
     301    def __init__(self,  
     302                 cfg=None,  
     303                 cfgFileSection='DEFAULT',  
     304                 cfgPrefix='',  
     305                 wssCfgKw={}, 
     306                 **kw): 
    223307        """Create store of user credentials for their current session 
    224308 
    225         @type userX509Cert: string / M2Crypto.X509.X509 / 
    226         ndg.security.common.X509.X509Cert 
    227         @param userX509Cert: X.509 certificate for user 
    228          
    229         @type userPriKey: string / M2Crypto.RSA.RSA  
    230         @param userPriKey: private key for user cert 
    231          
    232         @type issuingX509Cert: string / ndg.security.common.X509.X509Cert 
    233         @param issuingX509Cert: X.509 cert for issuer of user cert 
    234          
    235         @type attributeAuthorityURI: string 
    236         @param attributeAuthorityURI: URI of Attribute Authority to make  
    237         requests to.  Setting this ALSO creates an AttAuthorityClient instance  
    238         self._attributeAuthorityClnt.  - See attributeAuthorityURI property for 
    239         details. 
    240          
    241         @type attributeAuthority: ndg.security.server.AttAuthority.AttAuthority 
    242         @param attributeAuthority: Attribute Authority to make requests to.   
    243         attributeAuthorityURI takes precedence over this keyword i.e. if an 
    244         attributeAuthorityURI has been set, then calls are made to the AA web  
    245         service at this location rather to any self.attributeAuthority running  
    246         locally. 
    247          
    248         @type caCertFilePathList: string (for single file), list or tuple 
    249         @param caCertFilePathList: Certificate Authority's certificates - used 
    250         in validation of signed Attribute Certificates and WS-Security  
    251         signatures of incoming messages.  If not set here, it must 
    252         be input in call to getAttCert. 
    253                  
    254         @type credentialRepository: instance of CredentialRepository derived  
    255         class 
    256         @param credentialRepository: Credential Repository instance.  If not  
    257         set, defaults to NullCredentialRepository type - see class below... 
    258          
    259         @type mapFromTrustedHosts: bool 
    260         @param mapFromTrustedHosts sets behaviour for getAttCert().  If 
    261         set True and authorisation fails with the given Attribute Authority,  
    262         attempt to get authorisation using Attribute Certificates issued by  
    263         other trusted AAs. 
    264          
    265         @type rtnExtAttCertList: bool 
    266         @param rtnExtAttCertList: behaviour for getAttCert().  If True, and  
    267         authorisation fails with the given Attribute Authority, return a list  
    268         of Attribute Certificates from other trusted AAs which could be used  
    269         to obtain a mapped Attribute Certificate on a subsequent authorisation 
    270         attempt 
    271          
    272         @type attCertRefreshElapse: float / int 
    273         @param attCertRefreshElapse: used by getAttCert to determine  
    274         whether to replace an existing AC in the cache with a fresh one.  If  
    275         the existing one has less than attCertRefreshElapse time in seconds 
    276         left before expiry then replace it. 
    277          
    278         @type wssSignatureHandlerKw: dict 
    279         @param wssSignatureHandlerKw: keywords to WS-Security SignatureHandler 
    280         used for Credential Wallet's SOAP interface to Attribute Authorities 
    281         """ 
     309        @type cfg: string / ConfigParser object 
     310        @param cfg: if a string type, this is interpreted as the file path to 
     311        a configuration file, otherwise it will be treated as a ConfigParser  
     312        object  
     313        @type cfgSection: string 
     314        @param cfgSection: sets the section name to retrieve config params  
     315        from 
     316        @type cfgPrefix: basestring 
     317        @param cfgPrefix: apply a prefix to all CredWallet config params so  
     318        that if placed in a file with other parameters they can be  
     319        distinguished 
     320        @type cfgKw: dict 
     321        @param cfgKw: set parameters as key value pairs.""" 
    282322 
    283323        log.debug("Calling CredWallet.__init__ ...") 
    284324 
    285325        # Initialise attributes 
    286         param = {}.fromkeys(CredWallet.__slots__) 
    287         param.update(CredWallet._defParam) 
    288         for k, v in param.items(): 
     326        attr = {}.fromkeys(CredWallet.__slots__) 
     327        attr.update(CredWallet._defParam) 
     328        for k, v in attr.items(): 
    289329            try: 
    290330                setattr(self, k, v) 
    291331            except AttributeError, e: 
     332                # FIXME: remove this test exception handling code  
    292333                pass 
    293334             
     
    297338 
    298339        # Update attributes from keywords passed 
    299         for k,v in kw: 
     340        for k,v in kw.items(): 
    300341            setattr(self, k, v) 
    301 #         
    302 #        self.username = username 
    303 #         
    304 #        self.attCertRefreshElapse = attCertRefreshElapse 
    305 #         
    306 #        # Nb. these attribute are defined as properties 
    307 #        if userCreds is not None: 
    308 #            self.userX509Cert = userCreds[0] 
    309 #            self.userPriKey = userCreds[1] 
    310 #            self.issuingX509Cert = userCreds[2] 
    311 #         
    312 #        self.attributeAuthorityURI = attributeAuthorityURI 
    313 #        self.caCertFilePathList = caCertFilePathList 
    314 #                 
    315 #        self.__credentialRepository = credentialRepository or \ 
    316 #                                                    NullCredentialRepository() 
    317 #         
    318 #        # Set behaviour for authorisation requests 
    319 #        self._mapFromTrustedHosts = mapFromTrustedHosts 
    320 #        self._rtnExtAttCertList = rtnExtAttCertList 
    321 #         
    322 #        self.wssSignatureHandlerKw = wssSignatureHandlerKw 
    323 #         
    324 #        # Get the distinguished name from the user certificate 
    325 #        self.__dn = self._userX509Cert.dn.serialise() 
    326 #         
    327 #         
    328 #        # Credentials are stored as a dictionary one element per attribute 
    329 #        # certicate held and indexed by certificate issuer name 
    330 #        self._credentials = {} 
    331 # 
    332 # 
    333 #        # Make a connection to the Credentials Repository 
    334 #        if self.__credentialRepository: 
    335 #            log.info('Checking CredentialRepository for credentials for user ' 
    336 #                     '"%s"' % self.__dn) 
    337 #             
    338 #            if not isinstance(self.__credentialRepository,  
    339 #                              CredentialRepository): 
    340 #                raise CredWalletError("Input Credentials Repository instance " 
    341 #                                      "must be of a class derived from " 
    342 #                                      "\"CredentialRepository\"") 
    343 #     
    344 #        
    345 #            # Check for valid attribute certificates for the user 
    346 #            try: 
    347 #                self.__credentialRepository.auditCredentials(dn=self.__dn) 
    348 #                userCred=self.__credentialRepository.getCredentials(self.__dn) 
    349 #     
    350 #            except Exception, e: 
    351 #                raise CredWalletError("Error updating wallet with credentials " 
    352 #                                      "from repository: " + str(e)) 
    353 #     
    354 #     
    355 #            # Update wallet with attribute certificates stored in the  
    356 #            # repository.  Store ID and certificate instantiated as an AttCert 
    357 #            # type 
    358 #            try: 
    359 #                for cred in userCred:  
    360 #                    attCert = AttCertParse(cred.attCert) 
    361 #                    issuerName = attCert['issuerName'] 
    362 #                     
    363 #                    self._credentials[issuerName] = \ 
    364 #                                             {'id':cred.id, 'attCert':attCert}     
    365 #            except Exception, e: 
    366 #                try: 
    367 #                    raise CredWalletError("Error parsing Attribute Certificate" 
    368 #                                          " ID '%s' retrieved from the "  
    369 #                                          "Credentials Repository: %s" %  
    370 #                                          (cred.id, e))             
    371 #                except: 
    372 #                    raise CredWalletError("Error parsing Attribute " 
    373 #                                          "Certificate retrieved from the " 
    374 #                                          "Credentials Repository: %s:"%str(e)) 
    375 #             
    376 #            # Filter out expired or otherwise invalid certificates 
    377 #            self.audit() 
     342 
     343        # Get the distinguished name from the user certificate 
     344        if self._userX509Cert: 
     345            self._dn = self._userX509Cert.dn.serialise() 
     346         
     347         
     348        # Credentials are stored as a dictionary one element per attribute 
     349        # certicate held and indexed by certificate issuer name 
     350        self._credentials = {} 
     351 
     352 
     353        # Make a connection to the Credentials Repository 
     354        if self._credentialRepository is None: 
     355            log.info('Applying default CredentialRepository %r for user ' 
     356                     '"%s"' % (NullCredentialRepository, self.userId)) 
     357            self._credentialRepository = NullCredentialRepository() 
     358        else: 
     359            log.info('Checking CredentialRepository for credentials for user ' 
     360                     '"%s"' % self.userId) 
     361             
     362            if not isinstance(self._credentialRepository,CredentialRepository): 
     363                raise CredWalletError("Input Credential Repository instance " 
     364                                      "must be of a class derived from " 
     365                                      "\"CredentialRepository\"") 
     366     
     367        
     368            # Check for valid attribute certificates for the user 
     369            try: 
     370                self._credentialRepository.auditCredentials(self.userId) 
     371                userCred = self._credentialRepository.getCredentials(self.userId) 
     372     
     373            except Exception, e: 
     374                log.error("Error updating wallet with credentials from " 
     375                          "repository: %s" % e) 
     376                raise 
     377     
     378     
     379            # Update wallet with attribute certificates stored in the  
     380            # repository.  Store ID and certificate instantiated as an AttCert 
     381            # type 
     382            try: 
     383                for cred in userCred:  
     384                    attCert = AttCertParse(cred.attCert) 
     385                    issuerName = attCert['issuerName'] 
     386                     
     387                    self._credentials[issuerName] = {'id':cred.id,  
     388                                                     'attCert':attCert}     
     389            except Exception, e: 
     390                try: 
     391                    raise CredWalletError("Error parsing Attribute Certificate" 
     392                                          " ID '%s' retrieved from the "  
     393                                          "Credentials Repository: %s" %  
     394                                          (cred.id, e))             
     395                except: 
     396                    raise CredWalletError("Error parsing Attribute " 
     397                                          "Certificate retrieved from the " 
     398                                          "Credentials Repository: %s:" % e) 
     399             
     400            # Filter out expired or otherwise invalid certificates 
     401            self.audit() 
    378402 
    379403    def parseConfig(self, cfg, prefix='', section='DEFAULT'): 
     
    381405         
    382406        if isinstance(cfg, basestring): 
    383             cfgFilePath = cfg 
    384             cfgObj = None 
     407            cfgFilePath = os.path.expandvars(cfg) 
     408            self._cfg = None 
    385409        else: 
    386410            cfgFilePath = None 
    387             cfgObj = cfg 
     411            self._cfg = cfg 
    388412             
    389413        # Configuration file properties are held together in a dictionary 
    390         prop = readAndValidateProperties(cfgFilePath, 
    391                                          cfg=cfgObj, 
    392                                          validKeys=CredWallet._defParam, 
    393                                          prefix=prefix, 
    394                                          sections=(section,)) 
    395          
    396         # Copy dict into object attributes 
    397         for key, val in prop: 
     414        readAndValidate = INIPropertyFileWithValidation() 
     415        prop = readAndValidate(cfgFilePath, 
     416                               cfg=self._cfg, 
     417                               validKeys=CredWallet._defParam, 
     418                               prefix=prefix, 
     419                               sections=(section,)) 
     420         
     421        # Keep a copy of config for use by WS-Security SignatureHandler parser 
     422        if self._cfg is None: 
     423            self._cfg = readAndValidate.cfg 
     424         
     425        # Copy prop dict into object attributes - __slots__ definition and  
     426        # property methods will ensure only the correct attributes are set 
     427        for key, val in prop.items(): 
    398428            setattr(self, key, val) 
    399429 
    400          
     430 
     431    def _getAttCertRefreshElapse(self): 
     432        return self._attCertRefreshElapse 
     433     
     434    def _setAttCertRefreshElapse(self, val): 
     435        if isinstance(val, (float, int)): 
     436            self._attCertRefreshElapse = val 
     437             
     438        elif isinstance(val, basestring): 
     439            self._attCertRefreshElapse = float(val) 
     440        else: 
     441            raise AttributeError("Expecting int, float or string type input " 
     442                                 "for attCertRefreshElapse") 
     443             
     444    attCertRefreshElapse = property(fget=_getAttCertRefreshElapse,  
     445                                    fset=_setAttCertRefreshElapse, 
     446                                    doc="If an existing one has AC less than " 
     447                                        "attCertRefreshElapse time in seconds " 
     448                                        "left before expiry then replace it") 
     449     
    401450    def _setX509Cert(self, cert): 
    402451        """filter and convert input cert to signing verifying cert set  
     
    457506                               doc="X.509 user certificate instance") 
    458507      
    459   
     508 
     509    def _getUserPriKey(self): 
     510        "Get method for user private key" 
     511        return self._userPriKey 
     512     
    460513    def _setUserPriKey(self, userPriKey): 
    461         """Set method for client private key 
     514        """Set method for user private key 
    462515         
    463516        Nb. if input is a string, userPriKeyPwd will need to be set if 
     
    467520        @param userPriKey: private key used to sign message""" 
    468521         
    469         if isinstance(userPriKey, basestring): 
     522        if userPriKey is None: 
     523            log.warning("Setting user private key to None") 
     524            self._userPriKey = None 
     525        elif isinstance(userPriKey, basestring): 
    470526            self._userPriKey = RSA.load_key_string(userPriKey, 
    471527                                             callback=lambda *ar, **kw: None) 
     
    474530        else: 
    475531            raise AttributeError("user private key must be a valid " 
    476                                   "M2Crypto.RSA.RSA type or a string") 
     532                                 "M2Crypto.RSA.RSA type or a string") 
    477533                 
    478     userPriKey = property(fset=_setUserPriKey, 
    479                           doc="Private key used to sign outbound message") 
     534    userPriKey = property(fget=_getUserPriKey, 
     535                          fset=_setUserPriKey, 
     536                          doc="User private key if set, used to sign outbound " 
     537                              "messages to Attribute authority") 
    480538 
    481539    
     
    492550 
    493551 
    494     def _getCAcertFilePathList(self): 
     552    def _getCACertFilePathList(self): 
    495553        """Get CA cert or certs used to validate AC signatures and signatures 
    496554        of peer SOAP messages. 
     
    500558        return self._caCertFilePathList 
    501559     
    502     def _setCAcertFilePathList(self, caCertFilePathList): 
     560    def _setCACertFilePathList(self, caCertFilePathList): 
    503561        """Set CA cert or certs to validate AC signatures, signatures 
    504562        of Attribute Authority SOAP responses and SSL connections where  
     
    522580                                  "valid string")       
    523581         
    524     caCertFilePathList = property(fget=_getCAcertFilePathList, 
    525                                   fset=_setCAcertFilePathList, 
     582    caCertFilePathList = property(fget=_getCACertFilePathList, 
     583                                  fset=_setCACertFilePathList, 
    526584                                  doc="CA Certificates - used for " 
    527585                                      "verification of AC and SOAP message " 
    528                                       "signatures and SSL connections") 
    529  
     586                                      "signatures") 
     587 
     588    def _getSSLCACertFilePathList(self): 
     589        """Get CA cert or certs used to validate AC signatures and signatures 
     590        of peer SOAP messages. 
     591         
     592        @rtype sslCACertFilePathList: basestring, list or tuple 
     593        @return sslCACertFilePathList: file path(s) to CA certificates.""" 
     594        return self._sslCACertFilePathList 
     595     
     596    def _setSSLCACertFilePathList(self, sslCACertFilePathList): 
     597        """Set CA cert or certs to validate AC signatures, signatures 
     598        of Attribute Authority SOAP responses and SSL connections where  
     599        AA SOAP service is run over SSL. 
     600         
     601        @type sslCACertFilePathList: basestring, list, tuple or None 
     602        @param sslCACertFilePathList: file path(s) to CA certificates.  If None 
     603        then the input is quietly ignored.""" 
     604         
     605        if isinstance(sslCACertFilePathList, basestring): 
     606           self._sslCACertFilePathList = [sslCACertFilePathList] 
     607            
     608        elif isinstance(sslCACertFilePathList, list): 
     609           self._sslCACertFilePathList = sslCACertFilePathList 
     610            
     611        elif isinstance(sslCACertFilePathList, tuple): 
     612           self._sslCACertFilePathList = list(sslCACertFilePathList) 
     613 
     614        elif sslCACertFilePathList is not None: 
     615            raise CredWalletError("Input CA Certificate file path is not a " 
     616                                  "valid string")       
     617         
     618    sslCACertFilePathList = property(fget=_getSSLCACertFilePathList, 
     619                                  fset=_setSSLCACertFilePathList, 
     620                                  doc="CA Certificates - used for " 
     621                                      "verification of peer certs in SSL " 
     622                                      "connections") 
    530623 
    531624    def _createAttributeAuthorityClnt(self, attributeAuthorityURI): 
     
    540633        log.debug('CredWallet._createAttributeAuthorityClnt for service: "%s"'% 
    541634                  attributeAuthorityURI) 
    542          
    543         # Check for WS-Security settings made in self.wssSignatureHandlerKw  
    544         # dict. If not set, then pick up defaults from wallet credentials 
    545         if 'signingCert' and 'signingCertFilePath' and 'signingCertChain' \ 
    546            not in self.wssSignatureHandlerKw: 
    547              
    548             # Use user certificate for signing messages 
    549             if self._issuingX509Cert is not None: 
     635 
     636        attributeAuthorityClnt = AttAuthorityClient(uri=attributeAuthorityURI, 
     637                                sslCACertFilePathList=self._sslCACertFilePathList, 
     638                                cfg=self.wssCfgFilePath or self._cfg, 
     639                                cfgFileSection=self.wssCfgSection, 
     640                                **(self.wssCfgKw or {})) 
     641         
     642        # If a user certificate is set, use this to sign messages instead of 
     643        # the default settings in the WS-Security config.   
     644        if attributeAuthorityClnt.signatureHandler is not None and \ 
     645           self.userPriKey is not None: 
     646            if self.issuingX509Cert is not None: 
     647                # Pass a chain of certificates -  
    550648                # Initialise WS-Security signature handling to pass  
    551649                # BinarySecurityToken containing user cert and cert for user  
    552                 # cert  issuer  
    553                 self.wssSignatureHandlerKw['reqBinSecTokValType'] = \ 
     650                # cert issuer  
     651                attributeAuthorityClnt.signatureHandler.reqBinSecTokValType = \ 
    554652                            SignatureHandler.binSecTokValType["X509PKIPathv1"] 
    555                 self.wssSignatureHandlerKw['signingCertChain'] = \ 
    556                                     (self._issuingX509Cert, self._userX509Cert) 
    557                  
    558             else: 
     653                attributeAuthorityClnt.signatureHandler.signingCertChain = \ 
     654                                    (self._issuingX509Cert, self._userX509Cert)                 
     655 
     656                attributeAuthorityClnt.signatureHandler.signingPriKey = \ 
     657                                                            self.userPriKey 
     658            elif self.userX509Cert is not None: 
    559659                # Pass user cert only - no need to pass a cert chain.   
    560660                # This type of token is more likely to be supported by the  
    561661                # various WS-Security toolkits 
    562                 self.wssSignatureHandlerKw['reqBinSecTokValType'] = \ 
     662                attributeAuthorityClnt.signatureHandler.reqBinSecTokValType = \ 
    563663                                    SignatureHandler.binSecTokValType["X509v3"] 
    564                 self.wssSignatureHandlerKw['signingCert'] = self._userX509Cert 
    565  
    566             self.wssSignatureHandlerKw['signingPriKey'] = self._userPriKey 
    567  
    568         if 'caCertFilePathList' not in self.wssSignatureHandlerKw: 
    569             self.wssSignatureHandlerKw['caCertFilePathList'] = \ 
    570                                                     self._caCertFilePathList 
    571  
    572         attributeAuthorityClnt = AttAuthorityClient(uri=attributeAuthorityURI, 
    573                             sslCACertFilePathList=self._caCertFilePathList, 
    574                             **self.wssSignatureHandlerKw) 
     664                attributeAuthorityClnt.signatureHandler.signingCert = \ 
     665                                                            self._userX509Cert 
     666 
     667                attributeAuthorityClnt.signatureHandler.signingPriKey = \ 
     668                                                            self.userPriKey 
     669 
    575670        return attributeAuthorityClnt 
    576671 
     
    703798            # authorisation credentials.  This allows credentials for previous 
    704799            # sessions to be re-instated 
    705             if self.__credentialRepository and bUpdateCredentialRepository: 
     800            if self._credentialRepository and bUpdateCredentialRepository: 
    706801                self.updateCredentialRepository() 
    707802 
     
    738833        log.debug("CredWallet.updateCredentialRepository ...") 
    739834         
    740         if not self.__credentialRepository: 
     835        if not self._credentialRepository: 
    741836            raise CredWalletError("No Credential Repository has been created " 
    742837                                  "for this wallet") 
     
    750845                       if i['id'] == -1] 
    751846 
    752         self.__credentialRepository.addCredentials(self.__dn, attCertList) 
     847        self._credentialRepository.addCredentials(self.userId, attCertList) 
    753848 
    754849 
     
    12551350 
    12561351 
    1257     def addUser(self, username, dn): 
     1352    def addUser(self, userId, dn=None): 
    12581353        """A new user to Credentials Repository 
    12591354         
    1260         @type username: string 
    1261         @param username: username for new user 
     1355        @type userId: string 
     1356        @param userId: userId for new user 
    12621357        @type dn: string 
    1263         @param dn: users Distinguished Name""" 
     1358        @param dn: users Distinguished Name (optional)""" 
    12641359        raise NotImplementedError( 
    12651360            self.addUser.__doc__.replace('\n       ','')) 
    12661361 
    12671362                             
    1268     def auditCredentials(self, **attCertValidKeys): 
     1363    def auditCredentials(self, userId=None, **attCertValidKeys): 
    12691364        """Check the attribute certificates held in the repository and delete 
    12701365        any that have expired 
    12711366 
     1367        @type userId: basestring/list or tuple 
     1368        @param userId: audit credentials for the input user ID or list of IDs 
    12721369        @type attCertValidKeys: dict 
    12731370        @param **attCertValidKeys: keywords which set how to check the  
     
    12781375 
    12791376 
    1280     def getCredentials(self, dn): 
     1377    def getCredentials(self, userId): 
    12811378        """Get the list of credentials for a given users DN 
    12821379         
    1283         @type dn: string 
    1284         @param dn: users distinguished name 
     1380        @type userId: string 
     1381        @param userId: users userId, name or X.509 cert. distinguished name 
    12851382        @rtype: list  
    12861383        @return: list of Attribute Certificates""" 
     
    12891386 
    12901387         
    1291     def addCredentials(self, dn, attCertList): 
     1388    def addCredentials(self, userId, attCertList): 
    12921389        """Add new attribute certificates for a user.  The user must have 
    12931390        been previously registered in the repository 
    12941391 
    1295         @type dn: string 
    1296         @param dn: users Distinguished name 
     1392        @type userId: string 
     1393        @param userId: users userId, name or X.509 cert. distinguished name 
    12971394        @type attCertList: list 
    12981395        @param attCertList: list of attribute certificates""" 
     
    13091406        pass 
    13101407 
    1311     def addUser(self, userName, dn): 
     1408    def addUser(self, userId): 
    13121409        pass 
    13131410                             
     
    13151412        pass 
    13161413 
    1317     def getCredentials(self, dn): 
     1414    def getCredentials(self, userId): 
    13181415        return [] 
    13191416        
    1320     def addCredentials(self, dn, attCertList): 
     1417    def addCredentials(self, userId, attCertList): 
    13211418        pass 
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/authz/pdp/proftp.py

    r4067 r4285  
    8282        call to Session Manager 
    8383         
    84         @type uri: string 
    85         @param uri: URI corresponding to data granule ID 
    86          
    87         @type securityElement: ElementTree Element 
    88         @param securityElement: directory containing a .ftpaccess file 
     84        @type cfg: string / ConfigParser object 
     85        @param cfg: if a string type, this is interpreted as the file path to 
     86        a configuration file, otherwise it will be treated as a ConfigParser  
     87        object  
     88        @type cfgSection: string 
     89        @param cfgSection: sets the section name to retrieve config params  
     90        from 
     91        @type cfgKw: dict 
     92        @param cfgKw: set parameters as key value pairs. 
    8993        """ 
    9094         
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/ConfigFileParsers.py

    r4279 r4285  
    4141class ConfigFileParseError(Exception): 
    4242    """Raise for errors in configuration file formatting""" 
    43      
     43 
    4444def readAndValidateProperties(propFilePath, validKeys={}, **iniPropertyFileKw): 
    4545    """ 
     
    5656    - if all info should be read, this keyword should be left to its default  
    5757    value 
    58     - NB, this dict will also ensure list data is read in correctely 
     58    - NB, this dict will also ensure list data is read in correctly 
    5959    @type validKeys: dict 
    6060    @raise ValueError: if a key is read in from the file that is not included  
    6161    in the specified validKeys dict 
    6262    """ 
    63     log.debug("Reading properties from %s" %propFilePath) 
     63    log.debug("Reading properties from %s" % propFilePath) 
    6464    properties = {} 
    6565    if propFilePath.lower().endswith('.xml'): 
     
    109109         
    110110 
    111 def readINIPropertyFile(propFilePath, validKeys, cfg=None, sections=None, 
    112                         wsseSection='WS-Security', prefix=''): 
    113     """ 
    114     Read 'ini' type property file - i.e. a flat text file with key/value 
    115     data separated into sections 
    116  
    117     @param propFilePath: file path to properties file - either in xml or ini  
    118     format 
    119     @type propFilePath: string 
    120     @param validKeys: a dictionary of valid values to be read from the file 
    121     - if values are encountered that are not in this list, an exception will be 
    122     thrown 
    123     - if all info should be read, set this param to 'None' 
    124     @type validKeys: dict 
    125     @type sections: basestring 
    126     @param sections: sections to be read from - defaults to all sections in the 
    127     file 
    128     @type wsseSection: basestring 
    129     @param wsseSection: section to read WS-Security settings from as specified  
    130     by WSSecurityConfig class.  WS-Security section doesn't need to be  
    131     present and can be ignored. 
    132     @rtype: dict 
    133     @return: dict with the loaded properties in 
    134     @raise ValueError: if a key is read in from the file that is not included  
    135     in the specified validKeys dict 
    136     """ 
    137     log.debug("File is not marked as XML - treating as flat 'ini' format file") 
    138      
    139  
    140     if cfg is None: 
    141         cfg = CaseSensitiveConfigParser() 
    142         cfg.read(propFilePath) 
    143         if not os.path.isfile(propFilePath): 
    144             raise ValueError('Error parsing properties file "%s": No such ' 
    145                              'file' % propFilePath) 
    146         
    147     properties = {} 
    148      
    149     if sections is None: 
    150         # NB, add 'DEFAULT' section since this isn't returned by the  
    151         # 'sections()' 
    152         sections = cfg.sections() 
    153         sections.append('DEFAULT') 
    154      
    155     # parse data from the specified sections of the config file 
    156     for section in sections: 
    157         if section == 'DEFAULT': 
    158             properties.update(_parseConfig(cfg, validKeys, section=section, 
    159                                            prefix=prefix)) 
     111class INIPropertyFile(object): 
     112    '''INI Property file reading class 
     113     
     114    __call__ method enables a standalone read function''' 
     115     
     116    def __call__(self, *arg, **kw): 
     117        '''This method enables a standalone read function - see  
     118        readINIPropertyFile in this module''' 
     119        return self.read(*arg, **kw) 
     120         
     121    def read(self, propFilePath, validKeys, cfg=None, sections=None, 
     122             wsseSection='WS-Security', prefix=''): 
     123        """ 
     124        Read 'ini' type property file - i.e. a flat text file with key/value 
     125        data separated into sections 
     126     
     127        @param propFilePath: file path to properties file - either in xml or  
     128        ini format 
     129        @type propFilePath: string 
     130        @param validKeys: a dictionary of valid values to be read from the file 
     131        - if values are encountered that are not in this list, an exception  
     132        will be thrown 
     133        - if all info should be read, set this param to 'None' 
     134        @type validKeys: dict 
     135        @type sections: basestring 
     136        @param sections: sections to be read from - defaults to all sections in the 
     137        file 
     138        @type wsseSection: basestring 
     139        @param wsseSection: section to read WS-Security settings from as  
     140        specified by WSSecurityConfig class.  WS-Security section doesn't need  
     141        to be present and can be ignored. 
     142        @rtype: dict 
     143        @return: dict with the loaded properties in 
     144        @raise ValueError: if a key is read in from the file that is not  
     145        included in the specified validKeys dict 
     146        """ 
     147        log.debug("File is not marked as XML - treating as flat 'ini' format " 
     148                  "file") 
     149         
     150        # Keep a record of property file path setting 
     151        self.propFilePath = propFilePath 
     152             
     153        if cfg is None: 
     154            self.cfg = CaseSensitiveConfigParser() 
     155            self.cfg.read(propFilePath) 
     156            if not os.path.isfile(propFilePath): 
     157                raise ValueError('Error parsing properties file "%s": No such ' 
     158                                 'file' % propFilePath) 
     159            
     160        properties = {} 
     161         
     162        if sections is None: 
     163            # NB, add 'DEFAULT' section since this isn't returned by the  
     164            # 'sections()' 
     165            sections = self.cfg.sections() 
     166            sections.append('DEFAULT') 
     167         
     168        # parse data from the specified sections of the config file 
     169        for section in sections: 
     170            if section == 'DEFAULT': 
     171                properties.update(_parseConfig(self.cfg,  
     172                                               validKeys,  
     173                                               section=section, 
     174                                               prefix=prefix)) 
     175            else: 
     176                if section == wsseSection: 
     177                    keys = WSSecurityConfig.defParam 
     178                else: 
     179                    keys = validKeys 
     180                     
     181                properties[section] = _parseConfig(self.cfg,  
     182                                                   keys,  
     183                                                   section=section) 
     184     
     185        log.debug("Finished reading from INI properties file") 
     186        return properties 
     187     
     188# Enable read INI of file as a one shot call 
     189readINIPropertyFile = INIPropertyFile()    
     190 
     191 
     192class INIPropertyFileWithValidation(INIPropertyFile): 
     193    '''Extension of INI Property file reading class to make a callable that 
     194    validates as well as reads in the properties.  Also see  
     195    readAndValidateINIPropertyFile in this module''' 
     196     
     197    def readAndValidate(self, propFilePath, validKeys, **kw): 
     198        prop = super(INIPropertyFileWithValidation,self).__call__(propFilePath, 
     199                                                                  validKeys,  
     200                                                                  **kw) 
     201         
     202        # Pass wsseSection but respect validateProperties default value 
     203        wsseSection = kw.get('wssSection') 
     204        if wsseSection is not None: 
     205            validatePropKw = {'wsseSection': wsseSection} 
    160206        else: 
    161             if section == wsseSection: 
    162                 keys = WSSecurityConfig.defParam 
    163             else: 
    164                 keys = validKeys 
    165                  
    166             properties[section] = _parseConfig(cfg, keys, section=section) 
    167  
    168     log.debug("Finished reading from INI properties file") 
    169     return properties 
    170      
     207            validatePropKw = {} 
     208             
     209        validateProperties(prop, validKeys, **validatePropKw) 
     210        return prop 
     211     
     212    __call__ = readAndValidate 
     213     
     214# Enable read and validation of INI file as a one shot call 
     215readAndValidateINIPropertyFile = INIPropertyFileWithValidation() 
     216 
    171217 
    172218def _parseConfig(cfg, validKeys, section='DEFAULT', prefix=''): 
     
    369415            validateProperties(properties[key], WSSecurityConfig.defParam) 
    370416             
    371         elif isinstance(validKeys[key], dict): 
     417        elif validKeys[key] and isinstance(validKeys[key], dict): 
    372418            validateProperties(properties[key], validKeys[key]) 
    373419                 
     
    381427        raise ValueError(errorMessage) 
    382428 
    383 nonDefaultProperty = lambda prop: prop == NotImplemented or \ 
    384                                     prop == [NotImplemented] 
     429nonDefaultProperty = lambda prop:prop==NotImplemented or prop==[NotImplemented] 
    385430 
    386431def _expandEnvironmentVariables(properties): 
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/BaseSignatureHandler.py

    r4233 r4285  
    1 """ Base class for the WS-Security digital signature handlers - to allow sharing of common code 
     1""" Base class for the WS-Security digital signature handlers - to allow  
     2sharing of common code 
    23 
    34NERC Data Grid Project 
     
    8081    '''Try different utility namespace for use with WebSphere''' 
    8182    #UTILITY = "http://schemas.xmlsoap.org/ws/2003/06/utility" 
    82     UTILITY = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" 
     83    UTILITY = \ 
     84"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" 
    8385 
    8486class OASIS(_OASIS): 
    8587    # wss4j 1.5.3 
    86     WSSE11 = "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" 
     88    WSSE11 = \ 
     89        "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd" 
    8790    # wss4j 1.5.1 
    8891    #WSSE11 = "http://docs.oasis-open.org/wss/2005/xx/oasis-2005xx-wss-wssecurity-secext-1.1.xsd" 
     
    148151 
    149152 
    150     #_________________________________________________________________________ 
    151153    def __init__(self, cfg=None, cfgFileSection='DEFAULT', 
    152154                 cfgClass=WSSecurityConfig, **kw): 
    153155        ''' 
    154         @keyword reqBinSecTokValType: set the ValueType for the BinarySecurityToken 
    155         added to the WSSE header for a signed message.  See  
     156        @keyword reqBinSecTokValType: set the ValueType for the  
     157        BinarySecurityToken added to the WSSE header for a signed message.  See  
    156158        __setReqBinSecTokValType method and binSecTokValType class variable 
    157159        for options.  binSecTokValType determines whether signingCert or 
     
    215217        @type addTimestamp: bool  
    216218         
    217         @keyword applySignatureConfirmation: for servers - set this flag to enable the signature value of a 
    218         request to be recorded and included with a SignatureConfirmation  
    219         element in the response. 
     219        @keyword applySignatureConfirmation: for servers - set this flag to  
     220        enable the signature value of a request to be recorded and included  
     221        with a SignatureConfirmation element in the response. 
    220222        @type : bool  
    221223         
     
    305307 
    306308                 
    307     #_________________________________________________________________________ 
    308309    def _setReqBinSecTokValType(self, value): 
    309310        """Set ValueType attribute for BinarySecurityToken used in a request 
     
    321322            self._reqBinSecTokValType = value 
    322323        else: 
    323             raise WSSecurityError, \ 
    324                 'Request BinarySecurityToken ValueType "%s" not recognised' %\ 
    325                 value 
    326              
    327     #_________________________________________________________________________ 
     324            raise WSSecurityError('Request BinarySecurityToken ValueType ' 
     325                                  '"%s" not recognised' % value) 
     326             
    328327    def _getReqBinSecTokValType(self): 
    329328        """ 
     
    341340         
    342341 
    343     #_________________________________________________________________________ 
    344342    def __checkC14nKw(self, kw): 
    345343        """Check keywords for canonicalization in signing process - generic 
     
    360358             not isinstance(kw['inclusive_namespaces'], list) and \ 
    361359             not isinstance(kw['inclusive_namespaces'], tuple): 
    362             raise AttributeError, \ 
    363                 'Expecting list or tuple of prefix names for "%s" keyword' % \ 
    364                 'inclusive_namespaces' 
     360            raise AttributeError('Expecting list or tuple of prefix names for ' 
     361                                 '"%s" keyword' % 'inclusive_namespaces') 
    365362         
    366363                 
    367     #_________________________________________________________________________ 
    368364    def _setRefC14nKw(self, kw): 
    369365        """Set keywords for canonicalization of reference elements in the  
     
    383379         
    384380                 
    385     #_________________________________________________________________________ 
    386381    def _setSignedInfoC14nKw(self, kw): 
    387382        """Set keywords for canonicalization of SignedInfo element in the  
     
    401396 
    402397 
    403     #_________________________________________________________________________ 
    404398    def __refC14nIsExcl(self): 
    405399        return isinstance(self._refC14nKw, dict) and \ 
     
    411405 
    412406      
    413     #_________________________________________________________________________ 
    414407    def __signedInfoC14nIsExcl(self): 
    415408        return isinstance(self._signedInfoC14nKw, dict) and \ 
     
    418411         
    419412    signedInfoC14nIsExcl = property(fget=__signedInfoC14nIsExcl, 
    420                                     doc="Return True/False c14n for SignedInfo element set to exclusive type") 
    421      
    422      
    423     #_________________________________________________________________________ 
     413                                    doc="Return True/False c14n for " 
     414                                    "SignedInfo element set to exclusive type") 
     415     
     416     
    424417    def __setCert(self, cert): 
    425418        """filter and convert input cert to signing verifying cert set  
     
    453446 
    454447     
    455     #_________________________________________________________________________ 
    456448    def _getVerifyingCert(self): 
    457449        '''Return X.509 cert object corresponding to cert used to verify the  
     
    469461 
    470462 
    471     #_________________________________________________________________________ 
    472463    def _setVerifyingCert(self, verifyingCert): 
    473464        "Set property method for X.509 cert. used to verify a signature" 
     
    482473 
    483474 
    484     #_________________________________________________________________________ 
    485475    def _setVerifyingCertFilePath(self, verifyingCertFilePath): 
    486476        "Set method for Service X.509 cert. file path property" 
     
    497487 
    498488     
    499     #_________________________________________________________________________ 
    500489    def _getSigningCert(self): 
    501490        '''Return X.509 cert object corresponding to cert used with 
     
    508497 
    509498 
    510     #_________________________________________________________________________ 
    511499    def _setSigningCert(self, signingCert): 
    512500        "Set property method for X.509 cert. to be included with signature" 
     
    521509 
    522510  
    523     #_________________________________________________________________________ 
    524511    def _setSigningCertFilePath(self, signingCertFilePath): 
    525512        "Set signature X.509 cert property method" 
     
    529516             
    530517        elif signingCertFilePath is not None: 
    531             raise AttributeError, \ 
    532                 "Signature X.509 cert. file path must be a valid string" 
     518            raise AttributeError( 
     519                "Signature X.509 cert. file path must be a valid string") 
    533520         
    534521        self._signingCertFilePath = signingCertFilePath 
     
    539526 
    540527     
    541     #_________________________________________________________________________ 
    542528    def _setSigningCertChain(self, signingCertChain): 
    543529        '''Signature set-up with "X509PKIPathv1" BinarySecurityToken  
     
    551537        private key used to sign the message.''' 
    552538         
    553         if not isinstance(signingCertChain, list) and \ 
    554            not isinstance(signingCertChain, tuple): 
    555             log.warning('Expecting a list or tuple for "signingCertChain" - ignoring value set, "%s"' %signingCertChain) 
     539        if not isinstance(signingCertChain, (list, tuple)): 
     540            log.warning('Expecting a list or tuple for "signingCertChain" - ' 
     541                        'ignoring value set, "%s"' % signingCertChain) 
    556542            self._signingCertChain = None 
    557543            return 
     
    570556 
    571557  
    572     #_________________________________________________________________________ 
    573558    def _setSigningPriKeyPwd(self, signingPriKeyPwd): 
    574559        "Set method for private key file password used to sign message" 
     
    591576 
    592577  
    593     #_________________________________________________________________________ 
    594578    def _setSigningPriKey(self, signingPriKey): 
    595579        """Set method for client private key 
     
    610594                    
    611595        else: 
    612             raise AttributeError, "Signing private key must be a valid " + \ 
    613                                   "M2Crypto.RSA.RSA type or a string" 
     596            raise AttributeError("Signing private key must be a valid " 
     597                                  "M2Crypto.RSA.RSA type or a string") 
    614598                 
    615599    def _getSigningPriKey(self): 
     
    621605 
    622606  
    623     #_________________________________________________________________________ 
    624607    def _setSigningPriKeyFilePath(self, signingPriKeyFilePath): 
    625608        """Set method for client private key file path 
     
    634617                                                        callback=pwdCallback)            
    635618            except Exception, e: 
    636                 raise AttributeError, \ 
    637                                 "Setting private key for signature: %s" % e 
     619                raise AttributeError("Setting private key for signature: %s"%e) 
    638620         
    639621        elif signingPriKeyFilePath is not None: 
    640             raise AttributeError, \ 
    641                         "Private key file path must be a valid string or None" 
     622            raise AttributeError("Private key file path must be a valid " 
     623                                 "string or None") 
    642624         
    643625        self.__signingPriKeyFilePath = signingPriKeyFilePath 
     
    653635           doc='Check for CA certificate set (X.509 Stack has been created)') 
    654636     
    655     #_________________________________________________________________________ 
    656637    def __appendCAX509Stack(self, caCertList): 
    657638        '''Store CA certificates in an X.509 Stack 
     
    667648 
    668649 
    669     #_________________________________________________________________________ 
    670650    def __setCAX509StackFromDir(self, caCertDir): 
    671651        '''Read CA certificates from directory and add them to the X.509 
     
    683663                          if reg.match(caFile)] 
    684664        except Exception, e: 
    685             raise WSSecurityError, \ 
    686                 'Loading CA certificate "%s" from CA directory: %s' % \ 
    687                                                         (caFile, str(e)) 
     665            raise WSSecurityError('Loading CA certificate "%s" from CA ' 
     666                                  'directory: %s' % (caFile, str(e))) 
    688667                     
    689668        # Add to stack 
     
    691670         
    692671    caCertDirPath = property(fset=__setCAX509StackFromDir, 
    693                       doc="Dir. containing CA cert.s used for verification") 
    694  
    695  
    696     #_________________________________________________________________________ 
     672                             doc="Dir. containing CA cert.s used for " 
     673                                "verification") 
     674 
     675 
    697676    def __setCAX509StackFromCertFileList(self, caCertFilePathList): 
    698677        '''Read CA certificates from file and add them to the X.509 
     
    703682        be used to verify certificate used to sign message''' 
    704683         
    705         if not isinstance(caCertFilePathList, list) and \ 
    706            not isinstance(caCertFilePathList, tuple): 
    707             raise WSSecurityError, \ 
    708                         'Expecting a list or tuple for "caCertFilePathList"' 
     684        if not isinstance(caCertFilePathList, (list, tuple)): 
     685            raise WSSecurityError('Expecting a list or tuple for ' 
     686                                  '"caCertFilePathList"') 
    709687 
    710688        # Mimic OpenSSL -CApath option which expects directory of CA files 
     
    714692                          for caFile in caCertFilePathList] 
    715693        except Exception, e: 
    716             raise WSSecurityError, \ 
    717                     'Loading CA certificate "%s" from file list: %s' % \ 
    718                                                         (caFile, str(e)) 
     694            raise WSSecurityError('Loading CA certificate "%s" from file ' 
     695                                  'list: %s' % (caFile, str(e))) 
    719696                     
    720697        # Add to stack 
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/dom.py

    r4254 r4285  
    227227        # Add X.509 cert as binary security token 
    228228        if self.reqBinSecTokValType==self.binSecTokValType['X509PKIPathv1']: 
     229            if self.signingCertChain is None: 
     230                msg = 'SignatureHandler signingCertChain attribute is not set' 
     231                log.error(msg) 
     232                raise AttributeError(msg) 
     233             
    229234            binSecTokVal = base64.encodestring(self.signingCertChain.asDER()) 
    230235        else: 
    231236            # Assume X.509 / X.509 vers 3 
     237            if self.signingCert is None: 
     238                msg = 'SignatureHandler signingCert attribute is not set' 
     239                log.error(msg) 
     240                raise AttributeError(msg) 
     241             
    232242            binSecTokVal = base64.encodestring(self.signingCert.asDER()) 
    233243 
  • TI12-security/trunk/python/ndg.security.server/ndg/security/server/wsgi/soap.py

    r4254 r4285  
    300300            soapMethodName = 'soap_%s' % environ['HTTP_SOAPACTION'].strip('"') 
    301301             
    302             method = getattr(self.serviceSOAPBinding, soapMethodName) 
    303              
    304             # TODO: change method to return response only: request, response  
    305             # tuple is carry over from Twisted based code 
    306             req, resp = method(ps) 
     302            method = getattr(self.serviceSOAPBinding, soapMethodName)             
     303            resp = method(ps) 
    307304        except Exception, e: 
    308305            sw = self.exception2SOAPFault(environ, e) 
  • TI12-security/trunk/python/ndg.security.server/ndg/security/server/zsi/attributeauthority/__init__.py

    r4256 r4285  
    1515log = logging.getLogger(__name__) 
    1616 
    17  
     17from ndg.security.common.zsi.attributeauthority.AttAuthority_services import \ 
     18    getAttCertInputMsg, getAttCertOutputMsg, \ 
     19    getHostInfoInputMsg, getHostInfoOutputMsg, \ 
     20    getTrustedHostInfoInputMsg, getTrustedHostInfoOutputMsg, \ 
     21    getAllHostsInfoInputMsg, getAllHostsInfoOutputMsg, \ 
     22    getX509CertInputMsg, getX509CertOutputMsg 
     23     
    1824from ndg.security.server.zsi.attributeauthority.AttAuthority_services_server \ 
    1925    import AttAuthorityService as _AttAuthorityService 
     
    4854        @type ps: ZSI ParsedSoap 
    4955        @param ps: client SOAP message 
    50         @rtype: tuple 
    51         @return: request and response objects''' 
    52         if self.__debug: 
    53             import pdb 
    54             pdb.set_trace() 
    55              
     56        @rtype: ndg.security.common.zsi.attributeauthority.AttAuthority_services_types.getAttCertResponse_Holder 
     57        @return: response''' 
     58        if self.__debug: 
     59            import pdb 
     60            pdb.set_trace() 
     61         
     62        request = ps.Parse(getAttCertInputMsg.typecode)     
    5663        response = _AttAuthorityService.soap_getAttCert(self, ps) 
    5764 
     
    7178            holderCert = request.UserCert 
    7279 
    73         try:     
     80        try: 
    7481            attCert = self.aa.getAttCert(userId=request.UserId, 
    7582                                         holderCert=holderCert, 
     
    8895        @type ps: ZSI ParsedSoap 
    8996        @param ps: client SOAP message 
    90         @rtype: tuple 
    91         @return: request and response objects''' 
     97        @rtype: response 
     98        @return: response''' 
    9299        if self.__debug: 
    93100            import pdb 
     
    114121        @param ps: client SOAP message 
    115122        @rtype: tuple 
    116         @return: request and response objects''' 
     123        @return: response object''' 
    117124        if self.__debug: 
    118125            import pdb 
     
    168175        @param ps: client SOAP message 
    169176        @rtype: tuple 
    170         @return: request and response objects''' 
    171         if self.__debug: 
    172             import pdb 
    173             pdb.set_trace() 
    174              
     177        @return: response object''' 
     178        if self.__debug: 
     179            import pdb 
     180            pdb.set_trace() 
     181             
     182        request = ps.Parse(getTrustedHostInfoInputMsg.typecode)     
    175183        response = _AttAuthorityService.soap_getTrustedHostInfo(self, ps) 
    176184         
     
    203211        @param ps: client SOAP message 
    204212        @rtype: tuple 
    205         @return: request and response objects''' 
     213        @return: response object''' 
    206214        if self.__debug: 
    207215            import pdb 
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/attAuthority/wsgi/site-a.ini

    r4254 r4285  
    9999# Certificate associated with private key used to sign a message.  The sign  
    100100# method will add this to the BinarySecurityToken element of the WSSE header.   
    101 #signingCertFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/siteA-aa.crt 
    102 signingCertFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/java-ca-server.crt 
     101signingCertFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/siteA-aa.crt 
     102#signingCertFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/java-ca-server.crt 
    103103 
    104104# PEM encoded private key file 
    105 #signingPriKeyFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/siteA-aa.key 
    106 signingPriKeyFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/java-ca-server.key 
     105signingPriKeyFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/siteA-aa.key 
     106#signingPriKeyFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/java-ca-server.key 
    107107 
    108108# Set the ValueType for the BinarySecurityToken added to the WSSE header for a 
     
    127127 
    128128# Provide a space separated list of file paths 
    129 caCertFilePathList=$NDGSEC_AACLNT_UNITTEST_DIR/ca/ndg-test-ca.crt $NDGSEC_AACLNT_UNITTEST_DIR/ca/java-ca.crt 
     129caCertFilePathList=$NDGSEC_AACLNT_UNITTEST_DIR/ca/ndg-test-ca.crt 
     130#caCertFilePathList=$NDGSEC_AACLNT_UNITTEST_DIR/ca/ndg-test-ca.crt $NDGSEC_AACLNT_UNITTEST_DIR/ca/java-ca.crt 
    130131 
    131132 
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/credwallet/credWallet.cfg

    r4279 r4285  
    1010# version 1.0 or later. 
    1111[DEFAULT] 
    12 username=ndg-user 
    13 userCreds= 
    14 caCertFilePathList= 
    15 attributeAuthorityURI= 
    16 attributeAuthority= 
    17 credentialRepository= 
    18 mapFromTrustedHosts=False 
     12userId=ndg-user 
     13userX509Cert= 
     14userPriKey= 
     15issuingX509Cert= 
     16 
     17# CA certificates for Attribute Certificate signautre validation 
     18caCertFilePathList=$NDGSEC_CREDWALLET_UNITTEST_DIR/ca/ndg-test-ca.crt 
     19 
     20# CA certificates for SSL connection peer cert. validation 
     21sslCACertFilePathList=$NDGSEC_CREDWALLET_UNITTEST_DIR/ca/ndg-test-ca.crt 
     22 
     23# See attAuthority unit tests to get this service running 
     24#attributeAuthorityURI=http://localhost:5000/AttributeAuthority 
     25attributeAuthorityURI=http://localhost:4900/AttributeAuthority 
     26 
     27# Omit Credential Repository and use default NullCredentialRepository 
     28#credentialRepository= 
     29 
     30# Allow the Get Attribute Certificate call to try to get a mapped certificate 
     31# from another organisation trusted by the target Attribute Authority 
     32mapFromTrustedHosts=True 
    1933rtnExtAttCertList=True 
     34 
     35# Refresh an Attribute Certificate, if an existing one in the wallet has only 
     36# this length of time left before it expires 
    2037attCertRefreshElapse=7200 
     38 
     39# Section in this file from which to retrieve WS-Security settings for  
     40# digital signature of SOAP messages to Attribute Authorities 
     41wssCfgSection=WS-Security 
     42 
     43[WS-Security] 
     44# 
     45# OUTBOUND MESSAGE CONFIG 
     46 
     47# Signature of an outbound message 
     48 
     49# Certificate associated with private key used to sign a message.  The sign  
     50# method will add this to the BinarySecurityToken element of the WSSE header.   
     51# binSecTokValType attribute must be set to 'X509' or 'X509v3' ValueType.   
     52signingCertFilePath=$NDGSEC_CREDWALLET_UNITTEST_DIR/clnt.crt 
     53 
     54# ... or provide file path to PEM encoded private key file 
     55signingPriKeyFilePath=$NDGSEC_CREDWALLET_UNITTEST_DIR/clnt.key 
     56 
     57# Password protecting private key.  Leave blank if there is no password. 
     58signingPriKeyPwd= 
     59 
     60# Set the ValueType for the BinarySecurityToken added to the WSSE header for a 
     61# signed message.  See __setReqBinSecTokValType method and binSecTokValType  
     62# class variable for options - it may be one of X509, X509v3, X509PKIPathv1 or  
     63# give full namespace to alternative - see  
     64# ZSI.wstools.Namespaces.OASIS.X509TOKEN 
     65# 
     66# binSecTokValType determines whether signingCert or signingCertChain  
     67# attributes will be used. 
     68reqBinSecTokValType=X509v3 
     69 
     70# Add a timestamp element to an outbound message 
     71addTimestamp=True 
     72 
     73# For WSSE 1.1 - service returns signature confirmation containing signature  
     74# value sent by client 
     75applySignatureConfirmation=True 
     76 
     77# 
     78# INBOUND MESSAGE CONFIG 
     79 
     80# Provide a space separated list of file paths 
     81caCertFilePathList=$NDGSEC_CREDWALLET_UNITTEST_DIR/ca/ndg-test-ca.crt  
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/credwallet/credWalletTest.cfg

    r4279 r4285  
    1010# $Id:$ 
    1111[setUp] 
    12 propFilePath = $NDGSEC_CREDWALLET_UNITTEST_DIR/credWallet.cfg 
     12cfgFilePath = $NDGSEC_CREDWALLET_UNITTEST_DIR/credWallet.cfg 
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/credwallet/test_credwallet.py

    r4279 r4285  
    4949                                "credWalletTest.cfg") 
    5050        self.cfg.read(configFilePath) 
    51                      
    52         self.credWallet = CredWallet() 
    53          
    54  
    55     def test1SetAccessDenied(self): 
     51         
     52 
     53    def test1ReadOnlyClassVariables(self): 
    5654         
    5755        try: 
    58             self.credWallet.accessDenied = 'yes' 
    59             self.fail("accessDenied class variable must only be set to True/" 
    60                       "False") 
     56            CredWallet.accessDenied = 'yes' 
     57            self.fail("accessDenied class variable should be read-only") 
    6158        except Exception, e: 
    62             print("PASS - accessDenied must be set to True/False") 
    63              
    64         self.credWallet.accessDenied = True 
    65         self.credWallet.accessDenied = False 
     59            print("PASS - accessDenied class variable is read-only") 
     60 
     61        try: 
     62            CredWallet.accessGranted = False 
     63            self.fail("accessGranted class variable should be read-only") 
     64        except Exception, e: 
     65            print("PASS - accessGranted class variable is read-only") 
     66             
     67        assert(not CredWallet.accessDenied) 
     68        assert(CredWallet.accessGranted) 
     69         
    6670         
    6771    def test2SetAttributes(self): 
    68         self.credWallet.userX509Cert = \ 
     72         
     73        credWallet = CredWallet() 
     74        credWallet.userX509Cert = \ 
    6975'''-----BEGIN CERTIFICATE----- 
    7076MIICazCCAdSgAwIBAgICAPcwDQYJKoZIhvcNAQEEBQAwLzEMMAoGA1UEChMDTkRH 
     
    8389-----END CERTIFICATE----- 
    8490''' 
    85         print("userCert=%s" % self.credWallet.userX509Cert) 
    86         self.credWallet.username = 'ndg-user' 
    87         print("username=%s" % self.credWallet.username) 
     91        print("userCert=%s" % credWallet.userX509Cert) 
     92        credWallet.userId = 'ndg-user' 
     93        print("userId=%s" % credWallet.userId) 
    8894         
    8995        try: 
    90             self.credWallet.blah = 'blah blah' 
     96            credWallet.blah = 'blah blah' 
    9197            self.fail("Attempting to set attribute not in __slots__ class " 
    9298                      "variable should fail") 
     
    95101                  "not in __slots__ class variable") 
    96102             
    97         self.credWallet.userCreds=None, 
    98         self.credWallet.caCertFilePathList=None, 
    99         self.credWallet.attributeAuthorityURI=None, 
    100         self.credWallet.attributeAuthority=None, 
    101         self.credWallet.credentialRepository=None, 
    102         self.credWallet.mapFromTrustedHosts=False, 
    103         self.credWallet.rtnExtAttCertList=True, 
    104         self.credWallet.attCertRefreshElapse=7200, 
    105         self.credWallet.wssSignatureHandlerKw 
    106  
    107              
    108     def test3(self): 
    109         pass 
     103        credWallet.caCertFilePathList=None 
     104        credWallet.attributeAuthorityURI='http://localhost/AttributeAuthority' 
     105             
     106        credWallet.attributeAuthority = None 
     107        credWallet.credentialRepository = None 
     108        credWallet.mapFromTrustedHosts = False 
     109        credWallet.rtnExtAttCertList = True 
     110        credWallet.attCertRefreshElapse = 7200 
     111             
     112    def test3GetAttCertWithUserId(self): 
     113                     
     114        credWallet = CredWallet(cfg=self.cfg.get('setUp', 'cfgFilePath')) 
     115        attCert = credWallet.getAttCert() 
    110116     
    111117#    def test6GetAttCertWithSessID(self): 
Note: See TracChangeset for help on using the changeset viewer.