5976b6621eae81bfbd3b34ae09ba190fe31ee2db
[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
33 from sfa.util.sfalogging import sfa_logger
34 from sfa.trust.certificate import Certificate
35 from sfa.util.namespace import hrn_to_urn, urn_to_hrn
36
37 ##
38 # Create a new uuid. Returns the UUID as a string.
39
40 def create_uuid():
41     return str(uuid.uuid4().int)
42
43 ##
44 # GID is a tuple:
45 #    (uuid, urn, public_key)
46 #
47 # UUID is a unique identifier and is created by the python uuid module
48 #    (or the utility function create_uuid() in gid.py).
49 #
50 # HRN is a human readable name. It is a dotted form similar to a backward domain
51 #    name. For example, planetlab.us.arizona.bakers.
52 #
53 # URN is a human readable identifier of form:
54 #   "urn:publicid:IDN+toplevelauthority[:sub-auth.]*[\res. type]\ +object name"
55 #   For  example, urn:publicid:IDN+planetlab:us:arizona+user+bakers      
56 #
57 # PUBLIC_KEY is the public key of the principal identified by the UUID/HRN.
58 # It is a Keypair object as defined in the cert.py module.
59 #
60 # It is expected that there is a one-to-one pairing between UUIDs and HRN,
61 # but it is uncertain how this would be inforced or if it needs to be enforced.
62 #
63 # These fields are encoded using xmlrpc into the subjectAltName field of the
64 # x509 certificate. Note: Call encode() once the fields have been filled in
65 # to perform this encoding.
66
67
68 class GID(Certificate):
69     uuid = None
70     hrn = None
71     urn = None
72
73     ##
74     # Create a new GID object
75     #
76     # @param create If true, create the X509 certificate
77     # @param subject If subject!=None, create the X509 cert and set the subject name
78     # @param string If string!=None, load the GID from a string
79     # @param filename If filename!=None, load the GID from a file
80
81     def __init__(self, create=False, subject=None, string=None, filename=None, uuid=None, hrn=None, urn=None):
82         
83         Certificate.__init__(self, create, subject, string, filename)
84         if subject:
85             sfa_logger().debug("Creating GID for subject: %s" % subject)
86         if uuid:
87             self.uuid = int(uuid)
88         if hrn:
89             self.hrn = hrn
90             self.urn = hrn_to_urn(hrn, 'unknown')
91         if urn:
92             self.urn = urn
93             self.hrn, type = urn_to_hrn(urn)
94
95     def set_uuid(self, uuid):
96         if isinstance(uuid, str):
97             self.uuid = int(uuid)
98         else:
99             self.uuid = uuid
100
101     def get_uuid(self):
102         if not self.uuid:
103             self.decode()
104         return self.uuid
105
106     def set_hrn(self, hrn):
107         self.hrn = hrn
108
109     def get_hrn(self):
110         if not self.hrn:
111             self.decode()
112         return self.hrn
113
114     def set_urn(self, urn):
115         self.urn = urn
116         self.hrn, type = urn_to_hrn(urn)
117  
118     def get_urn(self):
119         if not self.urn:
120             self.decode()
121         return self.urn            
122
123     def get_type(self):
124         if not self.urn:
125             self.decode()
126         _, t = urn_to_hrn(self.urn)
127         return t
128     
129     ##
130     # Encode the GID fields and package them into the subject-alt-name field
131     # of the X509 certificate. This must be called prior to signing the
132     # certificate. It may only be called once per certificate.
133
134     def encode(self):
135         if self.urn:
136             urn = self.urn
137         else:
138             urn = hrn_to_urn(self.hrn, None)
139             
140         str = "URI:" + urn
141
142         if self.uuid:
143             str += ", " + "URI:" + uuid.UUID(int=self.uuid).urn
144         
145         self.set_data(str, 'subjectAltName')
146
147         
148
149
150     ##
151     # Decode the subject-alt-name field of the X509 certificate into the
152     # fields of the GID. This is automatically called by the various get_*()
153     # functions in this class.
154
155     def decode(self):
156         data = self.get_data('subjectAltName')
157         dict = {}
158         if data:
159             if data.lower().startswith('uri:http://<params>'):
160                 dict = xmlrpclib.loads(data[11:])[0][0]
161             else:
162                 spl = data.split(', ')
163                 for val in spl:
164                     if val.lower().startswith('uri:urn:uuid:'):
165                         dict['uuid'] = uuid.UUID(val[4:]).int
166                     elif val.lower().startswith('uri:urn:publicid:idn+'):
167                         dict['urn'] = val[4:]
168                     
169         self.uuid = dict.get("uuid", None)
170         self.urn = dict.get("urn", None)
171         self.hrn = dict.get("hrn", None)    
172         if self.urn:
173             self.hrn = urn_to_hrn(self.urn)[0]
174
175     ##
176     # Dump the credential to stdout.
177     #
178     # @param indent specifies a number of spaces to indent the output
179     # @param dump_parents If true, also dump the parents of the GID
180
181     def dump(self, *args, **kwargs):
182         print self.dump_string(*args,**kwargs)
183
184     def dump_string(self, indent=0, dump_parents=False):
185         result="GID\n"
186         result += " "*indent + "hrn:" + str(self.get_hrn()) +"\n"
187         result += " "*indent + "urn:" + str(self.get_urn()) +"\n"
188         result += " "*indent + "uuid:" + str(self.get_uuid()) + "\n"
189         filename=self.get_filename()
190         if filename: result += "Filename %s\n"%filename
191
192         if self.parent and dump_parents:
193             result += " "*indent + "parent:\n"
194             result += self.parent.dump_string(indent+4, dump_parents)
195         return result
196
197     ##
198     # Verify the chain of authenticity of the GID. First perform the checks
199     # of the certificate class (verifying that each parent signs the child,
200     # etc). In addition, GIDs also confirm that the parent's HRN is a prefix
201     # of the child's HRN.
202     #
203     # Verifying these prefixes prevents a rogue authority from signing a GID
204     # for a principal that is not a member of that authority. For example,
205     # planetlab.us.arizona cannot sign a GID for planetlab.us.princeton.foo.
206
207     def verify_chain(self, trusted_certs = None):
208         # do the normal certificate verification stuff
209         trusted_root = Certificate.verify_chain(self, trusted_certs)        
210        
211         if self.parent:
212             # make sure the parent's hrn is a prefix of the child's hrn
213             if not self.get_hrn().startswith(self.parent.get_hrn()):
214                 raise GidParentHrn("This cert HRN %s doesnt start with parent HRN %s" % (self.get_hrn(), self.parent.get_hrn()))
215         else:
216             # make sure that the trusted root's hrn is a prefix of the child's
217             trusted_gid = GID(string=trusted_root.save_to_string())
218             trusted_type = trusted_gid.get_type()
219             trusted_hrn = trusted_gid.get_hrn()
220             #if trusted_type == 'authority':
221             #    trusted_hrn = trusted_hrn[:trusted_hrn.rindex('.')]
222             cur_hrn = self.get_hrn()
223             if not self.get_hrn().startswith(trusted_hrn):
224                 raise GidParentHrn("Trusted roots HRN %s isnt start of this cert %s" % (trusted_hrn, cur_hrn))
225
226         return