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