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