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