* tried to put some sense in the way things get logged, at least on server-side for now
[sfa.git] / sfa / trust / hierarchy.py
1 ##
2 # This module implements a hierarchy of authorities and performs a similar
3 # function as the "tree" module of the original SFA prototype. An HRN
4 # is assumed to be a string of authorities separated by dots. For example,
5 # "planetlab.us.arizona.bakers". Each component of the HRN is a different
6 # authority, with the last component being a leaf in the tree.
7 #
8 # Each authority is stored in a subdirectory on the registry. Inside this
9 # subdirectory are several files:
10 #      *.GID - GID file
11 #      *.PKEY - private key file
12 #      *.DBINFO - database info
13 ##
14
15 ### $Id$
16 ### $URL$
17
18 import os
19
20 from sfa.util.sfalogging import sfa_logger
21 from sfa.util.report import *
22 from sfa.trust.certificate import Keypair
23 from sfa.trust.credential import *
24 from sfa.trust.gid import GID, create_uuid
25 from sfa.util.namespace import *
26 from sfa.util.config import Config
27 from sfa.util.sfaticket import SfaTicket
28
29 ##
30 # The AuthInfo class contains the information for an authority. This information
31 # includes the GID, private key, and database connection information.
32
33 class AuthInfo:
34     hrn = None
35     gid_object = None
36     gid_filename = None
37     privkey_filename = None
38     dbinfo_filename = None
39
40     ##
41     # Initialize and authority object.
42     #
43     # @param xrn the human readable name of the authority (urn will be converted to hrn)
44     # @param gid_filename the filename containing the GID
45     # @param privkey_filename the filename containing the private key
46     # @param dbinfo_filename the filename containing the database info
47
48     def __init__(self, xrn, gid_filename, privkey_filename, dbinfo_filename):
49         hrn, type = urn_to_hrn(xrn)
50         self.hrn = hrn
51         self.set_gid_filename(gid_filename)
52         self.privkey_filename = privkey_filename
53         self.dbinfo_filename = dbinfo_filename
54
55     ##
56     # Set the filename of the GID
57     #
58     # @param fn filename of file containing GID
59
60     def set_gid_filename(self, fn):
61         self.gid_filename = fn
62         self.gid_object = None
63
64     def get_privkey_filename(self):
65         return self.privkey_filename
66
67     def get_gid_filename(self):
68         return self.gid_filename
69
70     ##
71     # Get the GID in the form of a GID object
72
73     def get_gid_object(self):
74         if not self.gid_object:
75             self.gid_object = GID(filename = self.gid_filename)
76         return self.gid_object
77
78     ##
79     # Get the private key in the form of a Keypair object
80
81     def get_pkey_object(self):
82         return Keypair(filename = self.privkey_filename)
83
84     ##
85     # Get the dbinfo in the form of a dictionary
86
87     def get_dbinfo(self):
88         f = file(self.dbinfo_filename)
89         dict = eval(f.read())
90         f.close()
91         return dict
92
93     ##
94     # Replace the GID with a new one. The file specified by gid_filename is
95     # overwritten with the new GID object
96     #
97     # @param gid object containing new GID
98
99     def update_gid_object(self, gid):
100         gid.save_to_file(self.gid_filename)
101         self.gid_object = gid
102
103 ##
104 # The Hierarchy class is responsible for managing the tree of authorities.
105 # Each authority is a node in the tree and exists as an AuthInfo object.
106 #
107 # The tree is stored on disk in a hierarchical manner than reflects the
108 # structure of the tree. Each authority is a subdirectory, and each subdirectory
109 # contains the GID, pkey, and dbinfo files for that authority (as well as
110 # subdirectories for each sub-authority)
111
112 class Hierarchy:
113     ##
114     # Create the hierarchy object.
115     #
116     # @param basedir the base directory to store the hierarchy in
117
118     def __init__(self, basedir = None):
119         if not basedir:
120             self.config = Config()
121             basedir = os.path.join(self.config.SFA_DATA_DIR, "authorities")
122         self.basedir = basedir
123     ##
124     # Given a hrn, return the filenames of the GID, private key, and dbinfo
125     # files.
126     #
127     # @param xrn the human readable name of the authority (urn will be convertd to hrn)
128
129     def get_auth_filenames(self, xrn):
130         hrn, type = urn_to_hrn(xrn)
131         leaf = get_leaf(hrn)
132         parent_hrn = get_authority(hrn)
133         directory = os.path.join(self.basedir, hrn.replace(".", "/"))
134
135         gid_filename = os.path.join(directory, leaf+".gid")
136         privkey_filename = os.path.join(directory, leaf+".pkey")
137         dbinfo_filename = os.path.join(directory, leaf+".dbinfo")
138
139         return (directory, gid_filename, privkey_filename, dbinfo_filename)
140
141     ##
142     # Check to see if an authority exists. An authority exists if it's disk
143     # files exist.
144     #
145     # @param the human readable name of the authority to check
146
147     def auth_exists(self, xrn):
148         hrn, type = urn_to_hrn(xrn) 
149         (directory, gid_filename, privkey_filename, dbinfo_filename) = \
150             self.get_auth_filenames(hrn)
151         
152         return os.path.exists(gid_filename) and \
153                os.path.exists(privkey_filename) and \
154                os.path.exists(dbinfo_filename)
155
156     ##
157     # Create an authority. A private key for the authority and the associated
158     # GID are created and signed by the parent authority.
159     #
160     # @param xrn the human readable name of the authority to create (urn will be converted to hrn) 
161     # @param create_parents if true, also create the parents if they do not exist
162
163     def create_auth(self, xrn, create_parents=False):
164         hrn, type = urn_to_hrn(xrn)
165         trace("Hierarchy: creating authority: " + hrn)
166
167         # create the parent authority if necessary
168         parent_hrn = get_authority(hrn)
169         parent_urn = hrn_to_urn(parent_hrn, 'authority')
170         if (parent_hrn) and (not self.auth_exists(parent_urn)) and (create_parents):
171             self.create_auth(parent_urn, create_parents)
172
173         (directory, gid_filename, privkey_filename, dbinfo_filename) = \
174             self.get_auth_filenames(hrn)
175
176         # create the directory to hold the files
177         try:
178             os.makedirs(directory)
179         # if the path already exists then pass
180         except OSError, (errno, strerr):
181             if errno == 17:
182                 pass
183
184         if os.path.exists(privkey_filename):
185             sfa_logger.debug("using existing key %r for authority %r"%(privkey_filename,hrn))
186             pkey = Keypair(filename = privkey_filename)
187         else:
188             pkey = Keypair(create = True)
189             pkey.save_to_file(privkey_filename)
190
191         gid = self.create_gid(xrn, create_uuid(), pkey)
192         gid.save_to_file(gid_filename, save_parents=True)
193
194         # XXX TODO: think up a better way for the dbinfo to work
195
196         dbinfo = Config().get_plc_dbinfo()
197         dbinfo_file = file(dbinfo_filename, "w")
198         dbinfo_file.write(str(dbinfo))
199         dbinfo_file.close()
200
201     ##
202     # Return the AuthInfo object for the specified authority. If the authority
203     # does not exist, then an exception is thrown. As a side effect, disk files
204     # and a subdirectory may be created to store the authority.
205     #
206     # @param xrn the human readable name of the authority to create (urn will be converted to hrn).
207
208     def get_auth_info(self, xrn):
209         
210         #trace("Hierarchy: getting authority: " + hrn)
211         hrn, type = urn_to_hrn(xrn)
212         if not self.auth_exists(hrn):
213             raise MissingAuthority(hrn)
214
215         (directory, gid_filename, privkey_filename, dbinfo_filename) = \
216             self.get_auth_filenames(hrn)
217
218         auth_info = AuthInfo(hrn, gid_filename, privkey_filename, dbinfo_filename)
219
220         # check the GID and see if it needs to be refreshed
221         gid = auth_info.get_gid_object()
222         gid_refreshed = self.refresh_gid(gid)
223         if gid != gid_refreshed:
224             auth_info.update_gid_object(gid_refreshed)
225
226         return auth_info
227
228     ##
229     # Create a new GID. The GID will be signed by the authority that is it's
230     # immediate parent in the hierarchy (and recursively, the parents' GID
231     # will be signed by its parent)
232     #
233     # @param hrn the human readable name to store in the GID
234     # @param uuid the unique identifier to store in the GID
235     # @param pkey the public key to store in the GID
236
237     def create_gid(self, xrn, uuid, pkey):
238         hrn, type = urn_to_hrn(xrn)
239         # Using hrn_to_urn() here to make sure the urn is in the right format
240         # If xrn was a hrn instead of a urn, then the gid's urn will be
241         # of type None 
242         urn = hrn_to_urn(hrn, type)
243         gid = GID(subject=hrn, uuid=uuid, hrn=hrn, urn=urn)
244
245         parent_hrn = get_authority(hrn)
246         if not parent_hrn or hrn == self.config.SFA_INTERFACE_HRN:
247             # if there is no parent hrn, then it must be self-signed. this
248             # is where we terminate the recursion
249             gid.set_issuer(pkey, hrn)
250         else:
251             # we need the parent's private key in order to sign this GID
252             parent_auth_info = self.get_auth_info(parent_hrn)
253             gid.set_issuer(parent_auth_info.get_pkey_object(), parent_auth_info.hrn)
254             gid.set_parent(parent_auth_info.get_gid_object())
255             gid.set_intermediate_ca(True)
256
257         gid.set_pubkey(pkey)
258         gid.encode()
259         gid.sign()
260
261         return gid
262
263     ##
264     # Refresh a GID. The primary use of this function is to refresh the
265     # the expiration time of the GID. It may also be used to change the HRN,
266     # UUID, or Public key of the GID.
267     #
268     # @param gid the GID to refresh
269     # @param hrn if !=None, change the hrn
270     # @param uuid if !=None, change the uuid
271     # @param pubkey if !=None, change the public key
272
273     def refresh_gid(self, gid, xrn=None, uuid=None, pubkey=None):
274         # TODO: compute expiration time of GID, refresh it if necessary
275         gid_is_expired = False
276
277         # update the gid if we need to
278         if gid_is_expired or xrn or uuid or pubkey:
279             
280             if not xrn:
281                 xrn = gid.get_urn()
282             if not uuid:
283                 uuid = gid.get_uuid()
284             if not pubkey:
285                 pubkey = gid.get_pubkey()
286
287             gid = self.create_gid(xrn, uuid, pubkey)
288
289         return gid
290
291     ##
292     # Retrieve an authority credential for an authority. The authority
293     # credential will contain the authority privilege and will be signed by
294     # the authority's parent.
295     #
296     # @param hrn the human readable name of the authority (urn is converted to hrn)
297     # @param authority type of credential to return (authority | sa | ma)
298
299     def get_auth_cred(self, xrn, kind="authority"):
300         hrn, type = urn_to_hrn(xrn) 
301         auth_info = self.get_auth_info(hrn)
302         gid = auth_info.get_gid_object()
303
304         cred = Credential(subject=hrn)
305         cred.set_gid_caller(gid)
306         cred.set_gid_object(gid)
307         cred.set_privileges(kind)
308         cred.get_privileges().delegate_all_privileges(True)
309         #cred.set_pubkey(auth_info.get_gid_object().get_pubkey())
310
311         parent_hrn = get_authority(hrn)
312         if not parent_hrn or hrn == self.config.SFA_INTERFACE_HRN:
313             # if there is no parent hrn, then it must be self-signed. this
314             # is where we terminate the recursion
315             cred.set_issuer_keys(auth_info.get_privkey_filename(), auth_info.get_gid_filename())
316         else:
317             # we need the parent's private key in order to sign this GID
318             parent_auth_info = self.get_auth_info(parent_hrn)
319             cred.set_issuer_keys(parent_auth_info.get_privkey_filename(), parent_auth_info.get_gid_filename())
320
321             
322             cred.set_parent(self.get_auth_cred(parent_hrn, kind))
323
324         cred.encode()
325         cred.sign()
326
327         return cred
328     ##
329     # Retrieve an authority ticket. An authority ticket is not actually a
330     # redeemable ticket, but only serves the purpose of being included as the
331     # parent of another ticket, in order to provide a chain of authentication
332     # for a ticket.
333     #
334     # This looks almost the same as get_auth_cred, but works for tickets
335     # XXX does similarity imply there should be more code re-use?
336     #
337     # @param xrn the human readable name of the authority (urn is converted to hrn)
338
339     def get_auth_ticket(self, xrn):
340         hrn, type = urn_to_hrn(xrn)
341         auth_info = self.get_auth_info(hrn)
342         gid = auth_info.get_gid_object()
343
344         ticket = SfaTicket(subject=hrn)
345         ticket.set_gid_caller(gid)
346         ticket.set_gid_object(gid)
347         ticket.set_delegate(True)
348         ticket.set_pubkey(auth_info.get_gid_object().get_pubkey())
349
350         parent_hrn = get_authority(hrn)
351         if not parent_hrn:
352             # if there is no parent hrn, then it must be self-signed. this
353             # is where we terminate the recursion
354             ticket.set_issuer(auth_info.get_pkey_object(), hrn)
355         else:
356             # we need the parent's private key in order to sign this GID
357             parent_auth_info = self.get_auth_info(parent_hrn)
358             ticket.set_issuer(parent_auth_info.get_pkey_object(), parent_auth_info.hrn)
359             ticket.set_parent(self.get_auth_cred(parent_hrn))
360
361         ticket.encode()
362         ticket.sign()
363
364         return ticket
365