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