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