renaming the toplevel geni/ package into sfa/
[sfa.git] / sfa / util / hierarchy.py
1 ##
2 # This module implements a hierarchy of authorities and performs a similar
3 # function as the "tree" module of the original geniwrapper 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 import report
20
21 from sfa.trust.certificate import Keypair
22 from sfa.trust.credential import *
23 from sfa.trust.gid import *
24
25 from sfa.util.misc import *
26 from sfa.util.config import *
27 from sfa.util.geniticket import *
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 hrn the human readable name of the authority
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, hrn, gid_filename, privkey_filename, dbinfo_filename):
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             config = Config()
114             basedir = config.config_path + os.sep + "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 hrn the human readable name of the authority
121
122     def get_auth_filenames(self, hrn):
123         leaf = get_leaf(hrn)
124         parent_hrn = get_authority(hrn)
125         directory = os.path.join(self.basedir, hrn.replace(".", "/"))
126
127         gid_filename = os.path.join(directory, leaf+".gid")
128         privkey_filename = os.path.join(directory, leaf+".pkey")
129         dbinfo_filename = os.path.join(directory, leaf+".dbinfo")
130
131         return (directory, gid_filename, privkey_filename, dbinfo_filename)
132
133     ##
134     # Check to see if an authority exists. An authority exists if it's disk
135     # files exist.
136     #
137     # @param the human readable name of the authority to check
138
139     def auth_exists(self, hrn):
140         (directory, gid_filename, privkey_filename, dbinfo_filename) = \
141             self.get_auth_filenames(hrn)
142         
143         return os.path.exists(gid_filename) and \
144                os.path.exists(privkey_filename) and \
145                os.path.exists(dbinfo_filename)
146
147     ##
148     # Create an authority. A private key for the authority and the associated
149     # GID are created and signed by the parent authority.
150     #
151     # @param hrn the human readable name of the authority to create
152     # @param create_parents if true, also create the parents if they do not exist
153
154     def create_auth(self, hrn, create_parents=False):
155         report.trace("Hierarchy: creating authority: " + hrn)
156
157         # create the parent authority if necessary
158         parent_hrn = get_authority(hrn)
159         if (parent_hrn) and (not self.auth_exists(parent_hrn)) and (create_parents):
160             self.create_auth(parent_hrn, create_parents)
161
162         (directory, gid_filename, privkey_filename, dbinfo_filename) = \
163             self.get_auth_filenames(hrn)
164
165         # create the directory to hold the files
166         try:
167             os.makedirs(directory)
168         # if the path already exists then pass
169         except OSError, (errno, strerr):
170             if errno == 17:
171                 pass
172
173         if os.path.exists(privkey_filename):
174             print "using existing key", privkey_filename, "for authority", hrn
175             pkey = Keypair(filename = privkey_filename)
176         else:
177             pkey = Keypair(create = True)
178             pkey.save_to_file(privkey_filename)
179
180         gid = self.create_gid(hrn, create_uuid(), pkey)
181         gid.save_to_file(gid_filename, save_parents=True)
182
183         # XXX TODO: think up a better way for the dbinfo to work
184
185         dbinfo = get_default_dbinfo()
186         dbinfo_file = file(dbinfo_filename, "w")
187         dbinfo_file.write(str(dbinfo))
188         dbinfo_file.close()
189
190     ##
191     # Return the AuthInfo object for the specified authority. If the authority
192     # does not exist, then an exception is thrown. As a side effect, disk files
193     # and a subdirectory may be created to store the authority.
194     #
195     # @param hrn the human readable name of the authority to create.
196
197     def get_auth_info(self, hrn):
198         #report.trace("Hierarchy: getting authority: " + hrn)
199    
200         if not self.auth_exists(hrn):
201             raise MissingAuthority(hrn)
202
203         (directory, gid_filename, privkey_filename, dbinfo_filename) = \
204             self.get_auth_filenames(hrn)
205
206         auth_info = AuthInfo(hrn, gid_filename, privkey_filename, dbinfo_filename)
207
208         # check the GID and see if it needs to be refreshed
209         gid = auth_info.get_gid_object()
210         gid_refreshed = self.refresh_gid(gid)
211         if gid != gid_refreshed:
212             auth_info.update_gid_object(gid_refreshed)
213
214         return auth_info
215
216     ##
217     # Create a new GID. The GID will be signed by the authority that is it's
218     # immediate parent in the hierarchy (and recursively, the parents' GID
219     # will be signed by its parent)
220     #
221     # @param hrn the human readable name to store in the GID
222     # @param uuid the unique identifier to store in the GID
223     # @param pkey the public key to store in the GID
224
225     def create_gid(self, hrn, uuid, pkey):
226         gid = GID(subject=hrn, uuid=uuid, hrn=hrn)
227
228         parent_hrn = get_authority(hrn)
229         if not parent_hrn:
230             # if there is no parent hrn, then it must be self-signed. this
231             # is where we terminate the recursion
232             gid.set_issuer(pkey, hrn)
233         else:
234             # we need the parent's private key in order to sign this GID
235             parent_auth_info = self.get_auth_info(parent_hrn)
236             gid.set_issuer(parent_auth_info.get_pkey_object(), parent_auth_info.hrn)
237             gid.set_parent(parent_auth_info.get_gid_object())
238
239         gid.set_pubkey(pkey)
240         gid.encode()
241         gid.sign()
242
243         return gid
244
245     ##
246     # Refresh a GID. The primary use of this function is to refresh the
247     # the expiration time of the GID. It may also be used to change the HRN,
248     # UUID, or Public key of the GID.
249     #
250     # @param gid the GID to refresh
251     # @param hrn if !=None, change the hrn
252     # @param uuid if !=None, change the uuid
253     # @param pubkey if !=None, change the public key
254
255     def refresh_gid(self, gid, hrn=None, uuid=None, pubkey=None):
256         # TODO: compute expiration time of GID, refresh it if necessary
257         gid_is_expired = False
258
259         # update the gid if we need to
260         if gid_is_expired or hrn or uuid or pubkey:
261             if not hrn:
262                 hrn = gid.get_hrn()
263             if not uuid:
264                 uuid = gid.get_uuid()
265             if not pubkey:
266                 pubkey = gid.get_pubkey()
267
268             gid = self.create_gid(hrn, uuid, pubkey)
269
270         return gid
271
272     ##
273     # Retrieve an authority credential for an authority. The authority
274     # credential will contain the authority privilege and will be signed by
275     # the authority's parent.
276     #
277     # @param hrn the human readable name of the authority
278     # @param authority type of credential to return (authority | sa | ma)
279
280     def get_auth_cred(self, hrn, kind="authority"):
281         auth_info = self.get_auth_info(hrn)
282         gid = auth_info.get_gid_object()
283
284         cred = Credential(subject=hrn)
285         cred.set_gid_caller(gid)
286         cred.set_gid_object(gid)
287         cred.set_privileges(kind)
288         cred.set_delegate(True)
289         cred.set_pubkey(auth_info.get_gid_object().get_pubkey())
290
291         parent_hrn = get_authority(hrn)
292         if not parent_hrn:
293             # if there is no parent hrn, then it must be self-signed. this
294             # is where we terminate the recursion
295             cred.set_issuer(auth_info.get_pkey_object(), hrn)
296         else:
297             # we need the parent's private key in order to sign this GID
298             parent_auth_info = self.get_auth_info(parent_hrn)
299             cred.set_issuer(parent_auth_info.get_pkey_object(), parent_auth_info.hrn)
300             cred.set_parent(self.get_auth_cred(parent_hrn, kind))
301
302         cred.encode()
303         cred.sign()
304
305         return cred
306     ##
307     # Retrieve an authority ticket. An authority ticket is not actually a
308     # redeemable ticket, but only serves the purpose of being included as the
309     # parent of another ticket, in order to provide a chain of authentication
310     # for a ticket.
311     #
312     # This looks almost the same as get_auth_cred, but works for tickets
313     # XXX does similarity imply there should be more code re-use?
314     #
315     # @param hrn the human readable name of the authority
316
317     def get_auth_ticket(self, hrn):
318         auth_info = self.get_auth_info(hrn)
319         gid = auth_info.get_gid_object()
320
321         ticket = Ticket(subject=hrn)
322         ticket.set_gid_caller(gid)
323         ticket.set_gid_object(gid)
324         ticket.set_delegate(True)
325         ticket.set_pubkey(auth_info.get_gid_object().get_pubkey())
326
327         parent_hrn = get_authority(hrn)
328         if not parent_hrn:
329             # if there is no parent hrn, then it must be self-signed. this
330             # is where we terminate the recursion
331             ticket.set_issuer(auth_info.get_pkey_object(), hrn)
332         else:
333             # we need the parent's private key in order to sign this GID
334             parent_auth_info = self.get_auth_info(parent_hrn)
335             ticket.set_issuer(parent_auth_info.get_pkey_object(), parent_auth_info.hrn)
336             ticket.set_parent(self.get_auth_cred(parent_hrn))
337
338         ticket.encode()
339         ticket.sign()
340
341         return ticket
342