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