a9be4298858cd1962290eee3835dd233934d6ff8
[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         self.xmlsec_path = '/usr/bin/env xmlsec1'
181
182
183         # Check if this is a legacy credential, translate it if so
184         if string or filename:
185             if string:                
186                 str = string
187             elif filename:
188                 str = file(filename).read()
189                 
190             if str.strip().startswith("-----"):
191                 self.legacy = CredentialLegacy(False,string=str)
192                 self.translate_legacy(str)
193             else:
194                 self.xml = str
195                 self.decode()
196
197
198     def get_signature(self):
199         if not self.signature:
200             self.decode()
201         return self.signature
202
203     def set_signature(self, sig):
204         self.signature = sig
205
206         
207     ##
208     # Translate a legacy credential into a new one
209     #
210     # @param String of the legacy credential
211
212     def translate_legacy(self, str):
213         legacy = CredentialLegacy(False,string=str)
214         self.gidCaller = legacy.get_gid_caller()
215         self.gidObject = legacy.get_gid_object()
216         lifetime = legacy.get_lifetime()
217         if not lifetime:
218             # Default to two years
219             self.set_lifetime(DEFAULT_CREDENTIAL_LIFETIME)
220         else:
221             self.set_lifetime(int(lifetime))
222         self.lifeTime = legacy.get_lifetime()
223         self.set_privileges(legacy.get_privileges())
224         self.get_privileges().delegate_all_privileges(legacy.get_delegate())
225
226     ##
227     # Need the issuer's private key and name
228     # @param key Keypair object containing the private key of the issuer
229     # @param gid GID of the issuing authority
230
231     def set_issuer_keys(self, privkey, gid):
232         self.issuer_privkey = privkey
233         self.issuer_gid = gid
234
235
236     ##
237     # Set this credential's parent
238     def set_parent(self, cred):
239         self.parent = cred
240         self.updateRefID()
241
242     ##
243     # set the GID of the caller
244     #
245     # @param gid GID object of the caller
246
247     def set_gid_caller(self, gid):
248         self.gidCaller = gid
249         # gid origin caller is the caller's gid by default
250         self.gidOriginCaller = gid
251
252     ##
253     # get the GID of the object
254
255     def get_gid_caller(self):
256         if not self.gidCaller:
257             self.decode()
258         return self.gidCaller
259
260     ##
261     # set the GID of the object
262     #
263     # @param gid GID object of the object
264
265     def set_gid_object(self, gid):
266         self.gidObject = gid
267
268     ##
269     # get the GID of the object
270
271     def get_gid_object(self):
272         if not self.gidObject:
273             self.decode()
274         return self.gidObject
275
276     ##
277     # set the lifetime of this credential
278     #
279     # @param lifetime lifetime of credential
280     # . if lifeTime is a datetime object, it is used for the expiration time
281     # . if lifeTime is an integer value, it is considered the number of minutes
282     #   remaining before expiration
283
284     def set_lifetime(self, lifeTime):
285         if isinstance(lifeTime, int):
286             self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
287         else:
288             self.expiration = lifeTime
289
290     ##
291     # get the lifetime of the credential (in minutes)
292
293     def get_lifetime(self):
294         if not self.expiration:
295             self.decode()
296         return self.expiration
297
298  
299     ##
300     # set the privileges
301     #
302     # @param privs either a comma-separated list of privileges of a RightList object
303
304     def set_privileges(self, privs):
305         if isinstance(privs, str):
306             self.privileges = RightList(string = privs)
307         else:
308             self.privileges = privs
309         
310
311     ##
312     # return the privileges as a RightList object
313
314     def get_privileges(self):
315         if not self.privileges:
316             self.decode()
317         return self.privileges
318
319     ##
320     # determine whether the credential allows a particular operation to be
321     # performed
322     #
323     # @param op_name string specifying name of operation ("lookup", "update", etc)
324
325     def can_perform(self, op_name):
326         rights = self.get_privileges()
327         
328         if not rights:
329             return False
330
331         return rights.can_perform(op_name)
332
333
334     ##
335     # Encode the attributes of the credential into an XML string    
336     # This should be done immediately before signing the credential.    
337     # WARNING:
338     # In general, a signed credential obtained externally should
339     # not be changed else the signature is no longer valid.  So, once
340     # you have loaded an existing signed credential, do not call encode() or sign() on it.
341
342     def encode(self):
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         while True:
406             filename = "/tmp/cred_%d" % randint(0,999999999)
407             if not os.path.isfile(filename):
408                 break
409             
410         self.save_to_file(filename)
411         return filename
412     
413     def save_to_file(self, filename, save_parents=True):
414         if not self.xml:
415             self.encode()
416         f = open(filename, "w")
417         f.write(self.xml)
418         f.close()
419
420     def save_to_string(self, save_parents=True):
421         if not self.xml:
422             self.encode()
423         return self.xml
424
425     def get_refid(self):
426         if not self.refid:
427             self.refid = 'ref0'
428         return self.refid
429
430     def set_refid(self, rid):
431         self.refid = rid
432
433     ##
434     # Figure out what refids exist, and update this credential's id
435     # so that it doesn't clobber the others.  Returns the refids of
436     # the parents.
437     
438     def updateRefID(self):
439         if not self.parent:
440             self.set_refid('ref0')
441             return []
442         
443         refs = []
444
445         next_cred = self.parent
446         while next_cred:
447             refs.append(next_cred.get_refid())
448             if next_cred.parent:
449                 next_cred = next_cred.parent
450             else:
451                 next_cred = None
452
453         
454         # Find a unique refid for this credential
455         rid = self.get_refid()
456         while rid in refs:
457             val = int(rid[3:])
458             rid = "ref%d" % (val + 1)
459
460         # Set the new refid
461         self.set_refid(rid)
462
463         # Return the set of parent credential ref ids
464         return refs
465
466     def get_xml(self):
467         if not self.xml:
468             self.encode()
469         return self.xml
470
471     ##
472     # Sign the XML file created by encode()
473     #
474     # WARNING:
475     # In general, a signed credential obtained externally should
476     # not be changed else the signature is no longer valid.  So, once
477     # you have loaded an existing signed credential, do not call encode() or sign() on it.
478
479     def sign(self):
480         if not self.issuer_privkey or not self.issuer_gid:
481             return
482         doc = parseString(self.get_xml())
483         sigs = doc.getElementsByTagName("signatures")[0]
484
485         # Create the signature template to be signed
486         signature = Signature()
487         signature.set_refid(self.get_refid())
488         sdoc = parseString(signature.get_xml())        
489         sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
490         sigs.appendChild(sig_ele)
491
492         self.xml = doc.toxml()
493
494
495         # Split the issuer GID into multiple certificates if it's a chain
496         chain = GID(filename=self.issuer_gid)
497         gid_files = []
498         while chain:
499             gid_files.append(chain.save_to_random_tmp_file(False))
500             if chain.get_parent():
501                 chain = chain.get_parent()
502             else:
503                 chain = None
504
505
506         # Call out to xmlsec1 to sign it
507         ref = 'Sig_%s' % self.get_refid()
508         filename = self.save_to_random_tmp_file()
509         signed = os.popen('%s --sign --node-id "%s" --privkey-pem %s,%s %s' \
510                  % (self.xmlsec_path, ref, self.issuer_privkey, ",".join(gid_files), filename)).read()
511         os.remove(filename)
512
513         for gid_file in gid_files:
514             os.remove(gid_file)
515
516         self.xml = signed
517
518         # This is no longer a legacy credential
519         if self.legacy:
520             self.legacy = None
521
522         # Update signatures
523         self.decode()
524
525         
526
527         
528     ##
529     # Retrieve the attributes of the credential from the XML.
530     # This is automatically called by the various get_* methods of
531     # this class and should not need to be called explicitly.
532
533     def decode(self):
534         if not self.xml:
535             return
536         doc = parseString(self.xml)
537         sigs = []
538         signed_cred = doc.getElementsByTagName("signed-credential")
539
540         # Is this a signed-cred or just a cred?
541         if len(signed_cred) > 0:
542             cred = signed_cred[0].getElementsByTagName("credential")[0]
543             signatures = signed_cred[0].getElementsByTagName("signatures")
544             if len(signatures) > 0:
545                 sigs = signatures[0].getElementsByTagName("Signature")
546         else:
547             cred = doc.getElementsByTagName("credential")[0]
548         
549
550
551         self.set_refid(cred.getAttribute("xml:id"))
552         sz_expires = getTextNode(cred, "expires")
553         if sz_expires != '':
554             self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')        
555         self.lifeTime = getTextNode(cred, "expires")
556         self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
557         self.gidObject = GID(string=getTextNode(cred, "target_gid"))   
558
559
560         # Process privileges
561         privs = cred.getElementsByTagName("privileges")[0]
562         rlist = RightList()
563         for priv in privs.getElementsByTagName("privilege"):
564             kind = getTextNode(priv, "name")
565             deleg = str2bool(getTextNode(priv, "can_delegate"))
566             if kind == '*':
567                 # Convert * into the default privileges for the credential's type                
568                 _ , type = urn_to_hrn(self.gidObject.get_urn())
569                 rl = rlist.determine_rights(type, self.gidObject.get_urn())
570                 for r in rl.rights:
571                     rlist.add(r)
572             else:
573                 rlist.add(Right(kind.strip(), deleg))
574         self.set_privileges(rlist)
575
576
577         # Is there a parent?
578         parent = cred.getElementsByTagName("parent")
579         if len(parent) > 0:
580             parent_doc = parent[0].getElementsByTagName("credential")[0]
581             parent_xml = parent_doc.toxml()
582             self.parent = Credential(string=parent_xml)
583             self.updateRefID()
584
585         # Assign the signatures to the credentials
586         for sig in sigs:
587             Sig = Signature(string=sig.toxml())
588
589             cur_cred = self
590             while cur_cred:
591                 if cur_cred.get_refid() == Sig.get_refid():
592                     cur_cred.set_signature(Sig)
593                     
594                 if cur_cred.parent:
595                     cur_cred = cur_cred.parent
596                 else:
597                     cur_cred = None
598                 
599             
600     ##
601     # Verify that:
602     # . All of the signatures are valid and that the issuers trace back
603     #   to trusted roots (performed by xmlsec1)
604     # . The XML matches the credential schema
605     # . That the issuer of the credential is the authority in the target's urn
606     #    . In the case of a delegated credential, this must be true of the root
607     # . That all of the gids presented in the credential are valid
608     #
609     # -- For Delegates (credentials with parents)
610     # . The privileges must be a subset of the parent credentials
611     # . The privileges must have "can_delegate" set for each delegated privilege
612     # . The target gid must be the same between child and parents
613     # . The expiry time on the child must be no later than the parent
614     # . The signer of the child must be the owner of the parent
615     #
616     # -- Verify does *NOT*
617     # . ensure that an xmlrpc client's gid matches a credential gid, that
618     #   must be done elsewhere
619     #
620     # @param trusted_certs: The certificates of trusted CA certificates
621     
622     def verify(self, trusted_certs):
623         if not self.xml:
624             self.decode()        
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('%s --verify --node-id "%s" %s %s 2>&1' \
661                             % (self.xmlsec_path, ref, cert_args, filename)).read()
662             if not verified.strip().startswith("OK"):
663                 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
664         os.remove(filename)
665
666         # Verify the parents (delegation)
667         if self.parent:
668             self.verify_parent(self.parent)
669         # Make sure the issuer is the target's authority
670         self.verify_issuer()
671         return True
672
673         
674     ##
675     # Make sure the issuer of this credential is the target's authority
676     def verify_issuer(self):        
677         target_authority = get_authority(self.get_gid_object().get_urn())
678
679         
680         # Find the root credential's signature
681         cur_cred = self
682         while cur_cred:            
683             if cur_cred.parent:
684                 cur_cred = cur_cred.parent
685             else:
686                 root_issuer = cur_cred.get_signature().get_issuer_gid().get_urn()
687                 cur_cred = None
688
689         # Ensure that the signer of the root credential is the target_authority
690         target_authority = hrn_to_urn(target_authority, 'authority')
691
692         if root_issuer != target_authority:
693             raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
694                                           % (root_issuer, target_authority))
695
696     ##
697     # -- For Delegates (credentials with parents) verify that:
698     # . The privileges must be a subset of the parent credentials
699     # . The privileges must have "can_delegate" set for each delegated privilege
700     # . The target gid must be the same between child and parents
701     # . The expiry time on the child must be no later than the parent
702     # . The signer of the child must be the owner of the parent
703         
704     def verify_parent(self, parent_cred):
705         # make sure the rights given to the child are a subset of the
706         # parents rights (and check delegate bits)
707         if not parent_cred.get_privileges().is_superset(self.get_privileges()):
708             raise ChildRightsNotSubsetOfParent(
709                 self.parent.get_privileges().save_to_string() + " " +
710                 self.get_privileges().save_to_string())
711
712         # make sure my target gid is the same as the parent's
713         if not parent_cred.get_gid_object().save_to_string() == \
714            self.get_gid_object().save_to_string():
715             raise CredentialNotVerifiable("target gid not equal between parent and child")
716
717         # make sure my expiry time is <= my parent's
718         if not parent_cred.get_lifetime() >= self.get_lifetime():
719             raise CredentialNotVerifiable("delegated credential expires after parent")
720
721         # make sure my signer is the parent's caller
722         if not parent_cred.get_gid_caller().save_to_string(False) == \
723            self.get_signature().get_issuer_gid().save_to_string(False):
724             raise CredentialNotVerifiable("delegated credential not signed by parent caller")
725                 
726         if parent_cred.parent:
727             parent_cred.verify_parent(parent_cred.parent)
728
729     ##
730     # Dump the contents of a credential to stdout in human-readable format
731     #
732     # @param dump_parents If true, also dump the parent certificates
733
734     def dump(self, dump_parents=False):
735         print "CREDENTIAL", self.get_subject()
736
737         print "      privs:", self.get_privileges().save_to_string()
738
739         print "  gidCaller:"
740         gidCaller = self.get_gid_caller()
741         if gidCaller:
742             gidCaller.dump(8, dump_parents)
743
744         print "  gidObject:"
745         gidObject = self.get_gid_object()
746         if gidObject:
747             gidObject.dump(8, dump_parents)
748
749
750         if self.parent and dump_parents:
751             print "PARENT",
752             self.parent.dump_parents()
753