python3 - 2to3 + miscell obvious tweaks
[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
29
30 import uuid
31
32 from sfa.trust.certificate import Certificate
33
34 from sfa.util.faults import GidInvalidParentHrn, GidParentHrn
35 from sfa.util.xrn import hrn_to_urn, urn_to_hrn, hrn_authfor_hrn
36 from sfa.util.sfalogging import logger
37 from sfa.util.py23 import xmlrpc_client
38
39 ##
40 # Create a new uuid. Returns the UUID as a string.
41
42
43 def create_uuid():
44     return str(uuid.uuid4().int)
45
46 ##
47 # GID is a tuple:
48 #    (uuid, urn, public_key)
49 #
50 # UUID is a unique identifier and is created by the python uuid module
51 #    (or the utility function create_uuid() in gid.py).
52 #
53 # HRN is a human readable name. It is a dotted form similar to a backward domain
54 #    name. For example, planetlab.us.arizona.bakers.
55 #
56 # URN is a human readable identifier of form:
57 #   "urn:publicid:IDN+toplevelauthority[:sub-auth.]*[\res. type]\ +object name"
58 #   For  example, urn:publicid:IDN+planetlab:us:arizona+user+bakers
59 #
60 # PUBLIC_KEY is the public key of the principal identified by the UUID/HRN.
61 # It is a Keypair object as defined in the cert.py module.
62 #
63 # It is expected that there is a one-to-one pairing between UUIDs and HRN,
64 # but it is uncertain how this would be inforced or if it needs to be enforced.
65 #
66 # These fields are encoded using xmlrpc into the subjectAltName field of the
67 # x509 certificate. Note: Call encode() once the fields have been filled in
68 # to perform this encoding.
69
70
71 class GID(Certificate):
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     # @param lifeDays life of GID in days - default is 1825==5 years
80     # @param email Email address to put in subjectAltName - default is None
81
82     def __init__(self, create=False, subject=None, string=None, filename=None,
83                  uuid=None, hrn=None, urn=None, lifeDays=1825, email=None):
84         self.uuid = None
85         self.hrn = None
86         self.urn = None
87         self.email = None  # for adding to the SubjectAltName
88         Certificate.__init__(self, lifeDays, create, subject, string, filename)
89
90         if subject:
91             logger.debug("Creating GID for subject: %s" % subject)
92         if uuid:
93             self.uuid = int(uuid)
94         if hrn:
95             self.hrn = hrn
96             self.urn = hrn_to_urn(hrn, 'unknown')
97         if urn:
98             self.urn = urn
99             self.hrn, type = urn_to_hrn(urn)
100
101         if email:
102             logger.debug("Creating GID for subject using email: %s" % email)
103             self.set_email(email)
104
105     def set_uuid(self, uuid):
106         if isinstance(uuid, str):
107             self.uuid = int(uuid)
108         else:
109             self.uuid = uuid
110
111     def get_uuid(self):
112         if not self.uuid:
113             self.decode()
114         return self.uuid
115
116     def set_hrn(self, hrn):
117         self.hrn = hrn
118
119     def get_hrn(self):
120         if not self.hrn:
121             self.decode()
122         return self.hrn
123
124     def set_urn(self, urn):
125         self.urn = urn
126         self.hrn, type = urn_to_hrn(urn)
127
128     def get_urn(self):
129         if not self.urn:
130             self.decode()
131         return self.urn
132
133     # Will be stuffed into subjectAltName
134     def set_email(self, email):
135         self.email = email
136
137     def get_email(self):
138         if not self.email:
139             self.decode()
140         return self.email
141
142     def get_type(self):
143         if not self.urn:
144             self.decode()
145         _, t = urn_to_hrn(self.urn)
146         return t
147
148     ##
149     # Encode the GID fields and package them into the subject-alt-name field
150     # of the X509 certificate. This must be called prior to signing the
151     # certificate. It may only be called once per certificate.
152
153     def encode(self):
154         if self.urn:
155             urn = self.urn
156         else:
157             urn = hrn_to_urn(self.hrn, None)
158
159         string = "URI:" + urn
160
161         if self.uuid:
162             string += ", " + "URI:" + uuid.UUID(int=self.uuid).urn
163
164         if self.email:
165             string += ", " + "email:" + self.email
166
167         self.set_data(string, 'subjectAltName')
168
169     ##
170     # Decode the subject-alt-name field of the X509 certificate into the
171     # fields of the GID. This is automatically called by the various get_*()
172     # functions in this class.
173
174     def decode(self):
175         data = self.get_data('subjectAltName')
176         dict = {}
177         if data:
178             if data.lower().startswith('uri:http://<params>'):
179                 dict = xmlrpc_client.loads(data[11:])[0][0]
180             else:
181                 spl = data.split(', ')
182                 for val in spl:
183                     if val.lower().startswith('uri:urn:uuid:'):
184                         dict['uuid'] = uuid.UUID(val[4:]).int
185                     elif val.lower().startswith('uri:urn:publicid:idn+'):
186                         dict['urn'] = val[4:]
187                     elif val.lower().startswith('email:'):
188                         # FIXME: Ensure there isn't cruft in that address...
189                         # EG look for email:copy,....
190                         dict['email'] = val[6:]
191
192         self.uuid = dict.get("uuid", None)
193         self.urn = dict.get("urn", None)
194         self.hrn = dict.get("hrn", None)
195         self.email = dict.get("email", None)
196         if self.urn:
197             self.hrn = urn_to_hrn(self.urn)[0]
198
199     ##
200     # Dump the credential to stdout.
201     #
202     # @param indent specifies a number of spaces to indent the output
203     # @param dump_parents If true, also dump the parents of the GID
204
205     def dump(self, *args, **kwargs):
206         print(self.dump_string(*args, **kwargs))
207
208     def dump_string(self, indent=0, dump_parents=False):
209         result = " " * (indent - 2) + "GID\n"
210         result += " " * indent + "hrn:" + str(self.get_hrn()) + "\n"
211         result += " " * indent + "urn:" + str(self.get_urn()) + "\n"
212         result += " " * indent + "uuid:" + str(self.get_uuid()) + "\n"
213         if self.get_email() is not None:
214             result += " " * indent + "email:" + str(self.get_email()) + "\n"
215         filename = self.get_filename()
216         if filename:
217             result += "Filename %s\n" % filename
218
219         if self.parent and dump_parents:
220             result += " " * indent + "parent:\n"
221             result += self.parent.dump_string(indent + 4, dump_parents)
222         return result
223
224     ##
225     # Verify the chain of authenticity of the GID. First perform the checks
226     # of the certificate class (verifying that each parent signs the child,
227     # etc). In addition, GIDs also confirm that the parent's HRN is a prefix
228     # of the child's HRN, and the parent is of type 'authority'.
229     #
230     # Verifying these prefixes prevents a rogue authority from signing a GID
231     # for a principal that is not a member of that authority. For example,
232     # planetlab.us.arizona cannot sign a GID for planetlab.us.princeton.foo.
233
234     def verify_chain(self, trusted_certs=None):
235         logger.debug(10*'=' + " GID.verify_chain with {} trusted certs"
236                      .format(len(trusted_certs)))
237         logger.debug("on {}".format(self.pretty_name()))
238         # do the normal certificate verification stuff
239         trusted_root = Certificate.verify_chain(self, trusted_certs)
240
241         if self.parent:
242             # make sure the parent's hrn is a prefix of the child's hrn
243             if not hrn_authfor_hrn(self.parent.get_hrn(), self.get_hrn()):
244                 raise GidParentHrn(
245                     "This cert HRN {} isn't in the namespace for parent HRN {}"
246                     .format(self.get_hrn(), self.parent.get_hrn()))
247
248             # Parent must also be an authority (of some type) to sign a GID
249             # There are multiple types of authority - accept them all here
250             if not self.parent.get_type().find('authority') == 0:
251                 raise GidInvalidParentHrn(
252                     "This cert {}'s parent {} is not an authority (is a %{})"
253                     .format(self.get_hrn(), self.parent.get_hrn(), self.parent.get_type()))
254
255             # Then recurse up the chain - ensure the parent is a trusted
256             # root or is in the namespace of a trusted root
257             self.parent.verify_chain(trusted_certs)
258         else:
259             # make sure that the trusted root's hrn is a prefix of the child's
260             trusted_gid = GID(string=trusted_root.save_to_string())
261             trusted_type = trusted_gid.get_type()
262             trusted_hrn = trusted_gid.get_hrn()
263             # if trusted_type == 'authority':
264             #    trusted_hrn = trusted_hrn[:trusted_hrn.rindex('.')]
265             cur_hrn = self.get_hrn()
266             if not hrn_authfor_hrn(trusted_hrn, cur_hrn):
267                 raise GidParentHrn(
268                     "Trusted root with HRN {} isn't a namespace authority for this cert: {}"
269                     .format(trusted_hrn, cur_hrn))
270
271             # There are multiple types of authority - accept them all here
272             if not trusted_type.find('authority') == 0:
273                 raise GidInvalidParentHrn(
274                     "This cert {}'s trusted root signer {} is not an authority (is a {})"
275                     .format(self.get_hrn(), trusted_hrn, trusted_type))