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