improved error and log messages
[sfa.git] / sfa / trust / credential.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 Credentials\r
25 #\r
26 # Credentials are signed XML files that assign a subject gid privileges to an object gid\r
27 ##\r
28 \r
29 import os\r
30 from types import StringTypes\r
31 import datetime\r
32 from StringIO import StringIO\r
33 from tempfile import mkstemp\r
34 from xml.dom.minidom import Document, parseString\r
35 \r
36 HAVELXML = False\r
37 try:\r
38     from lxml import etree\r
39     HAVELXML = True\r
40 except:\r
41     pass\r
42 \r
43 from sfa.util.faults import *\r
44 from sfa.util.sfalogging import logger\r
45 from sfa.util.sfatime import utcparse\r
46 from sfa.trust.certificate import Keypair\r
47 from sfa.trust.credential_legacy import CredentialLegacy\r
48 from sfa.trust.rights import Right, Rights, determine_rights\r
49 from sfa.trust.gid import GID\r
50 from sfa.util.xrn import urn_to_hrn, hrn_authfor_hrn\r
51 \r
52 # 2 weeks, in seconds \r
53 DEFAULT_CREDENTIAL_LIFETIME = 86400 * 14\r
54 \r
55 \r
56 # TODO:\r
57 # . make privs match between PG and PL\r
58 # . Need to add support for other types of credentials, e.g. tickets\r
59 # . add namespaces to signed-credential element?\r
60 \r
61 signature_template = \\r
62 '''\r
63 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">\r
64   <SignedInfo>\r
65     <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>\r
66     <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>\r
67     <Reference URI="#%s">\r
68       <Transforms>\r
69         <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />\r
70       </Transforms>\r
71       <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>\r
72       <DigestValue></DigestValue>\r
73     </Reference>\r
74   </SignedInfo>\r
75   <SignatureValue />\r
76   <KeyInfo>\r
77     <X509Data>\r
78       <X509SubjectName/>\r
79       <X509IssuerSerial/>\r
80       <X509Certificate/>\r
81     </X509Data>\r
82     <KeyValue />\r
83   </KeyInfo>\r
84 </Signature>\r
85 '''\r
86 \r
87 # PG formats the template (whitespace) slightly differently.\r
88 # Note that they don't include the xmlns in the template, but add it later.\r
89 # Otherwise the two are equivalent.\r
90 #signature_template_as_in_pg = \\r
91 #'''\r
92 #<Signature xml:id="Sig_%s" >\r
93 # <SignedInfo>\r
94 #  <CanonicalizationMethod      Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>\r
95 #  <SignatureMethod      Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>\r
96 #  <Reference URI="#%s">\r
97 #    <Transforms>\r
98 #      <Transform         Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />\r
99 #    </Transforms>\r
100 #    <DigestMethod        Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>\r
101 #    <DigestValue></DigestValue>\r
102 #    </Reference>\r
103 # </SignedInfo>\r
104 # <SignatureValue />\r
105 # <KeyInfo>\r
106 #  <X509Data >\r
107 #   <X509SubjectName/>\r
108 #   <X509IssuerSerial/>\r
109 #   <X509Certificate/>\r
110 #  </X509Data>\r
111 #  <KeyValue />\r
112 # </KeyInfo>\r
113 #</Signature>\r
114 #'''\r
115 \r
116 ##\r
117 # Convert a string into a bool\r
118 # used to convert an xsd:boolean to a Python boolean\r
119 def str2bool(str):\r
120     if str.lower() in ['true','1']:\r
121         return True\r
122     return False\r
123 \r
124 \r
125 ##\r
126 # Utility function to get the text of an XML element\r
127 \r
128 def getTextNode(element, subele):\r
129     sub = element.getElementsByTagName(subele)[0]\r
130     if len(sub.childNodes) > 0:            \r
131         return sub.childNodes[0].nodeValue\r
132     else:\r
133         return None\r
134         \r
135 ##\r
136 # Utility function to set the text of an XML element\r
137 # It creates the element, adds the text to it,\r
138 # and then appends it to the parent.\r
139 \r
140 def append_sub(doc, parent, element, text):\r
141     ele = doc.createElement(element)\r
142     ele.appendChild(doc.createTextNode(text))\r
143     parent.appendChild(ele)\r
144 \r
145 ##\r
146 # Signature contains information about an xmlsec1 signature\r
147 # for a signed-credential\r
148 #\r
149 \r
150 class Signature(object):\r
151    \r
152     def __init__(self, string=None):\r
153         self.refid = None\r
154         self.issuer_gid = None\r
155         self.xml = None\r
156         if string:\r
157             self.xml = string\r
158             self.decode()\r
159 \r
160 \r
161     def get_refid(self):\r
162         if not self.refid:\r
163             self.decode()\r
164         return self.refid\r
165 \r
166     def get_xml(self):\r
167         if not self.xml:\r
168             self.encode()\r
169         return self.xml\r
170 \r
171     def set_refid(self, id):\r
172         self.refid = id\r
173 \r
174     def get_issuer_gid(self):\r
175         if not self.gid:\r
176             self.decode()\r
177         return self.gid        \r
178 \r
179     def set_issuer_gid(self, gid):\r
180         self.gid = gid\r
181 \r
182     def decode(self):\r
183         doc = parseString(self.xml)\r
184         sig = doc.getElementsByTagName("Signature")[0]\r
185         self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))\r
186         keyinfo = sig.getElementsByTagName("X509Data")[0]\r
187         szgid = getTextNode(keyinfo, "X509Certificate")\r
188         szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid\r
189         self.set_issuer_gid(GID(string=szgid))        \r
190         \r
191     def encode(self):\r
192         self.xml = signature_template % (self.get_refid(), self.get_refid())\r
193 \r
194 \r
195 ##\r
196 # A credential provides a caller gid with privileges to an object gid.\r
197 # A signed credential is signed by the object's authority.\r
198 #\r
199 # Credentials are encoded in one of two ways.  The legacy style places\r
200 # it in the subjectAltName of an X509 certificate.  The new credentials\r
201 # are placed in signed XML.\r
202 #\r
203 # WARNING:\r
204 # In general, a signed credential obtained externally should\r
205 # not be changed else the signature is no longer valid.  So, once\r
206 # you have loaded an existing signed credential, do not call encode() or sign() on it.\r
207 \r
208 def filter_creds_by_caller(creds, caller_hrn):\r
209         """\r
210         Returns a list of creds who's gid caller matches the\r
211         specified caller hrn\r
212         """\r
213         if not isinstance(creds, list): creds = [creds]\r
214         caller_creds = []\r
215         for cred in creds:\r
216             try:\r
217                 tmp_cred = Credential(string=cred)\r
218                 if tmp_cred.get_gid_caller().get_hrn() == caller_hrn:\r
219                     caller_creds.append(cred)\r
220             except: pass\r
221         return caller_creds\r
222 \r
223 class Credential(object):\r
224 \r
225     ##\r
226     # Create a Credential object\r
227     #\r
228     # @param create If true, create a blank x509 certificate\r
229     # @param subject If subject!=None, create an x509 cert with the subject name\r
230     # @param string If string!=None, load the credential from the string\r
231     # @param filename If filename!=None, load the credential from the file\r
232     # FIXME: create and subject are ignored!\r
233     def __init__(self, create=False, subject=None, string=None, filename=None):\r
234         self.gidCaller = None\r
235         self.gidObject = None\r
236         self.expiration = None\r
237         self.privileges = None\r
238         self.issuer_privkey = None\r
239         self.issuer_gid = None\r
240         self.issuer_pubkey = None\r
241         self.parent = None\r
242         self.signature = None\r
243         self.xml = None\r
244         self.refid = None\r
245         self.legacy = None\r
246 \r
247         # Check if this is a legacy credential, translate it if so\r
248         if string or filename:\r
249             if string:                \r
250                 str = string\r
251             elif filename:\r
252                 str = file(filename).read()\r
253                 \r
254             if str.strip().startswith("-----"):\r
255                 self.legacy = CredentialLegacy(False,string=str)\r
256                 self.translate_legacy(str)\r
257             else:\r
258                 self.xml = str\r
259                 self.decode()\r
260 \r
261         # Find an xmlsec1 path\r
262         self.xmlsec_path = ''\r
263         paths = ['/usr/bin','/usr/local/bin','/bin','/opt/bin','/opt/local/bin']\r
264         for path in paths:\r
265             if os.path.isfile(path + '/' + 'xmlsec1'):\r
266                 self.xmlsec_path = path + '/' + 'xmlsec1'\r
267                 break\r
268 \r
269     def get_subject(self):\r
270         if not self.gidObject:\r
271             self.decode()\r
272         return self.gidObject.get_printable_subject()\r
273 \r
274     def get_summary_tostring(self):\r
275         if not self.gidObject:\r
276             self.decode()\r
277         obj = self.gidObject.get_printable_subject()\r
278         caller = self.gidCaller.get_printable_subject()\r
279         exp = self.get_expiration()\r
280         # Summarize the rights too? The issuer?\r
281         return "[ Grant %s rights on %s until %s ]" % (caller, obj, exp)\r
282 \r
283     def get_signature(self):\r
284         if not self.signature:\r
285             self.decode()\r
286         return self.signature\r
287 \r
288     def set_signature(self, sig):\r
289         self.signature = sig\r
290 \r
291         \r
292     ##\r
293     # Translate a legacy credential into a new one\r
294     #\r
295     # @param String of the legacy credential\r
296 \r
297     def translate_legacy(self, str):\r
298         legacy = CredentialLegacy(False,string=str)\r
299         self.gidCaller = legacy.get_gid_caller()\r
300         self.gidObject = legacy.get_gid_object()\r
301         lifetime = legacy.get_lifetime()\r
302         if not lifetime:\r
303             self.set_expiration(datetime.datetime.utcnow() + datetime.timedelta(seconds=DEFAULT_CREDENTIAL_LIFETIME))\r
304         else:\r
305             self.set_expiration(int(lifetime))\r
306         self.lifeTime = legacy.get_lifetime()\r
307         self.set_privileges(legacy.get_privileges())\r
308         self.get_privileges().delegate_all_privileges(legacy.get_delegate())\r
309 \r
310     ##\r
311     # Need the issuer's private key and name\r
312     # @param key Keypair object containing the private key of the issuer\r
313     # @param gid GID of the issuing authority\r
314 \r
315     def set_issuer_keys(self, privkey, gid):\r
316         self.issuer_privkey = privkey\r
317         self.issuer_gid = gid\r
318 \r
319 \r
320     ##\r
321     # Set this credential's parent\r
322     def set_parent(self, cred):\r
323         self.parent = cred\r
324         self.updateRefID()\r
325 \r
326     ##\r
327     # set the GID of the caller\r
328     #\r
329     # @param gid GID object of the caller\r
330 \r
331     def set_gid_caller(self, gid):\r
332         self.gidCaller = gid\r
333         # gid origin caller is the caller's gid by default\r
334         self.gidOriginCaller = gid\r
335 \r
336     ##\r
337     # get the GID of the object\r
338 \r
339     def get_gid_caller(self):\r
340         if not self.gidCaller:\r
341             self.decode()\r
342         return self.gidCaller\r
343 \r
344     ##\r
345     # set the GID of the object\r
346     #\r
347     # @param gid GID object of the object\r
348 \r
349     def set_gid_object(self, gid):\r
350         self.gidObject = gid\r
351 \r
352     ##\r
353     # get the GID of the object\r
354 \r
355     def get_gid_object(self):\r
356         if not self.gidObject:\r
357             self.decode()\r
358         return self.gidObject\r
359 \r
360 \r
361             \r
362     ##\r
363     # Expiration: an absolute UTC time of expiration (as either an int or string or datetime)\r
364     # \r
365     def set_expiration(self, expiration):\r
366         if isinstance(expiration, (int, float)):\r
367             self.expiration = datetime.datetime.fromtimestamp(expiration)\r
368         elif isinstance (expiration, datetime.datetime):\r
369             self.expiration = expiration\r
370         elif isinstance (expiration, StringTypes):\r
371             self.expiration = utcparse (expiration)\r
372         else:\r
373             logger.error ("unexpected input type in Credential.set_expiration")\r
374 \r
375 \r
376     ##\r
377     # get the lifetime of the credential (always in datetime format)\r
378 \r
379     def get_expiration(self):\r
380         if not self.expiration:\r
381             self.decode()\r
382         # at this point self.expiration is normalized as a datetime - DON'T call utcparse again\r
383         return self.expiration\r
384 \r
385     ##\r
386     # For legacy sake\r
387     def get_lifetime(self):\r
388         return self.get_expiration()\r
389  \r
390     ##\r
391     # set the privileges\r
392     #\r
393     # @param privs either a comma-separated list of privileges of a Rights object\r
394 \r
395     def set_privileges(self, privs):\r
396         if isinstance(privs, str):\r
397             self.privileges = Rights(string = privs)\r
398         else:\r
399             self.privileges = privs\r
400         \r
401 \r
402     ##\r
403     # return the privileges as a Rights object\r
404 \r
405     def get_privileges(self):\r
406         if not self.privileges:\r
407             self.decode()\r
408         return self.privileges\r
409 \r
410     ##\r
411     # determine whether the credential allows a particular operation to be\r
412     # performed\r
413     #\r
414     # @param op_name string specifying name of operation ("lookup", "update", etc)\r
415 \r
416     def can_perform(self, op_name):\r
417         rights = self.get_privileges()\r
418         \r
419         if not rights:\r
420             return False\r
421 \r
422         return rights.can_perform(op_name)\r
423 \r
424 \r
425     ##\r
426     # Encode the attributes of the credential into an XML string    \r
427     # This should be done immediately before signing the credential.    \r
428     # WARNING:\r
429     # In general, a signed credential obtained externally should\r
430     # not be changed else the signature is no longer valid.  So, once\r
431     # you have loaded an existing signed credential, do not call encode() or sign() on it.\r
432 \r
433     def encode(self):\r
434         # Create the XML document\r
435         doc = Document()\r
436         signed_cred = doc.createElement("signed-credential")\r
437 \r
438 # Declare namespaces\r
439 # Note that credential/policy.xsd are really the PG schemas\r
440 # in a PL namespace.\r
441 # Note that delegation of credentials between the 2 only really works\r
442 # cause those schemas are identical.\r
443 # Also note these PG schemas talk about PG tickets and CM policies.\r
444         signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")\r
445         signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.planet-lab.org/resources/sfa/credential.xsd")\r
446         signed_cred.setAttribute("xsi:schemaLocation", "http://www.planet-lab.org/resources/sfa/ext/policy/1 http://www.planet-lab.org/resources/sfa/ext/policy/1/policy.xsd")\r
447 \r
448 # PG says for those last 2:\r
449 #        signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
450 #        signed_cred.setAttribute("xsi:schemaLocation", "http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd")\r
451 \r
452         doc.appendChild(signed_cred)  \r
453         \r
454         # Fill in the <credential> bit        \r
455         cred = doc.createElement("credential")\r
456         cred.setAttribute("xml:id", self.get_refid())\r
457         signed_cred.appendChild(cred)\r
458         append_sub(doc, cred, "type", "privilege")\r
459         append_sub(doc, cred, "serial", "8")\r
460         append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())\r
461         append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())\r
462         append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())\r
463         append_sub(doc, cred, "target_urn", self.gidObject.get_urn())\r
464         append_sub(doc, cred, "uuid", "")\r
465         if not self.expiration:\r
466             self.set_expiration(datetime.datetime.utcnow() + datetime.timedelta(seconds=DEFAULT_CREDENTIAL_LIFETIME))\r
467         self.expiration = self.expiration.replace(microsecond=0)\r
468         append_sub(doc, cred, "expires", self.expiration.isoformat())\r
469         privileges = doc.createElement("privileges")\r
470         cred.appendChild(privileges)\r
471 \r
472         if self.privileges:\r
473             rights = self.get_privileges()\r
474             for right in rights.rights:\r
475                 priv = doc.createElement("privilege")\r
476                 append_sub(doc, priv, "name", right.kind)\r
477                 append_sub(doc, priv, "can_delegate", str(right.delegate).lower())\r
478                 privileges.appendChild(priv)\r
479 \r
480         # Add the parent credential if it exists\r
481         if self.parent:\r
482             sdoc = parseString(self.parent.get_xml())\r
483             # If the root node is a signed-credential (it should be), then\r
484             # get all its attributes and attach those to our signed_cred\r
485             # node.\r
486             # Specifically, PG and PLadd attributes for namespaces (which is reasonable),\r
487             # and we need to include those again here or else their signature\r
488             # no longer matches on the credential.\r
489             # We expect three of these, but here we copy them all:\r
490 #        signed_cred.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")\r
491 # and from PG (PL is equivalent, as shown above):\r
492 #        signed_cred.setAttribute("xsi:noNamespaceSchemaLocation", "http://www.protogeni.net/resources/credential/credential.xsd")\r
493 #        signed_cred.setAttribute("xsi:schemaLocation", "http://www.protogeni.net/resources/credential/ext/policy/1 http://www.protogeni.net/resources/credential/ext/policy/1/policy.xsd")\r
494 \r
495             # HOWEVER!\r
496             # PL now also declares these, with different URLs, so\r
497             # the code notices those attributes already existed with\r
498             # different values, and complains.\r
499             # This happens regularly on delegation now that PG and\r
500             # PL both declare the namespace with different URLs.\r
501             # If the content ever differs this is a problem,\r
502             # but for now it works - different URLs (values in the attributes)\r
503             # but the same actual schema, so using the PG schema\r
504             # on delegated-to-PL credentials works fine.\r
505 \r
506             # Note: you could also not copy attributes\r
507             # which already exist. It appears that both PG and PL\r
508             # will actually validate a slicecred with a parent\r
509             # signed using PG namespaces and a child signed with PL\r
510             # namespaces over the whole thing. But I don't know\r
511             # if that is a bug in xmlsec1, an accident since\r
512             # the contents of the schemas are the same,\r
513             # or something else, but it seems odd. And this works.\r
514             parentRoot = sdoc.documentElement\r
515             if parentRoot.tagName == "signed-credential" and parentRoot.hasAttributes():\r
516                 for attrIx in range(0, parentRoot.attributes.length):\r
517                     attr = parentRoot.attributes.item(attrIx)\r
518                     # returns the old attribute of same name that was\r
519                     # on the credential\r
520                     # Below throws InUse exception if we forgot to clone the attribute first\r
521                     oldAttr = signed_cred.setAttributeNode(attr.cloneNode(True))\r
522                     if oldAttr and oldAttr.value != attr.value:\r
523                         msg = "Delegating cred from owner %s to %s over %s replaced attribute %s value '%s' with '%s'" % (self.parent.gidCaller.get_urn(), self.gidCaller.get_urn(), self.gidObject.get_urn(), oldAttr.name, oldAttr.value, attr.value)\r
524                         logger.warn(msg)\r
525                         #raise CredentialNotVerifiable("Can't encode new valid delegated credential: %s" % msg)\r
526 \r
527             p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)\r
528             p = doc.createElement("parent")\r
529             p.appendChild(p_cred)\r
530             cred.appendChild(p)\r
531         # done handling parent credential\r
532 \r
533         # Create the <signatures> tag\r
534         signatures = doc.createElement("signatures")\r
535         signed_cred.appendChild(signatures)\r
536 \r
537         # Add any parent signatures\r
538         if self.parent:\r
539             for cur_cred in self.get_credential_list()[1:]:\r
540                 sdoc = parseString(cur_cred.get_signature().get_xml())\r
541                 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)\r
542                 signatures.appendChild(ele)\r
543                 \r
544         # Get the finished product\r
545         self.xml = doc.toxml()\r
546 \r
547 \r
548     def save_to_random_tmp_file(self):       \r
549         fp, filename = mkstemp(suffix='cred', text=True)\r
550         fp = os.fdopen(fp, "w")\r
551         self.save_to_file(filename, save_parents=True, filep=fp)\r
552         return filename\r
553     \r
554     def save_to_file(self, filename, save_parents=True, filep=None):\r
555         if not self.xml:\r
556             self.encode()\r
557         if filep:\r
558             f = filep \r
559         else:\r
560             f = open(filename, "w")\r
561         f.write(self.xml)\r
562         f.close()\r
563 \r
564     def save_to_string(self, save_parents=True):\r
565         if not self.xml:\r
566             self.encode()\r
567         return self.xml\r
568 \r
569     def get_refid(self):\r
570         if not self.refid:\r
571             self.refid = 'ref0'\r
572         return self.refid\r
573 \r
574     def set_refid(self, rid):\r
575         self.refid = rid\r
576 \r
577     ##\r
578     # Figure out what refids exist, and update this credential's id\r
579     # so that it doesn't clobber the others.  Returns the refids of\r
580     # the parents.\r
581     \r
582     def updateRefID(self):\r
583         if not self.parent:\r
584             self.set_refid('ref0')\r
585             return []\r
586         \r
587         refs = []\r
588 \r
589         next_cred = self.parent\r
590         while next_cred:\r
591             refs.append(next_cred.get_refid())\r
592             if next_cred.parent:\r
593                 next_cred = next_cred.parent\r
594             else:\r
595                 next_cred = None\r
596 \r
597         \r
598         # Find a unique refid for this credential\r
599         rid = self.get_refid()\r
600         while rid in refs:\r
601             val = int(rid[3:])\r
602             rid = "ref%d" % (val + 1)\r
603 \r
604         # Set the new refid\r
605         self.set_refid(rid)\r
606 \r
607         # Return the set of parent credential ref ids\r
608         return refs\r
609 \r
610     def get_xml(self):\r
611         if not self.xml:\r
612             self.encode()\r
613         return self.xml\r
614 \r
615     ##\r
616     # Sign the XML file created by encode()\r
617     #\r
618     # WARNING:\r
619     # In general, a signed credential obtained externally should\r
620     # not be changed else the signature is no longer valid.  So, once\r
621     # you have loaded an existing signed credential, do not call encode() or sign() on it.\r
622 \r
623     def sign(self):\r
624         if not self.issuer_privkey or not self.issuer_gid:\r
625             return\r
626         doc = parseString(self.get_xml())\r
627         sigs = doc.getElementsByTagName("signatures")[0]\r
628 \r
629         # Create the signature template to be signed\r
630         signature = Signature()\r
631         signature.set_refid(self.get_refid())\r
632         sdoc = parseString(signature.get_xml())        \r
633         sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)\r
634         sigs.appendChild(sig_ele)\r
635 \r
636         self.xml = doc.toxml()\r
637 \r
638 \r
639         # Split the issuer GID into multiple certificates if it's a chain\r
640         chain = GID(filename=self.issuer_gid)\r
641         gid_files = []\r
642         while chain:\r
643             gid_files.append(chain.save_to_random_tmp_file(False))\r
644             if chain.get_parent():\r
645                 chain = chain.get_parent()\r
646             else:\r
647                 chain = None\r
648 \r
649 \r
650         # Call out to xmlsec1 to sign it\r
651         ref = 'Sig_%s' % self.get_refid()\r
652         filename = self.save_to_random_tmp_file()\r
653         signed = os.popen('%s --sign --node-id "%s" --privkey-pem %s,%s %s' \\r
654                  % (self.xmlsec_path, ref, self.issuer_privkey, ",".join(gid_files), filename)).read()\r
655         os.remove(filename)\r
656 \r
657         for gid_file in gid_files:\r
658             os.remove(gid_file)\r
659 \r
660         self.xml = signed\r
661 \r
662         # This is no longer a legacy credential\r
663         if self.legacy:\r
664             self.legacy = None\r
665 \r
666         # Update signatures\r
667         self.decode()       \r
668 \r
669         \r
670     ##\r
671     # Retrieve the attributes of the credential from the XML.\r
672     # This is automatically called by the various get_* methods of\r
673     # this class and should not need to be called explicitly.\r
674 \r
675     def decode(self):\r
676         if not self.xml:\r
677             return\r
678         doc = parseString(self.xml)\r
679         sigs = []\r
680         signed_cred = doc.getElementsByTagName("signed-credential")\r
681 \r
682         # Is this a signed-cred or just a cred?\r
683         if len(signed_cred) > 0:\r
684             creds = signed_cred[0].getElementsByTagName("credential")\r
685             signatures = signed_cred[0].getElementsByTagName("signatures")\r
686             if len(signatures) > 0:\r
687                 sigs = signatures[0].getElementsByTagName("Signature")\r
688         else:\r
689             creds = doc.getElementsByTagName("credential")\r
690         \r
691         if creds is None or len(creds) == 0:\r
692             # malformed cred file\r
693             raise CredentialNotVerifiable("Malformed XML: No credential tag found")\r
694 \r
695         # Just take the first cred if there are more than one\r
696         cred = creds[0]\r
697 \r
698         self.set_refid(cred.getAttribute("xml:id"))\r
699         self.set_expiration(utcparse(getTextNode(cred, "expires")))\r
700         self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))\r
701         self.gidObject = GID(string=getTextNode(cred, "target_gid"))   \r
702 \r
703 \r
704         # Process privileges\r
705         privs = cred.getElementsByTagName("privileges")[0]\r
706         rlist = Rights()\r
707         for priv in privs.getElementsByTagName("privilege"):\r
708             kind = getTextNode(priv, "name")\r
709             deleg = str2bool(getTextNode(priv, "can_delegate"))\r
710             if kind == '*':\r
711                 # Convert * into the default privileges for the credential's type\r
712                 # Each inherits the delegatability from the * above\r
713                 _ , type = urn_to_hrn(self.gidObject.get_urn())\r
714                 rl = determine_rights(type, self.gidObject.get_urn())\r
715                 for r in rl.rights:\r
716                     r.delegate = deleg\r
717                     rlist.add(r)\r
718             else:\r
719                 rlist.add(Right(kind.strip(), deleg))\r
720         self.set_privileges(rlist)\r
721 \r
722 \r
723         # Is there a parent?\r
724         parent = cred.getElementsByTagName("parent")\r
725         if len(parent) > 0:\r
726             parent_doc = parent[0].getElementsByTagName("credential")[0]\r
727             parent_xml = parent_doc.toxml()\r
728             self.parent = Credential(string=parent_xml)\r
729             self.updateRefID()\r
730 \r
731         # Assign the signatures to the credentials\r
732         for sig in sigs:\r
733             Sig = Signature(string=sig.toxml())\r
734 \r
735             for cur_cred in self.get_credential_list():\r
736                 if cur_cred.get_refid() == Sig.get_refid():\r
737                     cur_cred.set_signature(Sig)\r
738                                     \r
739             \r
740     ##\r
741     # Verify\r
742     #   trusted_certs: A list of trusted GID filenames (not GID objects!) \r
743     #                  Chaining is not supported within the GIDs by xmlsec1.\r
744     #\r
745     #   trusted_certs_required: Should usually be true. Set False means an\r
746     #                 empty list of trusted_certs would still let this method pass.\r
747     #                 It just skips xmlsec1 verification et al. Only used by some utils\r
748     #    \r
749     # Verify that:\r
750     # . All of the signatures are valid and that the issuers trace back\r
751     #   to trusted roots (performed by xmlsec1)\r
752     # . The XML matches the credential schema\r
753     # . That the issuer of the credential is the authority in the target's urn\r
754     #    . In the case of a delegated credential, this must be true of the root\r
755     # . That all of the gids presented in the credential are valid\r
756     #    . Including verifying GID chains, and includ the issuer\r
757     # . The credential is not expired\r
758     #\r
759     # -- For Delegates (credentials with parents)\r
760     # . The privileges must be a subset of the parent credentials\r
761     # . The privileges must have "can_delegate" set for each delegated privilege\r
762     # . The target gid must be the same between child and parents\r
763     # . The expiry time on the child must be no later than the parent\r
764     # . The signer of the child must be the owner of the parent\r
765     #\r
766     # -- Verify does *NOT*\r
767     # . ensure that an xmlrpc client's gid matches a credential gid, that\r
768     #   must be done elsewhere\r
769     #\r
770     # @param trusted_certs: The certificates of trusted CA certificates\r
771     def verify(self, trusted_certs=None, schema=None, trusted_certs_required=True):\r
772         if not self.xml:\r
773             self.decode()\r
774 \r
775         # validate against RelaxNG schema\r
776         if HAVELXML and not self.legacy:\r
777             if schema and os.path.exists(schema):\r
778                 tree = etree.parse(StringIO(self.xml))\r
779                 schema_doc = etree.parse(schema)\r
780                 xmlschema = etree.XMLSchema(schema_doc)\r
781                 if not xmlschema.validate(tree):\r
782                     error = xmlschema.error_log.last_error\r
783                     message = "%s: %s (line %s)" % (self.get_summary_tostring(), error.message, error.line)\r
784                     raise CredentialNotVerifiable(message)\r
785 \r
786         if trusted_certs_required and trusted_certs is None:\r
787             trusted_certs = []\r
788 \r
789 #        trusted_cert_objects = [GID(filename=f) for f in trusted_certs]\r
790         trusted_cert_objects = []\r
791         ok_trusted_certs = []\r
792         # If caller explicitly passed in None that means skip cert chain validation.\r
793         # Strange and not typical\r
794         if trusted_certs is not None:\r
795             for f in trusted_certs:\r
796                 try:\r
797                     # Failures here include unreadable files\r
798                     # or non PEM files\r
799                     trusted_cert_objects.append(GID(filename=f))\r
800                     ok_trusted_certs.append(f)\r
801                 except Exception, exc:\r
802                     logger.error("Failed to load trusted cert from %s: %r", f, exc)\r
803             trusted_certs = ok_trusted_certs\r
804 \r
805         # Use legacy verification if this is a legacy credential\r
806         if self.legacy:\r
807             self.legacy.verify_chain(trusted_cert_objects)\r
808             if self.legacy.client_gid:\r
809                 self.legacy.client_gid.verify_chain(trusted_cert_objects)\r
810             if self.legacy.object_gid:\r
811                 self.legacy.object_gid.verify_chain(trusted_cert_objects)\r
812             return True\r
813         \r
814         # make sure it is not expired\r
815         if self.get_expiration() < datetime.datetime.utcnow():\r
816             raise CredentialNotVerifiable("Credential %s expired at %s" % (self.get_summary_tostring(), self.expiration.isoformat()))\r
817 \r
818         # Verify the signatures\r
819         filename = self.save_to_random_tmp_file()\r
820         if trusted_certs is not None:\r
821             cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])\r
822 \r
823         # If caller explicitly passed in None that means skip cert chain validation.\r
824         # - Strange and not typical\r
825         if trusted_certs is not None:\r
826             # Verify the gids of this cred and of its parents\r
827             for cur_cred in self.get_credential_list():\r
828                 cur_cred.get_gid_object().verify_chain(trusted_cert_objects)\r
829                 cur_cred.get_gid_caller().verify_chain(trusted_cert_objects)\r
830 \r
831         refs = []\r
832         refs.append("Sig_%s" % self.get_refid())\r
833 \r
834         parentRefs = self.updateRefID()\r
835         for ref in parentRefs:\r
836             refs.append("Sig_%s" % ref)\r
837 \r
838         for ref in refs:\r
839             # If caller explicitly passed in None that means skip xmlsec1 validation.\r
840             # Strange and not typical\r
841             if trusted_certs is None:\r
842                 break\r
843 \r
844 #            print "Doing %s --verify --node-id '%s' %s %s 2>&1" % \\r
845 #                (self.xmlsec_path, ref, cert_args, filename)\r
846             verified = os.popen('%s --verify --node-id "%s" %s %s 2>&1' \\r
847                             % (self.xmlsec_path, ref, cert_args, filename)).read()\r
848             if not verified.strip().startswith("OK"):\r
849                 # xmlsec errors have a msg= which is the interesting bit.\r
850                 mstart = verified.find("msg=")\r
851                 msg = ""\r
852                 if mstart > -1 and len(verified) > 4:\r
853                     mstart = mstart + 4\r
854                     mend = verified.find('\\', mstart)\r
855                     msg = verified[mstart:mend]\r
856                 raise CredentialNotVerifiable("xmlsec1 error verifying cred %s using Signature ID %s: %s %s" % (self.get_summary_tostring(), ref, msg, verified.strip()))\r
857         os.remove(filename)\r
858 \r
859         # Verify the parents (delegation)\r
860         if self.parent:\r
861             self.verify_parent(self.parent)\r
862 \r
863         # Make sure the issuer is the target's authority, and is\r
864         # itself a valid GID\r
865         self.verify_issuer(trusted_cert_objects)\r
866         return True\r
867 \r
868     ##\r
869     # Creates a list of the credential and its parents, with the root \r
870     # (original delegated credential) as the last item in the list\r
871     def get_credential_list(self):    \r
872         cur_cred = self\r
873         list = []\r
874         while cur_cred:\r
875             list.append(cur_cred)\r
876             if cur_cred.parent:\r
877                 cur_cred = cur_cred.parent\r
878             else:\r
879                 cur_cred = None\r
880         return list\r
881     \r
882     ##\r
883     # Make sure the credential's target gid (a) was signed by or (b)\r
884     # is the same as the entity that signed the original credential,\r
885     # or (c) is an authority over the target's namespace.\r
886     # Also ensure that the credential issuer / signer itself has a valid\r
887     # GID signature chain (signed by an authority with namespace rights).\r
888     def verify_issuer(self, trusted_gids):\r
889         root_cred = self.get_credential_list()[-1]\r
890         root_target_gid = root_cred.get_gid_object()\r
891         root_cred_signer = root_cred.get_signature().get_issuer_gid()\r
892 \r
893         # Case 1:\r
894         # Allow non authority to sign target and cred about target.\r
895         #\r
896         # Why do we need to allow non authorities to sign?\r
897         # If in the target gid validation step we correctly\r
898         # checked that the target is only signed by an authority,\r
899         # then this is just a special case of case 3.\r
900         # This short-circuit is the common case currently -\r
901         # and cause GID validation doesn't check 'authority',\r
902         # this allows users to generate valid slice credentials.\r
903         if root_target_gid.is_signed_by_cert(root_cred_signer):\r
904             # cred signer matches target signer, return success\r
905             return\r
906 \r
907         # Case 2:\r
908         # Allow someone to sign credential about themeselves. Used?\r
909         # If not, remove this.\r
910         #root_target_gid_str = root_target_gid.save_to_string()\r
911         #root_cred_signer_str = root_cred_signer.save_to_string()\r
912         #if root_target_gid_str == root_cred_signer_str:\r
913         #    # cred signer is target, return success\r
914         #    return\r
915 \r
916         # Case 3:\r
917 \r
918         # root_cred_signer is not the target_gid\r
919         # So this is a different gid that we have not verified.\r
920         # xmlsec1 verified the cert chain on this already, but\r
921         # it hasn't verified that the gid meets the HRN namespace\r
922         # requirements.\r
923         # Below we'll ensure that it is an authority.\r
924         # But we haven't verified that it is _signed by_ an authority\r
925         # We also don't know if xmlsec1 requires that cert signers\r
926         # are marked as CAs.\r
927         root_cred_signer.verify_chain(trusted_gids)\r
928 \r
929         # See if the signer is an authority over the domain of the target.\r
930         # There are multiple types of authority - accept them all here\r
931         # Maybe should be (hrn, type) = urn_to_hrn(root_cred_signer.get_urn())\r
932         root_cred_signer_type = root_cred_signer.get_type()\r
933         if (root_cred_signer_type.find('authority') == 0):\r
934             #logger.debug('Cred signer is an authority')\r
935             # signer is an authority, see if target is in authority's domain\r
936             signerhrn = root_cred_signer.get_hrn()\r
937             if hrn_authfor_hrn(signerhrn, root_target_gid.get_hrn()):\r
938                 return\r
939 \r
940         # We've required that the credential be signed by an authority\r
941         # for that domain. Reasonable and probably correct.\r
942         # A looser model would also allow the signer to be an authority\r
943         # in my control framework - eg My CA or CH. Even if it is not\r
944         # the CH that issued these, eg, user credentials.\r
945 \r
946         # Give up, credential does not pass issuer verification\r
947 \r
948         raise CredentialNotVerifiable("Could not verify credential owned by %s for object %s. Cred signer %s not the trusted authority for Cred target %s" % (self.gidCaller.get_urn(), self.gidObject.get_urn(), root_cred_signer.get_hrn(), root_target_gid.get_hrn()))\r
949 \r
950 \r
951     ##\r
952     # -- For Delegates (credentials with parents) verify that:\r
953     # . The privileges must be a subset of the parent credentials\r
954     # . The privileges must have "can_delegate" set for each delegated privilege\r
955     # . The target gid must be the same between child and parents\r
956     # . The expiry time on the child must be no later than the parent\r
957     # . The signer of the child must be the owner of the parent        \r
958     def verify_parent(self, parent_cred):\r
959         # make sure the rights given to the child are a subset of the\r
960         # parents rights (and check delegate bits)\r
961         if not parent_cred.get_privileges().is_superset(self.get_privileges()):\r
962             raise ChildRightsNotSubsetOfParent(("Parent cred ref %s rights " % parent_cred.get_refid()) +\r
963                 self.parent.get_privileges().save_to_string() + (" not superset of delegated cred %s ref %s rights " % (self.get_summary_tostring(), self.get_refid())) +\r
964                 self.get_privileges().save_to_string())\r
965 \r
966         # make sure my target gid is the same as the parent's\r
967         if not parent_cred.get_gid_object().save_to_string() == \\r
968            self.get_gid_object().save_to_string():\r
969             raise CredentialNotVerifiable("Delegated cred %s: Target gid not equal between parent and child. Parent %s" % (self.get_summary_tostring(), parent_cred.get_summary_tostring()))\r
970 \r
971         # make sure my expiry time is <= my parent's\r
972         if not parent_cred.get_expiration() >= self.get_expiration():\r
973             raise CredentialNotVerifiable("Delegated credential %s expires after parent %s" % (self.get_summary_tostring(), parent_cred.get_summary_tostring()))\r
974 \r
975         # make sure my signer is the parent's caller\r
976         if not parent_cred.get_gid_caller().save_to_string(False) == \\r
977            self.get_signature().get_issuer_gid().save_to_string(False):\r
978             raise CredentialNotVerifiable("Delegated credential %s not signed by parent %s's caller" % (self.get_summary_tostring(), parent_cred.get_summary_tostring()))\r
979                 \r
980         # Recurse\r
981         if parent_cred.parent:\r
982             parent_cred.verify_parent(parent_cred.parent)\r
983 \r
984 \r
985     def delegate(self, delegee_gidfile, caller_keyfile, caller_gidfile):\r
986         """\r
987         Return a delegated copy of this credential, delegated to the \r
988         specified gid's user.    \r
989         """\r
990         # get the gid of the object we are delegating\r
991         object_gid = self.get_gid_object()\r
992         object_hrn = object_gid.get_hrn()        \r
993  \r
994         # the hrn of the user who will be delegated to\r
995         delegee_gid = GID(filename=delegee_gidfile)\r
996         delegee_hrn = delegee_gid.get_hrn()\r
997   \r
998         #user_key = Keypair(filename=keyfile)\r
999         #user_hrn = self.get_gid_caller().get_hrn()\r
1000         subject_string = "%s delegated to %s" % (object_hrn, delegee_hrn)\r
1001         dcred = Credential(subject=subject_string)\r
1002         dcred.set_gid_caller(delegee_gid)\r
1003         dcred.set_gid_object(object_gid)\r
1004         dcred.set_parent(self)\r
1005         dcred.set_expiration(self.get_expiration())\r
1006         dcred.set_privileges(self.get_privileges())\r
1007         dcred.get_privileges().delegate_all_privileges(True)\r
1008         #dcred.set_issuer_keys(keyfile, delegee_gidfile)\r
1009         dcred.set_issuer_keys(caller_keyfile, caller_gidfile)\r
1010         dcred.encode()\r
1011         dcred.sign()\r
1012 \r
1013         return dcred\r
1014 \r
1015     # only informative\r
1016     def get_filename(self):\r
1017         return getattr(self,'filename',None)\r
1018 \r
1019     ##\r
1020     # Dump the contents of a credential to stdout in human-readable format\r
1021     #\r
1022     # @param dump_parents If true, also dump the parent certificates\r
1023     def dump (self, *args, **kwargs):\r
1024         print self.dump_string(*args, **kwargs)\r
1025 \r
1026 \r
1027     def dump_string(self, dump_parents=False):\r
1028         result=""\r
1029         result += "CREDENTIAL %s\n" % self.get_subject()\r
1030         filename=self.get_filename()\r
1031         if filename: result += "Filename %s\n"%filename\r
1032         result += "      privs: %s\n" % self.get_privileges().save_to_string()\r
1033         gidCaller = self.get_gid_caller()\r
1034         if gidCaller:\r
1035             result += "  gidCaller:\n"\r
1036             result += gidCaller.dump_string(8, dump_parents)\r
1037 \r
1038         if self.get_signature():\r
1039             print "  gidIssuer:"\r
1040             self.get_signature().get_issuer_gid().dump(8, dump_parents)\r
1041 \r
1042         gidObject = self.get_gid_object()\r
1043         if gidObject:\r
1044             result += "  gidObject:\n"\r
1045             result += gidObject.dump_string(8, dump_parents)\r
1046 \r
1047         if self.parent and dump_parents:\r
1048             result += "\nPARENT"\r
1049             result += self.parent.dump_string(True)\r
1050 \r
1051         return result\r