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