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