Changeset 6419
- Timestamp:
- 26/01/10 17:09:55 (11 years ago)
- Location:
- TI12-security/trunk/NDGSoap/ndg/soap/wssecurity
- Files:
-
- 2 added
- 3 edited
Legend:
- Unmodified
- Added
- Removed
-
TI12-security/trunk/NDGSoap/ndg/soap/wssecurity/server/wsgi/signaturehandler.py
r6418 r6419 1 """WSGI Middleware for WS-Security 1 """WSGI Middleware for WS-Security Signature handler 2 2 3 3 Implements Digital Signature handling based around ZSI 4 4 5 NERC Data 5 NERC DataGrid Project""" 6 6 __author__ = "P J Kershaw" 7 7 __date__ = "11/06/08" … … 10 10 __contact__ = "Philip.Kershaw@stfc.ac.uk" 11 11 __revision__ = '$Id: $' 12 13 12 import logging 14 13 log = logging.getLogger(__name__) 15 14 16 15 from ZSI.parse import ParsedSoap 17 18 16 from ZSI.writer import SoapWriter 19 from ndg.security.common.wssecurity.signaturehandler.foursuite import \ 20 SignatureHandler 21 from ndg.security.server.wsgi.zsi import ZSIMiddleware, ZSIMiddlewareError 17 18 from ndg.soap.wssecurity.signaturehandler import SignatureHandlerFactory 19 from ndg.soap.server.wsgi.zsi import ZSIMiddleware, ZSIMiddlewareError 20 22 21 23 22 class WSSecurityFilterError(ZSIMiddlewareError): … … 25 24 _log = log 26 25 26 27 27 class WSSecurityFilterConfigError(WSSecurityFilterError): 28 28 """WS-Security Filter Config Error""" 29 29 30 30 31 class WSSecurityFilter(ZSIMiddleware): … … 72 73 None) 73 74 74 self.signatureHandler = SignatureHandler (cfg=wsseCfgFilePath,75 cfgFileSection=wsseCfgFileSection,76 cfgFilePrefix=wsseCfgFilePrefix,75 self.signatureHandler = SignatureHandlerFactory.fromKeywords( 76 sectionName=wsseCfgFileSection, 77 prefix=wsseCfgFilePrefix, 77 78 **app_conf) 78 79 -
TI12-security/trunk/NDGSoap/ndg/soap/wssecurity/test/unit/signaturehandler/foursuite/server/echoserver.py
r6400 r6419 1 1 #!/usr/bin/env python 2 """NDG SOAP WS-Security test service 3 4 NERC DataGrid Project 5 6 """ 7 __author__ = "P J Kershaw" 8 __date__ = "26/01/2010" 9 __copyright__ = "(C) 2010 Science and Technology Facilities Council" 10 __contact__ = "Philip.Kershaw@stfc.ac.uk" 11 __revision__ = "$Id: $" 12 import os 13 from os.path import dirname, abspath, join 14 15 16 # To start run 17 # $ paster serve echoservice.ini or run this file as a script 18 # $ ./echoservice.py [port #] 19 if __name__ == '__main__': 20 import sys 21 import logging 22 logging.basicConfig(level=logging.DEBUG) 23 24 if len(sys.argv) > 1: 25 port = int(sys.argv[1]) 26 else: 27 port = 9080 28 29 cfgFilePath = os.path.join(dirname(abspath(__file__)), 'echoservice.ini') 30 31 from paste.httpserver import serve 32 from paste.deploy import loadapp 33 from paste.script.util.logging_config import fileConfig 34 35 fileConfig(cfgFilePath) 36 app = loadapp('config:%s' % cfgFilePath) 37 serve(app, host='0.0.0.0', port=port) 38 39 ##!/usr/bin/env python 40 ## 41 ## How to build an echo server using the extended code generation 42 ## 43 #import sys 44 #import os 45 #from ConfigParser import SafeConfigParser 2 46 # 3 # How to build an echo server using the extended code generation 47 ## Import the ZSI stuff you'd need no matter what 48 #from ZSI.ServiceContainer import ServiceContainer 4 49 # 5 import sys 6 import os 7 from ConfigParser import SafeConfigParser 8 9 # Import the ZSI stuff you'd need no matter what 10 from ZSI.ServiceContainer import ServiceContainer 11 12 # This is a new method imported to show it's value 13 from ZSI.ServiceContainer import GetSOAPContext 14 15 from EchoService_services_server import EchoService as _EchoService 16 17 from ndg.wssecurity.common.signaturehandler import SignatureHandlerFactory 18 19 from os.path import expandvars as xpdVars 20 from os.path import join, dirname, abspath 21 mkPath = lambda file: join(os.environ['NDGSEC_WSSESRV_UNITTEST_DIR'], file) 22 23 import logging 24 log = logging.getLogger(__name__) 25 logging.basicConfig(level=logging.DEBUG, 26 format='%(asctime)s %(filename)s:%(lineno)d ' 27 '%(levelname)s %(message)s') 28 29 30 from ndg.security.test.unit import BaseTestCase, _getParentDir 31 32 # Initialize environment for unit tests 33 if BaseTestCase.configDirEnvVarName not in os.environ: 34 os.environ[BaseTestCase.configDirEnvVarName] = \ 35 join(abspath(_getParentDir(depth=1)), 'config') 36 37 class EchoService(_EchoService): 38 39 def __init__(self, **kw): 40 41 # Stop in debugger at beginning of SOAP stub if environment variable 42 # is set 43 self.__debug = bool(os.environ.get('NDGSEC_INT_DEBUG')) 44 if self.__debug: 45 import pdb 46 pdb.set_trace() 47 48 _EchoService.__init__(self, **kw) 49 50 def sign(self, sw): 51 '''\ 52 Overrides ServiceInterface class method to allow digital signature''' 53 self.signatureHandler.sign(sw) 54 55 def verify(self, ps): 56 '''\ 57 Overrides ServiceInterface class method to allow signature 58 verification''' 59 self.signatureHandler.verify(ps) 60 61 def soap_Echo(self, ps, **kw): 62 '''Simple echo method to test WS-Security DSIG 63 64 @type ps: ZSI ParsedSoap 65 @param ps: client SOAP message 66 @rtype: tuple 67 @return: response objects''' 68 log.info("Server received an Echo service request...") 69 if self.__debug: 70 import pdb 71 pdb.set_trace() 72 73 response = _EchoService.soap_Echo(self, ps) 74 response.EchoResult = "Received message from client: " + \ 75 self.request.EchoIn 76 return response 77 78 79 def authorize(self, auth_info, post, action): 80 '''Override default simply to display client request info''' 81 ctx = GetSOAPContext() 82 print "-"*80 83 print dir(ctx) 84 print "Container: ", ctx.connection 85 print "Parsed SOAP: ", ctx.parsedsoap 86 print "Container: ", ctx.container 87 print "HTTP Headers:\n", ctx.httpheaders 88 print "-"*80 89 print "Client Request:\n", ctx.xmldata 90 return 1 91 92 93 if __name__ == "__main__": 94 # Here we set up the server 95 96 if 'NDGSEC_WSSESRV_UNITTEST_DIR' not in os.environ: 97 os.environ['NDGSEC_WSSESRV_UNITTEST_DIR'] = abspath(dirname(__file__)) 98 99 if 'NDGSEC_TEST_CONFIG_DIR' not in os.environ: 100 os.environ['NDGSEC_TEST_CONFIG_DIR'] = \ 101 abspath(join(dirname(dirname(dirname(dirname(__file__)))), 102 'config')) 103 104 configFilePath = mkPath('echoServer.cfg') 105 106 cfg = SafeConfigParser() 107 files = cfg.read(configFilePath) 108 assert len(files) == 1, "Error reading %s" % configFilePath 109 110 hostname = cfg.get('setUp', 'hostname') 111 port = cfg.getint('setUp', 'port') 112 path = cfg.get('setUp', 'path') 113 114 wsseCfgFilePath = xpdVars(cfg.get('setUp', 'wsseCfgFilePath')) 115 116 serviceContainer = ServiceContainer((hostname, port)) 117 118 # Create the Inherited version of the server 119 echo = EchoService() 120 echo.signatureHandler = SignatureHandlerFactory.fromConfigFile( 121 wsseCfgFilePath) 122 123 serviceContainer.setNode(echo, url=path) 124 125 try: 126 # Run the service container 127 print "listening at http://%s:%s%s" % (hostname, port, path) 128 serviceContainer.serve_forever() 129 except KeyboardInterrupt: 130 sys.exit(0) 50 ## This is a new method imported to show it's value 51 #from ZSI.ServiceContainer import GetSOAPContext 52 # 53 #from EchoService_services_server import EchoService as _EchoService 54 # 55 #from ndg.wssecurity.common.signaturehandler import SignatureHandlerFactory 56 # 57 #from os.path import expandvars as xpdVars 58 #from os.path import join, dirname, abspath 59 #mkPath = lambda file: join(os.environ['NDGSEC_WSSESRV_UNITTEST_DIR'], file) 60 # 61 #import logging 62 #log = logging.getLogger(__name__) 63 #logging.basicConfig(level=logging.DEBUG, 64 # format='%(asctime)s %(filename)s:%(lineno)d ' 65 # '%(levelname)s %(message)s') 66 # 67 # 68 #from ndg.security.test.unit import BaseTestCase, _getParentDir 69 # 70 ## Initialize environment for unit tests 71 #if BaseTestCase.configDirEnvVarName not in os.environ: 72 # os.environ[BaseTestCase.configDirEnvVarName] = \ 73 # join(abspath(_getParentDir(depth=1)), 'config') 74 # 75 #class EchoService(_EchoService): 76 # 77 # def __init__(self, **kw): 78 # 79 # # Stop in debugger at beginning of SOAP stub if environment variable 80 # # is set 81 # self.__debug = bool(os.environ.get('NDGSEC_INT_DEBUG')) 82 # if self.__debug: 83 # import pdb 84 # pdb.set_trace() 85 # 86 # _EchoService.__init__(self, **kw) 87 # 88 # def sign(self, sw): 89 # '''\ 90 # Overrides ServiceInterface class method to allow digital signature''' 91 # self.signatureHandler.sign(sw) 92 # 93 # def verify(self, ps): 94 # '''\ 95 # Overrides ServiceInterface class method to allow signature 96 # verification''' 97 # self.signatureHandler.verify(ps) 98 # 99 # def soap_Echo(self, ps, **kw): 100 # '''Simple echo method to test WS-Security DSIG 101 # 102 # @type ps: ZSI ParsedSoap 103 # @param ps: client SOAP message 104 # @rtype: tuple 105 # @return: response objects''' 106 # log.info("Server received an Echo service request...") 107 # if self.__debug: 108 # import pdb 109 # pdb.set_trace() 110 # 111 # response = _EchoService.soap_Echo(self, ps) 112 # response.EchoResult = "Received message from client: " + \ 113 # self.request.EchoIn 114 # return response 115 # 116 # 117 # def authorize(self, auth_info, post, action): 118 # '''Override default simply to display client request info''' 119 # ctx = GetSOAPContext() 120 # print "-"*80 121 # print dir(ctx) 122 # print "Container: ", ctx.connection 123 # print "Parsed SOAP: ", ctx.parsedsoap 124 # print "Container: ", ctx.container 125 # print "HTTP Headers:\n", ctx.httpheaders 126 # print "-"*80 127 # print "Client Request:\n", ctx.xmldata 128 # return 1 129 # 130 # 131 #if __name__ == "__main__": 132 # # Here we set up the server 133 # 134 # if 'NDGSEC_WSSESRV_UNITTEST_DIR' not in os.environ: 135 # os.environ['NDGSEC_WSSESRV_UNITTEST_DIR'] = abspath(dirname(__file__)) 136 # 137 # if 'NDGSEC_TEST_CONFIG_DIR' not in os.environ: 138 # os.environ['NDGSEC_TEST_CONFIG_DIR'] = \ 139 # abspath(join(dirname(dirname(dirname(dirname(__file__)))), 140 # 'config')) 141 # 142 # configFilePath = mkPath('echoServer.cfg') 143 # 144 # cfg = SafeConfigParser() 145 # files = cfg.read(configFilePath) 146 # assert len(files) == 1, "Error reading %s" % configFilePath 147 # 148 # hostname = cfg.get('setUp', 'hostname') 149 # port = cfg.getint('setUp', 'port') 150 # path = cfg.get('setUp', 'path') 151 # 152 # wsseCfgFilePath = xpdVars(cfg.get('setUp', 'wsseCfgFilePath')) 153 # 154 # serviceContainer = ServiceContainer((hostname, port)) 155 # 156 # # Create the Inherited version of the server 157 # echo = EchoService() 158 # echo.signatureHandler = SignatureHandlerFactory.fromConfigFile( 159 # wsseCfgFilePath) 160 # 161 # serviceContainer.setNode(echo, url=path) 162 # 163 # try: 164 # # Run the service container 165 # print "listening at http://%s:%s%s" % (hostname, port, path) 166 # serviceContainer.serve_forever() 167 # except KeyboardInterrupt: 168 # sys.exit(0) -
TI12-security/trunk/NDGSoap/ndg/soap/wssecurity/test/unit/signaturehandler/foursuite/server/echoservice.ini
r6418 r6419 1 1 # 2 # NERC DataGrid S ecurity2 # NERC DataGrid SOAP WS-Security tests 3 3 # 4 # Paste configuration for combined Session Manager, Attribute Authority,5 # OpenID Relying Party and Provider services4 # Paste configuration for test application secured with WS-Security signature 5 # handler 6 6 # 7 7 # The %(here)s variable will be replaced with the parent directory of this file 8 8 # 9 9 # Author: P J Kershaw 10 # date: 26/0 2/0911 # Copyright: (C) 20 09Science and Technology Facilities Council10 # date: 26/01/2010 11 # Copyright: (C) 2010 Science and Technology Facilities Council 12 12 # license: BSD - see LICENSE file in top-level directory 13 13 # Contact: Philip.Kershaw@stfc.ac.uk 14 # Revision: $Id $14 # Revision: $Id: $ 15 15 16 16 [DEFAULT] 17 portNum = 744317 portNum = 9080 18 18 hostname = localhost 19 19 scheme = http 20 20 baseURI = %(scheme)s://%(hostname)s:%(portNum)s 21 openIDProviderIDBase = /openid 22 openIDProviderIDSelectURI = %(baseURI)s%(openIDProviderIDBase)s 23 testConfigDir = %(here)s/../../config 24 sessionManagerPath = /SessionManager 25 sessionManagerURI = %(baseURI)s%(sessionManagerPath)s 26 openid.ax.sessionManagerURI.typeURI=urn:ndg:security:openid:sessionManagerURI 27 openid.ax.sessionId.typeURI=urn:ndg:security:openid:sessionId 21 testConfigDir = %(here)s/../../../../config 22 echoServicePath = /echoService 23 echoServiceURI = %(baseURI)s%(echoServicePath)s 28 24 29 #______________________________________________________________________________30 # Attribute Authority settings31 # 'name' setting MUST agree with map config file 'thisHost' name attribute32 attributeAuthority.name: Site A33 34 # Lifetime is measured in seconds35 attributeAuthority.attCertLifetime: 2880036 37 # Allow an offset for clock skew between servers running38 # security services. NB, measured in seconds - use a minus sign for time in the39 # past40 attributeAuthority.attCertNotBeforeOff: 041 42 # All Attribute Certificates issued are recorded in this dir43 attributeAuthority.attCertDir: %(testConfigDir)s/attributeauthority/sitea/attributeCertificateLog44 45 # Files in attCertDir are stored using a rotating file handler46 # attCertFileLogCnt sets the max number of files created before the first is47 # overwritten48 attributeAuthority.attCertFileName: ac.xml49 attributeAuthority.attCertFileLogCnt: 1650 attributeAuthority.dnSeparator:/51 52 # Location of role mapping file53 attributeAuthority.mapConfigFilePath: %(testConfigDir)s/attributeauthority/sitea/siteAMapConfig.xml54 55 # Settings for custom AttributeInterface derived class to get user roles for given56 # user ID57 #attributeAuthority.attributeInterface.modFilePath: %(testConfigDir)s/attributeauthority/sitea58 attributeAuthority.attributeInterface.modName: ndg.soap.test.integration.authz.attributeinterface59 attributeAuthority.attributeInterface.className: TestUserRoles60 61 # Config for XML signature of Attribute Certificate62 attributeAuthority.signingPriKeyFilePath: %(testConfigDir)s/attributeauthority/sitea/siteA-aa.key63 attributeAuthority.signingCertFilePath: %(testConfigDir)s/attributeauthority/sitea/siteA-aa.crt64 attributeAuthority.caCertFilePathList: %(testConfigDir)s/ca/ndg-test-ca.crt65 66 #______________________________________________________________________________67 # Session Manager specific settings - commented out settings will take their68 # default settings. To override the defaults uncomment and set as required.69 # See ndg.soap.server.sessionmanager module for details70 71 # Credential Wallet Settings - global to all user sessions72 #73 # CA certificates for Attribute Certificate signature validation74 sessionManager.credentialWallet.caCertFilePathList=%(testConfigDir)s/ca/ndg-test-ca.crt75 76 # CA certificates for SSL connection peer cert. validation - required if77 # connecting to an Attribute Authority over SSL78 sessionManager.credentialWallet.sslCACertFilePathList=%(testConfigDir)s/ca/ndg-test-ca.crt79 80 # Allow Get Attribute Certificate calls to try to get a mapped certificate81 # from another organisation trusted by the target Attribute Authority82 sessionManager.credentialWallet.mapFromTrustedHosts=True83 sessionManager.credentialWallet.rtnExtAttCertList=True84 85 # Refresh an Attribute Certificate, if an existing one in the wallet has only86 # this length of time left before it expires87 credentialWallet.attCertRefreshElapse=720088 89 # Pointer to WS-Security settings. These WS-Security settings are for use90 # by user credential wallets held in user sessions hosted by the Session91 # Manager. They enable individual wallets to query Attribute Authorities for92 # user Attribute Certificates. Nb. the difference between these settings and93 # the WS-Security section for handling requests to the Session Manager.94 #95 # Settings are identified by a prefix.96 sessionManager.credentialWallet.wssCfgPrefix=sessionManager.credentialWallet.wssecurity97 98 # ...A section name could also be used.99 #sessionManager.credentialWallet.wssCfgSection=100 101 # SOAP Signature Handler settings for the Credential Wallet's Attribute102 # Authority interface103 #104 # CA Certificates used to verify X.509 certs used in Attribute Certificates.105 # The CA certificates of other NDG trusted sites should go here. NB, multiple106 # values should be delimited by a space107 sessionManager.credentialWallet.wssecurity.caCertFilePathList: %(testConfigDir)s/ca/ndg-test-ca.crt108 109 # Signature of an outbound message110 #111 # Certificate associated with private key used to sign a message. The sign112 # method will add this to the BinarySecurityToken element of the WSSE header.113 # binSecTokValType attribute must be set to 'X509' or 'X509v3' ValueType.114 # As an alternative, use signingCertChain - see below...115 116 # PEM encoded cert117 sessionManager.credentialWallet.wssecurity.signingCertFilePath: %(testConfigDir)s/sessionmanager/sm.crt118 119 # ... or provide file path to PEM encoded private key file120 sessionManager.credentialWallet.wssecurity.signingPriKeyFilePath: %(testConfigDir)s/sessionmanager/sm.key121 122 # Set the ValueType for the BinarySecurityToken added to the WSSE header for a123 # signed message. See __setReqBinSecTokValType method and binSecTokValType124 # class variable for options - it may be one of X509, X509v3, X509PKIPathv1 or125 # give full namespace to alternative - see126 # ZSI.wstools.Namespaces.OASIS.X509TOKEN127 #128 # binSecTokValType determines whether signingCert or signingCertChain129 # attributes will be used.130 sessionManager.credentialWallet.wssecurity.reqBinSecTokValType: X509v3131 132 # Add a timestamp element to an outbound message133 sessionManager.credentialWallet.wssecurity.addTimestamp: True134 135 # For WSSE 1.1 - service returns signature confirmation containing signature136 # value sent by client137 sessionManager.credentialWallet.wssecurity.applySignatureConfirmation: True138 139 # Authentication service properties140 sessionManager.authNService.moduleFilePath:141 sessionManager.authNService.moduleName: ndg.soap.test.config.sessionmanager.userx509certauthn142 sessionManager.authNService.className: UserX509CertAuthN143 144 # Specific settings for UserCertAuthN Session Manager authentication plugin145 # This sets up PKI credentials for a single test account146 sessionManager.authNService.userX509CertFilePath: %(testConfigDir)s/pki/user.crt147 sessionManager.authNService.userPriKeyFilePath: %(testConfigDir)s/pki/user.key148 sessionManager.authNService.userPriKeyPwd: testpassword149 25 150 26 [server:main] … … 173 49 # Use this ZSI generated SOAP service interface class to handle i/o for this 174 50 # filter 175 ServiceSOAPBindingClass = ndg.soap. server.zsi.sessionmanager.SessionManagerWS51 ServiceSOAPBindingClass = ndg.soap.wssecurity.test.unit.signatureHandler.foursuite.server.echoService.echoServiceWS 176 52 177 53 # SOAP Binding Class specific keywords are in this section identified by this 178 54 # prefix: 179 ServiceSOAPBindingPropPrefix = SessionManager55 ServiceSOAPBindingPropPrefix = echoService 180 56 181 # The SessionManagerclass has settings in the default section above identified57 # The echoService class has settings in the default section above identified 182 58 # by this prefix: 183 SessionManager.propPrefix = sessionManager 184 SessionManager.propFilePath = %(here)s/securityservices.ini59 echoService.propPrefix = echoService 60 echoService.propFilePath = %(here)s/securityservices.ini 185 61 186 # This filter references other filters - a local Attribute Authority (optional) 187 # and a WS-Security signature verification filter (required if using signature 188 # to authenticate user in requests 189 SessionManager.attributeAuthorityFilterID = filter:AttributeAuthorityFilter 190 SessionManager.wsseSignatureVerificationFilterID = filter:wsseSignatureVerificationFilter 62 # This filter may references the WS-Security signature verification 63 # filter to access content e.g. client certificate used 64 echoService.wsseSignatureVerificationFilterID = filter:wsseSignatureVerificationFilter 191 65 192 # The SessionManagerWS SOAP interface class needs to know about these other66 # The echoServiceWS SOAP interface class needs to know about these other 193 67 # filters 194 68 referencedFilters = filter:wsseSignatureVerificationFilter … … 196 70 197 71 # Path from URI for Session Manager in this Paste deployment 198 path = %( sessionManagerPath)s72 path = %(echoServicePath)s 199 73 200 # External endpoint for this Session Manager - must agree with setting used to 201 # invoke this service set in: 202 # * securityservicesapp.py 203 # * or port in [server:main] if calling with paster serve securityservices.ini 204 # * or something else e.g. proxied through Apache? 205 # This setting is used by Session Manager clients in this WSGI stack to see if 206 # a request is being made to the local service or to another session manager 207 # running elsewhere 208 publishedURI = %(sessionManagerURI)s 74 # External endpoint for this service 75 publishedURI = %(echoServiceURI)s 209 76 210 77 # Enable ?wsdl query argument to list the WSDL content … … 219 86 # WS-Security Signature Verification 220 87 [filter:wsseSignatureVerificationFilter] 221 paste.filter_app_factory = ndg.soap.wssecurity.server.wsgi.signaturehandler:SignatureVerificationFilter 88 paste.filter_app_factory = ndg.soap.wssecurity.server.wsgi.signaturehandler:SignatureVerificationFilter.filter_app_factory 222 89 filterID = %(__name__)s 223 90 … … 231 98 # Apply WS-Security Signature 232 99 [filter:wsseSignatureFilter] 233 paste.filter_app_factory = ndg.soap.wssecurity.server.wsgi.signaturehandler:ApplySignatureFilter 100 paste.filter_app_factory = ndg.soap.wssecurity.server.wsgi.signaturehandler:ApplySignatureFilter.filter_app_factory 234 101 235 102 # Reference the verification filter in order to be able to apply signature … … 294 161 295 162 [formatter_generic] 296 format = %(asctime)s ,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s297 datefmt = % H:%M:%S163 format = %(asctime)s.%(msecs)03d %(levelname)-5.5s [%(name)s:%(lineno)s] %(message)s 164 datefmt = %Y-%m-%d %H:%M:%S 298 165
Note: See TracChangeset
for help on using the changeset viewer.