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