Changeset 4233 for TI12-security


Ignore:
Timestamp:
24/09/08 16:25:09 (11 years ago)
Author:
pjkersha
Message:

More work on WSGI version of Attribute Authority unit tests. TODO: complete code to enable WS-Security config to be picked up from within the Paste ini file.

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

Legend:

Unmodified
Added
Removed
  • TI12-security/trunk/python/Tests/pylonsAttributeAuthority/ndgsecurity/development.ini

    r4185 r4233  
    3232paste.filter_app_factory = ndg.security.server.wsgi.soap:SOAPBindingMiddleware 
    3333ServiceSOAPBindingClass = ndg.security.server.zsi.attributeauthority.AttributeAuthorityWS 
    34 path = /AttributeAuthority/ 
     34referencedFilters = wsseSignatureVerificationFilter01 
     35path = /AttributeAuthority 
    3536enableWSDLQuery = True 
    3637charset = utf-8 
     
    3839[filter:wsseSignatureVerificationFilter] 
    3940paste.filter_app_factory = ndg.security.server.wsgi.wssecurity:SignatureVerificationFilter 
     41filterID = wsseSignatureVerificationFilter01 
    4042 
    4143[filter:wsseSignatureFilter] 
  • TI12-security/trunk/python/Tests/pylonsAttributeAuthority/ndgsecurity/ndgsecurity/config/middleware.py

    r4020 r4233  
    1212 
    1313from ndgsecurity.config.environment import load_environment 
    14  
    15 from ndgsecurity.config.attributeauthority import AttributeAuthorityWS 
    16 from ndgsecurity.config.soap import SOAPMiddleware 
    17 from ndgsecurity.config.wssecurity import SignatureVerificationMiddleware, \ 
    18     SignatureMiddleware 
    1914 
    2015def make_app(global_conf, full_stack=True, **app_conf): 
     
    4136    # The Pylons WSGI app 
    4237    app = PylonsApp() 
    43      
    44     # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) 
    45     #app = SignatureMiddleware(app, global_conf) 
    46 #    app = SOAPMiddleware(app, global_conf, 
    47 #                         ServiceSOAPBinding=AttributeAuthorityWS(), 
    48 #                         pathInfo='/AttributeAuthority') 
    49     #app = SignatureVerificationMiddleware(app, global_conf) 
    50      
     38         
    5139    if asbool(full_stack): 
    5240        # Handle Python exceptions 
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/utils/ClassFactory.py

    r4158 r4233  
    2222 
    2323 
    24 def instantiateClass(moduleName, className, moduleFilePath=None, \ 
     24def instantiateClass(moduleName, className, moduleFilePath=None,  
    2525                     objectType=None, classProperties={}): 
    2626    ''' 
     
    3030    @param className: Name of the class to instantiate 
    3131    @type className: str 
    32     @keyword moduleFilePath: Path to the module - if unset, assume module on system path already 
     32    @keyword moduleFilePath: Path to the module - if unset, assume module on  
     33    system path already 
    3334    @type moduleFilePath: str 
    34     @keyword classProperties: dict of properties to use when instantiating the class 
     35    @keyword classProperties: dict of properties to use when instantiating the  
     36    class 
    3537    @type classProperties: dict 
    36     @keyword objectType: expected type for the object to instantiate - to enforce use of 
    37     specific interfaces  
     38    @keyword objectType: expected type for the object to instantiate - to  
     39    enforce use of specific interfaces  
    3840    @type objectType: object 
    3941    @return: object - instance of the class specified  
     
    4244    log.debug("Instantiating class, %s" %className) 
    4345     
    44     # ensure that classproperties is a dict - NB, it may be passed in as a null value 
    45     # which can override the default val 
     46    # ensure that classproperties is a dict - NB, it may be passed in as a null 
     47    # value which can override the default val 
    4648    if not classProperties: 
    4749        classProperties = {} 
     
    5557            if moduleFilePath: 
    5658                if not os.path.exists(moduleFilePath): 
    57                     raise IOError, "Module file path '%s' doesn't exist" % \ 
    58                           moduleFilePath 
     59                    raise IOError("Module file path '%s' doesn't exist" % \ 
     60                                  moduleFilePath) 
    5961                           
    6062                # Temporarily extend system path ready for import 
     
    6769                                      locals(), [className]) 
    6870 
    69             importClass = eval('importModule.' + className) 
     71            #importClass = eval('importModule.' + className) 
     72            importClass = getattr(importModule, className) 
    7073        finally: 
    7174            # revert back to original sys path, if necessary 
     
    7578                             
    7679    except Exception, e: 
    77         raise ClassFactoryError,'Error importing %s module: %s' \ 
    78             %(moduleName, str(e)) 
     80        raise ClassFactoryError('Error importing %s module: %s'%(moduleName,e)) 
    7981 
    8082    # Check class inherits from AAproxy abstract base class 
     
    8688    # Instantiate class 
    8789    try: 
    88         print "Calling %s with dict:" %className 
    89         print classProperties 
    90         object=importClass(**classProperties) 
    91         log.info(\ 
    92                  'Instantiated "%s" class from module, "%s"' \ 
    93                  %(className, moduleName)) 
     90        object = importClass(**classProperties) 
     91        log.info('Instantiated "%s" class from module, "%s"' % (className, 
     92                                                                moduleName)) 
    9493        return object 
    9594         
    9695    except Exception, e: 
    97         print e 
    98         raise ClassFactoryError, \ 
    99             "Error instantiating class, %s: " %(importClass.__name__, str(e)) 
     96        raise ClassFactoryError("Error instantiating class, %s: " % \ 
     97                                                    (importClass.__name__, e)) 
    10098             
    10199                  
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/BaseSignatureHandler.py

    r4171 r4233  
    138138    @type b64EncSignatureValue: string/None""" 
    139139 
     140    _binSecTokEncType = \ 
     141"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" 
    140142     
    141143    binSecTokValType = { 
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/__init__.py

    r4129 r4233  
    1313__revision__ = "$Id$" 
    1414 
    15 from ZSI.wstools.Namespaces import OASIS 
    1615from ConfigParser import SafeConfigParser 
    1716from os.path import expandvars as exVar 
    1817import copy 
     18from ZSI.wstools.Namespaces import OASIS 
    1919 
    2020class WSSecurityConfigOpNotPermitted(Exception): 
     
    6363         
    6464 
    65     def read(self, *arg): 
    66         '''Read ConfigParser object''' 
     65    def read(self, *filePathList): 
     66        '''Read ConfigParser object 
     67         
     68        @type filePathList: tuple/list 
     69        @param filePathList: list of files to read config from''' 
    6770        self._cfg = SafeConfigParser() 
    68         self._cfg.read(*arg) 
     71         
     72        # Expand environment variables in file list 
     73        filePathList = exVar(':'.join(filePathList)).split(':') 
     74        readFilePaths = self._cfg.read(filePathList) 
     75         
     76        # Check files were read in OK 
     77        missingFilePaths = [file for file in filePathList \ 
     78                            if file not in readFilePaths] 
     79        if len(missingFilePaths) > 0: 
     80            raise IOError('Missing config file(s): "%s"' % \ 
     81                          '", "'.join(missingFilePaths)) 
     82         
    6983 
    7084 
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/dom.py

    r4133 r4233  
    1313 
    1414 
    15 from BaseSignatureHandler import _ENCRYPTION, _WSU, OASIS, BaseSignatureHandler, \ 
    16     WSSecurityError, NoSignatureFound, InvalidSignature, TimestampError, \ 
    17     VerifyError, SignatureError 
    1815import re 
    1916 
     
    6259from xml.dom.ext.reader.PyExpat import Reader 
    6360 
    64 # Enable settings from a config file 
    65 from ndg.security.common.wssecurity import WSSecurityConfig 
    66  
    67 from ndg.security.common.X509 import X509Cert, X509CertParse, X509CertRead, \ 
    68 X509Stack, X509StackParseFromDER 
    69  
    7061from datetime import datetime, timedelta 
    7162import logging 
    7263log = logging.getLogger(__name__) 
     64 
     65from BaseSignatureHandler import _ENCRYPTION, _WSU, OASIS, \ 
     66    BaseSignatureHandler, WSSecurityError, NoSignatureFound, InvalidSignature,\ 
     67    TimestampError, VerifyError, SignatureError 
     68 
     69# Enable settings from a config file 
     70from ndg.security.common.wssecurity import WSSecurityConfig 
     71 
     72from ndg.security.common.X509 import X509Cert, X509CertParse, X509CertRead, \ 
     73X509Stack, X509StackParseFromDER 
    7374 
    7475class SignatureHandler(BaseSignatureHandler): 
     
    145146        @param ctxt: XPath context object""" 
    146147 
    147         # TODO: do we need to be more rigorous in terms of handling the situation 
    148         # where no timestamp is found? 
     148        # TODO: do we need to be more rigorous in terms of handling the  
     149        # situation where no timestamp is found? 
    149150         
    150151        try: 
     
    170171        # Workaround for fractions of second 
    171172        try: 
    172             createdDateTime, createdSecFraction = createdNode[0].childNodes[0].nodeValue.split('.') 
     173            createdDateTime, createdSecFraction = \ 
     174                            createdNode[0].childNodes[0].nodeValue.split('.') 
    173175            dtCreated = datetime.strptime(createdDateTime, '%Y-%m-%dT%H:%M:%S') 
    174             dtCreated += timedelta(seconds=float("0." + createdSecFraction.replace('Z', ''))) 
     176            createdSeconds = float("0." + createdSecFraction.replace('Z', '')) 
     177            dtCreated += timedelta(seconds=createdSeconds) 
    175178                                             
    176179        except ValueError, e: 
    177             raise TimestampError("Failed to parse timestamp Created element: %s" % e) 
     180            raise TimestampError("Failed to parse timestamp Created element: " 
     181                                 "%s" % e) 
    178182         
    179183        if dtCreated >= dtNow: 
    180             raise TimestampError(\ 
    181             "Timestamp created time %s is equal to or after the current time %s" %\ 
    182                 (dtCreated, dtNow)) 
     184            raise TimestampError("Timestamp created time %s is equal to or " 
     185                                 "after the current time %s" % \ 
     186                                 (dtCreated, dtNow)) 
    183187         
    184188        expiresNode = timestampNode.getElementsByTagName("wsu:Expires") 
    185189        if expiresNode is None: 
    186             log.warning("Verifying message - No Expires element found in Timestamp") 
     190            log.warning("Verifying message - No Expires element found in " 
     191                        "Timestamp") 
    187192            return 
    188193 
    189194        try: 
    190             expiresDateTime, expiresSecFraction = expiresNode[0].childNodes[0].nodeValue.split('.') 
     195            expiresDateTime, expiresSecFraction = \ 
     196                            expiresNode[0].childNodes[0].nodeValue.split('.') 
    191197            dtExpiry = datetime.strptime(expiresDateTime, '%Y-%m-%dT%H:%M:%S') 
    192             dtExpiry += timedelta(seconds=float("0." + expiresSecFraction.replace('Z', ''))) 
     198            expirySeconds = float("0." + expiresSecFraction.replace('Z', '')) 
     199            dtExpiry += timedelta(seconds=expirySeconds) 
    193200 
    194201        except ValueError, e: 
    195             raise TimestampError("Failed to parse timestamp Expires element: %s" % e) 
     202            raise TimestampError("Failed to parse timestamp Expires element: " 
     203                                 "%s" % e) 
    196204 
    197205        if dtExpiry < dtNow: 
    198             raise TimestampError(\ 
    199                 "Timestamp expiry time %s is before the current time %s - i.e. the message has expired." % \ 
    200                 (dtExpiry, dtNow)) 
     206            raise TimestampError("Timestamp expiry time %s is before the " 
     207                                 "current time %s - i.e. the message has " 
     208                                 "expired." % (dtExpiry, dtNow)) 
    201209             
    202210                    
    203     #_________________________________________________________________________ 
    204211    def sign(self, soapWriter): 
    205212        '''Sign the message body and binary security token of a SOAP message 
     
    247254                                   context=ctxt) 
    248255        if len(wsseNodes) > 1: 
    249             raise SignatureError, 'wsse:Security element is already present' 
     256            raise SignatureError('wsse:Security element is already present') 
    250257 
    251258        # Add WSSE element 
     
    267274                                        self.reqBinSecTokValType) 
    268275 
    269         encodingType = \ 
    270 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" 
    271         binSecTokElem.node.setAttribute('EncodingType', encodingType) 
     276        binSecTokElem.node.setAttribute('EncodingType', self._binSecTokEncType) 
    272277         
    273278        # Add ID so that the binary token can be included in the signature 
     
    356361        refC14nAlg = c14nAlgOpt[self.refC14nIsExcl] 
    357362 
    358         log.info("Forcing use of exclusive namespaces - inclusive namespaces \ 
    359             do not seem to work for ZSI.Canonicalize") 
     363        log.info("Forcing use of exclusive C14N - inclusive C14N" 
     364                 "does not seem to work for ZSI.Canonicalize") 
    360365        # TODO: remove this line if ZSI.Canonicalize ever starts working with 
    361366        # inclusive NS 
     
    396401            # Use ds:Transforms or wsse:TransformationParameters? 
    397402            transformsElem = refElem.createAppendElement(DSIG.BASE,  
    398                                                         'Transforms') 
     403                                                         'Transforms') 
    399404            transformElem = transformsElem.createAppendElement(DSIG.BASE,  
    400405                                                               'Transform') 
     
    427432        ctxt = Context(docNode, processorNss=processorNss) 
    428433        signedInfoNode = xpath.Evaluate('//ds:SignedInfo',  
    429                                           contextNode=docNode,  
    430                                           context=ctxt)[0] 
     434                                        contextNode=docNode,  
     435                                        context=ctxt)[0] 
    431436 
    432437        signedInfoSubsetList = getChildNodes(signedInfoNode) 
     
    456461        place of keys with names 'unsupressedPrefixes' 
    457462        NB, this is required for the ZSI canonicalize method 
    458         @param dict: dictionary to convert 
    459         @return: dict with corrected keys 
     463        @type dictToConvert: dict 
     464        @param dictToConvert: dictionary to convert 
     465        @rtype: dict 
     466        @return: dictionary with corrected keys 
    460467        """ 
    461468        nsList = [] 
    462469        newDict = dictToConvert.copy() 
    463         log.debug("Adjusting key name from 'inclusive_namespaces' to 'unsupressedPrefixes'") 
     470        log.debug("Adjusting key name from 'inclusive_namespaces' to " 
     471                  "'unsupressedPrefixes'") 
    464472        if isinstance(newDict, dict) and \ 
    465473            isinstance(newDict.get('inclusive_namespaces'), list): 
     
    533541                transforms = getElements(transformsNode, "Transform") 
    534542     
    535                 refAlgorithm = \ 
    536                             transforms[0].getAttributeNode("Algorithm").value 
     543                refAlgorithm=transforms[0].getAttributeNode("Algorithm").value 
    537544            except Exception, e: 
    538                 raise VerifyError, \ 
    539             'failed to get transform algorithm for <ds:Reference URI="%s">'%\ 
    540                         (refURI, str(e)) 
     545                raise VerifyError('failed to get transform algorithm for ' 
     546                                  '<ds:Reference URI="%s">' % \ 
     547                                  (refURI, str(e))) 
    541548                 
    542549            # Add extra keyword for Exclusive canonicalization method 
     
    558565                        refC14nKw['unsuppressedPrefixes'] = [] 
    559566                except Exception, e: 
    560                     raise VerifyError( 
    561             'failed to handle transform (%s) in <ds:Reference URI="%s">: %s' %\ 
    562                         (transforms[0], refURI, e)) 
     567                    raise VerifyError('failed to handle transform (%s) in ' 
     568                                      '<ds:Reference URI="%s">: %s' % \ 
     569                                      (transforms[0], refURI, e)) 
    563570         
    564571            # Canonicalize the reference data and calculate the digest 
    565572            if refURI[0] != "#": 
    566                 raise VerifyError, \ 
    567                     "Expecting # identifier for Reference URI \"%s\"" % refURI 
     573                raise VerifyError("Expecting # identifier for Reference URI " 
     574                                  "\"%s\"" % refURI) 
    568575                     
    569576            # XPath reference 
     
    586593            # Reference validates if the two digest values are the same 
    587594            if digestValue != nodeDigestValue: 
    588                 raise InvalidSignature, \ 
    589                         'Digest Values do not match for URI: "%s"' % refURI 
     595                raise InvalidSignature('Digest Values do not match for URI: ' 
     596                                       '"%s"' % refURI) 
    590597             
    591598            log.info("Verified canonicalization for element %s" % refURI[1:]) 
     
    616623                    signedInfoC14nKw['unsuppressedPrefixes'] = [] 
    617624            except Exception, e: 
    618                 raise VerifyError, \ 
    619             'failed to handle exclusive canonicalisation for SignedInfo: %s'%\ 
    620                         str(e) 
     625                raise VerifyError('failed to handle exclusive ' 
     626                                  'canonicalisation for SignedInfo: %s' % e) 
    621627 
    622628        # Canonicalize the SignedInfo node and take digest 
     
    660666            # which case the verifying cert will need to have been set  
    661667            # elsewhere 
     668            log.info("No Binary Security Token found in WS-Security header") 
    662669            binSecTokNode = None 
    663670         
     
    689696                    self.verifyingCert = x509Stack[-1] 
    690697                else: 
    691                     raise WSSecurityError, "BinarySecurityToken ValueType " +\ 
    692                         'attribute is not recognised: "%s"' % valueType 
     698                    raise WSSecurityError("BinarySecurityToken ValueType " 
     699                                          'attribute is not recognised: "%s"'%\ 
     700                                          valueType) 
    693701                                
    694702            except Exception, e: 
    695                 raise VerifyError, "Error extracting BinarySecurityToken " + \ 
    696                                    "from WSSE header: " + str(e) 
     703                raise VerifyError("Error extracting BinarySecurityToken " 
     704                                  "from WSSE header: " % e) 
    697705 
    698706        if self.verifyingCert is None: 
    699             raise VerifyError, "No certificate set for verification " + \ 
    700                 "of the signature" 
     707            raise VerifyError("No certificate set for verification of the " 
     708                              "signature") 
    701709         
    702710        # Extract RSA public key from the cert 
     
    707715            verify = rsaPubKey.verify(signedInfoDigestValue, signatureValue) 
    708716        except RSA.RSAError, e: 
    709             raise VerifyError, "Error in Signature: " + str(e) 
     717            raise VerifyError("Error in Signature: " % e) 
    710718         
    711719        if not verify: 
    712             raise InvalidSignature, "Invalid signature" 
     720            raise InvalidSignature("Invalid signature") 
    713721         
    714722        # Verify chain of trust  
  • TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/etree.py

    r4129 r4233  
    7575    WS-Security 
    7676    """ 
    77  
    78     _binSecTokEncType = \ 
    79 "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" 
    8077 
    8178    # Namespaces for XPath searches 
  • TI12-security/trunk/python/ndg.security.server/ndg/security/server/wsgi/soap.py

    r4185 r4233  
    2323         
    2424class SOAPMiddlewareError(Exception): 
    25     """Base error handling exception for this module""" 
     25    """Base error handling exception class for the SOAP WSGI middleware module 
     26    """ 
    2627     
    2728class SOAPMiddlewareReadError(SOAPMiddlewareError): 
    28     """SOAP read error""" 
    29      
     29    """SOAP Middleware read error""" 
     30 
     31class SOAPMiddlewareConfigError(SOAPMiddlewareError): 
     32    """SOAP Middleware configuration error""" 
     33 
    3034class SOAPMiddleware(object): 
    3135    '''Middleware configurable to a given ZSI SOAP binding'''   
     
    6064        log.debug("SOAPMiddleware.__call__") 
    6165                         
     66        # Derived class must implement SOAP Response via overloaded version of 
     67        # this method.  ParsedSoap object is available as a key in environ via 
     68        # the parseRequest method 
     69         
     70        return self.writeResponse(environ, start_response) 
     71 
     72     
     73    def _initCall(self, environ, start_response): 
    6274        # Apply filter for calls 
    6375        if not self.isSOAPMessage(environ): 
     
    7890            return self.app(environ, start_response) 
    7991 
    80         self.parseRequest(environ) 
    81  
    82         # Derived class must implement SOAP Response via overloaded version of 
    83         # this method.  ParsedSoap object is available as a key in environ via 
    84         # the parseRequest method 
    85          
    86         return self.writeResponse(environ, start_response) 
     92        # Parse input into a ZSI ParsedSoap object set as a key in environ 
     93        try: 
     94            self.parseRequest(environ) 
     95        except Exception, e: 
     96            sw = self.exception2SOAPFault(environ, e) 
     97            self.setSOAPWriter(environ, sw) 
     98            return self.writeResponse(environ, start_response) 
     99         
     100        self.addFilter2Environ(environ) 
     101         
     102        # Return None to __call__ to indicate that it can proceed with  
     103        # processing the input 
     104        return None 
    87105 
    88106    @classmethod 
     
    191209        environ[SOAPMiddleware.soapWriterKey] = sw 
    192210 
    193  
     211    def addFilter2Environ(self, environ): 
     212        '''Add a key to the current application in the environment so that 
     213        other middleware can reference it.  This is dependent on filterID set 
     214        in app_conf''' 
     215        filterID = self.app_conf.get('filterID') 
     216        if filterID is not None:            
     217            if filterID in environ: 
     218                raise SOAPMiddlewareConfigError("An filterID key '%s' is " 
     219                                                "already set in environ" % \ 
     220                                                filterID) 
     221            environ[filterID] = self 
     222             
     223         
    194224class SOAPBindingMiddleware(SOAPMiddleware):   
    195225    '''Apply a ZSI ServiceSOAPBinding type SOAP service''' 
     
    220250                                hasattr(self.serviceSOAPBinding, '_wsdl') 
    221251 
     252        # Check for a list of other filters to be referenced by this one 
     253        if 'referencedFilters' in self.app_conf: 
     254            # __call__ will add any filters found to the service SOAP Binding 
     255            # - check this doesn't have a name clash with the attribute to be 
     256            # added 
     257            if hasattr(self.serviceSOAPBinding, 'referencedWSGIFilters'): 
     258                raise SOAPMiddlewareConfigError("Service SOAP binding class " 
     259                                                "%r already has an attribute " 
     260                                                "'referencedWSGIFilters'" % \ 
     261                                                self.serviceSOAPBinding) 
     262            self.referencedFilterKeys = \ 
     263                                    self.app_conf['referencedFilters'].split() 
    222264 
    223265    def __call__(self, environ, start_response): 
    224         log.debug("SOAPBindingMiddleware.__call__") 
    225                  
    226         if environ.get('REQUEST_METHOD') == 'GET' and \ 
     266        log.debug("SOAPBindingMiddleware.__call__ ...") 
     267                 
     268        if self.pathMatch(environ) and self.enableWSDLQuery and \ 
     269           environ.get('REQUEST_METHOD') == 'GET' and \ 
    227270           environ.get('QUERY_STRING') == 'wsdl': 
    228             if self.enableWSDLQuery: 
    229                 wsdl = self.serviceSOAPBinding._wsdl 
    230                 start_response("200 OK", [('Content-type', 'text/xml'), 
    231                                           ('Content-length', str(len(wsdl)))]) 
    232                 return wsdl 
     271            wsdl = self.serviceSOAPBinding._wsdl 
     272            start_response("200 OK", [('Content-type', 'text/xml'), 
     273                                      ('Content-length', str(len(wsdl)))]) 
     274            return wsdl 
    233275                 
    234276                 
    235277        # Apply filter for calls 
    236         if not self.isSOAPMessage(environ) or \ 
    237            not self.pathMatch(environ) or \ 
    238            self.isSOAPFaultSet(environ): 
    239             return self.app(environ, start_response) 
    240  
     278        response = self._initCall(environ, start_response) 
     279        if response is not None: 
     280            return response 
     281         
     282         
    241283        try: 
     284            # Other filters in the middleware chain may be passed by setting 
     285            # a reference to them in the config.  This is useful if the SOAP 
     286            # binding code needs to access results from upstream middleware  
     287            # e.g. check output from signature verification filter 
     288            if hasattr(self, 'referencedFilterKeys'): 
     289                self.serviceSOAPBinding.referencedWSGIFilters = \ 
     290                                    dict([(i, environ[i]) \ 
     291                                          for i in self.referencedFilterKeys]) 
     292                     
    242293            ps = self.parseRequest(environ) 
    243294             
  • TI12-security/trunk/python/ndg.security.server/ndg/security/server/wsgi/wssecurity.py

    r4185 r4233  
    4242        super(SignatureFilter, self).__init__(app, app_conf, **kw) 
    4343         
    44         wsseCfgFilePath = self.app_conf.get('wsseCfgFilePath') 
    45         if not wsseCfgFilePath: 
    46             raise WSSecurityFilterConfigError("No configuration file set") 
     44        wsseCfgFilePath = self.app_conf.get('wsseCfgFilePath')         
     45        wsseCfgFileSection = self.app_conf.get('wsseCfgFileSection') 
     46        wsseCfg = app_conf.copy() 
     47        wsseCfg.update(kw) 
    4748         
    48         self.signatureHandler = SignatureHandler(cfg=wsseCfgFilePath) 
     49        self.signatureHandler = SignatureHandler(cfg=wsseCfgFilePath, 
     50                                            cfgFileSection=wsseCfgFileSection, 
     51                                            **wsseCfg) 
    4952            
    5053     
     
    97100        log.debug("Verifying inbound message signature...") 
    98101 
     102        # Add a reference to this filter in environ so that other middleware 
     103        # can reference it 
     104        self.addFilter2Environ(environ) 
     105         
    99106        try: 
    100107            ps = self.parseRequest(environ) 
  • TI12-security/trunk/python/ndg.security.server/ndg/security/server/zsi/attributeauthority.py

    r4138 r4233  
     1"""ZSI Server side SOAP Binding for Attribute Authority Web Service 
     2 
     3NERC Data Grid Project""" 
     4__author__ = "P J Kershaw" 
     5__date__ = "11/06/08" 
     6__copyright__ = "(C) 2008 STFC & NERC" 
     7__license__ = \ 
     8"""This software may be distributed under the terms of the Q Public  
     9License, version 1.0 or later.""" 
     10__contact__ = "P.J.Kershaw@rl.ac.uk" 
     11__revision__ = '$Id$' 
    112import os, sys 
    213import base64 
     
    1324from ndg.security.common.wssecurity.dom import SignatureHandler 
    1425from ndg.security.common.X509 import X509Cert, X509CertRead 
    15  
    16 from ndgsecurity.config.soap import SOAPMiddleware 
    1726 
    1827 
     
    5261            # Get certificate corresponding to private key that signed the 
    5362            # message - i.e. the user's proxy 
    54             holderCert = WSSecurityHandler.signatureHandler.verifyingCert 
     63            signatureFilter = \ 
     64                self.referencedWSGIFilters['wsseSignatureVerificationFilter01'] 
     65            holderCert = signatureFilter.signatureHandler.verifyingCert 
    5566        else: 
    5667            # No signature from client - they must instead provide the 
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/attAuthority/wsgi/site-a.ini

    r4195 r4233  
    1212 
    1313[DEFAULT] 
    14 wsseCfgFilePath = ./wssecurity.cfg 
     14#wsseCfgFilePath = $NDGSEC_AACLNT_UNITTEST_DIR/wssecurity.cfg 
     15wsseCfgFileSection = WS-Security 
    1516 
    1617[server:main] 
     
    4445writeResponse = True 
    4546 
     47 
     48[WS-Security] 
     49# 
     50# OUTBOUND MESSAGE CONFIG 
     51 
     52# Signature of an outbound message 
     53 
     54# Certificate associated with private key used to sign a message.  The sign  
     55# method will add this to the BinarySecurityToken element of the WSSE header.   
     56signingCertFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/siteA-aa.crt 
     57 
     58# PEM encoded private key file 
     59signingPriKeyFilePath=$NDGSEC_AACLNT_UNITTEST_DIR/siteA-aa.key 
     60 
     61# Set the ValueType for the BinarySecurityToken added to the WSSE header for a 
     62# signed message.  See __setReqBinSecTokValType method and binSecTokValType  
     63# class variable for options - it may be one of X509, X509v3, X509PKIPathv1 or  
     64# give full namespace to alternative - see  
     65# ZSI.wstools.Namespaces.OASIS.X509TOKEN 
     66# 
     67# binSecTokValType determines whether signingCert or signingCertChain  
     68# attributes will be used. 
     69reqBinSecTokValType=X509v3 
     70 
     71# Add a timestamp element to an outbound message 
     72addTimestamp=True 
     73 
     74# For WSSE 1.1 - service returns signature confirmation containing signature  
     75# value sent by client 
     76applySignatureConfirmation=False 
     77 
     78# 
     79# INBOUND MESSAGE CONFIG 
     80 
     81# Provide a space separated list of file paths 
     82caCertFilePathList=$NDGSEC_AACLNT_UNITTEST_DIR/ca/ndg-test-ca.crt 
     83 
    4684# Logging configuration 
    4785[loggers] 
  • TI12-security/trunk/python/ndg.security.test/ndg/security/test/attAuthority/wsgi/siteAServerApp.py

    r4195 r4233  
    11#!/usr/bin/env python 
     2"""NDG Security Attribute Authority test harness for unit test site 'A' 
     3 
     4NERC Data Grid Project 
     5 
     6This software may be distributed under the terms of the Q Public License, 
     7version 1.0 or later. 
     8""" 
     9__author__ = "P J Kershaw" 
     10__date__ = "24/09/08" 
     11__copyright__ = "(C) 2008 STFC & NERC" 
     12__contact__ = "P.J.Kershaw@rl.ac.uk" 
     13__revision__ = "$Id$" 
    214import os 
    315 
     
    2032#                                     "siteAAttAuthority.cfg") 
    2133                                     "siteAAttAuthorityProperties.xml") 
    22     
    23 if 'NDGSEC_DIR' in os.environ: 
    24     tacFilePath=os.path.join(os.environ['NDGSEC_DIR'], 
    25                              "conf", 
    26                              "attAuthority.tac") 
    27 else: 
    28     import pkg_resources 
    29     eggConfigDir=pkg_resources.resource_filename('ndg.security.server','conf') 
    30     os.environ['NDGSEC_DIR'] = os.path.dirname(eggConfigDir) 
    3134 
    3235# To start the Site A Attribute Authority run  
     
    3538if __name__ == '__main__': 
    3639    import sys 
    37     if len(sys.argv) > 0: 
     40    if len(sys.argv) > 1: 
    3841        port = int(sys.argv[1]) 
    3942    else: 
     
    4144         
    4245    cfgFilePath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 
    43                                 'site-a.ini') 
     46                               'site-a.ini') 
    4447         
    4548    from paste.httpserver import serve 
Note: See TracChangeset for help on using the changeset viewer.