merge from geni_api
[sfa.git] / sfa / trust / gid.py
1 #----------------------------------------------------------------------
2 # Copyright (c) 2008 Board of Trustees, Princeton University
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and/or hardware specification (the "Work") to
6 # deal in the Work without restriction, including without limitation the
7 # rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Work, and to permit persons to whom the Work
9 # is furnished to do so, subject to the following conditions:
10 #
11 # The above copyright notice and this permission notice shall be
12 # included in all copies or substantial portions of the Work.
13 #
14 # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
16 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
17 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 
18 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
19 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
20 # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS 
21 # IN THE WORK.
22 #----------------------------------------------------------------------
23 ##
24 # Implements SFA GID. GIDs are based on certificates, and the GID class is a
25 # descendant of the certificate class.
26 ##
27
28 ### $Id$
29 ### $URL$
30 import xmlrpclib
31 import uuid
32 from sfa.trust.certificate import Certificate
33 from sfa.util.namespace import *
34 from sfa.util.sfalogging import logger
35
36 ##
37 # Create a new uuid. Returns the UUID as a string.
38
39 def create_uuid():
40     return str(uuid.uuid4().int)
41
42 ##
43 # GID is a tuple:
44 #    (uuid, urn, public_key)
45 #
46 # UUID is a unique identifier and is created by the python uuid module
47 #    (or the utility function create_uuid() in gid.py).
48 #
49 # HRN is a human readable name. It is a dotted form similar to a backward domain
50 #    name. For example, planetlab.us.arizona.bakers.
51 #
52 # URN is a human readable identifier of form:
53 #   "urn:publicid:IDN+toplevelauthority[:sub-auth.]*[\res. type]\ +object name"
54 #   For  example, urn:publicid:IDN+planetlab:us:arizona+user+bakers      
55 #
56 # PUBLIC_KEY is the public key of the principal identified by the UUID/HRN.
57 # It is a Keypair object as defined in the cert.py module.
58 #
59 # It is expected that there is a one-to-one pairing between UUIDs and HRN,
60 # but it is uncertain how this would be inforced or if it needs to be enforced.
61 #
62 # These fields are encoded using xmlrpc into the subjectAltName field of the
63 # x509 certificate. Note: Call encode() once the fields have been filled in
64 # to perform this encoding.
65
66
67 class GID(Certificate):
68     uuid = None
69     hrn = None
70     urn = None
71
72     ##
73     # Create a new GID object
74     #
75     # @param create If true, create the X509 certificate
76     # @param subject If subject!=None, create the X509 cert and set the subject name
77     # @param string If string!=None, load the GID from a string
78     # @param filename If filename!=None, load the GID from a file
79
80     def __init__(self, create=False, subject=None, string=None, filename=None, uuid=None, hrn=None, urn=None):
81         
82         Certificate.__init__(self, create, subject, string, filename)
83         if subject:
84             logger.info("subject: %s" % subject)
85         if uuid:
86             self.uuid = int(uuid)
87         if hrn:
88             self.hrn = hrn
89             self.urn = hrn_to_urn(hrn, 'unknown')
90         if urn:
91             self.urn = urn
92             self.hrn, type = urn_to_hrn(urn)
93
94     def set_uuid(self, uuid):
95         if isinstance(uuid, str):
96             self.uuid = int(uuid)
97         else:
98             self.uuid = uuid
99
100     def get_uuid(self):
101         if not self.uuid:
102             self.decode()
103         return self.uuid
104
105     def set_hrn(self, hrn):
106         self.hrn = hrn
107
108     def get_hrn(self):
109         if not self.hrn:
110             self.decode()
111         return self.hrn
112
113     def set_urn(self, urn):
114         self.urn = urn
115         self.hrn, type = urn_to_hrn(urn)
116  
117     def get_urn(self):
118         if not self.urn:
119             self.decode()
120         return self.urn            
121
122     def get_type(self):
123         if not self.urn:
124             self.decode()
125         _, t = urn_to_hrn(self.urn)
126         return t
127     
128     ##
129     # Encode the GID fields and package them into the subject-alt-name field
130     # of the X509 certificate. This must be called prior to signing the
131     # certificate. It may only be called once per certificate.
132
133     def encode(self):
134         if self.urn:
135             urn = self.urn
136         else:
137             urn = hrn_to_urn(self.hrn, None)
138             
139         str = "URI:" + urn
140
141         if self.uuid:
142             str += ", " + "URI:" + uuid.UUID(int=self.uuid).urn
143         
144         self.set_data(str, 'subjectAltName')
145
146         
147
148
149     ##
150     # Decode the subject-alt-name field of the X509 certificate into the
151     # fields of the GID. This is automatically called by the various get_*()
152     # functions in this class.
153
154     def decode(self):
155         data = self.get_data('subjectAltName')
156         dict = {}
157         if data:
158             if data.lower().startswith('uri:http://<params>'):
159                 dict = xmlrpclib.loads(data[11:])[0][0]
160             else:
161                 spl = data.split(', ')
162                 for val in spl:
163                     if val.lower().startswith('uri:urn:uuid:'):
164                         dict['uuid'] = uuid.UUID(val[4:]).int
165                     elif val.lower().startswith('uri:urn:publicid:idn+'):
166                         dict['urn'] = val[4:]
167                     
168         self.uuid = dict.get("uuid", None)
169         self.urn = dict.get("urn", None)
170         self.hrn = dict.get("hrn", None)    
171         if self.urn:
172             self.hrn = urn_to_hrn(self.urn)[0]
173
174     ##
175     # Dump the credential to stdout.
176     #
177     # @param indent specifies a number of spaces to indent the output
178     # @param dump_parents If true, also dump the parents of the GID
179
180     def dump(self, indent=0, dump_parents=False):
181         print " "*indent, " hrn:", self.get_hrn()
182         print " "*indent, " urn:", self.get_urn()
183         print " "*indent, "uuid:", self.get_uuid()
184
185         if self.parent and dump_parents:
186             print " "*indent, "parent:"
187             self.parent.dump(indent+4, dump_parents)
188
189     ##
190     # Verify the chain of authenticity of the GID. First perform the checks
191     # of the certificate class (verifying that each parent signs the child,
192     # etc). In addition, GIDs also confirm that the parent's HRN is a prefix
193     # of the child's HRN.
194     #
195     # Verifying these prefixes prevents a rogue authority from signing a GID
196     # for a principal that is not a member of that authority. For example,
197     # planetlab.us.arizona cannot sign a GID for planetlab.us.princeton.foo.
198
199     def verify_chain(self, trusted_certs = None):
200         # do the normal certificate verification stuff
201         trusted_root = Certificate.verify_chain(self, trusted_certs)        
202
203         test_gid = None
204         if self.parent:
205             test_gid = self.parent
206         else:
207             test_gid = GID(string=trusted_root.save_to_string())
208
209         test_type = test_gid.get_type()
210         test_hrn = test_gid.get_hrn()
211         if test_type == 'authority':
212             # Could add a check for type == 'authority'
213             test_hrn = test_hrn[:test_hrn.rindex('.')]
214         cur_hrn = self.get_hrn()
215         if not self.get_hrn().startswith(test_hrn):
216             GidParentHrn(test_hrn + " " + self.get_hrn())
217
218         return
219
220
221
222
223