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