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