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