source: TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/__init__.py @ 3892

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.common/ndg/security/common/wssecurity/__init__.py@3892
Revision 3892, 6.9 KB checked in by pjkersha, 11 years ago (diff)
  • Big changes enabling modularised security from Discovery/Browse? Pylons code stack. Changes are for login only and don't include the Gatekeeper yet.
  • Updates to OpenID AuthKit? test code to enable kid templates.

ndg.security.server/ndg/security/server/sso/sso/config/ssoServiceMiddleware.py

  • include client in ndg.security.client.cfg class for globals - needed for server/sslServer config settings for SSO Client BaseController?
  • read WS-Security settings using ndg.security.common.wssecurity.WSSecurityConfig

ndg.security.server/ndg/security/server/sso/sso/controllers/login.py,
ndg.security.server/ndg/security/server/sso/sso/controllers/logout.py:

  • Give specific alias for kid templates to enable a separate security templates dir to ows_server

ndg.security.server/ndg/security/server/sso/sso/controllers/wayf.py:

  • ditto to above
  • fix to URL input into base 64 encode - convert from unicode to regular string as otherwise b64 code will fail

ndg.security.server/ndg/security/server/sso/sso/lib/base.py:

  • Provide full path to sso.* imports so that controllers can be imported across into ows_server or any other pylons code stack.
  • LoginServiceQuery? -> SSOServiceQuery

ndg.security.server/ndg/security/server/sso/sso/templates/ndg/security/wayf.kid:

  • got rid of login status info - it's confusing to the user

ndg.security.client/ndg/security/client/ssoclient/ssoClient.cfg:

  • added tracefile option for ZSI SOAP i/o display

ndg.security.client/ndg/security/client/ssoclient/ssoclient/config/ssoClientMiddleware.py:

  • SSOMiddleware interface changed to enable reading direct from an existing config object as well as from file

ndg.security.client/ndg/security/client/ssoclient/ssoclient/controllers/logout.py:

  • fixes for full path import statements + correct g config attr settings

ndg.security.client/ndg/security/client/ssoclient/ssoclient/lib/base.py:

  • enable processing of logout response from a separate SSO Service - logout flag in URL arg tells base controller to delete the security details from the cookie.

ndg.security.client/ndg/security/client/ssoclient/ssoclient/templates/ndg/security/ndgPage.kid: typo fix

Tests/authtest/development.ini,
Tests/authtest/authtest/config/environment.py,
Tests/authtest/authtest/controllers/auth.py:

  • enable kid template for OpenID signin

Tests/authtest/authtest/tests/functional/test_test2.py,
Tests/authtest/authtest/controllers/test2.py: test controller

ndg.security.common/ndg/security/common/wssecurity/init.py:

  • enable initialisation from an existing config file object

ndg.security.common/ndg/security/common/pylons/security_util.py:

ndg.security.common/ndg/security/common/init.py: fix to imports

ndg.security.common/ndg/security/common/wsSecurity.py: fix for altered WSSecurityConfig interface

ndg.security.common/ndg/security/common/m2CryptoSSLUtility.py:

  • fix to HostCheck?.call - check for peerCert is None when peer tries http instead of https
