Merge branch 'master' into senslab2
[sfa.git] / sfa / client / sfaclientlib.py
1 # Thierry Parmentelat -- INRIA
2 #
3 # a minimal library for writing "lightweight" SFA clients
4 #
5
6 # xxx todo
7 # this library should probably check for the expiration date of the various
8 # certificates and automatically retrieve fresh ones when expired
9
10 import sys
11 import os,os.path
12 from datetime import datetime
13
14 import sfa.util.sfalogging
15 # importing sfa.utils.faults does pull a lot of stuff 
16 # OTOH it's imported from Certificate anyways, so..
17 from sfa.util.faults import RecordNotFound
18
19 from sfa.client.sfaserverproxy import SfaServerProxy
20
21 # see optimizing dependencies below
22 from sfa.trust.certificate import Keypair, Certificate
23 from sfa.trust.credential import Credential
24 ########## 
25 # a helper class to implement the bootstrapping of crypto. material
26 # assuming we are starting from scratch on the client side 
27 # what's needed to complete a full slice creation cycle
28 # (**) prerequisites: 
29 #  (*) a local private key 
30 #  (*) the corresp. public key in the registry 
31 # (**) step1: a self-signed certificate
32 #      default filename is <hrn>.sscert
33 # (**) step2: a user credential
34 #      obtained at the registry with GetSelfCredential
35 #      using the self-signed certificate as the SSL cert
36 #      default filename is <hrn>.user.cred
37 # (**) step3: a registry-provided certificate (i.e. a GID)
38 #      obtained at the registry using Resolve
39 #      using the step2 credential as credential
40 #      default filename is <hrn>.user.gid
41 #
42 # From that point on, the GID is used as the SSL certificate
43 # and the following can be done
44 #
45 # (**) retrieve a slice (or authority) credential 
46 #      obtained at the registry with GetCredential
47 #      using the (step2) user-credential as credential
48 #      default filename is <hrn>.<type>.cred
49 # (**) retrieve a slice (or authority) GID 
50 #      obtained at the registry with Resolve
51 #      using the (step2) user-credential as credential
52 #      default filename is <hrn>.<type>.cred
53
54
55 ########## Implementation notes
56 #
57 # (*) decorators
58 #
59 # this implementation is designed as a guideline for 
60 # porting to other languages
61 #
62 # the decision to go for decorators aims at focusing 
63 # on the core of what needs to be done when everything
64 # works fine, and to take caching and error management 
65 # out of the way
66
67 # for non-pythonic developers, it should be enough to 
68 # implement the bulk of this code, namely the _produce methods
69 # and to add caching and error management by whichever means 
70 # is available, including inline 
71 #
72 # (*) self-signed certificates
73
74 # still with other languages in mind, we've tried to keep the
75 # dependencies to the rest of the code as low as possible
76
77 # however this still relies on the sfa.trust.certificate module
78 # for the initial generation of a self-signed-certificate that
79 # is associated to the user's ssh-key
80 # (for user-friendliness, and for smooth operations with planetlab, 
81 # the usage model is to reuse an existing keypair)
82
83 # there might be a more portable, i.e. less language-dependant way, to
84 # implement this step by exec'ing the openssl command a known
85 # successful attempt at this approach that worked for Java is
86 # documented below
87 # http://nam.ece.upatras.gr/fstoolkit/trac/wiki/JavaSFAClient
88 #
89 ####################
90
91 class SfaClientException (Exception): pass
92
93 class SfaClientBootstrap:
94
95     # dir is mandatory but defaults to '.'
96     def __init__ (self, user_hrn, registry_url, dir=None, 
97                   verbose=False, timeout=None, logger=None):
98         self.hrn=user_hrn
99         self.registry_url=registry_url
100         if dir is None: dir="."
101         self.dir=dir
102         self.verbose=verbose
103         self.timeout=timeout
104         # default for the logger is to use the global sfa logger
105         if logger is None: 
106             logger = sfa.util.sfalogging.logger
107         self.logger=logger
108
109     ######################################## *_produce methods
110     ### step1
111     # unconditionnally create a self-signed certificate
112     def self_signed_cert_produce (self,output):
113         self.assert_private_key()
114         private_key_filename = self.private_key_filename()
115         keypair=Keypair(filename=private_key_filename)
116         self_signed = Certificate (subject = self.hrn)
117         self_signed.set_pubkey (keypair)
118         self_signed.set_issuer (keypair, self.hrn)
119         self_signed.sign ()
120         self_signed.save_to_file (output)
121         self.logger.debug("SfaClientBootstrap: Created self-signed certificate for %s in %s"%\
122                               (self.hrn,output))
123         return output
124
125     ### step2 
126     # unconditionnally retrieve my credential (GetSelfCredential)
127     # we always use the self-signed-cert as the SSL cert
128     def my_credential_produce (self, output):
129         self.assert_self_signed_cert()
130         certificate_filename = self.self_signed_cert_filename()
131         certificate_string = self.plain_read (certificate_filename)
132         self.assert_private_key()
133         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
134                                          certificate_filename)
135         credential_string=registry_proxy.GetSelfCredential (certificate_string, self.hrn, "user")
136         self.plain_write (output, credential_string)
137         self.logger.debug("SfaClientBootstrap: Wrote result of GetSelfCredential in %s"%output)
138         return output
139
140     ### step3
141     # unconditionnally retrieve my GID - use the general form 
142     def my_gid_produce (self,output):
143         return self.gid_produce (output, self.hrn, "user")
144
145     ### retrieve any credential (GetCredential) unconditionnal form
146     # we always use the GID as the SSL cert
147     def credential_produce (self, output, hrn, type):
148         self.assert_my_gid()
149         certificate_filename = self.my_gid_filename()
150         self.assert_private_key()
151         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
152                                          certificate_filename)
153         self.assert_my_credential()
154         my_credential_string = self.my_credential_string()
155         credential_string=registry_proxy.GetCredential (my_credential_string, hrn, type)
156         self.plain_write (output, credential_string)
157         self.logger.debug("SfaClientBootstrap: Wrote result of GetCredential in %s"%output)
158         return output
159
160     def slice_credential_produce (self, output, hrn):
161         return self.credential_produce (output, hrn, "slice")
162
163     def authority_credential_produce (self, output, hrn):
164         return self.credential_produce (output, hrn, "authority")
165
166     ### retrieve any gid (Resolve) - unconditionnal form
167     # use my GID when available as the SSL cert, otherwise the self-signed
168     def gid_produce (self, output, hrn, type ):
169         try:
170             self.assert_my_gid()
171             certificate_filename = self.my_gid_filename()
172         except:
173             self.assert_self_signed_cert()
174             certificate_filename = self.self_signed_cert_filename()
175             
176         self.assert_private_key()
177         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
178                                          certificate_filename)
179         credential_string=self.plain_read (self.my_credential())
180         records = registry_proxy.Resolve (hrn, credential_string)
181         records=[record for record in records if record['type']==type]
182         if not records:
183             raise RecordNotFound, "hrn %s (%s) unknown to registry %s"%(hrn,type,self.registry_url)
184         record=records[0]
185         self.plain_write (output, record['gid'])
186         self.logger.debug("SfaClientBootstrap: Wrote GID for %s (%s) in %s"% (hrn,type,output))
187         return output
188
189
190     # Returns True if credential file is valid. Otherwise return false.
191     def validate_credential(self, filename):
192         valid = True
193         cred = Credential(filename=filename)
194         # check if credential is expires
195         if cred.get_expiration() < datetime.now():
196             valid = False
197         return valid
198     
199
200     #################### public interface
201     
202     # return my_gid, run all missing steps in the bootstrap sequence
203     def bootstrap_my_gid (self):
204         self.self_signed_cert()
205         self.my_credential()
206         return self.my_gid()
207
208     # once we've bootstrapped we can use this object to issue any other SFA call
209     # always use my gid
210     def server_proxy (self, url):
211         self.assert_my_gid()
212         return SfaServerProxy (url, self.private_key_filename(), self.my_gid_filename(),
213                                verbose=self.verbose, timeout=self.timeout)
214
215     # now in some cases the self-signed is enough
216     def server_proxy_simple (self, url):
217         self.assert_self_signed_cert()
218         return SfaServerProxy (url, self.private_key_filename(), self.self_signed_cert_filename(),
219                                verbose=self.verbose, timeout=self.timeout)
220
221     # this method can optionnally be invoked to ensure proper
222     # installation of the private key that belongs to this user
223     # installs private_key in working dir with expected name -- preserve mode
224     # typically user_private_key would be ~/.ssh/id_rsa
225     # xxx should probably check the 2 files are identical
226     def init_private_key_if_missing (self, user_private_key):
227         private_key_filename=self.private_key_filename()
228         if not os.path.isfile (private_key_filename):
229             key=self.plain_read(user_private_key)
230             self.plain_write(private_key_filename, key)
231             os.chmod(private_key_filename,os.stat(user_private_key).st_mode)
232             self.logger.debug("SfaClientBootstrap: Copied private key from %s into %s"%\
233                                   (user_private_key,private_key_filename))
234         
235     #################### private details
236     # stupid stuff
237     def fullpath (self, file): return os.path.join (self.dir,file)
238
239     # the expected filenames for the various pieces
240     def private_key_filename (self): 
241         return self.fullpath ("%s.pkey"%self.hrn)
242     def self_signed_cert_filename (self): 
243         return self.fullpath ("%s.sscert"%self.hrn)
244     def my_credential_filename (self):
245         return self.credential_filename (self.hrn, "user")
246     def credential_filename (self, hrn, type): 
247         return self.fullpath ("%s.%s.cred"%(hrn,type))
248     def slice_credential_filename (self, hrn): 
249         return self.credential_filename(hrn,'slice')
250     def authority_credential_filename (self, hrn): 
251         return self.credential_filename(hrn,'authority')
252     def my_gid_filename (self):
253         return self.gid_filename (self.hrn, "user")
254     def gid_filename (self, hrn, type): 
255         return self.fullpath ("%s.%s.gid"%(hrn,type))
256     
257
258 # optimizing dependencies
259 # originally we used classes GID or Credential or Certificate 
260 # like e.g. 
261 #        return Credential(filename=self.my_credential()).save_to_string()
262 # but in order to make it simpler to other implementations/languages..
263     def plain_read (self, filename):
264         infile=file(filename,"r")
265         result=infile.read()
266         infile.close()
267         return result
268
269     def plain_write (self, filename, contents):
270         outfile=file(filename,"w")
271         result=outfile.write(contents)
272         outfile.close()
273
274     def assert_filename (self, filename, kind):
275         if not os.path.isfile (filename):
276             raise IOError,"Missing %s file %s"%(kind,filename)
277         return True
278         
279     def assert_private_key (self): return self.assert_filename (self.private_key_filename(),"private key")
280     def assert_self_signed_cert (self): return self.assert_filename (self.self_signed_cert_filename(),"self-signed certificate")
281     def assert_my_credential (self): return self.assert_filename (self.my_credential_filename(),"user's credential")
282     def assert_my_gid (self): return self.assert_filename (self.my_gid_filename(),"user's GID")
283
284
285     # decorator to make up the other methods
286     def get_or_produce (filename_method, produce_method, validate_method=None):
287         # default validator returns true
288         def wrap (f):
289             def wrapped (self, *args, **kw):
290                 filename=filename_method (self, *args, **kw)
291                 if os.path.isfile ( filename ):
292                     if not validate_method:
293                         return filename
294                     elif validate_method(self, filename): 
295                         return filename
296                     else:
297                         # remove invalid file
298                         self.logger.warning ("Removing %s - has expired"%filename)
299                         os.unlink(filename) 
300                 try:
301                     produce_method (self, filename, *args, **kw)
302                     return filename
303                 except IOError:
304                     raise 
305                 except :
306                     error = sys.exc_info()[:2]
307                     message="Could not produce/retrieve %s (%s -- %s)"%\
308                         (filename,error[0],error[1])
309                     self.logger.log_exc(message)
310                     raise Exception, message
311             return wrapped
312         return wrap
313
314     @get_or_produce (self_signed_cert_filename, self_signed_cert_produce)
315     def self_signed_cert (self): pass
316
317     @get_or_produce (my_credential_filename, my_credential_produce, validate_credential)
318     def my_credential (self): pass
319
320     @get_or_produce (my_gid_filename, my_gid_produce)
321     def my_gid (self): pass
322
323     @get_or_produce (credential_filename, credential_produce, validate_credential)
324     def credential (self, hrn, type): pass
325
326     @get_or_produce (slice_credential_filename, slice_credential_produce, validate_credential)
327     def slice_credential (self, hrn): pass
328
329     @get_or_produce (authority_credential_filename, authority_credential_produce, validate_credential)
330     def authority_credential (self, hrn): pass
331
332     @get_or_produce (gid_filename, gid_produce)
333     def gid (self, hrn, type ): pass
334
335
336     # get the credentials as strings, for inserting as API arguments
337     def my_credential_string (self): 
338         self.my_credential()
339         return self.plain_read(self.my_credential_filename())
340     def slice_credential_string (self, hrn): 
341         self.slice_credential(hrn)
342         return self.plain_read(self.slice_credential_filename(hrn))
343     def authority_credential_string (self, hrn): 
344         self.authority_credential(hrn)
345         return self.plain_read(self.authority_credential_filename(hrn))
346
347     # for consistency
348     def private_key (self):
349         self.assert_private_key()
350         return self.private_key_filename()