source: TI12-security/trunk/python/ndg.security.common/ndg/security/common/AttAuthorityClient/__init__.py @ 1713

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndg.security.common/ndg/security/common/AttAuthorityClient/__init__.py@1713
Revision 1713, 12.6 KB checked in by pjkersha, 14 years ago (diff)

AttAuthorityClient? package:

  • moved AttAuthorityClient? module to package -> init.py
  • added AttAuthority_services* files generated from wsdl2py
  • README contains record of wsdl2py command used.
Line 
1#!/usr/bin/env python
2"""NDG Security Attribute Authority client - client interface classes to the
3Attribute Authority.  These have been separated from their
4original location in the SecurityClient since they have the
5unusual place of being required by both client and server
6NDG security packages.  For the server side they are required
7as the CredWallet invoked by the Session Manager acts as a
8client to Attribute Authorities when negotiating the required
9Attribute Certificate.
10
11Make requests for Attribute Certificates used for authorisation
12
13NERC Data Grid Project
14
15P J Kershaw 17/11/06
16
17Copyright (C) 2006 CCLRC & NERC
18
19This software may be distributed under the terms of the Q Public License,
20version 1.0 or later.
21"""
22#_____________________________________________________________________________
23class AttAuthorityClientError(Exception):
24    """Exception handling for SessionClient class"""
25    pass
26
27
28#_____________________________________________________________________________
29class AttAuthorityClient(object):
30   
31    #_________________________________________________________________________
32    def __init__(self, 
33                 aaWSDL=None, 
34                 aaPubKeyFilePath=None,
35                 clntPubKeyFilePath=None,
36                 clntPriKeyFilePath=None,
37                 traceFile=None):
38        """
39        aaWSDL:                  WSDL URI for Attribute Authority WS.  Setting
40                                 it will set the Service Proxy
41        aaPubKeyFilePath:   
42                                 Public key of Attribute Authority used to
43                                 encrypt the outgoing message if required -
44                                 set as a path on the local file system or as
45                                 a URI
46        clntPubKeyFilePath:      Public key of client.  This is passed to the
47                                 Attribute Authority so that it can encrypt
48                                 responses.  WARNING: if not set, responses
49                                 are returned as clear text
50        clntPriKeyFilePath:      Private key of client.  If clntPubKeyFilePath
51                                 is set, the private key is needed to decrypt
52                                 the response from the Attribute Authority
53        traceFile:               set to file object such as sys.stderr to
54                                 give extra WS debug information"""
55
56        self.__aaSrv = None
57        self.__aaWSDL = None
58        self.__aaPubKeyFilePath = None
59        self.__aaPubKeyFilePath = None
60        self.__clntPubKeyFilePath = None
61        self.__clntPubKey = None
62        self.__clntPriKeyFilePath = None
63       
64        self.__aaPubKeyTempFile = None
65       
66       
67        if aaWSDL:
68            self.__setAAwsdl(aaWSDL)
69           
70        if aaPubKeyFilePath:
71            self.__setAApubKeyFilePath(aaPubKeyFilePath)
72           
73        if clntPriKeyFilePath:
74            self.__setClntPriKeyFilePath(clntPriKeyFilePath)
75           
76        if clntPubKeyFilePath:
77            if clntPriKeyFilePath is None:
78                raise AttAuthorityClientError, \
79                    "A Client private key file is required as well a " + \
80                    "public key"
81                   
82            self.__setClntPubKeyFilePath(clntPubKeyFilePath)
83
84           
85        self.__traceFile = traceFile
86
87         
88        # Instantiate Attribute Authority WS proxy
89        if self.__aaWSDL:
90            self.serviceProxy()
91       
92
93    #_________________________________________________________________________
94    def __setAAwsdl(self, aaWSDL):
95       
96        if not isinstance(aaWSDL, basestring):
97            raise AttAuthorityClientError, \
98                        "Attribute Authority WSDL URI must be a valid string"
99       
100        self.__aaWSDL = aaWSDL
101       
102    aaWSDL = property(fset=__setAAwsdl,doc="Set Attribute Authority WSDL URI")
103
104
105    #_________________________________________________________________________
106    def __setAApubKeyFilePath(self, aaPubKeyFilePath):
107       
108        if not isinstance(aaPubKeyFilePath, basestring):
109            raise AttAuthorityClientError, \
110                "Attribute Authority public key URI must be a valid string"
111       
112        self.__aaPubKeyFilePath = aaPubKeyFilePath
113       
114    aaPubKeyFilePath = property(fset=__setAApubKeyFilePath,
115                                doc="Set Attribute Authority public key URI")
116
117 
118    #_________________________________________________________________________
119    def __setClntPubKeyFilePath(self, clntPubKeyFilePath):
120       
121        if not isinstance(clntPubKeyFilePath, basestring):
122            raise AttAuthorityClientError(\
123                "Client public key file path must be a valid string")
124       
125        self.__clntPubKeyFilePath = clntPubKeyFilePath
126        try:
127            self.__clntPubKey = open(self.__clntPubKeyFilePath).read()
128           
129        except IOError, (errNo, errMsg):
130            raise AttAuthorityClientError(\
131                    "Reading certificate file \"%s\": %s" % \
132                    (self.__clntPubKeyFilePath, errMsg))
133                               
134        except Exception, e:
135            raise AttAuthorityClientError, \
136                                    "Reading certificate file \"%s\": %s" % \
137                                    (self.__clntPubKeyFilePath, str(e))
138       
139    clntPubKeyFilePath = property(fset=__setClntPubKeyFilePath,
140                                  doc="File path for client public key")
141
142 
143    #_________________________________________________________________________
144    def __setClntPriKeyFilePath(self, clntPriKeyFilePath):
145       
146        if not isinstance(clntPriKeyFilePath, basestring):
147            raise AttAuthorityClientError(\
148                "Client public key file path must be a valid string")
149       
150        self.__clntPriKeyFilePath = clntPriKeyFilePath
151       
152    clntPriKeyFilePath = property(fset=__setClntPriKeyFilePath,
153                                  doc="File path for client private key")
154
155
156    #_________________________________________________________________________
157    def __getAttAuthorityPubKey(self):
158        """Retrieve the public key from the URI"""
159       
160        # Don't proceed unless URI was set - user may have set public key via
161        # aaPubKeyFilePath instead
162        if self.__aaPubKeyFilePath is not None:
163            return
164               
165        try:
166            self.__aaPubKeyTempFile = tempfile.NamedTemporaryFile()
167           
168            pubKey = self.getPubKey()
169            open(self.__aaPubKeyTempFile.name, "w").write(pubKey)
170           
171            self.__aaPubKeyFilePath = self.__aaPubKeyTempFile.name
172           
173        except IOError, (errNo, errMsg):
174            raise AttAuthorityClientError, \
175                                "Writing public key to temp \"%s\": %s" % \
176                                (self.__aaPubKeyTempFile.name, errMsg)                                                                     
177        except Exception, e:
178            raise AttAuthorityClientError, "Retrieving Attribute Authority "+\
179                                          "public key: %s" % str(e)
180   
181       
182    #_________________________________________________________________________
183    def serviceProxy(self, aaWSDL=None):
184        """Set the WS proxy for the Attribute Authority"""
185        if aaWSDL:
186            self.__setAAwsdl(aaWSDL)
187
188        try:
189            self.__aaSrv = ServiceProxy(self.__aaWSDL, 
190                                        use_wsdl=True, 
191                                        tracefile=self.__traceFile)
192        except HTTPResponse, e:
193            raise AttAuthorityClientError, \
194                "Error initialising WSDL Service Proxy for \"%s\": %s %s" % \
195                (self.__aaWSDL, e.status, e.reason)
196           
197        except Exception, e:
198            raise AttAuthorityClientError, \
199                "Initialising WSDL Service Proxy for \"%s\": %s" % \
200                 (self.__aaWSDL, str(e))
201
202                                   
203    #_________________________________________________________________________
204    def getHostInfo(self, clntPriKeyPwd=None):
205        """Get host information for the data provider which the
206        Attribute Authority represents
207       
208        """
209
210        # If Public key was not set, retrieve from server
211        self.__getAttAuthorityPubKey()
212           
213        try:   
214            hostInfoReq = aaIO.HostInfoReq(encrCert=self.__clntPubKey,
215                                encrPubKeyFilePath=self.__aaPubKeyFilePath) 
216
217            # Pass encrypted request
218            resp = self.__aaSrv.getHostInfo(hostInfoReq=hostInfoReq())
219                       
220            hostInfoResp = aaIO.HostInfoResp(\
221                                xmlTxt=resp['hostInfoResp'],
222                                encrPriKeyFilePath=self.__clntPriKeyFilePath,
223                                encrPriKeyPwd=clntPriKeyPwd)           
224        except Exception, e:
225            raise AttAuthorityClientError, "Error: " + str(e)
226 
227                           
228        if 'errMsg' in hostInfoResp and hostInfoResp['errMsg']:
229            raise AttAuthorityClientError, hostInfoResp['errMsg']
230
231        return hostInfoResp['thisHost']
232
233                                   
234    #_________________________________________________________________________
235    def getTrustedHostInfo(self, role=None, clntPriKeyPwd=None):
236        """Get list of trusted hosts for an Attribute Authority
237       
238        """
239
240        # If Public key was not set, retrieve from server
241        self.__getAttAuthorityPubKey()
242           
243        try:   
244            trustedHostInfoReq = aaIO.TrustedHostInfoReq(role=role, 
245                                encrCert=self.__clntPubKey,
246                                encrPubKeyFilePath=self.__aaPubKeyFilePath) 
247
248            # Pass encrypted request
249            resp = self.__aaSrv.getTrustedHostInfo(\
250                                    trustedHostInfoReq=trustedHostInfoReq())
251                       
252            trustedHostInfoResp = aaIO.TrustedHostInfoResp(\
253                                xmlTxt=resp['trustedHostInfoResp'],
254                                encrPriKeyFilePath=self.__clntPriKeyFilePath,
255                                encrPriKeyPwd=clntPriKeyPwd)           
256        except Exception, e:
257            raise AttAuthorityClientError, "Error: " + str(e)
258 
259                           
260        if 'errMsg' in trustedHostInfoResp and trustedHostInfoResp['errMsg']:
261            raise AttAuthorityClientError, trustedHostInfoResp['errMsg']
262
263        return trustedHostInfoResp['trustedHosts']
264   
265
266    #_________________________________________________________________________
267    def reqAuthorisation(self, 
268                         proxyCert, 
269                         userAttCert=None, 
270                         clntPriKeyPwd=None):
271        """Request authorisation from NDG Attribute Authority Web Service."""
272
273
274        # If Public key was not set, retrieve from server
275        self.__getAttAuthorityPubKey()
276
277
278        try:   
279            authzReq = aaIO.AuthorisationReq(proxyCert=proxyCert,
280                                 userAttCert=userAttCert,
281                                 encrCert=self.__clntPubKey,
282                                 encrPubKeyFilePath=self.__aaPubKeyFilePath) 
283
284            resp = self.__aaSrv.reqAuthorisation(authorisationReq=authzReq())
285                                     
286            authzResp=aaIO.AuthorisationResp(xmlTxt=resp['authorisationResp'],
287                                encrPriKeyFilePath=self.__clntPriKeyFilePath,
288                                encrPriKeyPwd=clntPriKeyPwd)           
289        except Exception, e:
290            raise AttAuthorityClientError, "Error: " + str(e)
291           
292        if authzResp['statCode'] == authzResp.accessError:
293            raise AttAuthorityClientError, authzResp['errMsg']
294       
295        return authzResp
296
297                                   
298    #_________________________________________________________________________
299    def getPubKey(self):
300        """Retrieve the public key of the Session Manager"""
301       
302        try:   
303            pubKeyReq = aaIO.PubKeyReq() 
304
305            # Pass request
306            resp = self.__aaSrv.getPubKey(pubKeyReq=pubKeyReq())
307                       
308            pubKeyResp = aaIO.PubKeyResp(xmlTxt=resp['pubKeyResp'])
309                           
310            if 'errMsg' in pubKeyResp and pubKeyResp['errMsg']:
311                raise AttAuthorityClientError(pubKeyResp['errMsg'])
312           
313            return pubKeyResp['pubKey']
314       
315        except Exception, e:
316            raise AttAuthorityClientError, \
317                                    "Error retrieving public key: " + str(e) 
Note: See TracBrowser for help on using the repository browser.