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