source: TI12-security/trunk/python/ndg.security.server/ndg/security/server/wsgi/openid/relyingparty/validation.py @ 5372

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.server/ndg/security/server/wsgi/openid/relyingparty/validation.py@5372
Revision 5372, 4.4 KB checked in by pjkersha, 12 years ago (diff)

Added code for validation of OpenID Provider by Relying Party using M2Crypto.m2urllib2 for SSL peer authN

Line 
1"""NDG Security OpenID Relying Party Provider Validator module
2
3Based on the Earth System Grid IdPValidator interface for restricting
4OpenID Providers that a Relying Party may connect to
5
6An Identity Provider (IdP) is equivalent to an OpenID Provider
7
8NERC DataGrid Project
9"""
10__author__ = "P J Kershaw"
11__date__ = "09/06/2009"
12__copyright__ = "(C) 2009 Science and Technology Facilities Council"
13__license__ = "BSD - see top-level directory for LICENSE file"
14__contact__ = "Philip.Kershaw@stfc.ac.uk"
15__revision__ = "$Id$"
16import logging
17log = logging.getLogger(__name__)
18import os
19
20class IdPValidatorException(Exception):
21    """Base class for IdPValidator exceptions"""
22   
23class IdPInvalidException():
24    """Raise from IdPValidator.validate if the IdP is not acceptable"""
25
26class ConfigException():
27    """Problem with configuration for the validator"""
28
29class IdPValidator(object):
30    '''Interface class for implementing OpenID Provider validators for a
31    Relying Party to call'''
32   
33    def __init__(self):
34        raise NotImplementedError()
35
36    def initialize(self, parameters):
37        '''@raise ConfigException:''' 
38        raise NotImplementedError()
39       
40    def validate(self, idpEndpoint, idpIdentity):
41        '''@raise IdPInvalidException:
42        @raise ConfigException:''' 
43        raise NotImplementedError()
44 
45class IdPValidationDriver(object):
46    """Parse an XML Validation configuration containing XML Validators and
47    execute these against the Provider (IdP) input"""   
48   
49    @classmethod
50    def performIdPValidation(cls, identifier, discoveries):
51        idpConfigFilePath = os.environ("IDP_CONFIG_FILE")
52        if idpConfigFilePath is None:
53            return discoveries
54       
55        # TODO: refactor code copied direct from Java implementation
56        XmlConfigReader configReader = new XmlConfigReader()
57        Vector validatorConfigs = configReader.getValidators(idpConfigFile)
58        Vector validators = new Vector()
59        IdPValidator validator = None
60
61        for(int i = 0 i < validatorConfigs.size() i++)
62       
63            IdPValidatorConfig idpConfig = (IdPValidatorConfig)validatorConfigs.get(i)
64            String className = idpConfig.getClassName()
65            NameValuePair[] parameters = idpConfig.getParameters()
66
67            try
68           
69                validator = (IdPValidator)Class.forName(className).newInstance()
70                validator.initialize(parameters)
71                validators.add(validator)
72           
73            catch(Exception e)
74           
75                log.error("Failed to initialize validator: " + e)
76           
77       
78
79        log.info(validators.size() + " IdPValidators initialized!")
80
81        // validate the discovered endpoints
82        if validators.size() > 0:
83       
84            List newDiscoveries = new ArrayList()
85            Iterator validatorIter = validators.iterator()
86            while(validatorIter.hasNext())
87           
88                validator = (IdPValidator)validatorIter.next()
89
90                Iterator iter = discoveries.iterator()
91                while(iter.hasNext())
92               
93                    DiscoveryInformation dInfo = (DiscoveryInformation)iter.next()
94                    try
95                   
96                        validator.validate(
97                            dInfo.getOPEndpoint(), identifier.getIdentifier())
98
99                        log.info(
100                            "Whitelist Validator Accepting " +
101                            "endpoint: " + dInfo.getOPEndpoint())
102
103                        newDiscoveries.add((Object)dInfo)
104                   
105                    catch(Exception e)
106                   
107                        log.info(
108                            "Whitelist Validator rejecting " +
109                            "endpoint: " + dInfo.getOPEndpoint() +
110                            ": " + e)
111                   
112               
113           
114
115            if newDiscoveries.size() > 0)
116           
117                discoveries = newDiscoveries
118                log.info("Found " + discoveries.size() +
119                          " valid endpoints.")
120           
121            else
122           
123                discoveries = None
124                log.info("No valid endpoints were found " +
125                          "after validation.")
126                throw new IdPInvalidException(
127                    "No valid endpoints were found after validation")
128           
129       
130   
131    return discoveries
Note: See TracBrowser for help on using the repository browser.