2 # Implements SFA Credentials
4 # Credentials are layered on top of certificates, and are essentially a
5 # certificate that stores a tuple of parameters.
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
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?
38 signature_template = \
40 <Signature xml:id="Sig_%s" xmlns="http://www.w3.org/2000/09/xmldsig#">
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"/>
46 <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
48 <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
49 <DigestValue></DigestValue>
67 # Utility function to get the text of an XML element
69 def getTextNode(element, subele):
70 sub = element.getElementsByTagName(subele)[0]
71 if len(sub.childNodes) > 0:
72 return sub.childNodes[0].nodeValue
79 # Signature contains information about an xmlsec1 signature
80 # for a signed-credential
82 class Signature(object):
87 def __init__(self, string=None):
104 def set_refid(self, id):
107 def get_issuer_gid(self):
112 def set_issuer_gid(self, gid):
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))
125 self.xml = signature_template % (self.get_refid(), self.get_refid())
129 # Credential is a tuple:
130 # (GIDCaller, GIDObject, Expiration (in UTC time), Privileges, DelegateBit)
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.
137 class Credential(object):
143 issuer_privkey = None
152 # Create a Credential object
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
159 def __init__(self, create=False, subject=None, string=None, filename=None):
161 # Check if this is a legacy credential, translate it if so
162 if string or filename:
166 str = file(filename).read()
168 if str.strip().startswith("-----"):
169 self.translate_legacy(str)
175 # Translate a legacy credential into a new one
177 # @param String of the legacy credential
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()
185 self.set_lifetime(3600)
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()
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
197 def set_issuer_keys(self, privkey, gid):
198 self.issuer_privkey = privkey
199 self.issuer_gid = gid
201 #def set_issuer(self, issuer):
204 #def set_subject(self, subject):
207 #def set_pubkey(self, pubkey):
208 # self.issuer_pubkey = pubkey
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):
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")
225 self.parent_xml = cred.toxml()
228 self.signatures.append(Signature(string=sig.toxml()))
234 # set the GID of the caller
236 # @param gid GID object of the caller
238 def set_gid_caller(self, gid):
240 # gid origin caller is the caller's gid by default
241 self.gidOriginCaller = gid
244 # get the GID of the object
246 def get_gid_caller(self):
247 if not self.gidCaller:
249 return self.gidCaller
252 # set the GID of the object
254 # @param gid GID object of the object
256 def set_gid_object(self, gid):
260 # get the GID of the object
262 def get_gid_object(self):
263 if not self.gidObject:
265 return self.gidObject
268 # set the lifetime of this credential
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
275 def set_lifetime(self, lifeTime):
276 if isinstance(lifeTime, int):
277 self.expiration = datetime.timedelta(seconds=lifeTime*60) + datetime.datetime.utcnow()
279 self.expiration = lifeTime
282 # get the lifetime of the credential (in minutes)
284 def get_lifetime(self):
285 if not self.lifeTime:
287 return self.expiration
290 # set the delegate bit
292 # @param delegate boolean (True or False)
294 def set_delegate(self, delegate):
295 self.delegate = delegate
298 # get the delegate bit
300 def get_delegate(self):
301 if not self.delegate:
308 # @param privs either a comma-separated list of privileges of a RightList object
310 def set_privileges(self, privs):
311 if isinstance(privs, str):
312 self.privileges = RightList(string = privs)
314 self.privileges = privs
317 # return the privileges as a RightList object
319 def get_privileges(self):
320 if not self.privileges:
322 return self.privileges
325 # determine whether the credential allows a particular operation to be
328 # @param op_name string specifying name of operation ("lookup", "update", etc)
330 def can_perform(self, op_name):
331 rights = self.get_privileges()
336 return rights.can_perform(op_name)
338 def append_sub(self, doc, parent, element, text):
339 ele = doc.createElement(element)
340 ele.appendChild(doc.createTextNode(text))
341 parent.appendChild(ele)
344 # Encode the attributes of the credential into an XML string
345 # This should be done immediately before signing the credential.
350 # Create the XML document
352 signed_cred = doc.createElement("signed-credential")
353 doc.appendChild(signed_cred)
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)
374 rights = self.privileges.save_to_string().split(",")
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)
381 # Add the parent credential if it exists
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)
390 # Create the <signatures> tag
391 signatures = doc.createElement("signatures")
392 signed_cred.appendChild(signatures)
394 # Add any parent signatures
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)
401 # Get the finished product
402 self.xml = doc.toxml()
407 def save_to_random_tmp_file(self):
408 filename = "/tmp/cred_%d" % random.randint(0,999999999)
409 self.save_to_file(filename)
412 def save_to_file(self, filename, save_parents=True):
415 f = open(filename, "w")
419 def save_to_string(self, save_parents=True):
429 def set_refid(self, rid):
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
437 def updateRefID(self):
438 if not self.parent_xml:
439 self.set_refid('ref0')
444 next_cred = Credential(string=self.parent_xml)
446 refs.append(next_cred.get_refid())
447 if next_cred.parent_xml:
448 next_cred = Credential(string=next_cred.parent_xml)
452 # Find a unique refid for this credential
453 rid = self.get_refid()
456 rid = "ref%d" % (val + 1)
461 # Return the set of parent credential ref ids
470 if not self.issuer_privkey or not self.issuer_gid:
473 doc = parseString(self.get_xml())
474 sigs = doc.getElementsByTagName("signatures")[0]
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)
483 self.xml = doc.toxml()
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()
495 def getTextNode(self, element, subele):
496 sub = element.getElementsByTagName(subele)[0]
497 if len(sub.childNodes) > 0:
498 return sub.childNodes[0].nodeValue
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.
508 doc = parseString(self.xml)
510 signed_cred = doc.getElementsByTagName("signed-credential")
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")
519 cred = doc.getElementsByTagName("credential")[0]
523 self.set_refid(cred.getAttribute("xml:id"))
524 sz_expires = getTextNode(cred, "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]
533 for priv in privs.getElementsByTagName("privilege"):
534 sz_privs += getTextNode(priv, "name")
536 delegates.append(getTextNode(priv, "can_delegate"))
540 if "false" not in delegates:
543 # Make the rights list
544 sz_privs.rstrip(", ")
545 self.privileges = RightList(string=sz_privs)
549 parent = cred.getElementsByTagName("parent")
551 self.parent_xml = getTextNode(cred, "parent")
556 self.signatures.append(Signature(string=sig.toxml()))
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
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
572 # -- Verify does *NOT*
573 # . ensure that an xmlrpc client's gid matches a credential gid, that
574 # must be done elsewhere
576 # @param trusted_certs: The certificates of trusted CA certificates
578 def verify(self, trusted_certs):
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])
588 refs.append("Sig_%s" % self.get_refid())
590 parentRefs = self.updateRefID()
591 for ref in parentRefs:
592 refs.append("Sig_%s" % ref)
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)
602 # Verify the parents (delegation)
604 # self.verify_parent(Credential(string=self.parent_xml))
606 # Make sure the issuer is the target's authority
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())
618 # Find the root credential's refid
622 if cur_cred.parent_xml:
623 cur_cred = Credential(string=cur_cred.parent_xml)
625 root_refid = cur_cred.get_refid()
628 # Find the signature for the root credential
630 for sig in self.signatures:
631 if sig.get_refid().lower() == root_refid.lower():
632 root_issuer = sig.get_issuer_gid().get_urn()
634 # Ensure that the signer of the root credential is the target_authority
635 target_authority = hrn_to_urn(target_authority, 'authority')
637 if root_issuer != target_authority:
638 raise CredentialNotVerifiable("issuer (%s) != authority of target (%s)" \
639 % (root_issuer, target_authority))
642 def verify_parent(self, parent_cred):
643 if parent_cred.parent_xml:
644 parent_cred.verify_parent(Credential(string=parent_cred.parent_xml))
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.
652 # Each credential must be a subset of the rights of the parent.
654 def verify_chain(self, trusted_certs):
657 ## def verify_chain(self, trusted_certs = None):
658 ## # do the normal certificate verification stuff
659 ## Certificate.verify_chain(self, trusted_certs)
662 ## # make sure the parent delegated rights to the child
663 ## if not self.parent.get_delegate():
664 ## raise MissingDelegateBit(self.parent.get_subject())
666 ## # make sure the rights given to the child are a subset of the
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())
676 # Dump the contents of a credential to stdout in human-readable format
678 # @param dump_parents If true, also dump the parent certificates
680 def dump(self, dump_parents=False):
681 print "CREDENTIAL", self.get_subject()
683 print " privs:", self.get_privileges().save_to_string()
686 gidCaller = self.get_gid_caller()
688 gidCaller.dump(8, dump_parents)
691 gidObject = self.get_gid_object()
693 gidObject.dump(8, dump_parents)
695 print " delegate:", self.get_delegate()
697 if self.parent_xml and dump_parents:
699 #self.parent.dump(dump_parents)