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