merge from geni_api branch
[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 xml.dom.minidom import Document, parseString
35 from tempfile import mkstemp
36
37 from sfa.trust.credential_legacy import CredentialLegacy
38 from sfa.trust.rights import *
39 from sfa.trust.gid import *
40 from sfa.util.faults import *
41
42 from sfa.util.sfalogging import logger
43 from dateutil.parser import parse
44
45
46
47 # Two years, in seconds 
48 DEFAULT_CREDENTIAL_LIFETIME = 60 * 60 * 24 * 365 * 2
49
50
51 # TODO:
52 # . make privs match between PG and PL
53 # . Need to add support for other types of credentials, e.g. tickets
54
55
56 signature_template = \
57 '''
58 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
59     <SignedInfo>
60       <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
61       <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
62       <Reference URI="#%s">
63       <Transforms>
64         <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
65       </Transforms>
66       <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
67       <DigestValue></DigestValue>
68       </Reference>
69     </SignedInfo>
70     <SignatureValue />
71       <KeyInfo>
72         <X509Data>
73           <X509SubjectName/>
74           <X509IssuerSerial/>
75           <X509Certificate/>
76         </X509Data>
77       <KeyValue />
78       </KeyInfo>
79     </Signature>
80 '''
81
82 ##
83 # Convert a string into a bool
84
85 def str2bool(str):
86     if str.lower() in ['yes','true','1']:
87         return True
88     return False
89
90
91 ##
92 # Utility function to get the text of an XML element
93
94 def getTextNode(element, subele):
95     sub = element.getElementsByTagName(subele)[0]
96     if len(sub.childNodes) > 0:            
97         return sub.childNodes[0].nodeValue
98     else:
99         return None
100         
101 ##
102 # Utility function to set the text of an XML element
103 # It creates the element, adds the text to it,
104 # and then appends it to the parent.
105
106 def append_sub(doc, parent, element, text):
107     ele = doc.createElement(element)
108     ele.appendChild(doc.createTextNode(text))
109     parent.appendChild(ele)
110
111 ##
112 # Signature contains information about an xmlsec1 signature
113 # for a signed-credential
114 #
115
116 class Signature(object):
117    
118     def __init__(self, string=None):
119         self.refid = None
120         self.issuer_gid = None
121         self.xml = None
122         if string:
123             self.xml = string
124             self.decode()
125
126
127     def get_refid(self):
128         if not self.refid:
129             self.decode()
130         return self.refid
131
132     def get_xml(self):
133         if not self.xml:
134             self.encode()
135         return self.xml
136
137     def set_refid(self, id):
138         self.refid = id
139
140     def get_issuer_gid(self):
141         if not self.gid:
142             self.decode()
143         return self.gid        
144
145     def set_issuer_gid(self, gid):
146         self.gid = gid
147
148     def decode(self):
149         doc = parseString(self.xml)
150         sig = doc.getElementsByTagName("Signature")[0]
151         self.set_refid(sig.getAttribute("xml:id").strip("Sig_"))
152         keyinfo = sig.getElementsByTagName("X509Data")[0]
153         szgid = getTextNode(keyinfo, "X509Certificate")
154         szgid = "-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----" % szgid
155         self.set_issuer_gid(GID(string=szgid))        
156         
157     def encode(self):
158         self.xml = signature_template % (self.get_refid(), self.get_refid())
159
160
161 ##
162 # A credential provides a caller gid with privileges to an object gid.
163 # A signed credential is signed by the object's authority.
164 #
165 # Credentials are encoded in one of two ways.  The legacy style places
166 # it in the subjectAltName of an X509 certificate.  The new credentials
167 # are placed in signed XML.
168 #
169 # WARNING:
170 # In general, a signed credential obtained externally should
171 # not be changed else the signature is no longer valid.  So, once
172 # you have loaded an existing signed credential, do not call encode() or sign() on it.
173
174 class Credential(object):
175
176     ##
177     # Create a Credential object
178     #
179     # @param create If true, create a blank x509 certificate
180     # @param subject If subject!=None, create an x509 cert with the subject name
181     # @param string If string!=None, load the credential from the string
182     # @param filename If filename!=None, load the credential from the file
183     # FIXME: create and subject are ignored!
184     def __init__(self, create=False, subject=None, string=None, filename=None):
185         self.gidCaller = None
186         self.gidObject = None
187         self.expiration = None
188         self.privileges = None
189         self.issuer_privkey = None
190         self.issuer_gid = None
191         self.issuer_pubkey = None
192         self.parent = None
193         self.signature = None
194         self.xml = None
195         self.refid = None
196         self.legacy = None
197
198         # Check if this is a legacy credential, translate it if so
199         if string or filename:
200             if string:                
201                 str = string
202             elif filename:
203                 str = file(filename).read()
204                 
205             if str.strip().startswith("-----"):
206                 self.legacy = CredentialLegacy(False,string=str)
207                 self.translate_legacy(str)
208             else:
209                 self.xml = str
210                 self.decode()
211
212         # Find an xmlsec1 path
213         self.xmlsec_path = ''
214         paths = ['/usr/bin','/usr/local/bin','/bin','/opt/bin','/opt/local/bin']
215         for path in paths:
216             if os.path.isfile(path + '/' + 'xmlsec1'):
217                 self.xmlsec_path = path + '/' + 'xmlsec1'
218                 break
219
220
221     def get_signature(self):
222         if not self.signature:
223             self.decode()
224         return self.signature
225
226     def set_signature(self, sig):
227         self.signature = sig
228
229         
230     ##
231     # Translate a legacy credential into a new one
232     #
233     # @param String of the legacy credential
234
235     def translate_legacy(self, str):
236         legacy = CredentialLegacy(False,string=str)
237         self.gidCaller = legacy.get_gid_caller()
238         self.gidObject = legacy.get_gid_object()
239         lifetime = legacy.get_lifetime()
240         if not lifetime:
241             # Default to two years
242             self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
243         else:
244             self.set_lifetime(int(lifetime))
245         self.lifeTime = legacy.get_lifetime()
246         self.set_privileges(legacy.get_privileges())
247         self.get_privileges().delegate_all_privileges(legacy.get_delegate())
248
249     ##
250     # Need the issuer's private key and name
251     # @param key Keypair object containing the private key of the issuer
252     # @param gid GID of the issuing authority
253
254     def set_issuer_keys(self, privkey, gid):
255         self.issuer_privkey = privkey
256         self.issuer_gid = gid
257
258
259     ##
260     # Set this credential's parent
261     def set_parent(self, cred):
262         self.parent = cred
263         self.updateRefID()
264
265     ##
266     # set the GID of the caller
267     #
268     # @param gid GID object of the caller
269
270     def set_gid_caller(self, gid):
271         self.gidCaller = gid
272         # gid origin caller is the caller's gid by default
273         self.gidOriginCaller = gid
274
275     ##
276     # get the GID of the object
277
278     def get_gid_caller(self):
279         if not self.gidCaller:
280             self.decode()
281         return self.gidCaller
282
283     ##
284     # set the GID of the object
285     #
286     # @param gid GID object of the object
287
288     def set_gid_object(self, gid):
289         self.gidObject = gid
290
291     ##
292     # get the GID of the object
293
294     def get_gid_object(self):
295         if not self.gidObject:
296             self.decode()
297         return self.gidObject
298
299     ##
300     # set the lifetime of this credential
301     #
302     # @param lifetime lifetime of credential
303     # . if lifeTime is a datetime object, it is used for the expiration time
304     # . if lifeTime is an integer value, it is considered the number of seconds
305     #   remaining before expiration
306
307     def set_lifetime(self, lifeTime):
308         if isinstance(lifeTime, int):
309             self.expiration = datetime.timedelta(seconds=lifeTime) + datetime.datetime.utcnow()
310         else:
311             self.expiration = lifeTime
312
313     ##
314     # get the lifetime of the credential (in datetime format)
315
316     def get_lifetime(self):
317         if not self.expiration:
318             self.decode()
319         return self.expiration
320
321  
322     ##
323     # set the privileges
324     #
325     # @param privs either a comma-separated list of privileges of a RightList object
326
327     def set_privileges(self, privs):
328         if isinstance(privs, str):
329             self.privileges = RightList(string = privs)
330         else:
331             self.privileges = privs
332         
333
334     ##
335     # return the privileges as a RightList object
336
337     def get_privileges(self):
338         if not self.privileges:
339             self.decode()
340         return self.privileges
341
342     ##
343     # determine whether the credential allows a particular operation to be
344     # performed
345     #
346     # @param op_name string specifying name of operation ("lookup", "update", etc)
347
348     def can_perform(self, op_name):
349         rights = self.get_privileges()
350         
351         if not rights:
352             return False
353
354         return rights.can_perform(op_name)
355
356
357     ##
358     # Encode the attributes of the credential into an XML string    
359     # This should be done immediately before signing the credential.    
360     # WARNING:
361     # In general, a signed credential obtained externally should
362     # not be changed else the signature is no longer valid.  So, once
363     # you have loaded an existing signed credential, do not call encode() or sign() on it.
364
365     def encode(self):
366         # Create the XML document
367         doc = Document()
368         signed_cred = doc.createElement("signed-credential")
369         doc.appendChild(signed_cred)  
370         
371         # Fill in the <credential> bit        
372         cred = doc.createElement("credential")
373         cred.setAttribute("xml:id", self.get_refid())
374         signed_cred.appendChild(cred)
375         append_sub(doc, cred, "type", "privilege")
376         append_sub(doc, cred, "serial", "8")
377         append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
378         append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
379         append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
380         append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
381         append_sub(doc, cred, "uuid", "")
382         if not self.expiration:
383             self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
384         self.expiration = self.expiration.replace(microsecond=0)
385         append_sub(doc, cred, "expires", self.expiration.isoformat())
386         privileges = doc.createElement("privileges")
387         cred.appendChild(privileges)
388
389         if self.privileges:
390             rights = self.get_privileges()
391             for right in rights.rights:
392                 priv = doc.createElement("privilege")
393                 append_sub(doc, priv, "name", right.kind)
394                 append_sub(doc, priv, "can_delegate", str(right.delegate).lower())
395                 privileges.appendChild(priv)
396
397         # Add the parent credential if it exists
398         if self.parent:
399             sdoc = parseString(self.parent.get_xml())
400             p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
401             p = doc.createElement("parent")
402             p.appendChild(p_cred)
403             cred.appendChild(p)
404
405
406         # Create the <signatures> tag
407         signatures = doc.createElement("signatures")
408         signed_cred.appendChild(signatures)
409
410         # Add any parent signatures
411         if self.parent:
412             for cur_cred in self.get_credential_list()[1:]:
413                 sdoc = parseString(cur_cred.get_signature().get_xml())
414                 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
415                 signatures.appendChild(ele)
416                 
417         # Get the finished product
418         self.xml = doc.toxml()
419
420
421     def save_to_random_tmp_file(self):       
422         fp, filename = mkstemp(suffix='cred', text=True)
423         fp = os.fdopen(fp, "w")
424         self.save_to_file(filename, save_parents=True, filep=fp)
425         return filename
426     
427     def save_to_file(self, filename, save_parents=True, filep=None):
428         if not self.xml:
429             self.encode()
430         if filep:
431             f = filep 
432         else:
433             f = open(filename, "w")
434         f.write(self.xml)
435         f.close()
436
437     def save_to_string(self, save_parents=True):
438         if not self.xml:
439             self.encode()
440         return self.xml
441
442     def get_refid(self):
443         if not self.refid:
444             self.refid = 'ref0'
445         return self.refid
446
447     def set_refid(self, rid):
448         self.refid = rid
449
450     ##
451     # Figure out what refids exist, and update this credential's id
452     # so that it doesn't clobber the others.  Returns the refids of
453     # the parents.
454     
455     def updateRefID(self):
456         if not self.parent:
457             self.set_refid('ref0')
458             return []
459         
460         refs = []
461
462         next_cred = self.parent
463         while next_cred:
464             refs.append(next_cred.get_refid())
465             if next_cred.parent:
466                 next_cred = next_cred.parent
467             else:
468                 next_cred = None
469
470         
471         # Find a unique refid for this credential
472         rid = self.get_refid()
473         while rid in refs:
474             val = int(rid[3:])
475             rid = "ref%d" % (val + 1)
476
477         # Set the new refid
478         self.set_refid(rid)
479
480         # Return the set of parent credential ref ids
481         return refs
482
483     def get_xml(self):
484         if not self.xml:
485             self.encode()
486         return self.xml
487
488     ##
489     # Sign the XML file created by encode()
490     #
491     # WARNING:
492     # In general, a signed credential obtained externally should
493     # not be changed else the signature is no longer valid.  So, once
494     # you have loaded an existing signed credential, do not call encode() or sign() on it.
495
496     def sign(self):
497         if not self.issuer_privkey or not self.issuer_gid:
498             return
499         doc = parseString(self.get_xml())
500         sigs = doc.getElementsByTagName("signatures")[0]
501
502         # Create the signature template to be signed
503         signature = Signature()
504         signature.set_refid(self.get_refid())
505         sdoc = parseString(signature.get_xml())        
506         sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
507         sigs.appendChild(sig_ele)
508
509         self.xml = doc.toxml()
510
511
512         # Split the issuer GID into multiple certificates if it's a chain
513         chain = GID(filename=self.issuer_gid)
514         gid_files = []
515         while chain:
516             gid_files.append(chain.save_to_random_tmp_file(False))
517             if chain.get_parent():
518                 chain = chain.get_parent()
519             else:
520                 chain = None
521
522
523         # Call out to xmlsec1 to sign it
524         ref = 'Sig_%s' % self.get_refid()
525         filename = self.save_to_random_tmp_file()
526         signed = os.popen('%s --sign --node-id "%s" --privkey-pem %s,%s %s' \
527                  % (self.xmlsec_path, ref, self.issuer_privkey, ",".join(gid_files), filename)).read()
528         os.remove(filename)
529
530         for gid_file in gid_files:
531             os.remove(gid_file)
532
533         self.xml = signed
534
535         # This is no longer a legacy credential
536         if self.legacy:
537             self.legacy = None
538
539         # Update signatures
540         self.decode()       
541
542         
543     ##
544     # Retrieve the attributes of the credential from the XML.
545     # This is automatically called by the various get_* methods of
546     # this class and should not need to be called explicitly.
547
548     def decode(self):
549         if not self.xml:
550             return
551         doc = parseString(self.xml)
552         sigs = []
553         signed_cred = doc.getElementsByTagName("signed-credential")
554
555         # Is this a signed-cred or just a cred?
556         if len(signed_cred) > 0:
557             cred = signed_cred[0].getElementsByTagName("credential")[0]
558             signatures = signed_cred[0].getElementsByTagName("signatures")
559             if len(signatures) > 0:
560                 sigs = signatures[0].getElementsByTagName("Signature")
561         else:
562             cred = doc.getElementsByTagName("credential")[0]
563         
564
565         self.set_refid(cred.getAttribute("xml:id"))
566         self.set_lifetime(parse(getTextNode(cred, "expires")))
567         self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
568         self.gidObject = GID(string=getTextNode(cred, "target_gid"))   
569
570
571         # Process privileges
572         privs = cred.getElementsByTagName("privileges")[0]
573         rlist = RightList()
574         for priv in privs.getElementsByTagName("privilege"):
575             kind = getTextNode(priv, "name")
576             deleg = str2bool(getTextNode(priv, "can_delegate"))
577             if kind == '*':
578                 # Convert * into the default privileges for the credential's type                
579                 _ , type = urn_to_hrn(self.gidObject.get_urn())
580                 rl = rlist.determine_rights(type, self.gidObject.get_urn())
581                 for r in rl.rights:
582                     rlist.add(r)
583             else:
584                 rlist.add(Right(kind.strip(), deleg))
585         self.set_privileges(rlist)
586
587
588         # Is there a parent?
589         parent = cred.getElementsByTagName("parent")
590         if len(parent) > 0:
591             parent_doc = parent[0].getElementsByTagName("credential")[0]
592             parent_xml = parent_doc.toxml()
593             self.parent = Credential(string=parent_xml)
594             self.updateRefID()
595
596         # Assign the signatures to the credentials
597         for sig in sigs:
598             Sig = Signature(string=sig.toxml())
599
600             for cur_cred in self.get_credential_list():
601                 if cur_cred.get_refid() == Sig.get_refid():
602                     cur_cred.set_signature(Sig)
603                                     
604             
605     ##
606     # Verify
607     #   trusted_certs: A list of trusted GID filenames (not GID objects!) 
608     #                  Chaining is not supported within the GIDs by xmlsec1.
609     #    
610     # Verify that:
611     # . All of the signatures are valid and that the issuers trace back
612     #   to trusted roots (performed by xmlsec1)
613     # . The XML matches the credential schema
614     # . That the issuer of the credential is the authority in the target's urn
615     #    . In the case of a delegated credential, this must be true of the root
616     # . That all of the gids presented in the credential are valid
617     # . The credential is not expired
618     #
619     # -- For Delegates (credentials with parents)
620     # . The privileges must be a subset of the parent credentials
621     # . The privileges must have "can_delegate" set for each delegated privilege
622     # . The target gid must be the same between child and parents
623     # . The expiry time on the child must be no later than the parent
624     # . The signer of the child must be the owner of the parent
625     #
626     # -- Verify does *NOT*
627     # . ensure that an xmlrpc client's gid matches a credential gid, that
628     #   must be done elsewhere
629     #
630     # @param trusted_certs: The certificates of trusted CA certificates
631     def verify(self, trusted_certs):
632         if not self.xml:
633             self.decode()        
634
635 #        trusted_cert_objects = [GID(filename=f) for f in trusted_certs]
636         trusted_cert_objects = []
637         ok_trusted_certs = []
638         for f in trusted_certs:
639             try:
640                 # Failures here include unreadable files
641                 # or non PEM files
642                 trusted_cert_objects.append(GID(filename=f))
643                 ok_trusted_certs.append(f)
644             except Exception, exc:
645                 logger.error("Failed to load trusted cert from %s: %r", f, exc)
646         trusted_certs = ok_trusted_certs
647
648         # Use legacy verification if this is a legacy credential
649         if self.legacy:
650             self.legacy.verify_chain(trusted_cert_objects)
651             if self.legacy.client_gid:
652                 self.legacy.client_gid.verify_chain(trusted_cert_objects)
653             if self.legacy.object_gid:
654                 self.legacy.object_gid.verify_chain(trusted_cert_objects)
655             return True
656         
657         # make sure it is not expired
658         if self.get_lifetime() < datetime.datetime.utcnow():
659             raise CredentialNotVerifiable("Credential expired at %s" % self.expiration.isoformat())
660
661         # Verify the signatures
662         filename = self.save_to_random_tmp_file()
663         cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
664
665         # Verify the gids of this cred and of its parents
666         for cur_cred in self.get_credential_list():
667             cur_cred.get_gid_object().verify_chain(trusted_cert_objects)
668             cur_cred.get_gid_caller().verify_chain(trusted_cert_objects) 
669
670         refs = []
671         refs.append("Sig_%s" % self.get_refid())
672
673         parentRefs = self.updateRefID()
674         for ref in parentRefs:
675             refs.append("Sig_%s" % ref)
676
677         for ref in refs:
678             verified = os.popen('%s --verify --node-id "%s" %s %s 2>&1' \
679                             % (self.xmlsec_path, ref, cert_args, filename)).read()
680             if not verified.strip().startswith("OK"):
681                 raise CredentialNotVerifiable("xmlsec1 error verifying cert: " + verified)
682         os.remove(filename)
683
684         # Verify the parents (delegation)
685         if self.parent:
686             self.verify_parent(self.parent)
687
688         # Make sure the issuer is the target's authority
689         self.verify_issuer()
690         return True
691
692     ##
693     # Creates a list of the credential and its parents, with the root 
694     # (original delegated credential) as the last item in the list
695     def get_credential_list(self):    
696         cur_cred = self
697         list = []
698         while cur_cred:
699             list.append(cur_cred)
700             if cur_cred.parent:
701                 cur_cred = cur_cred.parent
702             else:
703                 cur_cred = None
704         return list
705     
706     ##
707     # Make sure the credential's target gid was signed by (or is the same) the entity that signed
708     # the original credential or an authority over that namespace.
709     def verify_issuer(self):                
710         root_cred = self.get_credential_list()[-1]
711         root_target_gid = root_cred.get_gid_object()
712         root_cred_signer = root_cred.get_signature().get_issuer_gid()
713
714         if root_target_gid.is_signed_by_cert(root_cred_signer):
715             # cred signer matches target signer, return success
716             return
717
718         root_target_gid_str = root_target_gid.save_to_string()
719         root_cred_signer_str = root_cred_signer.save_to_string()
720         if root_target_gid_str == root_cred_signer_str:
721             # cred signer is target, return success
722             return
723
724         # See if it the signer is an authority over the domain of the target
725         # Maybe should be (hrn, type) = urn_to_hrn(root_cred_signer.get_urn())
726         root_cred_signer_type = root_cred_signer.get_type()
727         if (root_cred_signer_type == 'authority'):
728             #logger.debug('Cred signer is an authority')
729             # signer is an authority, see if target is in authority's domain
730             hrn = root_cred_signer.get_hrn()
731             if root_target_gid.get_hrn().startswith(hrn):
732                 return
733
734         # We've required that the credential be signed by an authority
735         # for that domain. Reasonable and probably correct.
736         # A looser model would also allow the signer to be an authority
737         # in my control framework - eg My CA or CH. Even if it is not
738         # the CH that issued these, eg, user credentials.
739
740         # Give up, credential does not pass issuer verification
741
742         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()))
743
744
745     ##
746     # -- For Delegates (credentials with parents) verify that:
747     # . The privileges must be a subset of the parent credentials
748     # . The privileges must have "can_delegate" set for each delegated privilege
749     # . The target gid must be the same between child and parents
750     # . The expiry time on the child must be no later than the parent
751     # . The signer of the child must be the owner of the parent        
752     def verify_parent(self, parent_cred):
753         # make sure the rights given to the child are a subset of the
754         # parents rights (and check delegate bits)
755         if not parent_cred.get_privileges().is_superset(self.get_privileges()):
756             raise ChildRightsNotSubsetOfParent(
757                 self.parent.get_privileges().save_to_string() + " " +
758                 self.get_privileges().save_to_string())
759
760         # make sure my target gid is the same as the parent's
761         if not parent_cred.get_gid_object().save_to_string() == \
762            self.get_gid_object().save_to_string():
763             raise CredentialNotVerifiable("Target gid not equal between parent and child")
764
765         # make sure my expiry time is <= my parent's
766         if not parent_cred.get_lifetime() >= self.get_lifetime():
767             raise CredentialNotVerifiable("Delegated credential expires after parent")
768
769         # make sure my signer is the parent's caller
770         if not parent_cred.get_gid_caller().save_to_string(False) == \
771            self.get_signature().get_issuer_gid().save_to_string(False):
772             raise CredentialNotVerifiable("Delegated credential not signed by parent caller")
773                 
774         # Recurse
775         if parent_cred.parent:
776             parent_cred.verify_parent(parent_cred.parent)
777
778     ##
779     # Dump the contents of a credential to stdout in human-readable format
780     #
781     # @param dump_parents If true, also dump the parent certificates
782
783     def dump(self, dump_parents=False):
784 # FIXME: get_subject doesnt exist
785 #        print "CREDENTIAL", self.get_subject()
786         print "CREDENTIAL"
787
788         print "      privs:", self.get_privileges().save_to_string()
789
790         print "  gidCaller:"
791         gidCaller = self.get_gid_caller()
792         if gidCaller:
793             gidCaller.dump(8, dump_parents)
794
795         print "  gidObject:"
796         gidObject = self.get_gid_object()
797         if gidObject:
798             gidObject.dump(8, dump_parents)
799
800
801         if self.parent and dump_parents:
802             print "PARENT",
803             self.parent.dump_parents()
804