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