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 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
18 from sfa.client.sfaserverproxy import SfaServerProxy
20 # see optimizing dependencies below
21 from sfa.trust.certificate import Keypair, Certificate
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
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
41 # From that point on, the GID is used as the SSL certificate
42 # and the following can be done
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
54 ########## Implementation notes
58 # this implementation is designed as a guideline for
59 # porting to other languages
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
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
71 # (*) self-signed certificates
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
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)
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
86 # http://nam.ece.upatras.gr/fstoolkit/trac/wiki/JavaSFAClient
90 class SfaClientException (Exception): pass
92 class SfaClientBootstrap:
94 # dir is mandatory but defaults to '.'
95 def __init__ (self, user_hrn, registry_url, dir=None,
96 verbose=False, timeout=None, logger=None):
98 self.registry_url=registry_url
99 if dir is None: dir="."
103 # default for the logger is to use the global sfa logger
105 logger = sfa.util.sfalogging.logger
108 ######################################## *_produce methods
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)
119 self_signed.save_to_file (output)
120 self.logger.debug("SfaClientBootstrap: Created self-signed certificate for %s in %s"%\
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)
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")
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):
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)
159 def slice_credential_produce (self, output, hrn):
160 return self.credential_produce (output, hrn, "slice")
162 def authority_credential_produce (self, output, hrn):
163 return self.credential_produce (output, hrn, "authority")
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 ):
170 certificate_filename = self.my_gid_filename()
172 self.assert_self_signed_cert()
173 certificate_filename = self.self_signed_cert_filename()
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]
182 raise RecordNotFound, "hrn %s (%s) unknown to registry %s"%(hrn,type,self.registry_url)
184 self.plain_write (output, record['gid'])
185 self.logger.debug("SfaClientBootstrap: Wrote GID for %s (%s) in %s"% (hrn,type,output))
188 #################### public interface
190 # return my_gid, run all missing steps in the bootstrap sequence
191 def bootstrap_my_gid (self):
192 self.self_signed_cert()
196 # once we've bootstrapped we can use this object to issue any other SFA call
198 def server_proxy (self, url):
200 return SfaServerProxy (url, self.private_key_filename(), self.my_gid_filename(),
201 verbose=self.verbose, timeout=self.timeout)
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)
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))
223 #################### private details
225 def fullpath (self, file): return os.path.join (self.dir,file)
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))
246 # optimizing dependencies
247 # originally we used classes GID or Credential or Certificate
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")
257 def plain_write (self, filename, contents):
258 outfile=file(filename,"w")
259 result=outfile.write(contents)
262 def assert_filename (self, filename, kind):
263 if not os.path.isfile (filename):
264 raise IOError,"Missing %s file %s"%(kind,filename)
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")
273 # decorator to make up the other methods
274 def get_or_produce (filename_method, produce_method):
276 def wrapped (self, *args, **kw):
277 filename=filename_method (self, *args, **kw)
278 if os.path.isfile ( filename ): return filename
280 produce_method (self, filename, *args, **kw)
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
293 @get_or_produce (self_signed_cert_filename, self_signed_cert_produce)
294 def self_signed_cert (self): pass
296 @get_or_produce (my_credential_filename, my_credential_produce)
297 def my_credential (self): pass
299 @get_or_produce (my_gid_filename, my_gid_produce)
300 def my_gid (self): pass
302 @get_or_produce (credential_filename, credential_produce)
303 def credential (self, hrn, type): pass
305 @get_or_produce (slice_credential_filename, slice_credential_produce)
306 def slice_credential (self, hrn): pass
308 @get_or_produce (authority_credential_filename, authority_credential_produce)
309 def authority_credential (self, hrn): pass
311 @get_or_produce (gid_filename, gid_produce)
312 def gid (self, hrn, type ): pass
315 # get the credentials as strings, for inserting as API arguments
316 def my_credential_string (self):
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))
327 def private_key (self):
328 self.assert_private_key()
329 return self.private_key_filename()