bc4a1d141bcd016abdff460cdeb7ee5a064b9851
[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 import subprocess
13 from datetime import datetime
14 from sfa.util.xrn import Xrn
15
16 import sfa.util.sfalogging
17 # importing sfa.utils.faults does pull a lot of stuff 
18 # OTOH it's imported from Certificate anyways, so..
19 from sfa.util.faults import RecordNotFound
20
21 from sfa.client.sfaserverproxy import SfaServerProxy
22
23 # see optimizing dependencies below
24 from sfa.trust.certificate import Keypair, Certificate
25 from sfa.trust.credential import Credential
26 from sfa.trust.gid import GID
27 ########## 
28 # a helper class to implement the bootstrapping of cryptoa. material
29 # assuming we are starting from scratch on the client side 
30 # what's needed to complete a full slice creation cycle
31 # (**) prerequisites: 
32 #  (*) a local private key 
33 #  (*) the corresp. public key in the registry 
34 # (**) step1: a self-signed certificate
35 #      default filename is <hrn>.sscert
36 # (**) step2: a user credential
37 #      obtained at the registry with GetSelfCredential
38 #      using the self-signed certificate as the SSL cert
39 #      default filename is <hrn>.user.cred
40 # (**) step3: a registry-provided certificate (i.e. a GID)
41 #      obtained at the registry using Resolve
42 #      using the step2 credential as credential
43 #      default filename is <hrn>.user.gid
44 #
45 # From that point on, the GID is used as the SSL certificate
46 # and the following can be done
47 #
48 # (**) retrieve a slice (or authority) credential 
49 #      obtained at the registry with GetCredential
50 #      using the (step2) user-credential as credential
51 #      default filename is <hrn>.<type>.cred
52 # (**) retrieve a slice (or authority) GID 
53 #      obtained at the registry with Resolve
54 #      using the (step2) user-credential as credential
55 #      default filename is <hrn>.<type>.cred
56 #
57 # (**) additionnally, it might make sense to upgrade a GID file 
58 # into a pkcs12 certificate usable in a browser
59 # this bundled format allows for embedding the private key
60
61
62 ########## Implementation notes
63 #
64 # (*) decorators
65 #
66 # this implementation is designed as a guideline for 
67 # porting to other languages
68 #
69 # the decision to go for decorators aims at focusing 
70 # on the core of what needs to be done when everything
71 # works fine, and to take caching and error management 
72 # out of the way
73
74 # for non-pythonic developers, it should be enough to 
75 # implement the bulk of this code, namely the _produce methods
76 # and to add caching and error management by whichever means 
77 # is available, including inline 
78 #
79 # (*) self-signed certificates
80
81 # still with other languages in mind, we've tried to keep the
82 # dependencies to the rest of the code as low as possible
83
84 # however this still relies on the sfa.trust.certificate module
85 # for the initial generation of a self-signed-certificate that
86 # is associated to the user's ssh-key
87 # (for user-friendliness, and for smooth operations with planetlab, 
88 # the usage model is to reuse an existing keypair)
89
90 # there might be a more portable, i.e. less language-dependant way, to
91 # implement this step by exec'ing the openssl command.
92 # a known successful attempt at this approach that worked 
93 # for Java is documented below
94 # http://nam.ece.upatras.gr/fstoolkit/trac/wiki/JavaSFAClient
95 #
96 # (*) pkcs12
97
98 # the implementation of the pkcs12 wrapping, which is a late addition,
99 # is done through direct calls to openssl
100 #
101 ####################
102
103 class SfaClientException (Exception): pass
104
105 class SfaClientBootstrap:
106
107     # dir is mandatory but defaults to '.'
108     def __init__ (self, user_hrn, registry_url, dir=None, 
109                   verbose=False, timeout=None, logger=None):
110         self.hrn=user_hrn
111         self.registry_url=registry_url
112         if dir is None: dir="."
113         self.dir=dir
114         self.verbose=verbose
115         self.timeout=timeout
116         # default for the logger is to use the global sfa logger
117         if logger is None: 
118             logger = sfa.util.sfalogging.logger
119         self.logger=logger
120
121     ######################################## *_produce methods
122     ### step1
123     # unconditionnally create a self-signed certificate
124     def self_signed_cert_produce (self, output):
125         self.assert_private_key()
126         private_key_filename = self.private_key_filename()
127         keypair=Keypair(filename=private_key_filename)
128         self_signed = Certificate (subject = self.hrn)
129         self_signed.set_pubkey (keypair)
130         self_signed.set_issuer (keypair, self.hrn)
131         self_signed.sign ()
132         self_signed.save_to_file (output)
133         self.logger.debug("SfaClientBootstrap: Created self-signed certificate for %s in %s"%\
134                               (self.hrn, output))
135         return output
136
137     ### step2 
138     # unconditionnally retrieve my credential (GetSelfCredential)
139     # we always use the self-signed-cert as the SSL cert
140     def my_credential_produce (self, output):
141         self.assert_self_signed_cert()
142         certificate_filename = self.self_signed_cert_filename()
143         certificate_string = self.plain_read (certificate_filename)
144         self.assert_private_key()
145         registry_proxy = SfaServerProxy (self.registry_url,
146                                          self.private_key_filename(),
147                                          certificate_filename)
148         try:
149             credential_string=registry_proxy.GetSelfCredential (certificate_string, self.hrn, "user")
150         except:
151             # some urns hrns may replace non hierarchy delimiters '.' with an '_' instead of escaping the '.'
152             hrn = Xrn(self.hrn).get_hrn().replace('\.', '_') 
153             credential_string=registry_proxy.GetSelfCredential (certificate_string, hrn, "user")
154         self.plain_write (output, credential_string)
155         self.logger.debug("SfaClientBootstrap: Wrote result of GetSelfCredential in %s"%output)
156         return output
157
158     ### step3
159     # unconditionnally retrieve my GID - use the general form 
160     def my_gid_produce (self,output):
161         return self.gid_produce (output, self.hrn, "user")
162
163     ### retrieve any credential (GetCredential) unconditionnal form
164     # we always use the GID as the SSL cert
165     def credential_produce (self, output, hrn, type):
166         self.assert_my_gid()
167         certificate_filename = self.my_gid_filename()
168         self.assert_private_key()
169         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
170                                          certificate_filename)
171         self.assert_my_credential()
172         my_credential_string = self.my_credential_string()
173         credential_string=registry_proxy.GetCredential (my_credential_string, hrn, type)
174         self.plain_write (output, credential_string)
175         self.logger.debug("SfaClientBootstrap: Wrote result of GetCredential in %s"%output)
176         return output
177
178     def slice_credential_produce (self, output, hrn):
179         return self.credential_produce (output, hrn, "slice")
180
181     def authority_credential_produce (self, output, hrn):
182         return self.credential_produce (output, hrn, "authority")
183
184     ### retrieve any gid (Resolve) - unconditionnal form
185     # use my GID when available as the SSL cert, otherwise the self-signed
186     def gid_produce (self, output, hrn, type ):
187         try:
188             self.assert_my_gid()
189             certificate_filename = self.my_gid_filename()
190         except:
191             self.assert_self_signed_cert()
192             certificate_filename = self.self_signed_cert_filename()
193             
194         self.assert_private_key()
195         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
196                                          certificate_filename)
197         credential_string=self.plain_read (self.my_credential())
198         records = registry_proxy.Resolve (hrn, credential_string)
199         records=[record for record in records if record['type']==type]
200         if not records:
201             raise RecordNotFound, "hrn %s (%s) unknown to registry %s"%(hrn,type,self.registry_url)
202         record=records[0]
203         self.plain_write (output, record['gid'])
204         self.logger.debug("SfaClientBootstrap: Wrote GID for %s (%s) in %s"% (hrn,type,output))
205         return output
206
207
208 # http://trac.myslice.info/wiki/MySlice/Developer/SFALogin
209 ### produce a pkcs12 bundled certificate from GID and private key
210 # xxx for now we put a hard-wired password that's just, well, 'password'
211 # when leaving this empty on the mac, result can't seem to be loaded in keychain..
212     def my_pkcs12_produce (self, filename):
213         password=raw_input("Enter password for p12 certificate: ")
214         openssl_command=['openssl', 'pkcs12', "-export"]
215         openssl_command += [ "-password", "pass:%s"%password ]
216         openssl_command += [ "-inkey", self.private_key_filename()]
217         openssl_command += [ "-in",    self.my_gid_filename()]
218         openssl_command += [ "-out",   filename ]
219         if subprocess.call(openssl_command) ==0:
220             print "Successfully created %s"%filename
221         else:
222             print "Failed to create %s"%filename
223
224     # Returns True if credential file is valid. Otherwise return false.
225     def validate_credential(self, filename):
226         valid = True
227         cred = Credential(filename=filename)
228         # check if credential is expires
229         if cred.get_expiration() < datetime.utcnow():
230             valid = False
231         return valid
232     
233
234     #################### public interface
235     
236     # return my_gid, run all missing steps in the bootstrap sequence
237     def bootstrap_my_gid (self):
238         self.self_signed_cert()
239         self.my_credential()
240         return self.my_gid()
241
242     # once we've bootstrapped we can use this object to issue any other SFA call
243     # always use my gid
244     def server_proxy (self, url):
245         self.assert_my_gid()
246         return SfaServerProxy (url, self.private_key_filename(), self.my_gid_filename(),
247                                verbose=self.verbose, timeout=self.timeout)
248
249     # now in some cases the self-signed is enough
250     def server_proxy_simple (self, url):
251         self.assert_self_signed_cert()
252         return SfaServerProxy (url, self.private_key_filename(), self.self_signed_cert_filename(),
253                                verbose=self.verbose, timeout=self.timeout)
254
255     # this method can optionnally be invoked to ensure proper
256     # installation of the private key that belongs to this user
257     # installs private_key in working dir with expected name -- preserve mode
258     # typically user_private_key would be ~/.ssh/id_rsa
259     # xxx should probably check the 2 files are identical
260     def init_private_key_if_missing (self, user_private_key):
261         private_key_filename=self.private_key_filename()
262         if not os.path.isfile (private_key_filename):
263             key=self.plain_read(user_private_key)
264             self.plain_write(private_key_filename, key)
265             os.chmod(private_key_filename,os.stat(user_private_key).st_mode)
266             self.logger.debug("SfaClientBootstrap: Copied private key from %s into %s"%\
267                                   (user_private_key,private_key_filename))
268         
269     #################### private details
270     # stupid stuff
271     def fullpath (self, file): return os.path.join (self.dir,file)
272
273     # the expected filenames for the various pieces
274     def private_key_filename (self): 
275         return self.fullpath ("%s.pkey" % Xrn.unescape(self.hrn))
276     def self_signed_cert_filename (self): 
277         return self.fullpath ("%s.sscert"%self.hrn)
278     def my_credential_filename (self):
279         return self.credential_filename (self.hrn, "user")
280     # the tests use sfi -u <pi-user>; meaning that the slice credential filename
281     # needs to keep track of the user too
282     def credential_filename (self, hrn, type): 
283         if type in ['user']:
284             basename="%s.%s.cred"%(hrn,type)
285         else:
286             basename="%s-%s.%s.cred"%(self.hrn,hrn,type)
287         return self.fullpath (basename)
288     def slice_credential_filename (self, hrn): 
289         return self.credential_filename(hrn,'slice')
290     def authority_credential_filename (self, hrn): 
291         return self.credential_filename(hrn,'authority')
292     def my_gid_filename (self):
293         return self.gid_filename (self.hrn, "user")
294     def gid_filename (self, hrn, type): 
295         return self.fullpath ("%s.%s.gid"%(hrn,type))
296     def my_pkcs12_filename (self):
297         return self.fullpath ("%s.p12"%self.hrn)
298
299 # optimizing dependencies
300 # originally we used classes GID or Credential or Certificate 
301 # like e.g. 
302 #        return Credential(filename=self.my_credential()).save_to_string()
303 # but in order to make it simpler to other implementations/languages..
304     def plain_read (self, filename):
305         infile=file(filename,"r")
306         result=infile.read()
307         infile.close()
308         return result
309
310     def plain_write (self, filename, contents):
311         outfile=file(filename,"w")
312         result=outfile.write(contents)
313         outfile.close()
314
315     def assert_filename (self, filename, kind):
316         if not os.path.isfile (filename):
317             raise IOError,"Missing %s file %s"%(kind,filename)
318         return True
319         
320     def assert_private_key (self):
321         return self.assert_filename (self.private_key_filename(),"private key")
322     def assert_self_signed_cert (self):
323         return self.assert_filename (self.self_signed_cert_filename(),"self-signed certificate")
324     def assert_my_credential (self):
325         return self.assert_filename (self.my_credential_filename(),"user's credential")
326     def assert_my_gid (self):
327         return self.assert_filename (self.my_gid_filename(),"user's GID")
328
329
330     # decorator to make up the other methods
331     def get_or_produce (filename_method, produce_method, validate_method=None):
332         # default validator returns true
333         def wrap (f):
334             def wrapped (self, *args, **kw):
335                 filename=filename_method (self, *args, **kw)
336                 if os.path.isfile ( filename ):
337                     if not validate_method:
338                         return filename
339                     elif validate_method(self, filename): 
340                         return filename
341                     else:
342                         # remove invalid file
343                         self.logger.warning ("Removing %s - has expired"%filename)
344                         os.unlink(filename) 
345                 try:
346                     produce_method (self, filename, *args, **kw)
347                     return filename
348                 except IOError:
349                     raise 
350                 except :
351                     error = sys.exc_info()[:2]
352                     message="Could not produce/retrieve %s (%s -- %s)"%\
353                         (filename,error[0],error[1])
354                     self.logger.log_exc(message)
355                     raise Exception, message
356             return wrapped
357         return wrap
358
359     @get_or_produce (self_signed_cert_filename, self_signed_cert_produce)
360     def self_signed_cert (self): pass
361
362     @get_or_produce (my_credential_filename, my_credential_produce, validate_credential)
363     def my_credential (self): pass
364
365     @get_or_produce (my_gid_filename, my_gid_produce)
366     def my_gid (self): pass
367
368     @get_or_produce (my_pkcs12_filename, my_pkcs12_produce)
369     def my_pkcs12 (self): pass
370
371     @get_or_produce (credential_filename, credential_produce, validate_credential)
372     def credential (self, hrn, type): pass
373
374     @get_or_produce (slice_credential_filename, slice_credential_produce, validate_credential)
375     def slice_credential (self, hrn): pass
376
377     @get_or_produce (authority_credential_filename, authority_credential_produce, validate_credential)
378     def authority_credential (self, hrn): pass
379
380     @get_or_produce (gid_filename, gid_produce)
381     def gid (self, hrn, type ): pass
382
383
384     # get the credentials as strings, for inserting as API arguments
385     def my_credential_string (self): 
386         self.my_credential()
387         return self.plain_read(self.my_credential_filename())
388     def slice_credential_string (self, hrn): 
389         self.slice_credential(hrn)
390         return self.plain_read(self.slice_credential_filename(hrn))
391     def authority_credential_string (self, hrn): 
392         self.authority_credential(hrn)
393         return self.plain_read(self.authority_credential_filename(hrn))
394
395     # for consistency
396     def private_key (self):
397         self.assert_private_key()
398         return self.private_key_filename()
399
400     def delegate_credential_string (self, original_credential, to_hrn, to_type='authority'):
401         """
402         sign a delegation credential to someone else
403
404         original_credential : typically one's user- or slice- credential to be delegated to s/b else
405         to_hrn : the hrn of the person that will be allowed to do stuff on our behalf
406         to_type : goes with to_hrn, usually 'user' or 'authority'
407
408         returns a string with the delegated credential
409
410         this internally uses self.my_gid()
411         it also retrieves the gid for to_hrn/to_type
412         and uses Credential.delegate()"""
413
414         # the gid and hrn of the object we are delegating
415         if isinstance (original_credential, str):
416             original_credential = Credential (string=original_credential)
417         original_gid = original_credential.get_gid_object()
418         original_hrn = original_gid.get_hrn()
419
420         if not original_credential.get_privileges().get_all_delegate():
421             self.logger.error("delegate_credential_string: original credential %s does not have delegate bit set"%original_hrn)
422             return
423
424         # the delegating user's gid
425         my_gid = self.my_gid()
426
427         # retrieve the GID for the entity that we're delegating to
428         to_gidfile = self.gid (to_hrn,to_type)
429 #        to_gid = GID ( to_gidfile )
430 #        to_hrn = delegee_gid.get_hrn()
431 #        print 'to_hrn',to_hrn
432         delegated_credential = original_credential.delegate(to_gidfile, self.private_key(), my_gid)
433         return delegated_credential.save_to_string(save_parents=True)