source: TI12-security/trunk/python/ndg.security.server/ndg/security/server/AttAuthority/__init__.py @ 2270

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.server/ndg/security/server/AttAuthority/__init__.py@2270
Revision 2270, 38.4 KB checked in by pjkersha, 13 years ago (diff)

Replaced

reposID = '$Id$'

with,

revision = '$Id$'

for all relevant files.

ndg.security.server/setup.py:

  • added license keyword to setup

ndg.security.server/ndg/security/server/AttAuthority/init.py:

  • removed refs to proxy certificate in getattCert call. Input cert may not necessarily be a proxy.

ndg.security.common/setup.py: Major fixes to give *working* version.

  • PyXML dependency to ZSI fixed by giving explict sourceforge dependency link
  • Get ZSI from PyPI insteads of Sourceforge
  • Moved SQLObject and MySQL dependency to a separate if clause. This will be completed later to

allow inclusion of these on provision of a given option

  • added license keyword to setup.
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1"""NDG Attribute Authority handles security authentication and authorization
2
3NERC Data Grid Project
4
5@author P J Kershaw 15/04/05
6
7@copyright (C) 2007 CCLRC & NERC
8
9@license This software may be distributed under the terms of the Q Public
10License, version 1.0 or later.
11"""
12
13__revision__ = '$Id$'
14
15import types
16
17
18# Create unique names for attribute certificates
19import tempfile
20import os
21
22# Alter system path for dynamic import of user roles class
23import sys
24
25# For parsing of properties file
26import cElementTree as ElementTree
27
28# X509 Certificate handling
29from ndg.security.common.X509 import *
30
31# NDG Attribute Certificate
32from ndg.security.common.AttCert import *
33
34
35#_____________________________________________________________________________
36class AttAuthorityError(Exception):
37    """Exception handling for NDG Attribute Authority class."""
38
39#_____________________________________________________________________________
40class AttAuthorityAccessDenied(AttAuthorityError):
41    """NDG Attribute Authority - access denied exception.
42
43    Raise from getAttCert method where no roles are available for the user
44    but that the request is otherwise valid.  In all other error cases raise
45    AttAuthorityError"""   
46
47class AttAuthorityNoTrustedHosts(AttAuthorityError):
48    """Raise from getTrustedHosts if there are no trusted hosts defined in
49    the map configuration"""
50
51class AttAuthorityNoMatchingRoleInTrustedHosts(AttAuthorityError):
52    """Raise from getTrustedHosts if there is no mapping to any of the
53    trusted hosts for the given input role name"""
54
55
56#_____________________________________________________________________________
57class AttAuthority(dict):
58    """NDG Attribute Authority - server for allocation of user authorization
59    tokens - attribute certificates.
60   
61    @type __validKeys: list
62    @cvar __validKeys: valid configuration property keywords - properties file
63    must contain these
64   
65    @type __confDir: string
66    @cvar __confDir: configuration directory under $NDG_DIR - default location
67    for properties file
68   
69    @type __propFileName: string
70    @cvar __propFileName: default file name for properties file under
71    __confDir
72    """
73
74    # Code designed from NERC Data Grid Enterprise and Information Viewpoint
75    # documents.
76    #
77    # Also, draws from Neil Bennett's ACServer class used in the Java
78    # implementation of NDG Security
79
80    __confDir = "conf"
81    __propFileName = "attAuthorityProperties.xml"
82   
83    # valid configuration property keywords
84    __validKeys = ( 'name',
85                    'portNum',
86                    'useSSL',
87                    'sslCertFile',
88                    'sslKeyFile',
89                    'sslKeyPwd',
90                    'certFile',
91                    'keyFile',
92                    'keyPwd',
93                    'caCertFile',
94                    'clntCertFile',
95                    'attCertLifetime',
96                    'attCertNotBeforeOff',
97                    'attCertFilePfx',
98                    'attCertFileSfx',
99                    'mapConfigFile',
100                    'attCertDir',
101                    'dnSeparator',
102                    'userRolesModFilePath',
103                    'userRolesModName',
104                    'userRolesClassName',
105                    'userRolesPropFile')
106   
107    def __init__(self, propFilePath=None, bReadMapConfig=True):
108        """Create new NDG Attribute Authority instance
109
110        @type propFilePath: string
111        @keyword propFilePath: path to file containing Attribute Authority
112        configuration parameters.  It defaults to $NDGSEC_AA_PROPFILEPATH or
113        if not set, $NDG_DIR/conf/attAuthorityProperties.xml
114        @type bReadMapConfig: boolean
115        @keyword bReadMapConfig: by default the Map Configuration file is
116        read.  Set this flag to False to override.
117        """
118
119        # Base class initialisation
120        dict.__init__(self)
121
122        # Set from input or use defaults based or environment variables
123        self.setPropFilePath(propFilePath)
124
125        # Initialise role mapping look-ups - These are set in readMapConfig()
126        self.__mapConfig = None
127        self.__localRole2RemoteRole = None
128        self.__remoteRole2LocalRole = None
129
130
131        # Configuration file properties are held together in a dictionary
132        self.__prop = {}
133
134        # Read Attribute Authority Properties file
135        self.readProperties()
136
137        # Read the Map Configuration file
138        if bReadMapConfig:
139            self.readMapConfig()
140
141        # Instantiate Certificate object
142        self.__cert = X509Cert(self.__prop['certFile'])
143        self.__cert.read()
144
145        # Check it's valid
146        try:
147            self.__cert.isValidTime(raiseExcep=True)
148           
149        except Exception, e:
150            raise AttAuthorityError, \
151                    "Attribute Authority's certificate is invalid: " + str(e)
152       
153        # Check CA certificate
154        caCert = X509Cert(self.__prop['caCertFile'])
155        caCert.read()
156       
157        try:
158            caCert.isValidTime(raiseExcep=True)
159           
160        except Exception, e:
161            raise AttAuthorityError, "CA certificate is invalid: " + str(e)
162       
163        # Issuer details - serialise using the separator string set in the
164        # properties file
165        self.__issuer = \
166            self.__cert.dn.serialise(separator=self.__prop['dnSeparator'])
167
168        self.__issuerSerialNumber = self.__cert.serialNumber
169       
170       
171        # Load host sites custom user roles interface to enable the AA to
172        # assign roles in an attribute certificate on a getAttCert request
173        self.loadUserRolesInterface()
174       
175
176    #_________________________________________________________________________
177    def loadUserRolesInterface(self):
178        """Set-up user roles interface - load host sites custom AAUserRoles
179        derived class.  This class interfaces with the sites mechanism for
180        mapping user ID to the roles to which they are entitled.  This
181        could be via a user database"""
182
183        try:
184            try:
185                # Module file path may be None if the new module to be loaded
186                # can be found in the existing system path           
187                if self.__prop['userRolesModFilePath'] is not None:
188                    if not os.path.exists(\
189                              self.__prop['userRolesModFilePath']):
190                        raise Exception, "File path '%s' doesn't exist" % \
191                              self.__prop['userRolesModFilePath']
192                             
193                    # Temporarily extend system path ready for import
194                    sysPathBak = sys.path[:]
195                             
196                    sys.path.append(self.__prop['userRolesModFilePath'])
197               
198                # Import module name specified in properties file
199                userRolesMod = __import__(self.__prop['userRolesModName'],
200                                          globals(),
201                                          locals(),
202                                          [self.__prop['userRolesClassName']])
203   
204                userRolesClass = eval('userRolesMod.' + \
205                                     self.__prop['userRolesClassName'])
206            finally:
207                try:
208                    sys.path[:] = sysPathBak
209                except NameError:
210                    # sysPathBak may not have been defined
211                    pass
212                               
213        except Exception, e:
214            raise AttAuthorityError,'Importing User Roles module: %s' % str(e)
215
216        # Check class inherits from AAUserRoles abstract base class
217        if not issubclass(userRolesClass, AAUserRoles):
218            raise AttAuthorityError, \
219                "User Roles class %s must be derived from AAUserRoles" % \
220                self.__prop['userRolesClassName']
221
222
223        # Instantiate custom class
224        try:
225            self.__userRoles = userRolesClass(self.__prop['userRolesPropFile'])
226           
227        except Exception, e:
228            raise AttAuthorityError, \
229                "Error instantiating User Roles interface: " + str(e)
230     
231       
232    #_________________________________________________________________________
233    # Methods for Attribute Authority dictionary like behaviour       
234    def __delitem__(self, key):
235        self.__class__.__name__ + " keys cannot be removed"       
236        raise KeyError, 'Keys cannot be deleted from '+self.__class__.__name__
237
238
239    def __getitem__(self, key):
240        self.__class__.__name__ + """ behaves as data dictionary of Attribute
241        Authority properties
242        """
243        if key not in self.__prop:
244            raise KeyError, "Invalid key '%s'" % key
245       
246        return self.__prop[key]
247       
248
249    def clear(self):
250        raise KeyError, "Data cannot be cleared from "+self.__class__.__name__
251   
252    def keys(self):
253        return self.__prop.keys()
254
255    def items(self):
256        return self.__prop.items()
257
258    def values(self):
259        return self.__prop.values()
260
261    def has_key(self, key):
262        return self.__prop.has_key(key)
263
264    # 'in' operator
265    def __contains__(self, key):
266        return key in self.__prop
267
268
269    def setPropFilePath(self, val=None):
270        """Set properties file from input or based on environment variable
271        settings"""
272        if not val:
273            if 'NDGSEC_AA_PROPFILEPATH' in os.environ:
274                val = os.environ['NDGSEC_AA_PROPFILEPATH']
275               
276            elif 'NDG_DIR' in os.environ:
277                val = os.path.join(os.environ['NDG_DIR'], 
278                                   self.__class__.__confDir,
279                                   self.__class__.__propFileName)
280            else:
281                raise AttributeError, 'Unable to set default Attribute ' + \
282                    'Authority properties file path: neither ' + \
283                    '"NDGSEC_AA_PROPFILEPATH" or "NDG_DIR" environment ' + \
284                    'variables are set'
285               
286        if not isinstance(val, basestring):
287            raise AttributeError, "Input Properties file path " + \
288                                  "must be a valid string."
289     
290        self.__propFilePath = val
291       
292    # Also set up as a property
293    propFilePath = property(fset=setPropFilePath,
294                            doc="Set the path to the properties file")   
295   
296   
297    #_________________________________________________________________________
298    def getAttCert(self,
299                   userId=None,
300                   holderCert=None,
301                   holderCertFilePath=None,
302                   userAttCert=None,
303                   userAttCertFilePath=None):
304
305        """Request a new Attribute Certificate for use in authorisation
306
307        getAttCert([userId=uid][holderCert=px|holderCertFilePath=pxFile, ]
308                   [userAttCert=cert|userAttCertFilePath=certFile])
309         
310        @type userId: string
311        @keyword userId: identifier for the user who is entitled to the roles
312        in the certificate that is issued.  If this keyword is omitted, then
313        the userId will be set to the DN of the holder.
314       
315        holder = the holder of the certificate - an inidividual user or an
316        organisation to which the user belongs who vouches for that user's ID
317       
318        userId = the identifier for the user who is entitled to the roles
319        specified in the Attribute Certificate that is issued.
320                 
321        @type holderCert: string / ndg.security.common.X509.X509Cert type
322        @keyword holderCert: base64 encoded string containing proxy cert./
323        X.509 cert object corresponding to the ID who will be the HOLDER of
324        the Attribute Certificate that will be issued.  - Normally, using
325        proxy certificates, the holder and user ID are the same but there
326        may be cases where the holder will be an organisation ID.  This is the
327        case for NDG security with the DEWS project
328       
329        @keyword holderCertFilePath: string
330        @param holderCertFilePath: file path to proxy/X.509 certificate of
331        candidate holder
332     
333        @type userAttCert: string or AttCert type
334        @keyword userAttCert: externally provided attribute certificate from
335        another data centre.  This is only necessary if the user is not
336        registered with this attribute authority.
337                       
338        @type userAttCertFilePath: string
339        @keyword userAttCertFilePath: alternative to userAttCert except pass
340        in as a file path to an attribute certificate instead.
341       
342        @rtype: AttCert
343        @return: new attribute certificate"""
344
345
346        # Read X.509 certificate
347        try:           
348            if holderCertFilePath is not None:
349                                   
350                # Proxy Certificate input as a file
351                holderCert = X509Cert()
352                holderCert.read(holderCertFilePath)
353               
354            elif isinstance(holderCert, basestring):
355
356                # Proxy Certificate input as string text
357                holderCert = X509CertParse(holderCert)
358               
359            elif not isinstance(holderCert, X509Cert):
360                raise AttAuthorityError, \
361                "No input X.509 certificate file path or cert text/object set"
362           
363        except Exception, e:
364            raise AttAuthorityError, "User certificate: %s" % e
365
366
367        # Check proxy certificate hasn't expired
368        try:
369            holderCert.isValidTime(raiseExcep=True)
370           
371        except Exception, e:
372            raise AttAuthorityError, "User certificate is invalid: " + str(e)
373
374           
375        # Get Distinguished name from certificate as an X500DN type
376        if userId is None:
377            try:
378                userId = holderCert.dn.serialise(\
379                                         separator=self.__prop['dnSeparator']) 
380            except Exception, e:
381                raise AttAuthorityError, \
382                    "Setting user Id from holder certificate DN: %s" % e
383       
384       
385        # Make a new Attribute Certificate instance passing in certificate
386        # details for later signing
387        #
388        # Nb. new attribute certificate file path is created from the
389        # Credentials Repository
390        attCert = AttCert(filePath=self.__newAttCertFilePath())
391
392        attCert.certFilePathList = [self.__prop['certFile'],
393                                    self.__prop['caCertFile']]
394       
395        attCert.signingKeyFilePath = self.__prop['keyFile']
396        attCert.signingKeyPwd = self.__prop['keyPwd']
397       
398       
399        # Set holder's (user's) Distinguished Name
400        try:
401            attCert['holder'] = \
402                holderCert.dn.serialise(separator=self.__prop['dnSeparator'])           
403        except Exception, e:
404            raise AttAuthorityError, "Holder DN: %s" % e
405
406       
407        # Set Issuer details from Attribute Authority
408        issuerDN = self.__cert.dn
409        try:
410            attCert['issuer'] = \
411                    issuerDN.serialise(separator=self.__prop['dnSeparator'])           
412        except Exception, e:
413            raise AttAuthorityError, "Issuer DN: %s" % e
414       
415        attCert['issuerName'] = self.__prop['name']
416        attCert['issuerSerialNumber'] = self.__issuerSerialNumber
417
418        attCert['userId'] = userId
419       
420        # Set validity time
421        try:
422            attCert.setValidityTime(\
423                        lifetime=self.__prop['attCertLifetime'],
424                        notBeforeOffset=self.__prop['attCertNotBeforeOff'])
425
426            # Check against the certificate's expiry
427            dtHolderCertNotAfter = holderCert.notAfter
428           
429            if attCert.getValidityNotAfter(asDatetime=True) > \
430               dtHolderCertNotAfter:
431
432                # Adjust the attribute certificate's expiry date time
433                # so that it agrees with that of the certificate
434                # ... but also make ensure that the not before skew is still
435                # applied
436                attCert.setValidityTime(dtNotAfter=dtHolderCertNotAfter,
437                        notBeforeOffset=self.__prop['attCertNotBeforeOff'])
438           
439        except Exception, e:
440            raise AttAuthorityError, "Error setting validity time: %s" % e
441       
442
443        # Check name is registered with this Attribute Authority - if no
444        # user roles are found, the user is not registered
445        userRoles = self.getRoles(userId)
446        if userRoles:           
447            # Set as an Original Certificate
448            #
449            # User roles found - user is registered with this data centre
450            # Add roles for this user for this data centre
451            attCert.addRoles(userRoles)
452
453            # Mark new Attribute Certificate as an original
454            attCert['provenance'] = AttCert.origProvenance
455
456        else:           
457            # Set as a Mapped Certificate
458            #
459            # No roles found - user is not registered with this data centre
460            # Check for an externally provided certificate from another
461            # trusted data centre
462            if userAttCertFilePath:
463               
464                # Read externally provided certificate
465                try:
466                    userAttCert = AttCertRead(userAttCertFilePath)
467                   
468                except Exception, e:
469                    raise AttAuthorityError, \
470                            "Reading external Attribute Certificate: %s" % e                           
471            elif userAttCert:
472                # Allow input as a string but convert to
473                if isinstance(userAttCert, basestring):
474                    userAttCert = AttCertParse(userAttCert)
475                   
476                elif not isinstance(userAttCert, AttCert):
477                    raise AttAuthorityError, \
478                        "Expecting userAttCert as a string or AttCert type"         
479            else:
480                raise AttAuthorityAccessDenied, \
481                    "User \"%s\" is not registered " % attCert['holder'] + \
482                    "and no external attribute certificate is available " + \
483                    "to make a mapping."
484
485
486            # Check it's an original certificate - mapped certificates can't
487            # be used to make further mappings
488            if userAttCert.isMapped():
489                raise AttAuthorityError, \
490                    "External Attribute Certificate must have an " + \
491                    "original provenance in order to make further mappings."
492
493
494            # Check it's valid and signed
495            try:
496                # Give path to CA cert to allow check
497                userAttCert.certFilePathList = self.__prop['caCertFile']
498                userAttCert.isValid(raiseExcep=True)
499               
500            except Exception, e:
501                raise AttAuthorityError, \
502                            "Invalid Remote Attribute Certificate: " + str(e)       
503
504
505            # Check that's it's holder matches the candidate holder
506            # certificate DN
507            if userAttCert.holderDN != holderCert.dn:
508                raise AttAuthorityError, \
509                    "User certificate and Attribute Certificate DNs " + \
510                    'don\'t match: "%s" and "%s"' % (holderCert.dn, 
511                                                     userAttCert.holderDN)
512           
513 
514            # Get roles from external Attribute Certificate
515            trustedHostRoles = userAttCert.roles
516
517
518            # Map external roles to local ones
519            localRoles = self.mapRemoteRoles2LocalRoles(\
520                                                    userAttCert['issuerName'],
521                                                    trustedHostRoles)
522            if not localRoles:
523                raise AttAuthorityAccessDenied, \
524                    "No local roles mapped to the %s roles: %s" % \
525                    (userAttCert['issuerName'], ', '.join(trustedHostRoles))
526
527            attCert.addRoles(localRoles)
528           
529           
530            # Mark new Attribute Certificate as mapped
531            attCert.provenance = AttCert.mappedProvenance
532
533            # End set mapped certificate block
534
535        try:
536            # Digitally sign certificate using Attribute Authority's
537            # certificate and private key
538            attCert.applyEnvelopedSignature()
539           
540            # Check the certificate is valid
541            attCert.isValid(raiseExcep=True)
542           
543            # Write out certificate to keep a record of it for auditing
544            attCert.write()
545
546            # Return the cert to caller
547            return attCert
548       
549        except Exception, e:
550            raise AttAuthorityError, "New Attribute Certificate \"%s\": %s" %\
551                                    (attCert.filePath, e)
552       
553       
554    #_________________________________________________________________________     
555    def readProperties(self):
556
557        """Read the configuration properties for the Attribute Authority.
558        Nb. if parameters for the user roles interface change
559        loadUserRolesInterface() must be called explicitly in order for the
560        changes to take effect
561
562        @type propFilePath: string
563        @keyword propFilePath: file path to properties file
564        """
565
566
567        try:
568            tree = ElementTree.parse(self.__propFilePath)
569           
570        except IOError, ioErr:
571            raise AttAuthorityError, \
572                                "Error parsing properties file \"%s\": %s" % \
573                                (ioErr.filename, ioErr.strerror)
574
575       
576        aaProp = tree.getroot()
577        if aaProp is None:
578            raise AttAuthorityError, \
579            "Parsing properties file \"%s\": root element is not defined" % \
580            self.__propFilePath
581
582
583        # Copy properties from file into a dictionary
584        self.__prop = {}
585        invalidKeys = []
586        try:
587            for elem in aaProp:
588                if elem.tag in self.__class__.__validKeys:
589               
590                    # Make sure to leave password element contents unchanged
591                    if 'eyPwd' not in elem.tag and elem.text: 
592                        self.__prop[elem.tag] = \
593                                        os.path.expandvars(elem.text.strip())
594                    else:
595                        self.__prop[elem.tag] = elem.text
596                else:
597                    invalidKeys.append(elem.tag)
598               
599        except Exception, e:
600            raise AttAuthorityError, \
601                "Error parsing tag \"%s\" in properties file \"%s\": %s" % \
602                (elem.tag, self.__propFilePath, e)
603 
604        if invalidKeys != []:
605            raise AttAuthorityError, "The following properties file " + \
606                                     "elements are invalid: " + \
607                                     ', '.join(invalidKeys)
608 
609        # Ensure Certificate time parameters are converted to numeric type
610        self.__prop['attCertLifetime'] = float(self.__prop['attCertLifetime'])
611        self.__prop['attCertNotBeforeOff'] = \
612                                    float(self.__prop['attCertNotBeforeOff'])
613
614        # Likewise port number
615        self.__prop['portNum'] = int(self.__prop['portNum'])
616       
617       
618        # Check directory path
619        try:
620            dirList = os.listdir(self.__prop['attCertDir'])
621
622        except OSError, osError:
623            raise AttAuthorityError, \
624            'Invalid directory path Attribute Certificates store "%s": %s' % \
625                (self.__prop['attCertDir'], osError.strerror)
626       
627       
628    #_________________________________________________________________________     
629    def readMapConfig(self, mapConfigFilePath=None):
630        """Parse Map Configuration file.
631
632        @type mapConfigFilePath: string
633        @keyword mapConfigFilePath: file path for map configuration file.  If
634        omitted, it uses member variable __prop['mapConfigFile'].
635        """
636       
637        if mapConfigFilePath is not None:
638            if not isinstance(mapConfigFilePath, basestring):
639                raise AttAuthorityError, \
640                "Input Map Configuration file path must be a valid string."
641           
642            self.__prop['mapConfigFile'] = mapConfigFilePath
643
644
645        try:
646            tree = ElementTree.parse(self.__prop['mapConfigFile'])
647            rootElem = tree.getroot()
648           
649        except IOError, e:
650            raise AttAuthorityError, \
651                            "Error parsing properties file \"%s\": %s" % \
652                            (e.filename, e.strerror)
653           
654        except Exception, e:
655            raise AttAuthorityError, \
656                "Error parsing Map Configuration file: \"%s\": %s" % \
657                (self.__prop['mapConfigFile'], e)
658
659           
660        trustedElem = rootElem.findall('trusted')
661        if not trustedElem: 
662            # Make an empty list so that for loop block below is skipped
663            # without an error 
664            trustedElem = ()
665
666        # Dictionaries:
667        # 1) to hold all the data
668        self.__mapConfig = {'thisHost': {}, 'trustedHosts': {}}
669
670        # ... look-up
671        # 2) hosts corresponding to a given role and
672        # 3) roles of external data centre to this data centre
673        self.__localRole2TrustedHost = {}
674        self.__localRole2RemoteRole = {}
675        self.__remoteRole2LocalRole = {}
676
677
678        # Information about this host
679        try:
680            thisHostElem = rootElem.findall('thisHost')[0]
681           
682        except Exception, e:
683            raise AttAuthorityError, \
684            "\"thisHost\" tag not found in Map Configuration file \"%s\"" % \
685            self.__prop['mapConfigFile']
686
687        try:
688            hostName = thisHostElem.attrib.values()[0]
689           
690        except Exception, e:
691            raise AttAuthorityError, "\"name\" attribute of \"thisHost\" " + \
692                        "tag not found in Map Configuration file \"%s\"" % \
693                        self.__prop['mapConfigFile']
694
695
696        # hostname is also stored in the AA's config file in the 'name' tag. 
697        # Check the two match as the latter is copied into Attribute
698        # Certificates issued by this AA
699        #
700        # TODO: would be better to rationalise this so that the hostname is
701        # stored in one place only.
702        #
703        # P J Kershaw 14/06/06
704        if hostName != self.__prop['name']:
705            raise AttAuthorityError, "\"name\" attribute of \"thisHost\" " + \
706                "element in Map Configuration file doesn't match " + \
707                "\"name\" element in properties file."
708       
709        self.__mapConfig['thisHost'][hostName] = \
710        {
711            'loginURI':     thisHostElem.findtext('loginURI'),
712            'aaURI':         thisHostElem.findtext('aaURI')
713        }       
714       
715       
716        # Information about trusted hosts
717        for elem in trustedElem:
718
719            roleElem = elem.findall('role')
720            if not roleElem:
721                raise AttAuthorityError("\"role\" tag not found in \"%s\"" % \
722                                        self.__prop['mapConfigFile'])
723
724            try:
725                trustedHost = elem.attrib.values()[0]
726               
727            except Exception, e:
728                raise AttAuthorityError, \
729                                    "Error reading trusted host name: %s" % e
730
731           
732            # Add signatureFile and list of roles
733            #
734            # (Currently Optional) additional tag allows query of the URI
735            # where a user would normally login at the trusted host.  Added
736            # this feature to allow users to be forwarded to their home site
737            # if they are accessing a secure resource and are not
738            # authenticated
739            #
740            # P J Kershaw 25/05/06
741            self.__mapConfig['trustedHosts'][trustedHost] = \
742            {
743                'loginURI':     elem.findtext('loginURI'),
744                'aaURI':         elem.findtext('aaURI'),
745                'role':         [dict(i.items()) for i in roleElem]
746            }
747
748                   
749            self.__localRole2RemoteRole[trustedHost] = {}
750            self.__remoteRole2LocalRole[trustedHost] = {}
751           
752            for role in self.__mapConfig['trustedHosts'][trustedHost]['role']:
753
754                localRole = role['local']
755                remoteRole = role['remote']
756               
757                # Role to host look-up
758                if localRole in self.__localRole2TrustedHost:
759                   
760                    if trustedHost not in \
761                       self.__localRole2TrustedHost[localRole]:
762                        self.__localRole2TrustedHost[localRole].\
763                                                        append(trustedHost)                       
764                else:
765                    self.__localRole2TrustedHost[localRole] = [trustedHost]
766
767
768                # Trusted Host to local role and trusted host to trusted role
769                # map look-ups
770                try:
771                    self.__remoteRole2LocalRole[trustedHost][remoteRole].\
772                                                            append(localRole)                 
773                except KeyError:
774                    self.__remoteRole2LocalRole[trustedHost][remoteRole] = \
775                                                                [localRole]
776                   
777                try:
778                    self.__localRole2RemoteRole[trustedHost][localRole].\
779                                                            append(remoteRole)                 
780                except KeyError:
781                    self.__localRole2RemoteRole[trustedHost][localRole] = \
782                                                                [remoteRole]                 
783       
784       
785    #_________________________________________________________________________     
786    def userIsRegistered(self, userId):
787        """Check a particular user is registered with the Data Centre that the
788        Attribute Authority represents
789       
790        Nb. this method is not used internally by AttAuthority class
791       
792        @type userId: string
793        @param userId: user identity - could be a X500 Distinguished Name
794        @rtype: bool
795        @return: True if user is registered, False otherwise"""
796        return self.__userRoles.userIsRegistered(userId)
797       
798       
799    #_________________________________________________________________________     
800    def getRoles(self, userId):
801        """Get the roles available to the registered user identified userId.
802
803        @type dn: string
804        @param dn: user identifier - could be a X500 Distinguished Name
805        @return: list of roles for the given user ID"""
806
807        # Call to AAUserRoles derived class.  Each Attribute Authority
808        # should define it's own roles class derived from AAUserRoles to
809        # define how roles are accessed
810        try:
811            return self.__userRoles.getRoles(userId)
812
813        except Exception, e:
814            raise AttAuthorityError, "Getting user roles: %s" % e
815       
816       
817    #_________________________________________________________________________     
818    def __getHostInfo(self):
819        """Return the host that this Attribute Authority represents: its ID,
820        the user login URI and WSDL address.  Call this method via the
821        'hostInfo' property
822       
823        @rtype: dict
824        @return: dictionary of host information derived from the map
825        configuration"""
826       
827        return self.__mapConfig['thisHost']
828       
829    hostInfo = property(fget=__getHostInfo, 
830                        doc="Return information about this host")
831       
832       
833    #_________________________________________________________________________     
834    def getTrustedHostInfo(self, role=None):
835        """Return a dictionary of the hosts that have trust relationships
836        with this AA.  The dictionary is indexed by the trusted host name
837        and contains AA service, login URIs and the roles that map to the
838        given input local role.
839
840        @type role: string
841        @keyword role: if set, return trusted hosts that having a mapping set
842        for this role.  If no role is input, return all the AA's trusted hosts
843        with all their possible roles
844
845        @rtype: dict
846        @return: dictionary of the hosts that have trust relationships
847        with this AA.  It returns an empty dictionary if role isn't
848        recognised"""
849                                         
850        if not self.__mapConfig or not self.__localRole2RemoteRole:
851            # This Attribute Authority has no trusted hosts
852            raise AttAuthorityNoTrustedHosts, \
853                "The %s Attribute Authority has no trusted hosts" % \
854                self.__prop['name']
855
856
857        if role is None:
858            # No role input - return all trusted hosts with their WSDL URIs
859            # and the remote roles they map to
860            #
861            # Nb. {}.fromkeys([...]).keys() is a fudge to get unique elements
862            # from a list i.e. convert the list elements to a dict eliminating
863            # duplicated elements and convert the keys back into a list.
864            trustedHostInfo = dict(\
865            [\
866                (\
867                    k, \
868                    {
869                        'aaURI':       v['aaURI'], \
870                        'loginURI':    v['loginURI'], \
871                        'role':        {}.fromkeys(\
872                            [role['remote'] for role in v['role']]\
873                        ).keys()
874                    }
875                ) for k, v in self.__mapConfig['trustedHosts'].items()
876            ])
877
878        else:           
879            # Get trusted hosts for given input local role       
880            try:
881                trustedHosts = self.__localRole2TrustedHost[role]
882            except:
883                raise AttAuthorityNoMatchingRoleInTrustedHosts, \
884                    'None of the trusted hosts have a mapping to the ' + \
885                    'input role "%s"' % role
886   
887   
888            # Get associated WSDL URI and roles for the trusted hosts
889            # identified and return as a dictionary indexed by host name
890            trustedHostInfo = dict(\
891   [(\
892        host, \
893        {
894            'aaURI':     self.__mapConfig['trustedHosts'][host]['aaURI'],
895            'loginURI': self.__mapConfig['trustedHosts'][host]['loginURI'],
896            'role':     self.__localRole2RemoteRole[host][role]
897        }\
898    ) for host in trustedHosts])
899                         
900        return trustedHostInfo
901       
902       
903    #_________________________________________________________________________     
904    def mapRemoteRoles2LocalRoles(self, trustedHost, trustedHostRoles):
905        """Map roles of trusted hosts to roles for this data centre
906
907        @type trustedHost: string
908        @param trustedHost: name of external trusted data centre
909        @type trustedHostRoles: list
910        @param trustedHostRoles:   list of external roles to map
911        @return: list of mapped roles"""
912
913        if not self.__remoteRole2LocalRole:
914            raise AttAuthorityError, "Roles map is not set - ensure " + \
915                                     "readMapConfig() has been called."
916
917
918        # Check the host name is a trusted one recorded in the map
919        # configuration
920        if not self.__remoteRole2LocalRole.has_key(trustedHost):
921            return []
922
923        # Add local roles, skipping if no mapping is found
924        localRoles = []
925        for trustedRole in trustedHostRoles:
926            if trustedRole in self.__remoteRole2LocalRole[trustedHost]:
927                localRoles.extend(\
928                        self.__remoteRole2LocalRole[trustedHost][trustedRole])
929               
930        return localRoles
931       
932       
933    #_________________________________________________________________________     
934    def __newAttCertFilePath(self):
935        """Create a new unique attribute certificate file path
936       
937        @return: string file path"""
938       
939        attCertFd, attCertFilePath = \
940                   tempfile.mkstemp(suffix=self.__prop['attCertFileSfx'],
941                                    prefix=self.__prop['attCertFilePfx'],
942                                    dir=self.__prop['attCertDir'],
943                                    text=True)
944
945        # The file is opened - close using the file descriptor returned in the
946        # first element of the tuple
947        os.close(attCertFd)
948
949        # The file path is the 2nd element
950        return attCertFilePath
951
952
953#_____________________________________________________________________________
954class AAUserRolesError(Exception):
955    """Exception handling for NDG Attribute Authority User Roles interface
956    class."""
957
958
959#_____________________________________________________________________________
960class AAUserRoles:
961    """An abstract base class to define the user roles interface to an
962    Attribute Authority.
963
964    Each NDG data centre should implement a derived class which implements
965    the way user roles are provided to its representative Attribute Authority.
966   
967    Roles are expected to indexed by user Distinguished Name (DN).  They
968    could be stored in a database or file."""
969
970    # User defined class may wish to specify a URI for a database interface or
971    # path for a user roles configuration file
972    def __init__(self, dbURI=None, filePath=None):
973        """User Roles abstract base class - derive from this class to define
974        roles interface to Attribute Authority
975       
976        @type dbURI: string
977        @keyword dbURI: database connection URI
978        @type filePath: string
979        @keyword filePath: file path for properties file containing settings
980        """
981        raise NotImplementedError, \
982            self.__init__.__doc__.replace('\n       ','')
983
984
985    def userIsRegistered(self, userId):
986        """Derived method should return True if user is known otherwise
987        False
988       
989        Nb. this method is not used by AttAuthority class and so does NOT need
990        to be implemented in a derived class.
991       
992        @type userId: string
993        @param userId: user Distinguished Name to look up.
994        @rtype: bool
995        @return: True if user is registered, False otherwise"""
996        raise NotImplementedError, \
997            self.userIsRegistered.__doc__.replace('\n       ','')
998
999
1000    def getRoles(self, userId):
1001        """Derived method should return the roles for the given user's
1002        Id or else raise an exception
1003       
1004        @type userId: string
1005        @param userId: user identity e.g. user Distinguished Name
1006        @rtype: list
1007        @return: list of roles for the given user ID"""
1008        raise NotImplementedError, \
1009            self.getRoles.__doc__.replace('\n       ','')
1010                         
Note: See TracBrowser for help on using the repository browser.