writing testCred.py
[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 # . Need to add support for other types of credentials, e.g. tickets
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     # set the GID of the caller
216     #
217     # @param gid GID object of the caller
218
219     def set_gid_caller(self, gid):
220         self.gidCaller = gid
221         # gid origin caller is the caller's gid by default
222         self.gidOriginCaller = gid
223
224     ##
225     # get the GID of the object
226
227     def get_gid_caller(self):
228         if not self.gidCaller:
229             self.decode()
230         return self.gidCaller
231
232     ##
233     # set the GID of the object
234     #
235     # @param gid GID object of the object
236
237     def set_gid_object(self, gid):
238         self.gidObject = gid
239
240     ##
241     # get the GID of the object
242
243     def get_gid_object(self):
244         if not self.gidObject:
245             self.decode()
246         return self.gidObject
247
248     ##
249     # set the lifetime of this credential
250     #
251     # @param lifetime lifetime of credential
252     # . if lifeTime is a datetime object, it is used for the expiration time
253     # . if lifeTime is an integer value, it is considered the number of minutes
254     #   remaining before expiration
255
256     def set_lifetime(self, lifeTime):
257         if isinstance(lifeTime, int):
258             self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
259         else:
260             self.expiration = lifeTime
261
262     ##
263     # get the lifetime of the credential (in minutes)
264
265     def get_lifetime(self):
266         if not self.expiration:
267             self.decode()
268         return self.expiration
269
270  
271     ##
272     # set the privileges
273     #
274     # @param privs either a comma-separated list of privileges of a RightList object
275
276     def set_privileges(self, privs):
277         if isinstance(privs, str):
278             self.privileges = RightList(string = privs)
279         else:
280             self.privileges = privs
281         
282
283     ##
284     # return the privileges as a RightList object
285
286     def get_privileges(self):
287         if not self.privileges:
288             self.decode()
289         return self.privileges
290
291     ##
292     # determine whether the credential allows a particular operation to be
293     # performed
294     #
295     # @param op_name string specifying name of operation ("lookup", "update", etc)
296
297     def can_perform(self, op_name):
298         rights = self.get_privileges()
299         
300         if not rights:
301             return False
302
303         return rights.can_perform(op_name)
304
305     def append_sub(self, doc, parent, element, text):
306         ele = doc.createElement(element)
307         ele.appendChild(doc.createTextNode(text))
308         parent.appendChild(ele)
309
310     ##
311     # Encode the attributes of the credential into an XML string    
312     # This should be done immediately before signing the credential.    
313
314     def encode(self):
315         p_sigs = None
316
317         # Create the XML document
318         doc = Document()
319         signed_cred = doc.createElement("signed-credential")
320         doc.appendChild(signed_cred)  
321         
322         # Fill in the <credential> bit        
323         cred = doc.createElement("credential")
324         cred.setAttribute("xml:id", self.get_refid())
325         signed_cred.appendChild(cred)
326         self.append_sub(doc, cred, "type", "privilege")
327         self.append_sub(doc, cred, "serial", "8")
328         self.append_sub(doc, cred, "owner_gid", self.gidCaller.save_to_string())
329         self.append_sub(doc, cred, "owner_urn", self.gidCaller.get_urn())
330         self.append_sub(doc, cred, "target_gid", self.gidObject.save_to_string())
331         self.append_sub(doc, cred, "target_urn", self.gidObject.get_urn())
332         self.append_sub(doc, cred, "uuid", "")
333         if  not self.expiration:
334             self.set_lifetime(3600)
335         self.expiration = self.expiration.replace(microsecond=0)
336         self.append_sub(doc, cred, "expires", self.expiration.isoformat())
337         privileges = doc.createElement("privileges")
338         cred.appendChild(privileges)
339
340         if self.privileges:
341             rights = self.get_privileges()
342             for right in rights.rights:
343                 priv = doc.createElement("privilege")
344                 self.append_sub(doc, priv, "name", right.kind)
345                 self.append_sub(doc, priv, "can_delegate", str(right.delegate))
346                 privileges.appendChild(priv)
347
348         # Add the parent credential if it exists
349         if self.parent:
350             sdoc = parseString(self.parent.get_xml())
351             p_cred = doc.importNode(sdoc.getElementsByTagName("credential")[0], True)
352             p = doc.createElement("parent")
353             p.appendChild(p_cred)
354             cred.appendChild(p)
355
356
357         # Create the <signatures> tag
358         signatures = doc.createElement("signatures")
359         signed_cred.appendChild(signatures)
360
361         # Add any parent signatures
362         if self.parent:
363             cur_cred = self.parent
364             while cur_cred:
365                 sdoc = parseString(cur_cred.get_signature().get_xml())
366                 ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
367                 signatures.appendChild(ele)
368
369                 if cur_cred.parent:
370                     cur_cred = cur_cred.parent
371                 else:
372                     cur_cred = None
373                 
374         # Get the finished product
375         self.xml = doc.toxml()
376         #print doc.toxml()
377         #self.sign()
378
379
380     def save_to_random_tmp_file(self):
381         filename = "/tmp/cred_%d" % random.randint(0,999999999)
382         self.save_to_file(filename)
383         return filename
384     
385     def save_to_file(self, filename, save_parents=True):
386         if not self.xml:
387             self.encode()
388         f = open(filename, "w")
389         f.write(self.xml)
390         f.close()
391
392     def save_to_string(self, save_parents=True):
393         if not self.xml:
394             self.encode()
395         return self.xml
396
397     def get_refid(self):
398         if not self.refid:
399             self.refid = 'ref0'
400         return self.refid
401
402     def set_refid(self, rid):
403         self.refid = rid
404
405     ##
406     # Figure out what refids exist, and update this credential's id
407     # so that it doesn't clobber the others.  Returns the refids of
408     # the parents.
409     
410     def updateRefID(self):
411         if not self.parent:
412             self.set_refid('ref0')
413             return []
414         
415         refs = []
416
417         next_cred = self.parent
418         while next_cred:
419             refs.append(next_cred.get_refid())
420             if next_cred.parent:
421                 next_cred = next_cred.parent
422             else:
423                 next_cred = None
424
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         doc = parseString(self.get_xml())
447         sigs = doc.getElementsByTagName("signatures")[0]
448
449         # Create the signature template to be signed
450         signature = Signature()
451         signature.set_refid(self.get_refid())
452         sdoc = parseString(signature.get_xml())        
453         sig_ele = doc.importNode(sdoc.getElementsByTagName("Signature")[0], True)
454         sigs.appendChild(sig_ele)
455
456         self.xml = doc.toxml()
457
458         # Call out to xmlsec1 to sign it
459         ref = 'Sig_%s' % self.get_refid()
460         filename = self.save_to_random_tmp_file()
461         signed = os.popen('/usr/bin/xmlsec1 --sign --node-id "%s" --privkey-pem %s,%s %s' \
462                  % (ref, self.issuer_privkey, self.issuer_gid, filename)).read()
463         os.remove(filename)
464
465         self.xml = signed
466         
467
468     def getTextNode(self, element, subele):
469         sub = element.getElementsByTagName(subele)[0]
470         if len(sub.childNodes) > 0:            
471             return sub.childNodes[0].nodeValue
472         else:
473             return None
474         
475     ##
476     # Retrieve the attributes of the credential from the XML.
477     # This is automatically caleld by the various get_* methods of
478     # this class and should not need to be called explicitly.
479
480     def decode(self):
481         if not self.xml:
482             return
483         doc = parseString(self.xml)
484         sigs = None
485         signed_cred = doc.getElementsByTagName("signed-credential")
486
487         # Is this a signed-cred or just a cred?
488         if len(signed_cred) > 0:
489             cred = signed_cred[0].getElementsByTagName("credential")[0]
490             signatures = signed_cred[0].getElementsByTagName("signatures")
491             if len(signatures) > 0:
492                 sigs = signatures[0].getElementsByTagName("Signature")
493         else:
494             cred = doc.getElementsByTagName("credential")[0]
495         
496
497
498         self.set_refid(cred.getAttribute("xml:id"))
499         sz_expires = getTextNode(cred, "expires")
500         if sz_expires != '':
501             self.expiration = datetime.datetime.strptime(sz_expires, '%Y-%m-%dT%H:%M:%S')        
502         self.lifeTime = getTextNode(cred, "expires")
503         self.gidCaller = GID(string=getTextNode(cred, "owner_gid"))
504         self.gidObject = GID(string=getTextNode(cred, "target_gid"))   
505
506
507         # Process privileges
508         privs = cred.getElementsByTagName("privileges")[0]
509         rlist = RightList()
510         for priv in privs.getElementsByTagName("privilege"):
511             kind = getTextNode(priv, "name")
512             deleg = bool(getTextNode(priv, "can_delegate"))
513             rlist.add(Right(kind.strip(), deleg))
514         self.set_privileges(rlist)
515
516
517         # Is there a parent?
518         parent = cred.getElementsByTagName("parent")
519         if len(parent) > 0:
520             self.parent = Credential(string=getTextNode(cred, "parent"))
521             self.updateRefID()
522
523         # Assign the signatures to the credentials
524         for sig in sigs:
525             Sig = Signature(string=sig.toxml())
526
527             cur_cred = self
528             while cur_cred:
529                 if cur_cred.get_refid() == Sig.get_refid():
530                     cur_cred.set_signature(Sig)
531                     
532                 if cur_cred.parent:
533                     cur_cred = cur_cred.parent
534                 else:
535                     cur_cred = None
536                 
537             
538     ##
539     # Verify that:
540     # . All of the signatures are valid and that the issuers trace back
541     #   to trusted roots (performed by xmlsec1)
542     # . That the issuer of the credential is the authority in the target's urn
543     #    . In the case of a delegated credential, this must be true of the root
544     # . That all of the gids presented in the credential are valid
545     #
546     # -- For Delegates (credentials with parents)
547     # . The privileges must be a subset of the parent credentials
548     # . The privileges must have "can_delegate" set for each delegated privilege
549     # . The target gid must be the same between child and parents
550     # . The expiry time on the child must be no later than the parent
551     # . The signer of the child must be the owner of the parent
552     #
553     # -- Verify does *NOT*
554     # . ensure that an xmlrpc client's gid matches a credential gid, that
555     #   must be done elsewhere
556     #
557     # @param trusted_certs: The certificates of trusted CA certificates
558     
559     def verify(self, trusted_certs):
560         if not self.xml:
561             self.decode()        
562
563         # Verify the signatures
564         filename = self.save_to_random_tmp_file()
565         cert_args = " ".join(['--trusted-pem %s' % x for x in trusted_certs])
566
567         # Verify the gids of this cred and of its parents
568         trusted_cert_objects = [GID(filename=f) for f in trusted_certs]
569
570         cur_cred = self
571         while cur_cred:
572             cur_cred.get_gid_object().verify_chain(trusted_cert_objects)
573             cur_cred.get_gid_caller().verify_chain(trusted_cert_objects)
574             if cur_cred.parent:
575                 cur_cred = cur_cred.parent
576             else:
577                 cur_cred = None
578         
579         refs = []
580         refs.append("Sig_%s" % self.get_refid())
581
582         parentRefs = self.updateRefID()
583         for ref in parentRefs:
584             refs.append("Sig_%s" % ref)
585
586         for ref in refs:
587             verified = os.popen('/usr/bin/xmlsec1 --verify --node-id "%s" %s %s 2>&1' \
588                             % (ref, cert_args, filename)).read()
589             if not verified.strip().startswith("OK"):
590                 raise CredentialNotVerifiable("xmlsec1 error: " + verified)
591
592         os.remove(filename)
593
594         # Verify the parents (delegation)
595         if self.parent:
596             self.verify_parent(self.parent)
597
598         # Make sure the issuer is the target's authority
599         self.verify_issuer()
600
601
602
603     ##
604     # Make sure the issuer of this credential is the target's authority
605     def verify_issuer(self):        
606         target_authority = get_authority(self.get_gid_object().get_urn())
607
608         # Find the root credential's signature
609         cur_cred = self
610         root_refid = None
611         while cur_cred:            
612             if cur_cred.parent:
613                 cur_cred = cur_cred.parent
614             else:
615                 root_issuer = cur_cred.get_signature().get_issuer_gid().get_urn()
616                 cur_cred = None
617
618                 
619         # Ensure that the signer of the root credential is the target_authority
620         target_authority = hrn_to_urn(target_authority, 'authority')
621
622         if root_issuer != target_authority:
623             raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
624                                           % (root_issuer, target_authority))
625
626     ##
627     # -- For Delegates (credentials with parents) verify that:
628     # . The privileges must be a subset of the parent credentials
629     # . The privileges must have "can_delegate" set for each delegated privilege
630     # . The target gid must be the same between child and parents
631     # . The expiry time on the child must be no later than the parent
632     # . The signer of the child must be the owner of the parent
633         
634     def verify_parent(self, parent_cred):
635         # make sure the rights given to the child are a subset of the
636         # parents rights (and check delegate bits)
637         if not parent_cred.get_privileges().is_superset(self.get_privileges()):
638             raise ChildRightsNotSubsetOfParent(
639                 self.parent.get_privileges().save_to_string() + " " +
640                 self.get_privileges().save_to_string())
641
642         # make sure my target gid is the same as the parent's
643         if not parent_cred.get_gid_object().save_to_string() == \
644            self.get_gid_object().save_to_string():
645             raise CredentialNotVerifiable("target gid not equal between parent and child")
646
647         # make sure my expiry time is <= my parent's
648         if not parent_cred.get_lifetime() >= self.get_lifetime():
649             raise CredentialNotVerifiable("delegated credential expires after parent")
650
651         # make sure my signer is the parent's caller
652         if not parent_cred.get_gid_caller().save_to_string(False) == \
653            self.get_signature().get_issuer_gid().save_to_string(False):
654             raise CredentialNotVerifiable("delegated credential not signed by parent caller")
655                 
656         if parent_cred.parent:
657             parent_cred.verify_parent(parent_cred.parent)
658
659     ##
660     # Dump the contents of a credential to stdout in human-readable format
661     #
662     # @param dump_parents If true, also dump the parent certificates
663
664     def dump(self, dump_parents=False):
665         print "CREDENTIAL", self.get_subject()
666
667         print "      privs:", self.get_privileges().save_to_string()
668
669         print "  gidCaller:"
670         gidCaller = self.get_gid_caller()
671         if gidCaller:
672             gidCaller.dump(8, dump_parents)
673
674         print "  gidObject:"
675         gidObject = self.get_gid_object()
676         if gidObject:
677             gidObject.dump(8, dump_parents)
678
679
680         if self.parent and dump_parents:
681            print "PARENT",
682            self.parent.dump_parents()
683