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