1 # Thierry Parmentelat -- INRIA
3 # a minimal library for writing "lightweight" SFA clients
7 # this library should probably check for the expiration date of the various
8 # certificates and automatically retrieve fresh ones when expired
13 from datetime import datetime
14 from sfa.util.xrn import Xrn
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
21 from sfa.client.sfaserverproxy import SfaServerProxy
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
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
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
45 # From that point on, the GID is used as the SSL certificate
46 # and the following can be done
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
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
62 ########## Implementation notes
66 # this implementation is designed as a guideline for
67 # porting to other languages
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
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
79 # (*) self-signed certificates
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
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)
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
98 # the implementation of the pkcs12 wrapping, which is a late addition,
99 # is done through direct calls to openssl
103 class SfaClientException (Exception): pass
105 class SfaClientBootstrap:
107 # dir is mandatory but defaults to '.'
108 def __init__ (self, user_hrn, registry_url, dir=None,
109 verbose=False, timeout=None, logger=None):
111 self.registry_url=registry_url
112 if dir is None: dir="."
116 # default for the logger is to use the global sfa logger
118 logger = sfa.util.sfalogging.logger
121 ######################################## *_produce methods
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)
132 self_signed.save_to_file (output)
133 self.logger.debug("SfaClientBootstrap: Created self-signed certificate for %s in %s"%\
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)
148 credential_string=registry_proxy.GetSelfCredential (certificate_string, self.hrn, "user")
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)
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")
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):
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)
177 def slice_credential_produce (self, output, hrn):
178 return self.credential_produce (output, hrn, "slice")
180 def authority_credential_produce (self, output, hrn):
181 return self.credential_produce (output, hrn, "authority")
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 ):
188 certificate_filename = self.my_gid_filename()
190 self.assert_self_signed_cert()
191 certificate_filename = self.self_signed_cert_filename()
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]
200 raise RecordNotFound, "hrn %s (%s) unknown to registry %s"%(hrn,type,self.registry_url)
202 self.plain_write (output, record['gid'])
203 self.logger.debug("SfaClientBootstrap: Wrote GID for %s (%s) in %s"% (hrn,type,output))
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
221 print "Failed to create %s"%filename
223 # Returns True if credential file is valid. Otherwise return false.
224 def validate_credential(self, filename):
226 cred = Credential(filename=filename)
227 # check if credential is expires
228 if cred.get_expiration() < datetime.utcnow():
233 #################### public interface
235 # return my_gid, run all missing steps in the bootstrap sequence
236 def bootstrap_my_gid (self):
237 self.self_signed_cert()
241 # once we've bootstrapped we can use this object to issue any other SFA call
243 def server_proxy (self, url):
245 return SfaServerProxy (url, self.private_key_filename(), self.my_gid_filename(),
246 verbose=self.verbose, timeout=self.timeout)
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)
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))
268 #################### private details
270 def fullpath (self, file): return os.path.join (self.dir,file)
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)
292 # optimizing dependencies
293 # originally we used classes GID or Credential or Certificate
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")
303 def plain_write (self, filename, contents):
304 outfile=file(filename,"w")
305 result=outfile.write(contents)
308 def assert_filename (self, filename, kind):
309 if not os.path.isfile (filename):
310 raise IOError,"Missing %s file %s"%(kind,filename)
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")
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
323 def wrapped (self, *args, **kw):
324 filename=filename_method (self, *args, **kw)
325 if os.path.isfile ( filename ):
326 if not validate_method:
328 elif validate_method(self, filename):
331 # remove invalid file
332 self.logger.warning ("Removing %s - has expired"%filename)
335 produce_method (self, filename, *args, **kw)
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
348 @get_or_produce (self_signed_cert_filename, self_signed_cert_produce)
349 def self_signed_cert (self): pass
351 @get_or_produce (my_credential_filename, my_credential_produce, validate_credential)
352 def my_credential (self): pass
354 @get_or_produce (my_gid_filename, my_gid_produce)
355 def my_gid (self): pass
357 @get_or_produce (my_pkcs12_filename, my_pkcs12_produce)
358 def my_pkcs12 (self): pass
360 @get_or_produce (credential_filename, credential_produce, validate_credential)
361 def credential (self, hrn, type): pass
363 @get_or_produce (slice_credential_filename, slice_credential_produce, validate_credential)
364 def slice_credential (self, hrn): pass
366 @get_or_produce (authority_credential_filename, authority_credential_produce, validate_credential)
367 def authority_credential (self, hrn): pass
369 @get_or_produce (gid_filename, gid_produce)
370 def gid (self, hrn, type ): pass
373 # get the credentials as strings, for inserting as API arguments
374 def my_credential_string (self):
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))
385 def private_key (self):
386 self.assert_private_key()
387 return self.private_key_filename()
389 def delegate_credential_string (self, original_credential, to_hrn, to_type='authority'):
391 sign a delegation credential to someone else
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'
397 returns a string with the delegated credential
399 this internally uses self.my_gid()
400 it also retrieves the gid for to_hrn/to_type
401 and uses Credential.delegate()"""
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()
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)
413 # the delegating user's gid
414 my_gid = self.my_gid()
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)