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