Line 
1"""NDG Security wssecurity package - contains signature handler and config
2
3NERC Data Grid Project
4"""
5__author__ = "P J Kershaw"
6__date__ = "01/04/08"
7__copyright__ = "(C) 2008 STFC & NERC"
8__contact__ = "P.J.Kershaw@rl.ac.uk"
9__license__ = \
10"""This software may be distributed under the terms of the Q Public
11License, version 1.0 or later."""
12__contact__ = "P.J.Kershaw@rl.ac.uk"
13__revision__ = "$Id$"
14
15from ZSI.wstools.Namespaces import OASIS
16from ConfigParser import SafeConfigParser
17from os.path import expandvars as exVar
18import copy
19
20class WSSecurityConfigOpNotPermitted(Exception):
21    "Raise for dict methods not allowed in WSSecurityConfig"
22   
23class WSSecurityConfig(dict):
24    """Parser for WS-Security configuration.  Extends dict to enable
25    convenient interface for access to params.
26    """
27    defParam = dict(
28             reqBinSecTokValType=OASIS.X509TOKEN.X509,
29             verifyingCert=None,
30             verifyingCertFilePath=None,
31             signingCert=None,
32             signingCertFilePath=None, 
33             signingCertChain=[],
34             signingPriKey=None,
35             signingPriKeyFilePath=None, 
36             signingPriKeyPwd=None,
37             caCertDirPath=None,
38             caCertFilePathList=[],
39             addTimestamp=True,
40             applySignatureConfirmation=False,
41             refC14nKw={'unsuppressedPrefixes': []},
42             refC14nInclNS=[],
43             signedInfoC14nKw = {'unsuppressedPrefixes': []},
44             signedInfoC14nInclNS=[])
45   
46    def __init__(self, cfg=SafeConfigParser()):
47        '''Initialise settings from an existing config file object or the
48        given path to config file
49       
50        @type cfg: SafeConfigParser or string
51        @param cfg: config object instance or file path to config file to be
52        parsed'''
53       
54        dict.__init__(self)
55       
56        # Initialise parameters from ref in class var
57        self._param = WSSecurityConfig.defParam.copy()
58       
59        if isinstance(cfg, basestring):
60            # Assume file path to be read
61            self.read(cfg)
62        else:
63            # Assume existing config type object
64            self._cfg = cfg
65       
66
67    def read(self, *arg):
68        '''Read ConfigParser object'''
69        self._cfg = SafeConfigParser()
70        self._cfg.read(*arg)
71
72
73    def parse(self, **kw):
74        '''Extract items from config file and place in dict
75        @type **kw: dict
76        @param **kw: this enables WS-Security params to be set in a config file
77        with other sections e.g. params could be under the section 'wssecurity'
78        '''
79        if 'section' in kw:
80            section = kw['section']
81        else:
82            section = 'DEFAULT'
83             
84        for paramName in self._param:
85            # Options may be omitted and set later
86            if self._cfg.has_option(section, paramName):
87                # Switch based defParam type - TODO: refC14nKw and
88                # signedInfoC14nKw - maybe these should be removed as they're
89                # clumsy
90                if isinstance(WSSecurityConfig.defParam[paramName], list):
91                    try:
92                        self._param[paramName] = \
93                            exVar(self._cfg.get(section, paramName)).split()
94                    except AttributeError:
95                        raise SecurityConfigError('Setting "%s"' % paramName)
96                   
97                elif isinstance(WSSecurityConfig.defParam[paramName], bool):           
98                    self._param[paramName] = self._cfg.getboolean(section, 
99                                                                  paramName)
100                else:
101                    # Default to None if setting is an empty string.  Settings
102                    # of '' causes problems for M2Crypto parsing
103                    self._param[paramName] = \
104                        exVar(self._cfg.get(section, paramName)) or None
105
106    def __len__(self):
107        return len(self._param)
108   
109    def __iter__(self):
110        return self._param.__iter__()
111   
112    def __repr__(self):
113        """Return file properties dictionary as representation"""
114        return repr(self._param)
115
116    def __delitem__(self, key):
117        "Session Manager keys cannot be removed"       
118        raise KeyError('Keys cannot be deleted from ' + \
119                        WSSecurityConfig.__name__)
120
121    def __getitem__(self, key):
122        WSSecurityConfig.__name__ + \
123        """ behaves as data dictionary of WS-Security properties
124        """
125        if key not in self.defParam:
126            raise KeyError("Invalid key '%s'" % key)
127       
128        return self._param[key] 
129   
130    def __setitem__(self, key, item):
131        WSSecurityConfig.__name__ + \
132        """ behaves as data dictionary of WS-Security properties"""
133        if key not in WSSecurityConfig.defParam:
134            raise KeyError("Parameter key '%s' is not recognised" % key)
135       
136        self._param[key] = item
137
138    def copy(self):
139        wsSecurityConfig = WSSecurityConfig()
140        wsSecurityConfig._param = self._param.copy()
141        return wsSecurityConfig
142   
143    def get(self, key, *arg):
144        return self._param.get(key, *arg)
145
146    def clear(self):
147        raise WSSecurityConfigOpNotPermitted("Data cannot be cleared from "+\
148                                             WSSecurityConfig.__name__)
149   
150    def keys(self):
151        return self._param.keys()
152
153    def items(self):
154        return self._param.items()
155
156    def values(self):
157        return self._param.values()
158
159    def has_key(self, key):
160        return self._param.has_key(key)
161
162    # 'in' operator
163    def __contains__(self, key):
164        return key in self._param
165   
166    def update(self, seq, *arg):
167        badKeys = [i for i in seq if i not in WSSecurityConfig.defParam]
168        if badKeys:
169            raise KeyError("Parameter key(s) %s not recognised" % \
170                           ','.join(badKeys))
171        return self._param.update(seq, *arg)
172   
173    def fromkeys(self, seq):
174        badKeys = [i for i in seq if i not in WSSecurityConfig.defParam]
175        if badKeys:
176            raise KeyError("Parameter key(s) %s not recognised" % \
177                           ','.join(badKeys))
178        return self._param.fromkeys(*arg)
179   
180    def setdefault(self, key, *arg):
181        badKeys = [i for i in b if i not in WSSecurityConfig.defParam]
182        if badKeys:
183            raise KeyError("Parameter keys '%s' not recognised" % badKeys)
184        return self._param.setdefault(key, *arg)
185
186    def pop(self, key, *arg):
187        raise WSSecurityConfigOpNotPermitted("Params should not be deleted")
188   
189    def popitem(self):
190        raise WSSecurityConfigOpNotPermitted("Params should not be deleted")
191   
192    def iteritems(self):
193        return self._param.iteritems()
194   
195    def iterkeys(self):
196        return self._param.iterkeys()
197   
198    def itervalues(self):
199        return self._param.itervalues()
200
201# Temporary measure - until...
202# TODO: Move wsSecurity module into this package
203from ndg.security.common.wsSecurity import *
204   
Note: See TracBrowser for help on using the repository browser.