8e126a73db70ce1c322a96aa6b0a8160d125e6ee
[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 ##
13
14 import os
15
16 from sfa.util.faults import MissingAuthority
17 from sfa.util.sfalogging import 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.trust.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
30 class AuthInfo:
31     hrn = None
32     gid_object = None
33     gid_filename = None
34     privkey_filename = None
35     ##
36     # Initialize and authority object.
37     #
38     # @param xrn the human readable name of the authority (urn will be converted to hrn)
39     # @param gid_filename the filename containing the GID
40     # @param privkey_filename the filename containing the private key
41
42     def __init__(self, xrn, gid_filename, privkey_filename):
43         hrn, type = urn_to_hrn(xrn)
44         self.hrn = hrn
45         self.set_gid_filename(gid_filename)
46         self.privkey_filename = privkey_filename
47
48     ##
49     # Set the filename of the GID
50     #
51     # @param fn filename of file containing GID
52
53     def set_gid_filename(self, fn):
54         self.gid_filename = fn
55         self.gid_object = None
56
57     def get_privkey_filename(self):
58         return self.privkey_filename
59
60     def get_gid_filename(self):
61         return self.gid_filename
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     # Replace the GID with a new one. The file specified by gid_filename is
79     # overwritten with the new GID object
80     #
81     # @param gid object containing new GID
82
83     def update_gid_object(self, gid):
84         gid.save_to_file(self.gid_filename)
85         self.gid_object = gid
86
87 ##
88 # The Hierarchy class is responsible for managing the tree of authorities.
89 # Each authority is a node in the tree and exists as an AuthInfo object.
90 #
91 # The tree is stored on disk in a hierarchical manner than reflects the
92 # structure of the tree. Each authority is a subdirectory, and each subdirectory
93 # contains the GID and pkey files for that authority (as well as
94 # subdirectories for each sub-authority)
95
96
97 class Hierarchy:
98     ##
99     # Create the hierarchy object.
100     #
101     # @param basedir the base directory to store the hierarchy in
102
103     def __init__(self, basedir=None):
104         self.config = Config()
105         if not basedir:
106             basedir = os.path.join(self.config.SFA_DATA_DIR, "authorities")
107         self.basedir = basedir
108     ##
109     # Given a hrn, return the filenames of the GID, private key
110     # files.
111     #
112     # @param xrn the human readable name of the authority (urn will be convertd to hrn)
113
114     def get_auth_filenames(self, xrn):
115         hrn, type = urn_to_hrn(xrn)
116         if '\\' in hrn:
117             hrn = hrn.replace('\\', '')
118             leaf = hrn
119         else:
120             leaf = get_leaf(hrn)
121         parent_hrn = get_authority(hrn)
122         directory = os.path.join(self.basedir, hrn.replace(".", "/"))
123
124         gid_filename = os.path.join(directory, leaf + ".gid")
125         privkey_filename = os.path.join(directory, leaf + ".pkey")
126
127         return (directory, gid_filename, privkey_filename)
128
129     ##
130     # Check to see if an authority exists. An authority exists if it's disk
131     # files exist.
132     #
133     # @param the human readable name of the authority to check
134
135     def auth_exists(self, xrn):
136         hrn, type = urn_to_hrn(xrn)
137         (directory, gid_filename, privkey_filename) = \
138             self.get_auth_filenames(hrn)
139
140         return os.path.exists(gid_filename) and os.path.exists(privkey_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 xrn the human readable name of the authority to create (urn will be converted to hrn)
147     # @param create_parents if true, also create the parents if they do not exist
148
149     def create_auth(self, xrn, create_parents=False):
150         hrn, type = urn_to_hrn(str(xrn))
151         logger.debug("Hierarchy: creating authority: %s" % hrn)
152
153         # create the parent authority if necessary
154         parent_hrn = get_authority(hrn)
155         parent_urn = hrn_to_urn(parent_hrn, 'authority')
156         if (parent_hrn) and (not self.auth_exists(parent_urn)) and (create_parents):
157             self.create_auth(parent_urn, create_parents)
158         directory, gid_filename, privkey_filename = self.get_auth_filenames(
159             hrn)
160
161         # create the directory to hold the files
162         try:
163             os.makedirs(directory)
164         # if the path already exists then pass
165         except OSError as xxx_todo_changeme:
166             (errno, strerr) = xxx_todo_changeme.args
167             if errno == 17:
168                 pass
169
170         if os.path.exists(privkey_filename):
171             logger.debug("using existing key %r for authority %r"
172                          % (privkey_filename, hrn))
173             pkey = Keypair(filename=privkey_filename)
174         else:
175             pkey = Keypair(create=True)
176             pkey.save_to_file(privkey_filename)
177
178         gid = self.create_gid(xrn, create_uuid(), pkey)
179         gid.save_to_file(gid_filename, save_parents=True)
180
181     def create_top_level_auth(self, hrn=None):
182         """
183         Create top level records (includes root and sub authorities (local/remote)
184         """
185         # create the authority if it doesnt alrady exist
186         if not self.auth_exists(hrn):
187             self.create_auth(hrn, create_parents=True)
188
189     def get_interface_auth_info(self, create=True):
190         hrn = self.config.SFA_INTERFACE_HRN
191         if not self.auth_exists(hrn):
192             if create == True:
193                 self.create_top_level_auth(hrn)
194             else:
195                 raise MissingAuthority(hrn)
196         return self.get_auth_info(hrn)
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             logger.warning(
208                 "Hierarchy: missing authority - xrn=%s, hrn=%s" % (xrn, hrn))
209             raise MissingAuthority(hrn)
210
211         (directory, gid_filename, privkey_filename, ) = \
212             self.get_auth_filenames(hrn)
213
214         auth_info = AuthInfo(hrn, gid_filename, privkey_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, CA=False, email=None, force_parent=None):
234         hrn, type = urn_to_hrn(xrn)
235         if not type:
236             type = 'authority'
237         parent_hrn = force_parent if force_parent else get_authority(hrn)
238         # Using hrn_to_urn() here to make sure the urn is in the right format
239         # If xrn was a hrn instead of a urn, then the gid's urn will be
240         # of type None
241         urn = hrn_to_urn(hrn, type)
242         gid = GID(subject=hrn, uuid=uuid, hrn=hrn, urn=urn, email=email)
243         # is this a CA cert
244         if hrn == self.config.SFA_INTERFACE_HRN or not parent_hrn:
245             # root or sub authority
246             gid.set_intermediate_ca(True)
247         elif type and 'authority' in type:
248             # authority type
249             gid.set_intermediate_ca(True)
250         elif CA:
251             gid.set_intermediate_ca(True)
252         else:
253             gid.set_intermediate_ca(False)
254
255         # set issuer
256         if not parent_hrn or hrn == self.config.SFA_INTERFACE_HRN:
257             # if there is no parent hrn, then it must be self-signed. this
258             # is where we terminate the recursion
259             gid.set_issuer(pkey, hrn)
260         else:
261             # we need the parent's private key in order to sign this GID
262             parent_auth_info = self.get_auth_info(parent_hrn)
263             gid.set_issuer(parent_auth_info.get_pkey_object(),
264                            parent_auth_info.hrn)
265             gid.set_parent(parent_auth_info.get_gid_object())
266
267         gid.set_pubkey(pkey)
268         gid.encode()
269         gid.sign()
270
271         return gid
272
273     ##
274     # Refresh a GID. The primary use of this function is to refresh the
275     # the expiration time of the GID. It may also be used to change the HRN,
276     # UUID, or Public key of the GID.
277     #
278     # @param gid the GID to refresh
279     # @param hrn if !=None, change the hrn
280     # @param uuid if !=None, change the uuid
281     # @param pubkey if !=None, change the public key
282
283     def refresh_gid(self, gid, xrn=None, uuid=None, pubkey=None):
284         # TODO: compute expiration time of GID, refresh it if necessary
285         gid_is_expired = False
286
287         # update the gid if we need to
288         if gid_is_expired or xrn or uuid or pubkey:
289
290             if not xrn:
291                 xrn = gid.get_urn()
292             if not uuid:
293                 uuid = gid.get_uuid()
294             if not pubkey:
295                 pubkey = gid.get_pubkey()
296
297             gid = self.create_gid(xrn, uuid, pubkey)
298
299         return gid
300
301     ##
302     # Retrieve an authority credential for an authority. The authority
303     # credential will contain the authority privilege and will be signed by
304     # the authority's parent.
305     #
306     # @param hrn the human readable name of the authority (urn is converted to hrn)
307     # @param authority type of credential to return (authority | sa | ma)
308
309     def get_auth_cred(self, xrn, kind="authority"):
310         hrn, type = urn_to_hrn(xrn)
311         auth_info = self.get_auth_info(hrn)
312         gid = auth_info.get_gid_object()
313
314         cred = Credential(subject=hrn)
315         cred.set_gid_caller(gid)
316         cred.set_gid_object(gid)
317         cred.set_privileges(kind)
318         cred.get_privileges().delegate_all_privileges(True)
319         # cred.set_pubkey(auth_info.get_gid_object().get_pubkey())
320
321         parent_hrn = get_authority(hrn)
322         if not parent_hrn or hrn == self.config.SFA_INTERFACE_HRN:
323             # if there is no parent hrn, then it must be self-signed. this
324             # is where we terminate the recursion
325             cred.set_issuer_keys(
326                 auth_info.get_privkey_filename(), auth_info.get_gid_filename())
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             cred.set_issuer_keys(parent_auth_info.get_privkey_filename(
331             ), parent_auth_info.get_gid_filename())
332
333             cred.set_parent(self.get_auth_cred(parent_hrn, kind))
334
335         cred.encode()
336         cred.sign()
337
338         return cred
339     ##
340     # Retrieve an authority ticket. An authority ticket is not actually a
341     # redeemable ticket, but only serves the purpose of being included as the
342     # parent of another ticket, in order to provide a chain of authentication
343     # for a ticket.
344     #
345     # This looks almost the same as get_auth_cred, but works for tickets
346     # XXX does similarity imply there should be more code re-use?
347     #
348     # @param xrn the human readable name of the authority (urn is converted to hrn)
349
350     def get_auth_ticket(self, xrn):
351         hrn, type = urn_to_hrn(xrn)
352         auth_info = self.get_auth_info(hrn)
353         gid = auth_info.get_gid_object()
354
355         ticket = SfaTicket(subject=hrn)
356         ticket.set_gid_caller(gid)
357         ticket.set_gid_object(gid)
358         ticket.set_delegate(True)
359         ticket.set_pubkey(auth_info.get_gid_object().get_pubkey())
360
361         parent_hrn = get_authority(hrn)
362         if not parent_hrn:
363             # if there is no parent hrn, then it must be self-signed. this
364             # is where we terminate the recursion
365             ticket.set_issuer(auth_info.get_pkey_object(), hrn)
366         else:
367             # we need the parent's private key in order to sign this GID
368             parent_auth_info = self.get_auth_info(parent_hrn)
369             ticket.set_issuer(
370                 parent_auth_info.get_pkey_object(), parent_auth_info.hrn)
371             ticket.set_parent(self.get_auth_cred(parent_hrn))
372
373         ticket.encode()
374         ticket.sign()
375
376         return ticket