sfa client bootstrap library has a new 'my_pkcs12' feature, and this is now invoked...
[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, self.private_key_filename(),
146                                          certificate_filename)
147         try:
148             credential_string=registry_proxy.GetSelfCredential (certificate_string, self.hrn, "user")
149         except:
150             # some urns hrns may replace non hierarchy delimiters '.' with an '_' instead of escaping the '.'
151             hrn = Xrn(self.hrn).get_hrn().replace('\.', '_') 
152             credential_string=registry_proxy.GetSelfCredential (certificate_string, hrn, "user")
153         self.plain_write (output, credential_string)
154         self.logger.debug("SfaClientBootstrap: Wrote result of GetSelfCredential in %s"%output)
155         return output
156
157     ### step3
158     # unconditionnally retrieve my GID - use the general form 
159     def my_gid_produce (self,output):
160         return self.gid_produce (output, self.hrn, "user")
161
162     ### retrieve any credential (GetCredential) unconditionnal form
163     # we always use the GID as the SSL cert
164     def credential_produce (self, output, hrn, type):
165         self.assert_my_gid()
166         certificate_filename = self.my_gid_filename()
167         self.assert_private_key()
168         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
169                                          certificate_filename)
170         self.assert_my_credential()
171         my_credential_string = self.my_credential_string()
172         credential_string=registry_proxy.GetCredential (my_credential_string, hrn, type)
173         self.plain_write (output, credential_string)
174         self.logger.debug("SfaClientBootstrap: Wrote result of GetCredential in %s"%output)
175         return output
176
177     def slice_credential_produce (self, output, hrn):
178         return self.credential_produce (output, hrn, "slice")
179
180     def authority_credential_produce (self, output, hrn):
181         return self.credential_produce (output, hrn, "authority")
182
183     ### retrieve any gid (Resolve) - unconditionnal form
184     # use my GID when available as the SSL cert, otherwise the self-signed
185     def gid_produce (self, output, hrn, type ):
186         try:
187             self.assert_my_gid()
188             certificate_filename = self.my_gid_filename()
189         except:
190             self.assert_self_signed_cert()
191             certificate_filename = self.self_signed_cert_filename()
192             
193         self.assert_private_key()
194         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
195                                          certificate_filename)
196         credential_string=self.plain_read (self.my_credential())
197         records = registry_proxy.Resolve (hrn, credential_string)
198         records=[record for record in records if record['type']==type]
199         if not records:
200             raise RecordNotFound, "hrn %s (%s) unknown to registry %s"%(hrn,type,self.registry_url)
201         record=records[0]
202         self.plain_write (output, record['gid'])
203         self.logger.debug("SfaClientBootstrap: Wrote GID for %s (%s) in %s"% (hrn,type,output))
204         return output
205
206
207 # http://trac.myslice.info/wiki/MySlice/Developer/SFALogin
208 ### produce a pkcs12 bundled certificate from GID and private key
209 # xxx for now we put a hard-wired password that's just, well, 'password'
210 # when leaving this empty on the mac, result can't seem to be loaded in keychain..
211     def my_pkcs12_produce (self, filename):
212         password=raw_input("Enter password for p12 certificate: ")
213         openssl_command=['openssl', 'pkcs12', "-export"]
214         openssl_command += [ "-password", "pass:%s"%password ]
215         openssl_command += [ "-inkey", self.private_key_filename()]
216         openssl_command += [ "-in",    self.my_gid_filename()]
217         openssl_command += [ "-out",   filename ]
218         if subprocess.call(openssl_command) ==0:
219             print "Successfully created %s"%filename
220         else:
221             print "Failed to create %s"%filename
222
223     # Returns True if credential file is valid. Otherwise return false.
224     def validate_credential(self, filename):
225         valid = True
226         cred = Credential(filename=filename)
227         # check if credential is expires
228         if cred.get_expiration() < datetime.utcnow():
229             valid = False
230         return valid
231     
232
233     #################### public interface
234     
235     # return my_gid, run all missing steps in the bootstrap sequence
236     def bootstrap_my_gid (self):
237         self.self_signed_cert()
238         self.my_credential()
239         return self.my_gid()
240
241     # once we've bootstrapped we can use this object to issue any other SFA call
242     # always use my gid
243     def server_proxy (self, url):
244         self.assert_my_gid()
245         return SfaServerProxy (url, self.private_key_filename(), self.my_gid_filename(),
246                                verbose=self.verbose, timeout=self.timeout)
247
248     # now in some cases the self-signed is enough
249     def server_proxy_simple (self, url):
250         self.assert_self_signed_cert()
251         return SfaServerProxy (url, self.private_key_filename(), self.self_signed_cert_filename(),
252                                verbose=self.verbose, timeout=self.timeout)
253
254     # this method can optionnally be invoked to ensure proper
255     # installation of the private key that belongs to this user
256     # installs private_key in working dir with expected name -- preserve mode
257     # typically user_private_key would be ~/.ssh/id_rsa
258     # xxx should probably check the 2 files are identical
259     def init_private_key_if_missing (self, user_private_key):
260         private_key_filename=self.private_key_filename()
261         if not os.path.isfile (private_key_filename):
262             key=self.plain_read(user_private_key)
263             self.plain_write(private_key_filename, key)
264             os.chmod(private_key_filename,os.stat(user_private_key).st_mode)
265             self.logger.debug("SfaClientBootstrap: Copied private key from %s into %s"%\
266                                   (user_private_key,private_key_filename))
267         
268     #################### private details
269     # stupid stuff
270     def fullpath (self, file): return os.path.join (self.dir,file)
271
272     # the expected filenames for the various pieces
273     def private_key_filename (self): 
274         return self.fullpath ("%s.pkey" % Xrn.unescape(self.hrn))
275     def self_signed_cert_filename (self): 
276         return self.fullpath ("%s.sscert"%self.hrn)
277     def my_credential_filename (self):
278         return self.credential_filename (self.hrn, "user")
279     def credential_filename (self, hrn, type): 
280         return self.fullpath ("%s.%s.cred"%(hrn,type))
281     def slice_credential_filename (self, hrn): 
282         return self.credential_filename(hrn,'slice')
283     def authority_credential_filename (self, hrn): 
284         return self.credential_filename(hrn,'authority')
285     def my_gid_filename (self):
286         return self.gid_filename (self.hrn, "user")
287     def gid_filename (self, hrn, type): 
288         return self.fullpath ("%s.%s.gid"%(hrn,type))
289     def my_pkcs12_filename (self):
290         return self.fullpath ("%s.p12"%self.hrn)
291
292 # optimizing dependencies
293 # originally we used classes GID or Credential or Certificate 
294 # like e.g. 
295 #        return Credential(filename=self.my_credential()).save_to_string()
296 # but in order to make it simpler to other implementations/languages..
297     def plain_read (self, filename):
298         infile=file(filename,"r")
299         result=infile.read()
300         infile.close()
301         return result
302
303     def plain_write (self, filename, contents):
304         outfile=file(filename,"w")
305         result=outfile.write(contents)
306         outfile.close()
307
308     def assert_filename (self, filename, kind):
309         if not os.path.isfile (filename):
310             raise IOError,"Missing %s file %s"%(kind,filename)
311         return True
312         
313     def assert_private_key (self): return self.assert_filename (self.private_key_filename(),"private key")
314     def assert_self_signed_cert (self): return self.assert_filename (self.self_signed_cert_filename(),"self-signed certificate")
315     def assert_my_credential (self): return self.assert_filename (self.my_credential_filename(),"user's credential")
316     def assert_my_gid (self): return self.assert_filename (self.my_gid_filename(),"user's GID")
317
318
319     # decorator to make up the other methods
320     def get_or_produce (filename_method, produce_method, validate_method=None):
321         # default validator returns true
322         def wrap (f):
323             def wrapped (self, *args, **kw):
324                 filename=filename_method (self, *args, **kw)
325                 if os.path.isfile ( filename ):
326                     if not validate_method:
327                         return filename
328                     elif validate_method(self, filename): 
329                         return filename
330                     else:
331                         # remove invalid file
332                         self.logger.warning ("Removing %s - has expired"%filename)
333                         os.unlink(filename) 
334                 try:
335                     produce_method (self, filename, *args, **kw)
336                     return filename
337                 except IOError:
338                     raise 
339                 except :
340                     error = sys.exc_info()[:2]
341                     message="Could not produce/retrieve %s (%s -- %s)"%\
342                         (filename,error[0],error[1])
343                     self.logger.log_exc(message)
344                     raise Exception, message
345             return wrapped
346         return wrap
347
348     @get_or_produce (self_signed_cert_filename, self_signed_cert_produce)
349     def self_signed_cert (self): pass
350
351     @get_or_produce (my_credential_filename, my_credential_produce, validate_credential)
352     def my_credential (self): pass
353
354     @get_or_produce (my_gid_filename, my_gid_produce)
355     def my_gid (self): pass
356
357     @get_or_produce (my_pkcs12_filename, my_pkcs12_produce)
358     def my_pkcs12 (self): pass
359
360     @get_or_produce (credential_filename, credential_produce, validate_credential)
361     def credential (self, hrn, type): pass
362
363     @get_or_produce (slice_credential_filename, slice_credential_produce, validate_credential)
364     def slice_credential (self, hrn): pass
365
366     @get_or_produce (authority_credential_filename, authority_credential_produce, validate_credential)
367     def authority_credential (self, hrn): pass
368
369     @get_or_produce (gid_filename, gid_produce)
370     def gid (self, hrn, type ): pass
371
372
373     # get the credentials as strings, for inserting as API arguments
374     def my_credential_string (self): 
375         self.my_credential()
376         return self.plain_read(self.my_credential_filename())
377     def slice_credential_string (self, hrn): 
378         self.slice_credential(hrn)
379         return self.plain_read(self.slice_credential_filename(hrn))
380     def authority_credential_string (self, hrn): 
381         self.authority_credential(hrn)
382         return self.plain_read(self.authority_credential_filename(hrn))
383
384     # for consistency
385     def private_key (self):
386         self.assert_private_key()
387         return self.private_key_filename()
388
389     def delegate_credential_string (self, original_credential, to_hrn, to_type='authority'):
390         """
391         sign a delegation credential to someone else
392
393         original_credential : typically one's user- or slice- credential to be delegated to s/b else
394         to_hrn : the hrn of the person that will be allowed to do stuff on our behalf
395         to_type : goes with to_hrn, usually 'user' or 'authority'
396
397         returns a string with the delegated credential
398
399         this internally uses self.my_gid()
400         it also retrieves the gid for to_hrn/to_type
401         and uses Credential.delegate()"""
402
403         # the gid and hrn of the object we are delegating
404         if isinstance (original_credential, str):
405             original_credential = Credential (string=original_credential)
406         original_gid = original_credential.get_gid_object()
407         original_hrn = original_gid.get_hrn()
408
409         if not original_credential.get_privileges().get_all_delegate():
410             self.logger.error("delegate_credential_string: original credential %s does not have delegate bit set"%original_hrn)
411             return
412
413         # the delegating user's gid
414         my_gid = self.my_gid()
415
416         # retrieve the GID for the entity that we're delegating to
417         to_gidfile = self.gid (to_hrn,to_type)
418 #        to_gid = GID ( to_gidfile )
419 #        to_hrn = delegee_gid.get_hrn()
420 #        print 'to_hrn',to_hrn
421         delegated_credential = original_credential.delegate(to_gidfile, self.private_key(), my_gid)
422         return delegated_credential.save_to_string(save_parents=True)