GID using email in SubjectAltName
[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 import xmlrpclib
29 import uuid
30
31 from sfa.trust.certificate import Certificate
32
33 from sfa.util.faults import GidInvalidParentHrn, GidParentHrn
34 from sfa.util.sfalogging import logger
35 from sfa.util.xrn import hrn_to_urn, urn_to_hrn, hrn_authfor_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     ##
70     # Create a new GID object
71     #
72     # @param create If true, create the X509 certificate
73     # @param subject If subject!=None, create the X509 cert and set the subject name
74     # @param string If string!=None, load the GID from a string
75     # @param filename If filename!=None, load the GID from a file
76     # @param lifeDays life of GID in days - default is 1825==5 years
77     # @param email Email address to put in subjectAltName - default is None
78
79     def __init__(self, create=False, subject=None, string=None, filename=None, uuid=None, hrn=None, urn=None, lifeDays=1825, email=None):
80         self.uuid = None
81         self.hrn = None
82         self.urn = None
83         self.email = None # for adding to the SubjectAltName             
84         Certificate.__init__(self, lifeDays, create, subject, string, filename)
85
86         if subject:
87             logger.debug("Creating GID for subject: %s" % subject)
88         if uuid:
89             self.uuid = int(uuid)
90         if hrn:
91             self.hrn = hrn
92             self.urn = hrn_to_urn(hrn, 'unknown')
93         if urn:
94             self.urn = urn
95             self.hrn, type = urn_to_hrn(urn)
96
97         if email:
98             logger.debug("Creating GID for subject using email: %s" % email)
99             self.set_email(email)
100
101     def set_uuid(self, uuid):
102         if isinstance(uuid, str):
103             self.uuid = int(uuid)
104         else:
105             self.uuid = uuid
106
107     def get_uuid(self):
108         if not self.uuid:
109             self.decode()
110         return self.uuid
111
112     def set_hrn(self, hrn):
113         self.hrn = hrn
114
115     def get_hrn(self):
116         if not self.hrn:
117             self.decode()
118         return self.hrn
119
120     def set_urn(self, urn):
121         self.urn = urn
122         self.hrn, type = urn_to_hrn(urn)
123  
124     def get_urn(self):
125         if not self.urn:
126             self.decode()
127         return self.urn            
128
129     # Will be stuffed into subjectAltName
130     def set_email(self, email):
131         self.email = email
132
133     def get_email(self):
134         if not self.email:
135             self.decode()
136         return self.email
137
138     def get_type(self):
139         if not self.urn:
140             self.decode()
141         _, t = urn_to_hrn(self.urn)
142         return t
143     
144     ##
145     # Encode the GID fields and package them into the subject-alt-name field
146     # of the X509 certificate. This must be called prior to signing the
147     # certificate. It may only be called once per certificate.
148
149     def encode(self):
150         if self.urn:
151             urn = self.urn
152         else:
153             urn = hrn_to_urn(self.hrn, None)
154             
155         str = "URI:" + urn
156
157         if self.uuid:
158             str += ", " + "URI:" + uuid.UUID(int=self.uuid).urn
159         
160         if self.email:
161             str += ", " + "email:" + self.email
162
163         self.set_data(str, 'subjectAltName')
164
165
166     ##
167     # Decode the subject-alt-name field of the X509 certificate into the
168     # fields of the GID. This is automatically called by the various get_*()
169     # functions in this class.
170
171     def decode(self):
172         data = self.get_data('subjectAltName')
173         dict = {}
174         if data:
175             if data.lower().startswith('uri:http://<params>'):
176                 dict = xmlrpclib.loads(data[11:])[0][0]
177             else:
178                 spl = data.split(', ')
179                 for val in spl:
180                     if val.lower().startswith('uri:urn:uuid:'):
181                         dict['uuid'] = uuid.UUID(val[4:]).int
182                     elif val.lower().startswith('uri:urn:publicid:idn+'):
183                         dict['urn'] = val[4:]
184                     elif val.lower().startswith('email:'):
185                         # FIXME: Ensure there isn't cruft in that address...
186                         # EG look for email:copy,....
187                         dict['email'] = val[6:]
188                     
189         self.uuid = dict.get("uuid", None)
190         self.urn = dict.get("urn", None)
191         self.hrn = dict.get("hrn", None)
192         self.email = dict.get("email", None)
193         if self.urn:
194             self.hrn = urn_to_hrn(self.urn)[0]
195
196     ##
197     # Dump the credential to stdout.
198     #
199     # @param indent specifies a number of spaces to indent the output
200     # @param dump_parents If true, also dump the parents of the GID
201
202     def dump(self, *args, **kwargs):
203         print self.dump_string(*args,**kwargs)
204
205     def dump_string(self, indent=0, dump_parents=False):
206         result=" "*(indent-2) + "GID\n"
207         result += " "*indent + "hrn:" + str(self.get_hrn()) +"\n"
208         result += " "*indent + "urn:" + str(self.get_urn()) +"\n"
209         result += " "*indent + "uuid:" + str(self.get_uuid()) + "\n"
210         if self.get_email() is not None:
211             result += " "*indent + "email:" + str(self.get_email()) + "\n"
212         filename=self.get_filename()
213         if filename: result += "Filename %s\n"%filename
214
215         if self.parent and dump_parents:
216             result += " "*indent + "parent:\n"
217             result += self.parent.dump_string(indent+4, dump_parents)
218         return result
219
220     ##
221     # Verify the chain of authenticity of the GID. First perform the checks
222     # of the certificate class (verifying that each parent signs the child,
223     # etc). In addition, GIDs also confirm that the parent's HRN is a prefix
224     # of the child's HRN, and the parent is of type 'authority'.
225     #
226     # Verifying these prefixes prevents a rogue authority from signing a GID
227     # for a principal that is not a member of that authority. For example,
228     # planetlab.us.arizona cannot sign a GID for planetlab.us.princeton.foo.
229
230     def verify_chain(self, trusted_certs = None):
231         # do the normal certificate verification stuff
232         trusted_root = Certificate.verify_chain(self, trusted_certs)        
233        
234         if self.parent:
235             # make sure the parent's hrn is a prefix of the child's hrn
236             if not hrn_authfor_hrn(self.parent.get_hrn(), self.get_hrn()):
237                 raise GidParentHrn("This cert HRN %s isn't in the namespace for parent HRN %s" % (self.get_hrn(), self.parent.get_hrn()))
238
239             # Parent must also be an authority (of some type) to sign a GID
240             # There are multiple types of authority - accept them all here
241             if not self.parent.get_type().find('authority') == 0:
242                 raise GidInvalidParentHrn("This cert %s's parent %s is not an authority (is a %s)" % (self.get_hrn(), self.parent.get_hrn(), self.parent.get_type()))
243
244             # Then recurse up the chain - ensure the parent is a trusted
245             # root or is in the namespace of a trusted root
246             self.parent.verify_chain(trusted_certs)
247         else:
248             # make sure that the trusted root's hrn is a prefix of the child's
249             trusted_gid = GID(string=trusted_root.save_to_string())
250             trusted_type = trusted_gid.get_type()
251             trusted_hrn = trusted_gid.get_hrn()
252             #if trusted_type == 'authority':
253             #    trusted_hrn = trusted_hrn[:trusted_hrn.rindex('.')]
254             cur_hrn = self.get_hrn()
255             if not hrn_authfor_hrn(trusted_hrn, cur_hrn):
256                 raise GidParentHrn("Trusted root with HRN %s isn't a namespace authority for this cert: %s" % (trusted_hrn, cur_hrn))
257
258             # There are multiple types of authority - accept them all here
259             if not trusted_type.find('authority') == 0:
260                 raise GidInvalidParentHrn("This cert %s's trusted root signer %s is not an authority (is a %s)" % (self.get_hrn(), trusted_hrn, trusted_type))
261
262         return