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