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
12 from datetime import datetime
13 from sfa.util.xrn import Xrn
15 import sfa.util.sfalogging
16 # importing sfa.utils.faults does pull a lot of stuff
17 # OTOH it's imported from Certificate anyways, so..
18 from sfa.util.faults import RecordNotFound
20 from sfa.client.sfaserverproxy import SfaServerProxy
22 # see optimizing dependencies below
23 from sfa.trust.certificate import Keypair, Certificate
24 from sfa.trust.credential import Credential
26 # a helper class to implement the bootstrapping of crypto. material
27 # assuming we are starting from scratch on the client side
28 # what's needed to complete a full slice creation cycle
30 # (*) a local private key
31 # (*) the corresp. public key in the registry
32 # (**) step1: a self-signed certificate
33 # default filename is <hrn>.sscert
34 # (**) step2: a user credential
35 # obtained at the registry with GetSelfCredential
36 # using the self-signed certificate as the SSL cert
37 # default filename is <hrn>.user.cred
38 # (**) step3: a registry-provided certificate (i.e. a GID)
39 # obtained at the registry using Resolve
40 # using the step2 credential as credential
41 # default filename is <hrn>.user.gid
43 # From that point on, the GID is used as the SSL certificate
44 # and the following can be done
46 # (**) retrieve a slice (or authority) credential
47 # obtained at the registry with GetCredential
48 # using the (step2) user-credential as credential
49 # default filename is <hrn>.<type>.cred
50 # (**) retrieve a slice (or authority) GID
51 # obtained at the registry with Resolve
52 # using the (step2) user-credential as credential
53 # default filename is <hrn>.<type>.cred
56 ########## Implementation notes
60 # this implementation is designed as a guideline for
61 # porting to other languages
63 # the decision to go for decorators aims at focusing
64 # on the core of what needs to be done when everything
65 # works fine, and to take caching and error management
68 # for non-pythonic developers, it should be enough to
69 # implement the bulk of this code, namely the _produce methods
70 # and to add caching and error management by whichever means
71 # is available, including inline
73 # (*) self-signed certificates
75 # still with other languages in mind, we've tried to keep the
76 # dependencies to the rest of the code as low as possible
78 # however this still relies on the sfa.trust.certificate module
79 # for the initial generation of a self-signed-certificate that
80 # is associated to the user's ssh-key
81 # (for user-friendliness, and for smooth operations with planetlab,
82 # the usage model is to reuse an existing keypair)
84 # there might be a more portable, i.e. less language-dependant way, to
85 # implement this step by exec'ing the openssl command a known
86 # successful attempt at this approach that worked for Java is
88 # http://nam.ece.upatras.gr/fstoolkit/trac/wiki/JavaSFAClient
92 class SfaClientException (Exception): pass
94 class SfaClientBootstrap:
96 # dir is mandatory but defaults to '.'
97 def __init__ (self, user_hrn, registry_url, dir=None,
98 verbose=False, timeout=None, logger=None):
100 self.registry_url=registry_url
101 if dir is None: dir="."
105 # default for the logger is to use the global sfa logger
107 logger = sfa.util.sfalogging.logger
110 ######################################## *_produce methods
112 # unconditionnally create a self-signed certificate
113 def self_signed_cert_produce (self,output):
114 self.assert_private_key()
115 private_key_filename = self.private_key_filename()
116 keypair=Keypair(filename=private_key_filename)
117 self_signed = Certificate (subject = self.hrn)
118 self_signed.set_pubkey (keypair)
119 self_signed.set_issuer (keypair, self.hrn)
121 self_signed.save_to_file (output)
122 self.logger.debug("SfaClientBootstrap: Created self-signed certificate for %s in %s"%\
127 # unconditionnally retrieve my credential (GetSelfCredential)
128 # we always use the self-signed-cert as the SSL cert
129 def my_credential_produce (self, output):
130 self.assert_self_signed_cert()
131 certificate_filename = self.self_signed_cert_filename()
132 certificate_string = self.plain_read (certificate_filename)
133 self.assert_private_key()
134 registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
135 certificate_filename)
137 credential_string=registry_proxy.GetSelfCredential (certificate_string, self.hrn, "user")
139 # some urns hrns may replace non hierarchy delimiters '.' with an '_' instead of escaping the '.'
140 hrn = Xrn(self.hrn).get_hrn().replace('\.', '_')
141 credential_string=registry_proxy.GetSelfCredential (certificate_string, hrn, "user")
142 self.plain_write (output, credential_string)
143 self.logger.debug("SfaClientBootstrap: Wrote result of GetSelfCredential in %s"%output)
147 # unconditionnally retrieve my GID - use the general form
148 def my_gid_produce (self,output):
149 return self.gid_produce (output, self.hrn, "user")
151 ### retrieve any credential (GetCredential) unconditionnal form
152 # we always use the GID as the SSL cert
153 def credential_produce (self, output, hrn, type):
155 certificate_filename = self.my_gid_filename()
156 self.assert_private_key()
157 registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
158 certificate_filename)
159 self.assert_my_credential()
160 my_credential_string = self.my_credential_string()
161 credential_string=registry_proxy.GetCredential (my_credential_string, hrn, type)
162 self.plain_write (output, credential_string)
163 self.logger.debug("SfaClientBootstrap: Wrote result of GetCredential in %s"%output)
166 def slice_credential_produce (self, output, hrn):
167 return self.credential_produce (output, hrn, "slice")
169 def authority_credential_produce (self, output, hrn):
170 return self.credential_produce (output, hrn, "authority")
172 ### retrieve any gid (Resolve) - unconditionnal form
173 # use my GID when available as the SSL cert, otherwise the self-signed
174 def gid_produce (self, output, hrn, type ):
177 certificate_filename = self.my_gid_filename()
179 self.assert_self_signed_cert()
180 certificate_filename = self.self_signed_cert_filename()
182 self.assert_private_key()
183 registry_proxy = SfaServerProxy (self.registry_url, self.private_key_filename(),
184 certificate_filename)
185 credential_string=self.plain_read (self.my_credential())
186 records = registry_proxy.Resolve (hrn, credential_string)
187 records=[record for record in records if record['type']==type]
189 raise RecordNotFound, "hrn %s (%s) unknown to registry %s"%(hrn,type,self.registry_url)
191 self.plain_write (output, record['gid'])
192 self.logger.debug("SfaClientBootstrap: Wrote GID for %s (%s) in %s"% (hrn,type,output))
196 # Returns True if credential file is valid. Otherwise return false.
197 def validate_credential(self, filename):
199 cred = Credential(filename=filename)
200 # check if credential is expires
201 if cred.get_expiration() < datetime.now():
206 #################### public interface
208 # return my_gid, run all missing steps in the bootstrap sequence
209 def bootstrap_my_gid (self):
210 self.self_signed_cert()
214 # once we've bootstrapped we can use this object to issue any other SFA call
216 def server_proxy (self, url):
218 return SfaServerProxy (url, self.private_key_filename(), self.my_gid_filename(),
219 verbose=self.verbose, timeout=self.timeout)
221 # now in some cases the self-signed is enough
222 def server_proxy_simple (self, url):
223 self.assert_self_signed_cert()
224 return SfaServerProxy (url, self.private_key_filename(), self.self_signed_cert_filename(),
225 verbose=self.verbose, timeout=self.timeout)
227 # this method can optionnally be invoked to ensure proper
228 # installation of the private key that belongs to this user
229 # installs private_key in working dir with expected name -- preserve mode
230 # typically user_private_key would be ~/.ssh/id_rsa
231 # xxx should probably check the 2 files are identical
232 def init_private_key_if_missing (self, user_private_key):
233 private_key_filename=self.private_key_filename()
234 if not os.path.isfile (private_key_filename):
235 key=self.plain_read(user_private_key)
236 self.plain_write(private_key_filename, key)
237 os.chmod(private_key_filename,os.stat(user_private_key).st_mode)
238 self.logger.debug("SfaClientBootstrap: Copied private key from %s into %s"%\
239 (user_private_key,private_key_filename))
241 #################### private details
243 def fullpath (self, file): return os.path.join (self.dir,file)
245 # the expected filenames for the various pieces
246 def private_key_filename (self):
247 return self.fullpath ("%s.pkey" % Xrn.unescape(self.hrn))
248 def self_signed_cert_filename (self):
249 return self.fullpath ("%s.sscert"%self.hrn)
250 def my_credential_filename (self):
251 return self.credential_filename (self.hrn, "user")
252 def credential_filename (self, hrn, type):
253 return self.fullpath ("%s.%s.cred"%(hrn,type))
254 def slice_credential_filename (self, hrn):
255 return self.credential_filename(hrn,'slice')
256 def authority_credential_filename (self, hrn):
257 return self.credential_filename(hrn,'authority')
258 def my_gid_filename (self):
259 return self.gid_filename (self.hrn, "user")
260 def gid_filename (self, hrn, type):
261 return self.fullpath ("%s.%s.gid"%(hrn,type))
264 # optimizing dependencies
265 # originally we used classes GID or Credential or Certificate
267 # return Credential(filename=self.my_credential()).save_to_string()
268 # but in order to make it simpler to other implementations/languages..
269 def plain_read (self, filename):
270 infile=file(filename,"r")
275 def plain_write (self, filename, contents):
276 outfile=file(filename,"w")
277 result=outfile.write(contents)
280 def assert_filename (self, filename, kind):
281 if not os.path.isfile (filename):
282 raise IOError,"Missing %s file %s"%(kind,filename)
285 def assert_private_key (self): return self.assert_filename (self.private_key_filename(),"private key")
286 def assert_self_signed_cert (self): return self.assert_filename (self.self_signed_cert_filename(),"self-signed certificate")
287 def assert_my_credential (self): return self.assert_filename (self.my_credential_filename(),"user's credential")
288 def assert_my_gid (self): return self.assert_filename (self.my_gid_filename(),"user's GID")
291 # decorator to make up the other methods
292 def get_or_produce (filename_method, produce_method, validate_method=None):
293 # default validator returns true
295 def wrapped (self, *args, **kw):
296 filename=filename_method (self, *args, **kw)
297 if os.path.isfile ( filename ):
298 if not validate_method:
300 elif validate_method(self, filename):
303 # remove invalid file
304 self.logger.warning ("Removing %s - has expired"%filename)
307 produce_method (self, filename, *args, **kw)
312 error = sys.exc_info()[:2]
313 message="Could not produce/retrieve %s (%s -- %s)"%\
314 (filename,error[0],error[1])
315 self.logger.log_exc(message)
316 raise Exception, message
320 @get_or_produce (self_signed_cert_filename, self_signed_cert_produce)
321 def self_signed_cert (self): pass
323 @get_or_produce (my_credential_filename, my_credential_produce, validate_credential)
324 def my_credential (self): pass
326 @get_or_produce (my_gid_filename, my_gid_produce)
327 def my_gid (self): pass
329 @get_or_produce (credential_filename, credential_produce, validate_credential)
330 def credential (self, hrn, type): pass
332 @get_or_produce (slice_credential_filename, slice_credential_produce, validate_credential)
333 def slice_credential (self, hrn): pass
335 @get_or_produce (authority_credential_filename, authority_credential_produce, validate_credential)
336 def authority_credential (self, hrn): pass
338 @get_or_produce (gid_filename, gid_produce)
339 def gid (self, hrn, type ): pass
342 # get the credentials as strings, for inserting as API arguments
343 def my_credential_string (self):
345 return self.plain_read(self.my_credential_filename())
346 def slice_credential_string (self, hrn):
347 self.slice_credential(hrn)
348 return self.plain_read(self.slice_credential_filename(hrn))
349 def authority_credential_string (self, hrn):
350 self.authority_credential(hrn)
351 return self.plain_read(self.authority_credential_filename(hrn))
354 def private_key (self):
355 self.assert_private_key()
356 return self.private_key_filename()