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