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