very first draft of an sfa client library for bootstrapping user gid
[sfa.git] / sfa / client / sfaclientlib.py
1 #
2 # a minimal library for writing "lightweight" SFA clients
3 #
4
5 import os,os.path
6
7 import sfa.util.sfalogging
8
9 from sfa.trust.gid import GID
10 from sfa.trust.certificate import Keypair, Certificate
11 from sfa.trust.credential import Credential
12
13 import sfa.client.sfaprotocol as sfaprotocol
14
15 class SfaServerProxy:
16
17     def __init__ (self, url, keyfile, certfile, verbose=False, timeout=None):
18         self.url=url
19         self.keyfile=keyfile
20         self.certfile=certfile
21         self.verbose=verbose
22         self.timeout=timeout
23         # an instance of xmlrpclib.ServerProxy
24         self.serverproxy=sfaprotocol.server_proxy \
25             (self.url, self.keyfile, self.certfile, self.timeout, self.verbose)
26
27     # this is python magic to return the code to run when 
28     # SfaServerProxy receives a method call
29     # so essentially we send the same method with identical arguments
30     # to the server_proxy object
31     def __getattr__(self, name):
32         def func(*args, **kwds):
33             return getattr(self.serverproxy, name)(*args, **kwds)
34         return func
35     
36
37 ########## 
38 # a helper class to implement the bootstrapping of crypto. material
39 # assuming we are starting from scratch on the client side 
40 # what's needed to complete a full slice creation cycle
41 # (**) prerequisites: 
42 #  (*) a local private key 
43 #  (*) the corresp. public key in the registry 
44 # (**) step1: a self-signed certificate
45 #      default filename is <hrn>.sscert
46 # (**) step2: a user credential
47 #      obtained at the registry with GetSelfCredential
48 #      using the self-signed certificate as the SSL cert
49 #      default filename is <hrn>.user.cred
50 # (**) step3: a registry-provided certificate (i.e. a GID)
51 #      obtained at the registry using Resolve
52 #      using the step2 credential as credential
53 #      default filename is <hrn>.user.gid
54 ##########
55 # from that point on, the GID can/should be used as the SSL cert for anything
56 # a new (slice) credential would be needed for slice operations and can be 
57 # obtained at the registry through GetCredential
58
59 # xxx todo should protect against write file permissions
60 # xxx todo review exceptions
61 class SfaClientBootstrap:
62
63     # xxx todo should account for verbose and timeout that the proxy offers
64     def __init__ (self, user_hrn, registry_url, dir=None, logger=None):
65         self.hrn=user_hrn
66         self.registry_url=registry_url
67         if dir is None: dir="."
68         self.dir=dir
69         if logger is None: 
70             print 'special case for logger'
71             logger = sfa.util.sfalogging.logger
72         self.logger=logger
73     
74     # stupid stuff
75     def fullpath (self, file): return os.path.join (self.dir,file)
76     # %s -> self.hrn
77     def fullpath_format(self,format): return self.fullpath (format%self.hrn)
78
79     def private_key_file (self): 
80         return self.fullpath_format ("%s.pkey")
81
82     def self_signed_cert_file (self): 
83         return self.fullpath_format ("%s.sscert")
84     def credential_file (self): 
85         return self.fullpath_format ("%s.user.cred")
86     def gid_file (self): 
87         return self.fullpath_format ("%s.user.gid")
88
89     def check_private_key (self):
90         if not os.path.isfile (self.private_key_file()):
91             raise Exception,"No such file %s"%self.private_key_file()
92         return True
93
94     # typically user_private_key is ~/.ssh/id_rsa
95     def init_private_key_if_missing (self, user_private_key):
96         private_key_file=self.private_key_file()
97         if not os.path.isfile (private_key_file):
98             infile=file(user_private_key)
99             outfile=file(private_key_file,'w')
100             outfile.write(infile.read())
101             outfile.close()
102             infile.close()
103             os.chmod(private_key_file,os.stat(user_private_key).st_mode)
104             self.logger.debug("SfaClientBootstrap: Copied private key from %s into %s"%\
105                                   (user_private_key,private_key_file))
106         
107
108     # get any certificate, gid preferred
109     def preferred_certificate_file (self):
110         attempts=[ self.gid_file(), self.self_signed_cert_file() ]
111         for attempt in attempts:
112             if os.path.isfile (attempt): return attempt
113         return None
114
115     ### step1
116     # unconditionnally
117     def create_self_signed_certificate (self,output):
118         self.check_private_key()
119         private_key_file = self.private_key_file()
120         keypair=Keypair(filename=private_key_file)
121         self_signed = Certificate (subject = self.hrn)
122         self_signed.set_pubkey (keypair)
123         self_signed.set_issuer (keypair, self.hrn)
124         self_signed.sign ()
125         self_signed.save_to_file (output)
126         self.logger.debug("SfaClientBootstrap: Created self-signed certificate for %s in %s"%\
127                               (self.hrn,output))
128         return output
129
130     def get_self_signed_cert (self):
131         self_signed_cert_file = self.self_signed_cert_file()
132         if os.path.isfile (self_signed_cert_file):
133             return self_signed_cert_file
134         return self.create_self_signed_certificate(self_signed_cert_file)
135         
136     ### step2 
137     # unconditionnally
138     def retrieve_credential (self, output):
139         self.check_private_key()
140         certificate_file = self.preferred_certificate_file()
141         registry_proxy = SfaServerProxy (self.registry_url, self.private_key_file(),
142                                          certificate_file)
143         certificate = Certificate (filename=certificate_file)
144         certificate_string = certificate.save_to_string(save_parents=True)
145         credential_string=registry_proxy.GetSelfCredential (certificate_string, self.hrn, "user")
146         credential = Credential (string=credential_string)
147         credential.save_to_file (output, save_parents=True)
148         self.logger.debug("SfaClientBootstrap: Wrote result of GetSelfCredential in %s"%output)
149         return output
150
151     def get_credential (self):
152         credential_file = self.credential_file ()
153         if os.path.isfile(credential_file): 
154             return credential_file
155         return self.retrieve_credential (credential_file)
156
157     def get_credential_string (self):
158         return Credential(filename=self.get_credential()).save_to_string()
159
160     ### step3
161     # unconditionnally
162     def retrieve_gid (self, hrn, type, output):
163          self.check_private_key()
164          certificate_file = self.preferred_certificate_file()
165          registry_proxy = SfaServerProxy (self.registry_url, self.private_key_file(),
166                                           certificate_file)
167          credential_string=Credential(filename=self.credential_file()).save_to_string()
168          records = registry_proxy.Resolve (hrn, credential_string)
169          records=[record for record in records if record['type']==type]
170          if not records:
171              # RecordNotFound
172              raise Exception, "hrn %s (%s) unknown to registry %s"%(hrn,type,self.registry_url)
173          record=records[0]
174          gid=GID(string=record['gid'])
175          gid.save_to_file (filename=output)
176          self.logger.debug("SfaClientBootstrap: Wrote GID for %s (%s) in %s"% (hrn,type,output))
177          return output
178
179     def get_gid (self):
180         gid_file=self.gid_file()
181         if os.path.isfile(gid_file): 
182             return gid_file
183         return self.retrieve_gid(self.hrn, "user", gid_file)
184
185     # make sure we have the GID at hand
186     def bootstrap_gid (self):
187         if self.preferred_certificate_file() is None:
188             self.get_self_signed_cert()
189         self.get_credential()
190         self.get_gid()
191
192     def server_proxy (self, url):
193         return SfaServerProxy (url, self.private_key_file(), self.gid_file())
194